From 7c5b694ea434eb4c180eefe6604fe2521aec6bb5 Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Thu, 24 Oct 2024 23:12:57 -0400 Subject: [PATCH 01/11] Fixed bug with adding a non-repeating structure for PDB files --- TurtleMol/__main__.py | 2 +- TurtleMol/examples/Argon/ArgonTest.txt | 1 - TurtleMol/makeStruc.py | 8 ++++++-- TurtleMol/mesh3D.py | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/TurtleMol/__main__.py b/TurtleMol/__main__.py index 66cc8ff..c48f08e 100644 --- a/TurtleMol/__main__.py +++ b/TurtleMol/__main__.py @@ -19,7 +19,7 @@ def parseCommandLine(dparams): parser.add_argument('-baseStruc', '--baseStrucFile', type=str, help='Path to base structure file', default=dparams['baseStrucFile']) parser.add_argument('-s', '--shape', type=str, - help="Shape (Box or Cube)", default=dparams['shape']) + help="Shape (Box, Cube, Sphere, Mesh, Multimesh)", default=dparams['shape']) parser.add_argument('-sl', '--sideLength', type=float, help="Dimensions of a cube in Angstroms", default=dparams['sideLength']) parser.add_argument('-xl', '--Xlen', type=float, diff --git a/TurtleMol/examples/Argon/ArgonTest.txt b/TurtleMol/examples/Argon/ArgonTest.txt index af8525a..71650a6 100644 --- a/TurtleMol/examples/Argon/ArgonTest.txt +++ b/TurtleMol/examples/Argon/ArgonTest.txt @@ -3,6 +3,5 @@ sideLength=10 numMolecules=20 structureFile=argon.xyz radius = 10 -fromWall=0.25 outputFile=out.xyz tol=0.5 \ No newline at end of file diff --git a/TurtleMol/makeStruc.py b/TurtleMol/makeStruc.py index 99a7475..47520a4 100644 --- a/TurtleMol/makeStruc.py +++ b/TurtleMol/makeStruc.py @@ -39,8 +39,12 @@ def reCenter(struc, shape): shapeCenter[1] - currentCenter[1], shapeCenter[2] - currentCenter[2] ) - newCoords = [(coord[0], coord[1] + displacement[0], coord[2] + displacement[1], - coord[3] + displacement[2]) for coord in struc] + if len(struc[0]) == 4: + newCoords = [(coord[0], coord[1] + displacement[0], coord[2] + displacement[1], + coord[3] + displacement[2]) for coord in struc] + else: + newCoords = [(coord[0], coord[1] + displacement[0], coord[2] + displacement[1], + coord[3] + displacement[2], coord[4]) for coord in struc] return newCoords diff --git a/TurtleMol/mesh3D.py b/TurtleMol/mesh3D.py index 815c747..20d62a8 100644 --- a/TurtleMol/mesh3D.py +++ b/TurtleMol/mesh3D.py @@ -55,7 +55,7 @@ def origin(self): return [0, 0, 0] def findCenter(self): - return self.origin + return self.origin() def translate(self): self.mesh.apply_translation(-self.bounds[0]) From bf9bf3a07c2595c480e5284b2b17e7f2b5c3a0eb Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Fri, 25 Oct 2024 14:24:27 -0400 Subject: [PATCH 02/11] Fixed bug with rotating unit cells by a user inputed amount --- TurtleMol/makeStruc.py | 10 +++++----- TurtleMol/multMesh.py | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/TurtleMol/makeStruc.py b/TurtleMol/makeStruc.py index 47520a4..daf07ea 100644 --- a/TurtleMol/makeStruc.py +++ b/TurtleMol/makeStruc.py @@ -345,17 +345,17 @@ def rotateUnitCell(latticeVec, atoms, rotAngles): atomCoords = rotZ.apply(atomCoords @ latticeVec) if len(atoms[0]) == 4: - rotatedAtoms = [atomTypes[i] + atomCoords[i] for i in range(len(atoms))] + rotatedAtoms = [[atomTypes[i], *atomCoords[i]] for i in range(len(atoms))] elif len(atoms[0]) == 5: - rotatedAtoms = [atomTypes[i] + atomCoords[i] + atoms[i][-1] for i in range(len(atoms))] + rotatedAtoms = [[atomTypes[i], *atomCoords[i], atoms[i][-1]] for i in range(len(atoms))] a = np.linalg.norm(latticeVec[0]) b = np.linalg.norm(latticeVec[1]) c = np.linalg.norm(latticeVec[2]) - alpha = np.degrees(np.acrcos(np.dot(latticeVec[1], latticeVec[2])/(b*c))) - beta = np.degrees(np.acrcos(np.dot(latticeVec[0], latticeVec[2])/(a*c))) - gamma = np.degrees(np.acrcos(np.dot(latticeVec[0], latticeVec[1])/(a*b))) + alpha = np.degrees(np.arccos(np.dot(latticeVec[1], latticeVec[2])/(b*c))) + beta = np.degrees(np.arccos(np.dot(latticeVec[0], latticeVec[2])/(a*c))) + gamma = np.degrees(np.arccos(np.dot(latticeVec[0], latticeVec[1])/(a*b))) cellParams = {'a' : a, 'b' : b, diff --git a/TurtleMol/multMesh.py b/TurtleMol/multMesh.py index 3776e32..af9210d 100644 --- a/TurtleMol/multMesh.py +++ b/TurtleMol/multMesh.py @@ -18,6 +18,7 @@ def buildMultiMesh(strucs, baseStruc, iparams): scaleXList = iparams['scaleX'] scaleYList = iparams['scaleY'] scaleZList = iparams['scaleZ'] + rotAngleList = iparams['rotAngles'] scaleList = [] if isinstance(iparams['meshScale'], float): @@ -37,6 +38,7 @@ def buildMultiMesh(strucs, baseStruc, iparams): for i in range(len(meshList)): iparams['mesh'] = str(meshList[i]) iparams['meshScale'] = float(scaleList[i]) + iparams['rotAngles'] = rotAngleList[i] struc = strucs[i] if scaleXList is not None and scaleYList is not None and scaleZList is not None: iparams['scaleX'] = float(scaleXList[i]) if scaleXList[i] is not None else scaleList[i] @@ -90,7 +92,8 @@ def buildMultiMesh(strucs, baseStruc, iparams): for i in range(len(meshList)): iparams['mesh'] = str(meshList[i]) iparams['meshScale'] = float(scaleList[i]) - struc = strucs[i] + iparams['rotAngles'] = rotAngleList[i] + struc = strucs if scaleXList is not None and scaleYList is not None and scaleZList is not None: iparams['scaleX'] = float(scaleXList[i]) if scaleXList[i] is not None else scaleList[i] iparams['scaleY'] = float(scaleYList[i]) if scaleYList[i] is not None else scaleList[i] From 55c03eff6d9e6b6c6440686da4f51ddbb9c8b99d Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Sun, 27 Oct 2024 23:24:38 -0400 Subject: [PATCH 03/11] Fixed bug when rotating unit cells --- TurtleMol/makeStruc.py | 81 +++++++++++++++++++------------------ TurtleMol/multMesh.py | 1 + TurtleMol/readWriteFiles.py | 2 +- TurtleMol/shiftUnitCell.py | 10 +++-- 4 files changed, 50 insertions(+), 44 deletions(-) diff --git a/TurtleMol/makeStruc.py b/TurtleMol/makeStruc.py index daf07ea..83d3792 100644 --- a/TurtleMol/makeStruc.py +++ b/TurtleMol/makeStruc.py @@ -320,49 +320,50 @@ def calcLatticeVectors(a, b, c, alpha, beta, gamma): return latticeVectors + def rotateUnitCell(latticeVec, atoms, rotAngles): - '''Rotate unit cell lattice vectors and atoms''' - xAxis = [1, 0, 0] - yAxis = [0, 1, 0] - zAxis = [0, 0, 1] + '''Rotate unit cell lattice vectors and atoms by specified rotation angles along x, y, and z.''' + + # Create cumulative rotation object for specified angles on x, y, and z axes + rotation = R.from_euler('xyz', rotAngles, degrees=True) + + # Apply rotation to lattice vectors + rotated_latticeVec = rotation.apply(latticeVec) + # Apply rotation to atom coordinates atomTypes = [atom[0] for atom in atoms] atomCoords = [atom[1:4] for atom in atoms] + rotated_atomCoords = rotation.apply(atomCoords) - if rotAngles[0] != 0: - rotX = R.from_rotvec(np.radians(rotAngles[0]) * np.array(xAxis)) - latticeVec = rotX.apply(latticeVec) - atomCoords = rotX.apply(atomCoords @ latticeVec) + # Reassemble rotated atom data + rotatedAtoms = [[atomTypes[i], *rotated_atomCoords[i], atoms[i][-1]] for i in range(len(atoms))] + + # Calculate lengths of rotated lattice vectors + lengths = np.linalg.norm(rotated_latticeVec, axis=1) + + # Identify which rotated lattice vector aligns with each primary axis + # Determine the primary direction (x, y, or z) based on the largest component in each vector + primary_axes = np.argmax(np.abs(rotated_latticeVec), axis=1) + axes_map = {0: 'a', 1: 'b', 2: 'c'} + + # Map lengths based on primary axis alignment + a = lengths[np.where(primary_axes == 0)[0][0]] + b = lengths[np.where(primary_axes == 1)[0][0]] + c = lengths[np.where(primary_axes == 2)[0][0]] - if rotAngles[1] != 0: - rotY = R.from_rotvec(np.radians(rotAngles[1]) * np.array(yAxis)) - latticeVec = rotY.apply(latticeVec) - atomCoords = rotY.apply(atomCoords @ latticeVec) - - if rotAngles[2] != 0: - rotZ = R.from_rotvec(np.radians(rotAngles[2]) * np.array(zAxis)) - latticeVec = rotZ.apply(latticeVec) - atomCoords = rotZ.apply(atomCoords @ latticeVec) - - if len(atoms[0]) == 4: - rotatedAtoms = [[atomTypes[i], *atomCoords[i]] for i in range(len(atoms))] - elif len(atoms[0]) == 5: - rotatedAtoms = [[atomTypes[i], *atomCoords[i], atoms[i][-1]] for i in range(len(atoms))] - - a = np.linalg.norm(latticeVec[0]) - b = np.linalg.norm(latticeVec[1]) - c = np.linalg.norm(latticeVec[2]) - - alpha = np.degrees(np.arccos(np.dot(latticeVec[1], latticeVec[2])/(b*c))) - beta = np.degrees(np.arccos(np.dot(latticeVec[0], latticeVec[2])/(a*c))) - gamma = np.degrees(np.arccos(np.dot(latticeVec[0], latticeVec[1])/(a*b))) - - cellParams = {'a' : a, - 'b' : b, - 'c' : c, - 'alpha' : alpha, - 'beta' : beta, - 'gamma' : gamma} - - - return rotatedAtoms, cellParams \ No newline at end of file + # Calculate angles between rotated lattice vectors + alpha = np.degrees(np.arccos(np.dot(rotated_latticeVec[1], rotated_latticeVec[2]) / (b * c))) + beta = np.degrees(np.arccos(np.dot(rotated_latticeVec[0], rotated_latticeVec[2]) / (a * c))) + gamma = np.degrees(np.arccos(np.dot(rotated_latticeVec[0], rotated_latticeVec[1]) / (a * b))) + + # Collect the new cell parameters + cellParams = { + 'a': a, + 'b': b, + 'c': c, + 'alpha': alpha, + 'beta': beta, + 'gamma': gamma + } + + return rotatedAtoms, cellParams diff --git a/TurtleMol/multMesh.py b/TurtleMol/multMesh.py index af9210d..52fc5fe 100644 --- a/TurtleMol/multMesh.py +++ b/TurtleMol/multMesh.py @@ -110,6 +110,7 @@ def buildMultiMesh(strucs, baseStruc, iparams): matrix = np.dot(iparams['globalMatrix'][i], scalingMatrix) else: matrix = iparams['globalMatrix'][i] * scaleList[i] + print(matrix) if iparams['unitCell']: tol = 0 diff --git a/TurtleMol/readWriteFiles.py b/TurtleMol/readWriteFiles.py index 60d57df..b931350 100644 --- a/TurtleMol/readWriteFiles.py +++ b/TurtleMol/readWriteFiles.py @@ -180,7 +180,7 @@ def writePdb(data, filePath, cellParams=None): )) atomNum += 1 - resNum += 1 + resNum += 0 pdbFile.write("END\n") def writeXYZ(data, filePath, strucType): diff --git a/TurtleMol/shiftUnitCell.py b/TurtleMol/shiftUnitCell.py index 5ab8003..017809a 100644 --- a/TurtleMol/shiftUnitCell.py +++ b/TurtleMol/shiftUnitCell.py @@ -137,19 +137,23 @@ def unitCellMesh(shape, cellDims, cellAngles, og, radius, rotAngles=np.array([0, # Box dimensions that completely contain the mesh maxBound, minBound = shape.bounds[1], shape.bounds[0] + print(cellDims) + print(cellAngles) boxDim = maxBound - minBound - + print(minBound, maxBound) if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])): latticeVec = calcLatticeVectors(cellDims[0], cellDims[1], cellDims[2], cellAngles[0], cellAngles[1], cellAngles[2]) og, cellInfo = rotateUnitCell(latticeVec, og, rotAngles) cellDims = [cellInfo['a'], cellInfo['b'], cellInfo['c']] + print(cellDims) cellAngles = [cellInfo['alpha'], cellInfo['beta'], cellInfo['gamma']] + print(cellAngles) alpha = np.radians(cellAngles[0]) beta = np.radians(cellAngles[1]) gamma = np.radians(cellAngles[2]) - dupeCount = [int(boxDim[i] / cellDims[i]) for i in range(3)] + dupeCount = [int(np.ceil(boxDim[i] / cellDims[i])) + 5 for i in range(3)] cellParams = f'CRYST1 {dupeCount[0]*cellDims[0]: .3f} {dupeCount[1]*cellDims[1]: .3f} {dupeCount[2]*cellDims[2]: .3f} {cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P1 1' @@ -167,7 +171,7 @@ def unitCellMesh(shape, cellDims, cellAngles, og, radius, rotAngles=np.array([0, for dx in range(dupeCount[0]): for dy in range(dupeCount[1]): for dz in range(dupeCount[2]): - disp = disp = dx*a1 + dy*a2 + dz*a3 + minBound + disp = dx*a1 + dy*a2 + dz*a3 + minBound currentCell = [] for atom in og: From 910ae1c5a8dddc1630f187be46e59f5760e1ec76 Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Tue, 15 Apr 2025 14:27:17 -0400 Subject: [PATCH 04/11] Added explainations to default parameters --- TurtleMol/defaultParams.py | 58 ++++++++--------- TurtleMol/shiftUnitCell.py | 6 +- docs/examples/exampleScript.py | 113 +++++++++++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 32 deletions(-) create mode 100644 docs/examples/exampleScript.py diff --git a/TurtleMol/defaultParams.py b/TurtleMol/defaultParams.py index 5357c43..27a0906 100644 --- a/TurtleMol/defaultParams.py +++ b/TurtleMol/defaultParams.py @@ -26,35 +26,35 @@ def defaultParams(): ''' params = { - 'shape' : 'box', - 'sideLength' : 1.0, - 'Xlen' : 1.0, - 'Ylen' : 1.0, - 'Zlen' : 1.0, - 'sphereCenter' : [0, 0, 0], - 'radius' : 1.0, - 'numMolecules' : 1, - 'tol' : 1.0, - 'maxAttempts' : 10000, - 'baseStrucCenter' : [0, 0, 0], - 'baseStrucFile' : None, - 'randomizeOrient' : False, - 'randFill' : False, - 'density' : None, - 'atomRadius' : 'AtomicRadius', - 'mesh' : None, - 'meshScale' : 1.0, - 'scaleX' : None, - 'scaleY' : None, - 'scaleZ' : None, - 'unitCell' : None, - 'angle' : [90, 90, 90], - 'hexagonal' : False, - 'globalMatrixPath' : None, - 'padding' : [0, 0, 0], - 'onSurface' : False, - 'alignNormal' : False, - 'rotAngles' : [0, 0, 0], + 'shape' : 'box', # (str): Other Options Inlcude: 'sphere', 'mesh', 'multimesh' + 'sideLength' : 1.0, # (float): Only use if you want all sides of a box to be the same + 'Xlen' : 1.0, # (float): Used to define the X dimension of a non-cuboid box + 'Ylen' : 1.0, # (float): Used to define the Y dimension of a non-cuboid box + 'Zlen' : 1.0, # (float): Used to define the Z dimension of a non-cuboid box + 'sphereCenter' : [0, 0, 0], # (lst) + 'radius' : 1.0, # Sets the radius of a spherical volume + 'numMolecules' : 1, # (int): This can also be set to the string 'fill' if you want to pack as many tiles as other parameters allow + 'tol' : 1.0, # (float): This is the minimum possible distance between any two tiles + 'maxAttempts' : 10000, # (int): Used for randomly placing tiles, used to prevent infinite loops of attempting and failing tile palcement + 'baseStrucCenter' : [0, 0, 0], # (lst) + 'baseStrucFile' : None, # (str): A path to a pre-existing structure you want in the end result, but not one that is tiled + 'randomizeOrient' : False, # (True/False): Randomly varies the orientation of the tile + 'randFill' : False, # (True/False): Fills the volume randomly instead of in a grid-like fashion + 'density' : None, # (float): Fills a volume based on density. This overrides othering filling options like numMolecules or tol. Units are in g/mL + 'atomRadius' : 'AtomicRadius', # (str): Default uses the vdW radius, the CovalentRadius can also be used + 'mesh' : None, # (str): A path to a .stl or .obj file for a volume defined by a mesh + 'meshScale' : 1.0, # (float): Scales your mesh up or down in size + 'scaleX' : None, # Currently not functioning properly + 'scaleY' : None, # Currently not functioning properly + 'scaleZ' : None, # Currently not functioning properly + 'unitCell' : None, # (lst): Defines your unit cell parameters, is usually read in with the structure file + 'angle' : [90, 90, 90], # (lst): Angles in your unit cell parameters, also read in with structure file + 'hexagonal' : False, # True/False): A quick way to check hexagonal unit cell packing, rather than having TurtleMol determine the unit cell type + 'globalMatrixPath' : None, # (str): Used for multimesh function. A path to a file that determines where meshes are in relation to each other, usually generated by Blender, SOLIDWORKS, ect. + 'padding' : [0, 0, 0], # Currently not functioning properly + 'onSurface' : False, # (True/False): Places the tiles on the nearest surface face of a mesh + 'alignNormal' : False, # (True/False): Aligns the tiles with the nearest surface face normal of a mesh + 'rotAngles' : [0, 0, 0], # (lst): Allows you to define a set rotation for your tile, rather than randomly rotating it } return params diff --git a/TurtleMol/shiftUnitCell.py b/TurtleMol/shiftUnitCell.py index 017809a..87fca03 100644 --- a/TurtleMol/shiftUnitCell.py +++ b/TurtleMol/shiftUnitCell.py @@ -153,9 +153,9 @@ def unitCellMesh(shape, cellDims, cellAngles, og, radius, rotAngles=np.array([0, beta = np.radians(cellAngles[1]) gamma = np.radians(cellAngles[2]) - dupeCount = [int(np.ceil(boxDim[i] / cellDims[i])) + 5 for i in range(3)] + dupeCount = [int(np.ceil(boxDim[i] / cellDims[i])) for i in range(3)] - cellParams = f'CRYST1 {dupeCount[0]*cellDims[0]: .3f} {dupeCount[1]*cellDims[1]: .3f} {dupeCount[2]*cellDims[2]: .3f} {cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P1 1' + cellParams = f'CRYST1 {(dupeCount[0])*cellDims[0]: .3f} {(dupeCount[1])*cellDims[1]: .3f} {(dupeCount[2])*cellDims[2]: .3f} {cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P1 1' # Define the basis vectors a1 = np.array([cellDims[0], 0, 0]) @@ -170,7 +170,7 @@ def unitCellMesh(shape, cellDims, cellAngles, og, radius, rotAngles=np.array([0, for dx in range(dupeCount[0]): for dy in range(dupeCount[1]): - for dz in range(dupeCount[2]): + for dz in range(dupeCount[2] + 5): disp = dx*a1 + dy*a2 + dz*a3 + minBound currentCell = [] diff --git a/docs/examples/exampleScript.py b/docs/examples/exampleScript.py new file mode 100644 index 0000000..c941e9b --- /dev/null +++ b/docs/examples/exampleScript.py @@ -0,0 +1,113 @@ +''' +Example TurtleMol Script +''' +import TurtleMol + +iParams = {} +dParams = TurtleMol.defaultParams() + +# Some very basic keywords, a full list has been provided below +iParams['shape'] = 'box' +iParams['numMolecules'] = 'fill' +iParams['structureFile'] = 'Your/Path/Here' +iParams['outputFile'] = 'Your/Path/Here' +iParams['sideLength'] = 4 + +# Updating the input parameters list using the default parameters to fill in gaps you didn't specify +for name in dParams: + if name not in iParams: + iParams[name] = dParams[name] + +# Checks if you have a pre-existing structure defined +if iParams['baseStrucFile'] is not None: + baseStruc, baseUnitCell = TurtleMol.readStrucFile(iParams['baseStrucFile']) +else: + baseStruc = None + +# Defines a unit cell variable that can store possible unit cell information +unitCell = None + +# Reads the input structure file for your repeating tile +if isinstance(iParams['structureFile'], str): + struc, unitCell = TurtleMol.readStrucFile(iParams['structureFile']) + +# If the a unit cell is defined by your structure file, this loads it into the parameters +if unitCell: + iParams['unitCell'] = [unitCell['a'], unitCell['b'], unitCell['c']] + iParams['angle'] = [unitCell['alpha'], unitCell['beta'], unitCell['gamma']] + +# Generates the structure based on the defined volume. Other functions for other volume shapes has been provided below +outStruc, strucType = TurtleMol.drawMolBox(struc, baseStruc, iParams) + +# Writes an output file to your desired location +TurtleMol.writeOutput(outStruc, iParams['outputFile'], strucType) + + +''' +The Parameters +NOTE: Some parameters override each other. If you ar building a sphere, but define a sideLenght for instance, the sideLength term will be ignored. + Make sure you define the correct parameters for each type of volume you want. +''' +dparams = { +'shape' : 'box', # (str): Other Options Inlcude: 'sphere', 'mesh', 'multimesh' +'sideLength' : 1.0, # (float): Only use if you want all sides of a box to be the same +'Xlen' : 1.0, # (float): Used to define the X dimension of a non-cuboid box +'Ylen' : 1.0, # (float): Used to define the Y dimension of a non-cuboid box +'Zlen' : 1.0, # (float): Used to define the Z dimension of a non-cuboid box +'sphereCenter' : [0, 0, 0], # (lst) +'radius' : 1.0, # Sets the radius of a spherical volume +'numMolecules' : 1, # (int): This can also be set to the string 'fill' if you want to pack as many tiles as other parameters allow +'tol' : 1.0, # (float): This is the minimum possible distance between any two tiles +'maxAttempts' : 10000, # (int): Used for randomly placing tiles, used to prevent infinite loops of attempting and failing tile palcement +'baseStrucCenter' : [0, 0, 0], # (lst) +'baseStrucFile' : None, # (str): A path to a pre-existing structure you want in the end result, but not one that is tiled +'randomizeOrient' : False, # (True/False): Randomly varies the orientation of the tile +'randFill' : False, # (True/False): Fills the volume randomly instead of in a grid-like fashion +'density' : None, # (float): Fills a volume based on density. This overrides othering filling options like numMolecules or tol. Units are in g/mL +'atomRadius' : 'AtomicRadius', # (str): Default uses the vdW radius, the CovalentRadius can also be used +'mesh' : None, # (str): A path to a .stl or .obj file for a volume defined by a mesh +'meshScale' : 1.0, # (float): Scales your mesh up or down in size +'scaleX' : None, # Currently not functioning properly +'scaleY' : None, # Currently not functioning properly +'scaleZ' : None, # Currently not functioning properly +'unitCell' : None, # (lst): Defines your unit cell parameters, is usually read in with the structure file +'angle' : [90, 90, 90], # (lst): Angles in your unit cell parameters, also read in with structure file +'hexagonal' : False, # True/False): A quick way to check hexagonal unit cell packing, rather than having TurtleMol determine the unit cell type +'globalMatrixPath' : None, # (str): Used for multimesh function. A path to a file that determines where meshes are in relation to each other, usually generated by Blender, SOLIDWORKS, ect. +'padding' : [0, 0, 0], # Currently not functioning properly +'onSurface' : False, # (True/False): Places the tiles on the nearest surface face of a mesh +'alignNormal' : False, # (True/False): Aligns the tiles with the nearest surface face normal of a mesh +'rotAngles' : [0, 0, 0], # (lst): Allows you to define a set rotation for your tile, rather than randomly rotating it +} + +''' +Structure Generation Functions +NOTE: If you have the cellParams arguement, it must also be added into the writeOutput function as cellParams=cellParams +''' + +# For a Box (No Unit Cell) +outStruc, strucType = TurtleMol.drawMolBox(struc, baseStruc, iParams) + +# For a Box (Unit Cell) +outStruc, strucType, cellParams = TurtleMol.drawMolBox(struc, baseStruc, iParams) + +# For a Sphere (No Unit Cell) +outStruc, strucType = TurtleMol.drawMolSphere(struc, baseStruc, iParams) + +# For a Sphere (Unit Cell) +outStruc, strucType, cellParams = TurtleMol.drawMolSphere(struc, baseStruc, iParams) + +# For a Mesh (No Unit Cell) +outStruc, strucType = TurtleMol.drawMolMesh(struc, baseStruc, iParams) + +# For a Mesh (Unit Cell) +outStruc, strucType, cellParams = TurtleMol.drawMolMesh(struc, baseStruc, iParams) + +# NOTE: For multiple meshes some more work may be needed on the script above. I have excluded it from this for simplicity +# but if you would like to use these functions, let me know and I will write a quick example + +# For Multiple Meshs (No Unit Cell) +outStruc, strucType = TurtleMol.buildMultiMesh(struc, baseStruc, iParams) + +# For Multiple Meshs (Unit Cell) +outStruc, strucType, cellParams = TurtleMol.buildMultiMesh(struc, baseStruc, iParams) \ No newline at end of file From e7f9d77fc71baca3725d9f064f3408a8fba609ac Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Tue, 8 Jul 2025 12:57:12 -0400 Subject: [PATCH 05/11] Fixed bug where tolerance was always 1 when using the fill function --- TurtleMol/shiftBox.py | 12 ++++++------ TurtleMol/shiftSphere.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/TurtleMol/shiftBox.py b/TurtleMol/shiftBox.py index 966fea5..eff56ce 100644 --- a/TurtleMol/shiftBox.py +++ b/TurtleMol/shiftBox.py @@ -20,9 +20,9 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): for xShift in range(x): for atom in og: # Calculate the shift for each tile and new point - newX = box.xCoord + atom[1] + xShift - newY = box.yCoord + atom[2] + yShift - newZ = box.zCoord + atom[3] + zShift + newX = box.xCoord + atom[1] + xShift*tol + newY = box.yCoord + atom[2] + yShift*tol + newZ = box.zCoord + atom[3] + zShift*tol # Adjust for atomic radiss newXMin = newX - radii[atom[0]] @@ -110,9 +110,9 @@ def moleculesFillBox(x, y, z, tol, og, box, radii, for atom in og: # Calculate the shift for each tile and new point - newX = box.xCoord + atom[1] + xShift - newY = box.yCoord + atom[2] + yShift - newZ = box.zCoord + atom[3] + zShift + newX = box.xCoord + atom[1] + xShift*tol + newY = box.yCoord + atom[2] + yShift*tol + newZ = box.zCoord + atom[3] + zShift*tol # Adjust for atomic radiss newXMin = newX - radii[atom[0]] diff --git a/TurtleMol/shiftSphere.py b/TurtleMol/shiftSphere.py index 0cebd27..7bb63c3 100644 --- a/TurtleMol/shiftSphere.py +++ b/TurtleMol/shiftSphere.py @@ -27,9 +27,9 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): atomType = atom[0] # Calculate the coordiantes within the sphere - x = (sphere.xCoord - sphere.radius) + relX + xShifts - y = (sphere.yCoord - sphere.radius) + relY + yShifts - z = (sphere.zCoord - sphere.radius) + relZ + zShifts + x = (sphere.xCoord - sphere.radius) + relX + xShifts*tol + y = (sphere.yCoord - sphere.radius) + relY + yShifts*tol + z = (sphere.zCoord - sphere.radius) + relZ + zShifts*tol # Adjust for atomic radii atomRadius = radii.get(atomType, 0.0) # Get the radius for the atom type @@ -118,9 +118,9 @@ def moleculeFillSphere(numShifts, sphere, og, radii, tol, atomType = atom[0] # Calculate the coordiantes within the sphere - x = (sphere.xCoord - sphere.radius) + relX + xShifts - y = (sphere.yCoord - sphere.radius) + relY + yShifts - z = (sphere.zCoord - sphere.radius) + relZ + zShifts + x = (sphere.xCoord - sphere.radius) + relX + xShifts*tol + y = (sphere.yCoord - sphere.radius) + relY + yShifts*tol + z = (sphere.zCoord - sphere.radius) + relZ + zShifts*tol # Adjust for atomic radii atomRadius = radii.get(atomType, 0.0) # Get the radius for the atom type From 60aa2c0a1c2186513267a9ba887a9c0c54d7d0ea Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Mon, 24 Nov 2025 19:55:32 -0500 Subject: [PATCH 06/11] Fixed bug where definite number of atoms builds didnt end when that number of atoms were reached --- TurtleMol/shiftBox.py | 13 +++++++++++++ TurtleMol/shiftMesh.py | 14 ++++++++++++-- TurtleMol/shiftSphere.py | 21 ++++++++++++++++++++- 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/TurtleMol/shiftBox.py b/TurtleMol/shiftBox.py index eff56ce..1dd89da 100644 --- a/TurtleMol/shiftBox.py +++ b/TurtleMol/shiftBox.py @@ -46,6 +46,9 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + if len(filledAtom) >= numMol: + return filledAtom + return filledAtom def atomsRandBox(numMol, maxAttempts, og, box, @@ -84,6 +87,9 @@ def atomsRandBox(numMol, maxAttempts, og, box, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + if len(filledAtom) >= numMol: + return filledAtom + attempts += 1 return list(filledAtom) @@ -148,6 +154,9 @@ def moleculesFillBox(x, y, z, tol, og, box, radii, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + if len(filledAtom) >= numMol: + return filledAtom + return filledAtom def moleculesRandBox(numMol, maxAttempts, og, box, radii, tol, @@ -203,6 +212,10 @@ def moleculesRandBox(numMol, maxAttempts, og, box, radii, tol, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + + if len(filledAtom) >= numMol: + return filledAtom + attempts += 1 return list(filledAtom) diff --git a/TurtleMol/shiftMesh.py b/TurtleMol/shiftMesh.py index de30b3d..f9ba9ad 100644 --- a/TurtleMol/shiftMesh.py +++ b/TurtleMol/shiftMesh.py @@ -46,6 +46,9 @@ def atomsFillMesh(mesh, og, tol, radii, numMol): # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + + if len(filled) >= numMol: + return filled return filled @@ -120,8 +123,8 @@ def moleculesFillMesh(mesh, og, tol, radii, numMol, baseStruc, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) - if len(filled) >= numMol: - return filled + if len(filled) >= numMol: + return filled return filled def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): @@ -156,6 +159,10 @@ def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + + if len(filled) >= numMol: + return filled + attempts += 1 return filled @@ -209,5 +216,8 @@ def moleculesRandMesh(mesh, og, tol, radii, numMol, baseStruc, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + if len(filled) >= numMol: + return filled + attempts += 1 return list(filled) diff --git a/TurtleMol/shiftSphere.py b/TurtleMol/shiftSphere.py index 7bb63c3..5f10430 100644 --- a/TurtleMol/shiftSphere.py +++ b/TurtleMol/shiftSphere.py @@ -19,6 +19,7 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): for zShifts in range(numShifts): for yShifts in range(numShifts): for xShifts in range(numShifts): + newMol = [] for atom in og: # Calculate the relative position of each atom within the molecule relX = atom[1] @@ -43,11 +44,16 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)) and \ numMol > len(filled): - filled.append(newAtom) + newMol.append(newAtom) + filled.append(newMol) + print(len(filled)) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + if len(filled) >= numMol: + return filled + return filled def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): @@ -86,6 +92,10 @@ def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + + if len(filled) >= numMol: + return filled + attempts += 1 return list(filled) @@ -148,6 +158,11 @@ def moleculeFillSphere(numShifts, sphere, og, radii, tol, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + + + if len(filled) >= numMol: + return filled + return filled def moleculeRandSphere(numMol, maxAttempts, og, sphere, radii, tol, @@ -209,6 +224,10 @@ def moleculeRandSphere(numMol, maxAttempts, og, sphere, radii, tol, # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + + if len(filled) >= numMol: + return filled + attempts += 1 return list(filled) From d6241792b3523c934a2c0ff9c0b000eaff5e77c9 Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Tue, 25 Nov 2025 10:21:19 -0500 Subject: [PATCH 07/11] Fixed issue with tesselation when input structures were only single atoms --- TurtleMol/shiftBox.py | 8 ++++++-- TurtleMol/shiftMesh.py | 9 ++++++--- TurtleMol/shiftSphere.py | 5 +++-- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/TurtleMol/shiftBox.py b/TurtleMol/shiftBox.py index 1dd89da..032c94e 100644 --- a/TurtleMol/shiftBox.py +++ b/TurtleMol/shiftBox.py @@ -19,6 +19,7 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): for yShift in range(y): for xShift in range(x): for atom in og: + newMol = [] # Calculate the shift for each tile and new point newX = box.xCoord + atom[1] + xShift*tol newY = box.yCoord + atom[2] + yShift*tol @@ -41,7 +42,8 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)) and \ numMol > len(filledAtom): - filledAtom.append(newAtom) + newMol.append(newAtom) + filledAtom.append(newMol) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) @@ -62,6 +64,7 @@ def atomsRandBox(numMol, maxAttempts, og, box, attempts = 0 while len(filledAtom) < numMol and attempts < maxAttempts: + newMol = [] for atom in og: # Calculate the shift for each tile and new point newX = atom[1] + random.uniform(0, box.length) @@ -82,7 +85,8 @@ def atomsRandBox(numMol, maxAttempts, og, box, newAtom = (atom[0], newX, newY, newZ) if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)): - filledAtom.append(newAtom) + newMol.append(newAtom) + filledAtom.append(newMol) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) diff --git a/TurtleMol/shiftMesh.py b/TurtleMol/shiftMesh.py index f9ba9ad..027dd2a 100644 --- a/TurtleMol/shiftMesh.py +++ b/TurtleMol/shiftMesh.py @@ -33,6 +33,7 @@ def atomsFillMesh(mesh, og, tol, radii, numMol): for x in np.nditer(gridX): for y in np.nditer(gridY): for z in np.nditer(gridZ): + newMol = [] for atom in og: # Construct atom data atomData = [atom[0], x, y, z] @@ -41,8 +42,8 @@ def atomsFillMesh(mesh, og, tol, radii, numMol): point = [x, y, z] if mesh.isInside(point) and \ (kdTree is None or not isOverlapAtomKDTree(atomData, kdTree, indexToAtom, radii, tol)): - - filled.append(atomData) + newMol.append(atomData) + filled.append(newMol) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) @@ -140,6 +141,7 @@ def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): minBound, maxBound = bounds[0], bounds[1] while len(filled) < numMol and attempts <= maxAttempts: + newMol = [] for atom in og: x = random.uniform(minBound[0], maxBound[0]) y = random.uniform(minBound[1], maxBound[1]) @@ -155,7 +157,8 @@ def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): atomData = (atomType, atomPoint[0], atomPoint[1], atomPoint[2], atom[4]) if (kdTree is None or not isOverlapAtomKDTree(atomData, kdTree, indexToAtom, radii, tol)): - filled.append(atomData) + newMol.append(atomData) + filled.append(newMol) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) diff --git a/TurtleMol/shiftSphere.py b/TurtleMol/shiftSphere.py index 5f10430..d2c7bee 100644 --- a/TurtleMol/shiftSphere.py +++ b/TurtleMol/shiftSphere.py @@ -46,7 +46,6 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): numMol > len(filled): newMol.append(newAtom) filled.append(newMol) - print(len(filled)) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) @@ -66,6 +65,7 @@ def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): while len(filled) < numMol and attempts <= maxAttempts: for atom in og: + newMol = [] # Calculate the shift for each tile and new point newX = atom[1] + random.uniform((sphere.xCoord - sphere.radius), @@ -87,7 +87,8 @@ def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): newAtom = (atom[0], newX, newY, newZ) if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)): - filled.append(newAtom) + newMol.append(newAtom) + filled.append(newMol) # Rebuild KDTree with newly added atoms kdTree, indexToAtom = buildKDTreeMapping(filled, radii) From 9401137389215e6090b5a538b0872f44c963c3bd Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Wed, 25 Feb 2026 13:20:11 -0800 Subject: [PATCH 08/11] Bug fixes and replacing old collision system with more streamlined system --- TurtleMol/mesh3D.py | 26 +++- TurtleMol/multMesh.py | 132 ++++++++++----------- TurtleMol/shiftBox.py | 68 ++++++----- TurtleMol/shiftDensity.py | 49 ++++---- TurtleMol/shiftMesh.py | 241 ++++++++++++++++++++------------------ TurtleMol/shiftSphere.py | 68 ++++++----- TurtleMol/treeManager.py | 82 +++++++++++++ 7 files changed, 394 insertions(+), 272 deletions(-) create mode 100644 TurtleMol/treeManager.py diff --git a/TurtleMol/mesh3D.py b/TurtleMol/mesh3D.py index 20d62a8..1e8907c 100644 --- a/TurtleMol/mesh3D.py +++ b/TurtleMol/mesh3D.py @@ -31,20 +31,42 @@ def __init__(self, filePath, scale, scaleX = None, scaleY = None, scaleZ = None) self.translate() # Scaled mesh - self.meshBound = self.mesh.apply_scale((1.1, 1.1, 1)) + self.meshBound = self.mesh.copy() + self.meshBound.apply_scale((1.1, 1.1, 1)) def isInside(self, point): '''Check if point is inside the mesh or on the boundary''' # Checks if the point is inside the mesh inside = self.meshBound.contains([point])[0] + if inside: + return True # Check if the point is on the boundary of the mesh # We will get the closest point on the mesh to our point and check if they are the same - closestPoint, distance, _ = trimesh.proximity.closest_point(self.mesh, [point]) + _, distance, _ = trimesh.proximity.closest_point(self.mesh, [point]) onBound = np.isclose(distance[0], 0, atol=1e-3) return inside or onBound + def isInsideMany(self, points): + ''' + Vectorized version of isInside for points shape (N, 3). Returns boolean mask shape (N,) + ''' + points = np.asarray(points, dtype=np.float64) + inside = self.meshBound.contains(points) + + if not np.any(~inside): + return inside + + outsideIdx = np.where(~inside)[0] + outsidePoints = points[outsideIdx] + + _, dist, _ = trimesh.proximity.closest_point(self.mesh, outsidePoints) + onBound = np.isclose(dist, 0.0, atol=1e-3) + + inside[outsideIdx] = onBound + return inside + def volume(self): return self.mesh.volume diff --git a/TurtleMol/multMesh.py b/TurtleMol/multMesh.py index 52fc5fe..c7096fe 100644 --- a/TurtleMol/multMesh.py +++ b/TurtleMol/multMesh.py @@ -2,9 +2,9 @@ import numpy as np from .drawMol import drawMolMesh -from .isOverlap import isOverlapMoleculeKDTree, buildKDTreeMapping from .setAtomProp import setAtomicRadius -from .makeStruc import computeCentroid, applyGlobalTransform, applyTranslation, findMinPoint +from .makeStruc import applyGlobalTransform, applyTranslation, findMinPoint +from .treeManager import PendingKDManager def buildMultiMesh(strucs, baseStruc, iparams): '''Builds meshes of molecules based on a given number of meshes and atomic structures''' @@ -30,7 +30,55 @@ def buildMultiMesh(strucs, baseStruc, iparams): radii = setAtomicRadius(iparams['atomRadius']) # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(coords, radii) + manager = PendingKDManager(radii, rebuildRate=500) + + def _matrixForIndex(i): + '''Build per-mesh global matrix including optional per-axis scaling''' + if scaleXList is not None and scaleYList is not None and scaleZList is not None: + iparams['scaleX'] = float(scaleXList[i]) if scaleXList[i] is not None else scaleList[i] + iparams['scaleY'] = float(scaleYList[i]) if scaleYList[i] is not None else scaleList[i] + iparams['scaleZ'] = float(scaleZList[i]) if scaleZList[i] is not None else scaleList[i] + + scaleFactors = np.array([iparams['scaleX'], iparams['scaleY'], iparams['scalyZ']], dtype=float) + + scalingMatrix = np.eye(4, dtype=float) + scalingMatrix[0,0] = scaleFactors[0] + scalingMatrix[1,1] = scaleFactors[1] + scalingMatrix[2,2] = scaleFactors[2] + + return np.dot(iparams['globalMatrix'][i], scalingMatrix) + else: + return iparams['globalMatrix'][i] * scaleList[i] + + def _flattenAndCapitalize(coord): + '''Coord is list of molecules; flatten to list of atoms, capitalize types''' + allAtoms = [] + for mol in coord: + for atom in mol: + if len(atom) == 4: + allAtoms.append((atom[0].capitalize(), atom[1], atom[2], atom[3])) + elif len(atom) == 5: + allAtoms.append((atom[0].capitalize(), atom[1], atom[2], atom[3], atom[4])) + else: + # Unexpected atom format; keep as-is but ensure type capitalization if possible + allAtoms.append(atom) + return allAtoms + + def _tryAddStruc(allMolMesh, tol): + """Overlap gate + commit to manager""" + if tol is None or tol <= 0: + coords.append(allMolMesh) + manager.addMolecule(allMolMesh) + manager.maybeRebuild() + return True + + if not manager.overlapsMolecule(allMolMesh, tol): + coords.append(allMolMesh) + manager.addMolecule(allMolMesh) + manager.maybeRebuild() + return True + + return False if isinstance(iparams['structureFile'], list): assert len(strucs) == len(meshList), "If more than one structure, the number of structures needs to be the same as the number of meshes" @@ -39,24 +87,10 @@ def buildMultiMesh(strucs, baseStruc, iparams): iparams['mesh'] = str(meshList[i]) iparams['meshScale'] = float(scaleList[i]) iparams['rotAngles'] = rotAngleList[i] + struc = strucs[i] - if scaleXList is not None and scaleYList is not None and scaleZList is not None: - iparams['scaleX'] = float(scaleXList[i]) if scaleXList[i] is not None else scaleList[i] - iparams['scaleY'] = float(scaleYList[i]) if scaleYList[i] is not None else scaleList[i] - iparams['scaleZ'] = float(scaleZList[i]) if scaleZList[i] is not None else scaleList[i] - - scaleFactors = np.array([iparams['scaleX'], iparams['scaleY'], iparams['scaleZ']]) - - # Create scaling matrix - scalingMatrix = np.eye(4) - scalingMatrix[0, 0] = scaleFactors[0] - scalingMatrix[1, 1] = scaleFactors[1] - scalingMatrix[2, 2] = scaleFactors[2] - - matrix = np.dot(iparams['globalMatrix'][i], scalingMatrix) - else: - matrix = iparams['globalMatrix'][i] * scaleList[i] - + matrix = _matrixForIndex(i) + if iparams['unitCells'][i] is not None: tol = 0 iparams['unitCell'] = [iparams['unitCells'][i][0], iparams['unitCells'][i][1], iparams['unitCells'][i][2]] @@ -69,23 +103,10 @@ def buildMultiMesh(strucs, baseStruc, iparams): coord, strucType = drawMolMesh(struc, baseStruc, iparams) cellParams.append(None) - allMolMesh = [] - for mol in coord: - newMol = [] - for atom in mol: - if len(atom) == 4: - atomData = (atom[0].capitalize(), atom[1], atom[2], atom[3]) - if len(atom) == 5: - atomData = (atom[0].capitalize(), atom[1], atom[2], atom[3], atom[4]) - newMol.append(atomData) - allMolMesh.extend(newMol) - - allMolMesh = applyGlobalTransform(allMolMesh, matrix) - if (kdTree is None or not isOverlapMoleculeKDTree(allMolMesh, kdTree, indexToAtom, radii, tol)): - coords.append(allMolMesh) - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(coords, radii) - + allMolMesh = _flattenAndCapitalize(coord) + allMolMesh = applyGlobalTransform(all, matrix) + + _tryAddStruc(allMolMesh, tol) strucTypes.append(strucType) elif isinstance(iparams['structureFile'], str): @@ -93,24 +114,9 @@ def buildMultiMesh(strucs, baseStruc, iparams): iparams['mesh'] = str(meshList[i]) iparams['meshScale'] = float(scaleList[i]) iparams['rotAngles'] = rotAngleList[i] - struc = strucs - if scaleXList is not None and scaleYList is not None and scaleZList is not None: - iparams['scaleX'] = float(scaleXList[i]) if scaleXList[i] is not None else scaleList[i] - iparams['scaleY'] = float(scaleYList[i]) if scaleYList[i] is not None else scaleList[i] - iparams['scaleZ'] = float(scaleZList[i]) if scaleZList[i] is not None else scaleList[i] - scaleFactors = np.array([iparams['scaleX'], iparams['scaleY'], iparams['scaleZ']]) - - # Create scaling matrix - scalingMatrix = np.eye(4) - scalingMatrix[0, 0] = scaleFactors[0] - scalingMatrix[1, 1] = scaleFactors[1] - scalingMatrix[2, 2] = scaleFactors[2] - - matrix = np.dot(iparams['globalMatrix'][i], scalingMatrix) - else: - matrix = iparams['globalMatrix'][i] * scaleList[i] - print(matrix) + struc = strucs + matrix = _matrixForIndex(i) if iparams['unitCell']: tol = 0 @@ -121,26 +127,14 @@ def buildMultiMesh(strucs, baseStruc, iparams): coord, strucType = drawMolMesh(strucs, baseStruc, iparams) cellParams = None - allMolMesh = [] - for mol in coord: - newMol = [] - for atom in mol: - if len(atom) == 4: - atomData = (atom[0].capitalize(), atom[1], atom[2], atom[3]) - if len(atom) == 5: - atomData = (atom[0].capitalize(), atom[1], atom[2], atom[3], atom[4]) - newMol.append(atomData) - allMolMesh.extend(newMol) - + allMolMesh = _flattenAndCapitalize(coord) allMolMesh = applyGlobalTransform(allMolMesh, matrix) - if (kdTree is None or not isOverlapMoleculeKDTree(allMolMesh, kdTree, indexToAtom, radii, tol)): - coords.append(allMolMesh) - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(coords, radii) + _tryAddStruc(allMolMesh, tol) strucTypes.append(strucType) transVector = np.array([0, 0, 0]) - findMinPoint(coords) coords = applyTranslation(coords, transVector, 'molecule') + return coords, 'molecule', cellParams diff --git a/TurtleMol/shiftBox.py b/TurtleMol/shiftBox.py index 032c94e..a0bd7da 100644 --- a/TurtleMol/shiftBox.py +++ b/TurtleMol/shiftBox.py @@ -2,8 +2,8 @@ import random import numpy as np -from .isOverlap import isOverlapAtomKDTree, isOverlapMoleculeKDTree, buildKDTreeMapping from .makeStruc import makeBase, reCenter, Reorient +from .treeManager import PendingKDManager def atomsFillBox(x, y, z, tol, og, box, radii, numMol): '''Fills box with single atoms''' @@ -13,13 +13,13 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): filledAtom = [] # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager = PendingKDManager(radii, rebuildRate=500) for zShift in range(z): for yShift in range(y): for xShift in range(x): + newMol = [] for atom in og: - newMol = [] # Calculate the shift for each tile and new point newX = box.xCoord + atom[1] + xShift*tol newY = box.yCoord + atom[2] + yShift*tol @@ -39,14 +39,14 @@ def atomsFillBox(x, y, z, tol, og, box, radii, numMol): newAtom = (atom[0], newX, newY, newZ, atom[4]) else: newAtom = (atom[0], newX, newY, newZ) + newMol.append(newAtom) - if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)) and \ - numMol > len(filledAtom): - newMol.append(newAtom) + if (numMol > len(filledAtom) and not manager.overlapsMolecule(newMol, tol)): filledAtom.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filledAtom) >= numMol: return filledAtom @@ -59,7 +59,7 @@ def atomsRandBox(numMol, maxAttempts, og, box, filledAtom = [] # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager = PendingKDManager(radii, rebuildRate=500) attempts = 0 @@ -83,13 +83,14 @@ def atomsRandBox(numMol, maxAttempts, og, box, newAtom = (atom[0], newX, newY, newZ, atom[4]) else: newAtom = (atom[0], newX, newY, newZ) + newMol.append(newAtom) - if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)): - newMol.append(newAtom) + if (numMol > len(filledAtom) and not manager.overlapsMolecule(newMol, tol)): filledAtom.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filledAtom) >= numMol: return filledAtom @@ -104,13 +105,16 @@ def moleculesFillBox(x, y, z, tol, og, box, radii, filledAtom = [] if str(numMol).lower() == 'fill': - numMol = 10000000000000 + numMol = 10**100 + + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) if baseStruc is not None: base = makeBase(baseStruc) filledAtom.append(reCenter(base, box)) - - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted for zShift in range(z): for yShift in range(y): @@ -144,19 +148,20 @@ def moleculesFillBox(x, y, z, tol, og, box, radii, else: anyAtomOutside = True - if randOrient and len(newMol) == len(og): - newMol = Reorient(newMol, randRotate=True) + if not anyAtomOutside and len(newMol) == len(og): + if randOrient: + newMol = Reorient(newMol, randRotate=True) - if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): - newMol = Reorient(newMol, angles=rotAngles) + if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): + newMol = Reorient(newMol, angles=rotAngles) - if ((kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)) and - not anyAtomOutside and numMol > len(filledAtom)): + if (not anyAtomOutside and numMol > len(filledAtom) and not manager.overlapsMolecule(newMol, tol)): filledAtom.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filledAtom) >= numMol: return filledAtom @@ -170,12 +175,13 @@ def moleculesRandBox(numMol, maxAttempts, og, box, radii, tol, attempts = 0 + manager = PendingKDManager(radii, rebuildRate=500) + if baseStruc is not None: base = makeBase(baseStruc) filledAtom.append(reCenter(base, box)) - - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted while len(filledAtom) < numMol and attempts < maxAttempts: newMol = [] @@ -205,17 +211,19 @@ def moleculesRandBox(numMol, maxAttempts, og, box, radii, tol, else: anyAtomOutside = True - if randOrient and len(newMol) == len(og): - newMol = Reorient(newMol, randRotate=True) + if not anyAtomOutside and len(newMol) == len (og): + if randOrient: + newMol = Reorient(newMol, randRotate=True) - if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): - newMol = Reorient(newMol, angles=rotAngles) + if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): + newMol = Reorient(newMol, angles=rotAngles) - if (kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)) and not anyAtomOutside: + if (not anyAtomOutside and numMol > len(filledAtom) and not manager.overlapsMolecule(newMol, tol)): filledAtom.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filledAtom, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filledAtom) >= numMol: return filledAtom diff --git a/TurtleMol/shiftDensity.py b/TurtleMol/shiftDensity.py index 1a9ae25..6ae4027 100644 --- a/TurtleMol/shiftDensity.py +++ b/TurtleMol/shiftDensity.py @@ -4,6 +4,7 @@ import scipy.spatial from .makeStruc import calcDistance, Reorient from .isOverlap import isOverlapMoleculeKDTree, isOverlapAtomKDTree, buildKDTreeMapping +from .treeManager import PendingKDManager def placeMols(shape, og, density, tol, shapeType, radii, randOrient,rotAngles): '''Place molecules in the grid defined by the density''' @@ -19,10 +20,10 @@ def translateMol(coords, target): '''Translate molecules to a new grid point''' atomLabels = [atom[0] for atom in coords] pdbInfo = [atom[4] if len(atom) == 5 else None for atom in coords] - xyzCoords = np.array([atom[1:4] for atom in coords]) + xyzCoords = np.array([atom[1:4] for atom in coords], dtype=np.float64) centroid = calcCentroid(xyzCoords) - transVec = np.array(target) - centroid + transVec = np.array(target, dtype=np.float64) - centroid translatedXYZ = xyzCoords + transVec transMol = [[label] + coord.tolist() + ([info] if info is not None else []) @@ -30,39 +31,29 @@ def translateMol(coords, target): return transMol - strucType = 'molecule' + strucType = 'atom' if len(og) == 1 else 'molecule' mols = [] + manager = PendingKDManager(radii, rebuildRate=500) + for point in gridPoints: newPoint = translateMol(og, point) - if len(mols) == 0: - mols.append(newPoint) - - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(mols, radii) - - if randOrient and len(newMol) == len(og): - newMol = Reorient(newMol, randRotate=True) - - if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): - newMol = Reorient(newMol, angles=rotAngles) + if randOrient and len(newPoint) == len(og): + newPoint = Reorient(newPoint, randRotate=True) - if len(og) == 1: - if (kdTree is None or not isOverlapAtomKDTree(newPoint, kdTree, indexToAtom, radii, tol)): - mols.append(newPoint) + if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newPoint) == len(og): + newPoint = Reorient(newPoint, angles=rotAngles) - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(mols, radii) - - strucType = "atom" - else: - if (kdTree is None or not isOverlapMoleculeKDTree(newPoint, kdTree, indexToAtom, radii, tol)): - mols.append(newPoint) - - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(mols, radii) + if len(mols) == 0: + mols.append(newPoint) + manager.addMolecule(newPoint) + manager.maybeRebuild(force=True) + continue - strucType = "molecule" + if not manager.overlapsMolecule(newPoint, tol): + mols.append(newPoint) + manager.addMolecule(newPoint) + manager.maybeRebuild() - return mols, strucType + return mols, strucType \ No newline at end of file diff --git a/TurtleMol/shiftMesh.py b/TurtleMol/shiftMesh.py index 027dd2a..69dd148 100644 --- a/TurtleMol/shiftMesh.py +++ b/TurtleMol/shiftMesh.py @@ -2,54 +2,58 @@ import random import numpy as np -import trimesh -from .isOverlap import isOverlapAtomKDTree, isOverlapMoleculeKDTree, buildKDTreeMapping from .makeStruc import makeBase, reCenter, Reorient from .surfaceNormal import placeOnSurfaceNormal, alignToNormal +from. treeManager import PendingKDManager def atomsFillMesh(mesh, og, tol, radii, numMol): '''Fills mesh with single atoms''' filled = [] if str(numMol).lower() == 'fill': - numMol = 10000000000000 + numMol = 10**100 # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager = PendingKDManager(radii, rebuildRate=500) # Determine bounds of mesh bounds = mesh.bounds minBound, maxBound = bounds[0], bounds[1] - - # Determine spacing between molecules - spacing = tol + print(minBound, maxBound) # Generate grid of points - gridX, gridY, gridZ = np.mgrid[minBound[0]:maxBound[0]:spacing, - minBound[1]:maxBound[1]:spacing, - minBound[2]:maxBound[2]:spacing] + xs = np.arange(minBound[0], maxBound[0], tol) + ys = np.arange(minBound[1], maxBound[1], tol) + zs = np.arange(minBound[2], maxBound[2], tol) + + X, Y, Z = np.meshgrid(xs, ys, zs, indexing="ij") + points = np.stack([X.ravel(), Y.ravel(), Z.ravel()], axis=1).astype(np.float64) + + # Vectorized inside test + # Depending on mesh wrapper + # if mesh.meshBound is a trimesh object: mesh.meshBound.contains(points) + # if mesh itself is trimesh: mesh.contains(points) + mask = mesh.isInsideMany(points) + insidePoints = points[mask] + if insidePoints.shape[0] == 0: + return filled + + atomTemplate = og[0] # pick the first atom type as the one we're placing + atomType = atomTemplate[0] + extra = atomTemplate[4:] # handles optional fields # Check each point in the grid - for x in np.nditer(gridX): - for y in np.nditer(gridY): - for z in np.nditer(gridZ): - newMol = [] - for atom in og: - # Construct atom data - atomData = [atom[0], x, y, z] - if len(atom) == 5: - atomData.append(atom[4]) - point = [x, y, z] - if mesh.isInside(point) and \ - (kdTree is None or not isOverlapAtomKDTree(atomData, kdTree, indexToAtom, radii, tol)): - newMol.append(atomData) - filled.append(newMol) - - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) - - if len(filled) >= numMol: - return filled + for (x, y, z) in insidePoints: + if len(filled) >= numMol: + break + + newAtom = (atomType, float(x), float(y), float(z), *extra) + newMol = [newAtom] + + if not manager.overlapsMolecule(newMol, tol): + filled.append(newMol) + manager.addMolecule(newMol) + manager.maybeRebuild() return filled @@ -59,73 +63,71 @@ def moleculesFillMesh(mesh, og, tol, radii, numMol, baseStruc, filled = [] if str(numMol).lower() == 'fill': - numMol = 10000000000000 + numMol = 10**100 + + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) if baseStruc is not None: base = makeBase(baseStruc) filled.append(reCenter(base, mesh)) - - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted # Determine bounds of mesh bounds = mesh.bounds minBound, maxBound = bounds[0], bounds[1] - # Determine spacing between molecules - spacing = tol + xs = np.arange(minBound[0], maxBound[0], tol) + ys = np.arange(minBound[1], maxBound[1], tol) + zs = np.arange(minBound[2], maxBound[2], tol) - # Generate grid of points - gridX, gridY, gridZ = np.mgrid[minBound[0]:maxBound[0] + spacing:spacing, - minBound[1]:maxBound[1] + spacing:spacing, - minBound[2]:maxBound[2] + spacing:spacing] + X, Y, Z = np.meshgrid(xs, ys, zs, indexing="ij") + anchors = np.stack([X.ravel(), Y.ravel(), Z.ravel()], axis=1).astype(np.float64) + + ogXYZ = np.array([[a[1], a[2], a[3]] for a in og], dtype=float) + center = ogXYZ.mean(axis=0) + + ogRel = [] + for a in og: + if len(a) == 4: + ogRel.append((a[0], float(a[1] - center[0]), float(a[2] - center[1]), float(a[3] - center[2]))) + else: + ogRel.append((a[0], float(a[1]-center[0]), float(a[2]-center[1]), float(a[3]-center[2]), a[4])) + + offsets = np.array([[a[1], a[2], a[3]] for a in ogRel], dtype=np.float64) + atomTypes = [a[0] for a in ogRel] + extras = [a[4] if len(a) == 5 else None for a in ogRel] + + for ax, ay, az in anchors: + if len(filled) >= numMol: + break + + points = offsets + np.array([ax, ay, az], dtype=np.float64) + + if not np.all(mesh.isInsideMany(points)): + continue + + newMol = [] + for (x, y, z), t, ex in zip(points, atomTypes, extras): + if ex is None: + newMol.append((t, float(x), float(y), float(z))) + else: + newMol.append((t, float(x), float(y), float(z), ex)) + if randOrient: + newMol = Reorient(newMol, randRotate=True) + if not np.allclose(np.array(rotAngles), np.array([0,0,0])): + newMol = Reorient(newMol, angles=rotAngles) + if alignNormal: + newMol = alignToNormal(mesh, newMol) + if onSurface: + newMol = placeOnSurfaceNormal(mesh, newMol) + + if not manager.overlapsMolecule(newMol, tol): + filled.append(newMol) + manager.addMolecule(newMol) + manager.maybeRebuild() - # Check each point in the grid - for i in range(gridX.shape[0]): - for j in range(gridY.shape[1]): - for k in range(gridZ.shape[2]): - x = gridX[i, j, k] - y = gridY[i, j, k] - z = gridZ[i, j, k] - - # Check if entire molecule can be placed - molValid = True - newMol = [] - for atom in og: - # Construct atom data - atomType, relX, relY, relZ = atom[:4] - atomPoint = [x + relX, y + relY, z + relZ] - - if not mesh.isInside(atomPoint): - molValid = False - break - - if molValid: - for atom in og: - atomType, relX, relY, relZ = atom[:4] - if len(atom) == 4: - atomData = (atomType, float(x + relX), float(y + relY), float(z + relZ)) - if len(atom) == 5: - atomData = (atomType, float(x + relX), float(y + relY), float(z + relZ), atom[4]) - - newMol.append(atomData) - - if randOrient and len(newMol) == len(og): - newMol = Reorient(newMol, randRotate=True) - if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): - newMol = Reorient(newMol, angles=rotAngles) - if alignNormal: - newMol = alignToNormal(mesh, newMol) - if onSurface: - newMol = placeOnSurfaceNormal(mesh, newMol) - if (kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)): - filled.append(newMol) - - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) - - if len(filled) >= numMol: - return filled return filled def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): @@ -133,8 +135,8 @@ def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): filled = [] attempts = 0 - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) # Determine bounds of mesh bounds = mesh.bounds @@ -156,12 +158,13 @@ def atomsRandMesh(mesh, og, tol, radii, numMol, maxAttempts): elif len(atom) == 5: atomData = (atomType, atomPoint[0], atomPoint[1], atomPoint[2], atom[4]) - if (kdTree is None or not isOverlapAtomKDTree(atomData, kdTree, indexToAtom, radii, tol)): - newMol.append(atomData) + newMol.append(atomData) + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): filled.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: return filled @@ -175,36 +178,52 @@ def moleculesRandMesh(mesh, og, tol, radii, numMol, baseStruc, filled = [] attempts = 0 + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) + if baseStruc is not None: base = makeBase(baseStruc) filled.append(reCenter(base, mesh)) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + # ensure og is relative offsets around 0 + ogXYZ = np.array([[a[1], a[2], a[3]] for a in og], dtype=np.float64) + center = ogXYZ.mean(axis=0) + + ogRel = [] + for a in og: + if len(a) == 4: + ogRel.append((a[0], float(a[1]-center[0]), float(a[2]-center[1]), float(a[3]-center[2]))) + else: + ogRel.append((a[0], float(a[1]-center[0]), float(a[2]-center[1]), float(a[3]-center[2]), a[4])) # Determine bounds of mesh bounds = mesh.bounds minBound, maxBound = bounds[0], bounds[1] + offsets = np.array([[a[1], a[2], a[3]] for a in ogRel], dtype=np.float64) + atomTypes = [a[0] for a in ogRel] + extras = [a[4] if len(a) == 5 else None for a in ogRel] + while len(filled) < numMol and attempts <= maxAttempts: newMol = [] - x = random.uniform(minBound[0], maxBound[0]) - y = random.uniform(minBound[1], maxBound[1]) - z = random.uniform(minBound[2], maxBound[2]) - - for atom in og: - atomType, xRel, yRel, zRel = atom[:4] - atomPoint = [x + xRel, y + yRel, z + zRel] + ax = random.uniform(minBound[0], maxBound[0]) + ay = random.uniform(minBound[1], maxBound[1]) + az = random.uniform(minBound[2], maxBound[2]) - if mesh.isInside(atomPoint): - if len(atom) == 4: - atomData = (atomType, atomPoint[0], atomPoint[1], atomPoint[2]) + points = offsets + np.array([ax, ay, az], dtype=np.float64) - elif len(atom) == 5: - atomData = (atomType, atomPoint[0], atomPoint[1], atomPoint[2], atom[4]) + if not np.all(mesh.isInsideMany(points)): + attempts += 1 + continue - newMol.append(atomData) + for (x, y, z), t, ex in zip(points, atomTypes, extras): + if ex is None: + newMol.append((t, float(x), float(y), float(z))) + else: + newMol.append((t, float(x), float(y), float(z), ex)) if randOrient and len(newMol) == len(og): newMol = Reorient(newMol, randRotate=True) @@ -212,12 +231,12 @@ def moleculesRandMesh(mesh, og, tol, radii, numMol, baseStruc, if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): newMol = Reorient(newMol, angles=rotAngles) - if (kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)): - if len(newMol) == len(og): - filled.append(newMol) + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): + filled.append(newMol) - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + # Rebuild KDTree with newly added atoms + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: return filled diff --git a/TurtleMol/shiftSphere.py b/TurtleMol/shiftSphere.py index d2c7bee..cda6161 100644 --- a/TurtleMol/shiftSphere.py +++ b/TurtleMol/shiftSphere.py @@ -3,8 +3,8 @@ import random import scipy.spatial import numpy as np -from .isOverlap import isOverlapAtomKDTree, isOverlapMoleculeKDTree, buildKDTreeMapping from .makeStruc import makeBase, reCenter, Reorient +from .treeManager import PendingKDManager def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): '''Fills sphere with single atoms''' @@ -14,7 +14,7 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): numMol = 10000000000000 # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager = PendingKDManager(radii, rebuildRate=500) for zShifts in range(numShifts): for yShifts in range(numShifts): @@ -42,13 +42,14 @@ def atomFillSphere(numShifts, sphere, og, radii, tol, numMol): else: newAtom = (atom[0], x, y, z) - if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)) and \ - numMol > len(filled): - newMol.append(newAtom) + newMol.append(newAtom) + + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): filled.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: return filled @@ -61,11 +62,11 @@ def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): attempts = 0 # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager = PendingKDManager(radii, rebuildRate=500) while len(filled) < numMol and attempts <= maxAttempts: + newMol = [] for atom in og: - newMol = [] # Calculate the shift for each tile and new point newX = atom[1] + random.uniform((sphere.xCoord - sphere.radius), @@ -85,13 +86,15 @@ def atomRandSphere(numMol, maxAttempts, og, sphere, radii, tol): newAtom = (atom[0], newX, newY, newZ, atom[4]) else: newAtom = (atom[0], newX, newY, newZ) + + newMol.append(newAtom) - if (kdTree is None or not isOverlapAtomKDTree(newAtom, kdTree, indexToAtom, radii, tol)): - newMol.append(newAtom) + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): filled.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: @@ -109,12 +112,14 @@ def moleculeFillSphere(numShifts, sphere, og, radii, tol, if str(numMol).lower() == 'fill': numMol = 10000000000000 + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) + if baseStruc is not None: base = makeBase(baseStruc) filled.append(reCenter(base, sphere)) - - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted for zShifts in range(numShifts): for yShifts in range(numShifts): @@ -152,13 +157,13 @@ def moleculeFillSphere(numShifts, sphere, og, radii, tol, if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): newMol = Reorient(newMol, angles=rotAngles) - if (kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)) and \ - numMol > len(filled): + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): if len(newMol) == len(og): filled.append(newMol) # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: @@ -172,12 +177,14 @@ def moleculeRandSphere(numMol, maxAttempts, og, sphere, radii, tol, filled = [] attempts = 0 + # Use pending-buffer KD manager + manager = PendingKDManager(radii, rebuildRate=500) + if baseStruc is not None: base = makeBase(baseStruc) filled.append(reCenter(base, sphere)) - - # Create KD-tree for filledAtoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + manager.addMolecule(base) + manager.maybeRebuild(force=True) #ensure the base is comitted while len(filled) < numMol and attempts <= maxAttempts: newMol = [] @@ -205,25 +212,24 @@ def moleculeRandSphere(numMol, maxAttempts, og, sphere, radii, tol, # Check if the new atom fits within the sphere if sphere.containsPoints(newX, newY, newZ, atomRadius): if len(atom) == 5: - newAtom = (atom[0], newX, newY, newX, atom[4]) + newAtom = (atom[0], newX, newY, newZ, atom[4]) else: newAtom = (atom[0], newX, newY, newZ) newMol.append(newAtom) - else: - break # If any atom doesn't fit, discard the whol molecule - if randOrient and len(newMol) == len(og): + if randOrient and len(newMol) == len(og): newMol = Reorient(newMol, randRotate=True) - if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): - newMol = Reorient(newMol, angles=rotAngles) + if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])) and len(newMol) == len(og): + newMol = Reorient(newMol, angles=rotAngles) - if (kdTree is None or not isOverlapMoleculeKDTree(newMol, kdTree, indexToAtom, radii, tol)): - if len(newMol) == len(og): - filled.append(newMol) + if (numMol > len(filled) and not manager.overlapsMolecule(newMol, tol)): + if len(newMol) == len(og): + filled.append(newMol) - # Rebuild KDTree with newly added atoms - kdTree, indexToAtom = buildKDTreeMapping(filled, radii) + # Rebuild KDTree with newly added atoms + manager.addMolecule(newMol) + manager.maybeRebuild() if len(filled) >= numMol: diff --git a/TurtleMol/treeManager.py b/TurtleMol/treeManager.py new file mode 100644 index 0000000..19be248 --- /dev/null +++ b/TurtleMol/treeManager.py @@ -0,0 +1,82 @@ +import numpy as np +from scipy.spatial import cKDTree + +class PendingKDManager: + def __init__(self, radii, rebuildRate=500): + self.radii = radii + self.rebuildRate = int(rebuildRate) + + self.kdTree = None + self._treeXYZ = np.empty((0,3), dtype=np.float64) + self._treeR = np.empty((0,), dtype=np.float64) + + self._pendingXYZ = np.empty((0,3), dtype=np.float64) + self._pendingR = np.empty((0,), dtype=np.float64) + + # Track max radius in comitted tree for KD queries + self._treeRMax = 0.0 + + def _atomsXYZR(self, mol): + xyz = np.array([[a[1], a[2], a[3]] for a in mol], dtype=np.float64) + r = np.array([self.radii[a[0]] for a in mol], dtype=np.float64) + + return xyz, r + + def overlapsMolecule(self, mol, tol): + # If empty, can't overlap + if self.kdTree is None and self._pendingXYZ.shape[0] == 0: + return False + + tol = float(tol) + + for atom in mol: + p = np.array([atom[1], atom[2], atom[3]], dtype=np.float64) + pr = float(self.radii[atom[0]]) + + # Check against comitted KDTree + if self.kdTree is not None: + query_r = pr + self._treeRMax + tol + idxs = self.kdTree.query_ball_point(p, r=query_r) + if idxs: + neighXYZ = self._treeXYZ[idxs] + neighR = self._treeR[idxs] + d = neighXYZ - p[None, :] + d2 = np.einsum("ij,ij->i", d, d) + cutoff = neighR + pr + tol + if np.any(d2 < cutoff * cutoff): + return True + + # Check against pending atoms + if self._pendingXYZ.shape[0] != 0: + d = self._pendingXYZ - p[None, :] + d2 = np.einsum("ij,ij->i", d, d) + cutoff = self._pendingR + pr + tol + if np.any(d2 < cutoff * cutoff): + return True + + return False + + def addMolecule(self, mol): + xyz, r = self._atomsXYZR(mol) + if xyz.size == 0: + return + self._pendingXYZ = np.vstack([self._pendingXYZ, xyz]) + self._pendingR = np.concatenate([self._pendingR, r]) + + def maybeRebuild(self, force=False): + if (not force) and (self._pendingXYZ.shape[0] < self.rebuildRate): + return + + # Merge pending into comitted arrays + if self._pendingXYZ.shape[0] != 0: + self._treeXYZ = np.vstack([self._treeXYZ, self._pendingXYZ]) + self._treeR = np.concatenate([self._treeR, self._pendingR]) + self._pendingXYZ = np.empty((0,3), dtype=np.float64) + self._pendingR = np.empty((0,), dtype=np.float64) + + if self._treeXYZ.shape[0] == 0: + self.kdTree = None + self._treeRMax = 0.0 + else: + self.kdTree = cKDTree(self._treeXYZ) + self._treeRMax = float(np.max(self._treeR)) \ No newline at end of file From 61131b466670b11fb9d68cffb953d703343f8175 Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Wed, 25 Mar 2026 14:18:56 -0700 Subject: [PATCH 09/11] Fixed bug with periodic boundary conditions when building a traditional unit cell --- TurtleMol/drawMol.py | 4 +- TurtleMol/shiftDensity.py | 1 - TurtleMol/shiftUnitCell.py | 137 ++++++++++++++++++++++++++++--------- TurtleMol/treeManager.py | 2 +- 4 files changed, 109 insertions(+), 35 deletions(-) diff --git a/TurtleMol/drawMol.py b/TurtleMol/drawMol.py index 6e59782..3a28057 100644 --- a/TurtleMol/drawMol.py +++ b/TurtleMol/drawMol.py @@ -31,8 +31,6 @@ def drawMolBox(struc, baseStruc, iparams): originalPoints = makeBase(struc) - originalPoints = shiftPoints(originalPoints, box) - if iparams['unitCell']: if iparams['hexagonal'] == False: filled, strucType, cellParams = unitCellBox(box, dims, iparams['unitCell'], iparams['angle'], @@ -42,6 +40,8 @@ def drawMolBox(struc, baseStruc, iparams): filled, strucType, cellParams = hexagonUnitCellBox(box, dims, iparams['unitCell'], originalPoints, radii) return filled, strucType, cellParams + + originalPoints = shiftPoints(originalPoints, box) if iparams['density']: filled, strucType = placeMols(box, originalPoints, iparams['density'], diff --git a/TurtleMol/shiftDensity.py b/TurtleMol/shiftDensity.py index 6ae4027..295a3ca 100644 --- a/TurtleMol/shiftDensity.py +++ b/TurtleMol/shiftDensity.py @@ -3,7 +3,6 @@ import numpy as np import scipy.spatial from .makeStruc import calcDistance, Reorient -from .isOverlap import isOverlapMoleculeKDTree, isOverlapAtomKDTree, buildKDTreeMapping from .treeManager import PendingKDManager def placeMols(shape, og, density, tol, shapeType, radii, randOrient,rotAngles): diff --git a/TurtleMol/shiftUnitCell.py b/TurtleMol/shiftUnitCell.py index 87fca03..60825a3 100644 --- a/TurtleMol/shiftUnitCell.py +++ b/TurtleMol/shiftUnitCell.py @@ -1,13 +1,40 @@ '''This module is for replicating a unit cell if it is defined in a given pdb''' import numpy as np +import math import trimesh from .shiftBox import inBox from .makeStruc import calcLatticeVectors, rotateUnitCell # Box + def unitCellBox(shape, dims, cellDims, cellAngles, og, radii, rotAngles=np.array([0, 0, 0]).all()): '''Duplicates unit cells to fill a given box''' + print('hello I am working') + + def _rebuildAtom(atom, xyz): + """Preserve original tuple shape and trailing meta data""" + return tuple([atom[0], xyz[0], xyz[1], xyz[2], *list(atom[4:])]) + + def _deduplicateAtomsPBC(atoms, latticeVec, tol=1e-3): + '''Wrap all atoms to canonical unit cell and remove duplicates outside cell''' + scale = 1.0/tol + seen = {} + unique = [] + + for atom in atoms: + key = ( + atom[0], + int(round(atom[1] * scale)), + int(round(atom[2] * scale)), + int(round(atom[3] * scale)), + tuple(atom[4:]), + ) + if key not in seen: + seen[key] = True + unique.append(atom) + + return unique # Find the atom types in the tile atomNames = {atom[0] for atom in og} @@ -19,21 +46,40 @@ def unitCellBox(shape, dims, cellDims, cellAngles, og, radii, rotAngles=np.array cellDims = [cellInfo['a'], cellInfo['b'], cellInfo['c']] cellAngles = [cellInfo['alpha'], cellInfo['beta'], cellInfo['gamma']] + latticeVec = calcLatticeVectors(cellDims[0], cellDims[1], cellDims[2], cellAngles[0], cellAngles[1], cellAngles[2]) + invLattice = np.linalg.inv(latticeVec) + alpha = np.radians(cellAngles[0]) beta = np.radians(cellAngles[1]) gamma = np.radians(cellAngles[2]) # Define the basis vectors - a1 = np.array([cellDims[0], 0, 0]) - a2 = np.array([cellDims[1] * np.cos(gamma), cellDims[1] * np.sin(gamma), 0]) - a3 = np.array([ - cellDims[2] * np.cos(beta), - cellDims[2] * (np.cos(alpha) - np.cos(beta) * np.cos(gamma)) / np.sin(gamma), - cellDims[2] * np.sqrt(1 - np.cos(beta)**2 - ((np.cos(alpha) - np.cos(beta) * np.cos(gamma)) / np.sin(gamma))**2) - ]) + a1 = latticeVec[0] + a2 = latticeVec[1] + a3 = latticeVec[2] + + # Wrap original atoms into on canonical unit cell + wrappedOg = [] + wrapTol = 1e-8 + + for atom in og: + coord = np.array([atom[1], atom[2], atom[3]], dtype=float) + + # Cartesian to fraction for row based lattice vectors + frac = coord @ invLattice + + # Wrap into [0,1] + frac = frac % 1.0 + frac[np.isclose(frac, 1.0, atol=wrapTol)] = 0.0 + + # Fractional to Cartesian + wrappedCoord = frac @ latticeVec + + wrappedOg.append(_rebuildAtom(atom, wrappedCoord)) + canonicalOg = _deduplicateAtomsPBC(wrappedOg, latticeVec) # Calculate how many times to duplicate the unit cell in a given dimension - dupeCount = [int(dims[i] / cellDims[i]) for i in range(3)] + dupeCount = [max(1, math.ceil(dims[i] / cellDims[i])) for i in range(3)] cellParams = f'CRYST1{dupeCount[0]*cellDims[0]:9.3f}{dupeCount[1]*cellDims[1]:9.3f}{dupeCount[2]*cellDims[2]:9.3f} {cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P 1 1' filled = [] @@ -46,33 +92,62 @@ def unitCellBox(shape, dims, cellDims, cellAngles, og, radii, rotAngles=np.array currentCell = [] - for atom in og: - newX = shape.xCoord + atom[1] + disp[0] - newY = shape.yCoord + atom[2] + disp[1] - newZ = shape.zCoord + atom[3] + disp[2] - atomType = atom[0] - - atomRadius = radii.get(atomType, 0.0) - - # Adjust for atomic radiss - newXMin = newX - atomRadius - newYMin = newY - atomRadius - newZMin = newZ - atomRadius - newXMax = newX + atomRadius - newYMax = newY + atomRadius - newZMax = newZ + atomRadius + for atom in canonicalOg: + newCoord = np.array([atom[1], atom[2], atom[3]], dtype=float) + disp + shiftedCoord = np.array([ + shape.xCoord + newCoord[0], + shape.yCoord + newCoord[1], + shape.zCoord + newCoord[2] + ], dtype=float) # Check if the new atom fits within the box - if inBox(newXMin, newXMax, newYMin, newYMax, newZMin, - newZMax, shape): - if len(atom) == 5: - newAtom = (atom[0], newX, newY, newZ, atom[4]) - else: - newAtom = (atom[0], newX, newY, newZ) - currentCell.append(newAtom) + currentCell.append(_rebuildAtom(atom, shiftedCoord)) filled.append(currentCell) - return filled, "molecule", cellParams + + superLattice = np.array([ + dupeCount[0] * a1, + dupeCount[1] * a2, + dupeCount[2] * a3 + ]) + + print("dims =", dims) + print("cellDims =", cellDims) + print("dupeCount =", dupeCount) + print("a1 =", a1) + print("a2 =", a2) + print("a3 =", a3) + print("superLattice =\n", superLattice) + + invSuper = np.linalg.inv(superLattice) + + wrappedFilled = [] + + for cell in filled: + wrappedCell = [] + + for atom in cell: + cart = np.array([ + atom[1] - shape.xCoord, + atom[2] - shape.yCoord, + atom[3] - shape.zCoord + ], dtype=float) + + frac = cart @ invSuper + frac = frac % 1.0 + frac[np.isclose(frac, 1.0, atol=wrapTol)] = 0.0 + + wrappedCart = frac @ superLattice + finalCoord = np.array([ + wrappedCart[0] + shape.xCoord, + wrappedCart[1] + shape.yCoord, + wrappedCart[2] + shape.zCoord + ], dtype=float) + + wrappedCell.append(_rebuildAtom(atom, finalCoord)) + + wrappedFilled.append(wrappedCell) + return wrappedFilled, "molecule", cellParams def unitCellSphere(shape, cellDims, cellAngles, og, radii, rotAngles=np.array([0, 0, 0]).all()): '''Duplicates unit cells to fill a given sphere''' diff --git a/TurtleMol/treeManager.py b/TurtleMol/treeManager.py index 19be248..795b5a5 100644 --- a/TurtleMol/treeManager.py +++ b/TurtleMol/treeManager.py @@ -18,7 +18,7 @@ def __init__(self, radii, rebuildRate=500): def _atomsXYZR(self, mol): xyz = np.array([[a[1], a[2], a[3]] for a in mol], dtype=np.float64) - r = np.array([self.radii[a[0]] for a in mol], dtype=np.float64) + r = np.array([self.radii[a[0].title()] for a in mol], dtype=np.float64) return xyz, r From d6af7fb80724a162b4938d45c70a19652308e858 Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Thu, 26 Mar 2026 11:10:27 -0700 Subject: [PATCH 10/11] Fixed bug with overlapping atoms in supercells --- TurtleMol/__main__.py | 6 +- TurtleMol/drawMol.py | 11 +- TurtleMol/readWriteFiles.py | 85 +++++++++++++--- TurtleMol/shiftUnitCell.py | 193 +++++++++++++++++++++++++++--------- TurtleMol/treeManager.py | 2 +- 5 files changed, 228 insertions(+), 69 deletions(-) diff --git a/TurtleMol/__main__.py b/TurtleMol/__main__.py index c48f08e..7071a9b 100644 --- a/TurtleMol/__main__.py +++ b/TurtleMol/__main__.py @@ -111,7 +111,7 @@ def main(): # Get structure if isinstance(iparams['structureFile'], str): - struc, unitCell = readStrucFile(iparams['structureFile']) + struc, unitCell, conect = readStrucFile(iparams['structureFile']) unitCells = None print(struc) elif isinstance(iparams['structureFile'], list): @@ -147,7 +147,7 @@ def main(): # Generate the new structure if unitCell: - outStruc, strucType, cellParams = drawMolBox(struc, baseStruc, iparams) + outStruc, strucType, cellParams, newConect = drawMolBox(struc, baseStruc, iparams, conect=conect) else: outStruc, strucType = drawMolBox(struc, baseStruc, iparams) @@ -171,7 +171,7 @@ def main(): if iparams['outputFile']: if unitCell: - writeOutput(outStruc, iparams['outputFile'], strucType, cellParams, iparams['padding']) + writeOutput(outStruc, iparams['outputFile'], strucType, cellParams, newConect, iparams['padding']) else: writeOutput(outStruc, iparams['outputFile'], strucType) diff --git a/TurtleMol/drawMol.py b/TurtleMol/drawMol.py index 3a28057..69e2941 100644 --- a/TurtleMol/drawMol.py +++ b/TurtleMol/drawMol.py @@ -21,7 +21,7 @@ from .shiftUnitCell import unitCellBox, unitCellMesh, unitCellSphere from .shiftHexagon import hexagonUnitCellBox, hexagonUnitCellSphere, hexagonUnitCellMesh -def drawMolBox(struc, baseStruc, iparams): +def drawMolBox(struc, baseStruc, iparams, conect=None): '''Utilized to place molecules in a box''' dims = drawBox(iparams) box = Box3d(0, 0, 0, dims) @@ -33,9 +33,14 @@ def drawMolBox(struc, baseStruc, iparams): if iparams['unitCell']: if iparams['hexagonal'] == False: - filled, strucType, cellParams = unitCellBox(box, dims, iparams['unitCell'], iparams['angle'], + if conect: + filled, strucType, cellParams, newConect = unitCellBox(box, dims, iparams['unitCell'], iparams['angle'], + originalPoints, radii, iparams['rotAngles'], conect=conect) + return filled, strucType, cellParams, newConect + else: + filled, strucType, cellParams, newConect = unitCellBox(box, dims, iparams['unitCell'], iparams['angle'], originalPoints, radii, iparams['rotAngles']) - return filled, strucType, cellParams + return filled, strucType, cellParams else: filled, strucType, cellParams = hexagonUnitCellBox(box, dims, iparams['unitCell'], originalPoints, radii) diff --git a/TurtleMol/readWriteFiles.py b/TurtleMol/readWriteFiles.py index b931350..d73ef9c 100644 --- a/TurtleMol/readWriteFiles.py +++ b/TurtleMol/readWriteFiles.py @@ -10,6 +10,7 @@ import numpy as np import pandas as pd import trimesh +from collections import defaultdict def getInput(filePath): '''Reads input file if provided''' @@ -26,14 +27,14 @@ def readStrucFile(filePath): # Reads XYZ if str(filePath[-3:]).lower() == 'xyz': return pd.read_csv(filePath, delim_whitespace=True, - skiprows=2, names=["Atom", "X", "Y", "Z"]), None + skiprows=2, names=["Atom", "X", "Y", "Z"]), None, None # Reads PDB if str(filePath[-3:]).lower() == 'pdb': return readPdb(filePath) # Reads CJSON if str(filePath[-5:]).lower() == 'cjson': - return readCJSON(filePath) + return readCJSON(filePath), None return f"ERROR: Issue generating file to {filePath}" @@ -41,6 +42,7 @@ def readPdb(filePath): '''Reads structure file if a pdb''' data = [] unitCell = None + conect = defaultdict(set) symbols = getElementData('AtomicMass') with open(filePath, 'r', encoding = 'utf-8') as pdbFile: @@ -58,6 +60,7 @@ def readPdb(filePath): elif line.startswith('ATOM') or line.startswith('HETATM'): # Parse relevant fields from the PDB format + serial = int(line[6:11].strip()) atomName = line[12:16].strip() element = line[76:78].strip() @@ -73,11 +76,31 @@ def readPdb(filePath): residueName = line[17:20].strip() residueSeq = int(line[22:26].strip()) - data.append([element, x, y, z, residueName, residueSeq]) - - df = pd.DataFrame(data, columns=['Atom', 'X', 'Y', 'Z', 'Residue', 'ResidueSeq']) - - return df, unitCell + data.append([serial, element, x, y, z, residueName, residueSeq]) + + elif line.startswith('CONECT'): + try: + src_str = line[6:11].strip() + if not src_str: + continue + src = int(src_str) + except ValueError: + continue + + for start in (11, 16, 21, 26): + dst_str = line[start:start+5].strip() + if not dst_str: + continue + try: + dst = int(dst_str) + except ValueError: + continue + conect[src].add(dst) + conect[dst].add(src) + + df = pd.DataFrame(data, columns=['Serial','Atom', 'X', 'Y', 'Z', 'Residue', 'ResidueSeq']) + + return df, unitCell, conect def readCJSON(filepath): '''Reads Structure from cjson file''' @@ -119,7 +142,7 @@ def readMesh(filePath): mesh = trimesh.load(filePath) return mesh -def writeOutput(data, filePath, strucType, cellParams=None, padding=[0, 0, 0]): +def writeOutput(data, filePath, strucType, cellParams=None, conect=None, padding=[0, 0, 0]): '''Writes data to output file''' try: # Writes XYZ @@ -127,9 +150,9 @@ def writeOutput(data, filePath, strucType, cellParams=None, padding=[0, 0, 0]): writeXYZ(data, filePath, strucType) # Writes PDB elif str(filePath[-3:]).lower() == 'pdb': - if cellParams != None: + if cellParams != None and conect != None: if isinstance(cellParams, str): - writePdb(data, filePath, cellParams) + writePdb(data, filePath, cellParams, conect=conect) else: newCellParams = multiUnitCell(data, padding) writePdb(data, filePath, newCellParams) @@ -139,7 +162,7 @@ def writeOutput(data, filePath, strucType, cellParams=None, padding=[0, 0, 0]): elif str(filePath[-5:]).lower() == 'cjson': if cellParams !=None: if isinstance(cellParams, str): - writeCJSON(data, filePath, cellParams) + writeCJSON(data, filePath, cellParams, conect) else: newCellParams = multiUnitCell(data, padding) writeCJSON(data, filePath, newCellParams) @@ -148,11 +171,11 @@ def writeOutput(data, filePath, strucType, cellParams=None, padding=[0, 0, 0]): except KeyError: print(f"Filetype {filePath[-3:]} not supported\n") -def writePdb(data, filePath, cellParams=None): +def writePdb(data, filePath, cellParams=None, conect=None): '''Writes a pdb file from results''' template = ( "HETATM{atomNum:5d} {atomType:>2} {residueName:>3} A{resNum: >4d}" - " {x: >8.3f}{y: >8.2f}{z: >8.3f}{occupancy: >6.2f}{tempFactor: >6.2f}" + " {x: >8.3f}{y: >8.3f}{z: >8.3f}{occupancy: >6.2f}{tempFactor: >6.2f}" " {element:>2}\n" ) @@ -164,13 +187,16 @@ def writePdb(data, filePath, cellParams=None): if cell != None: pdbFile.write(cell + '\n') + serialMap = {} + flatIdx = 1 + for mol in data: for atom in mol: pdbFile.write(template.format( atomNum = atomNum, atomType = atom[0].upper(), element = atom[0].capitalize(), - residueName = atom[4], + residueName = atom[4] if len(atom) > 4 else "MOL", resNum = resNum, x = atom[1], y = atom[2], @@ -179,8 +205,39 @@ def writePdb(data, filePath, cellParams=None): tempFactor = 0.00, # Default value )) + serialMap[flatIdx] = atomNum atomNum += 1 + flatIdx += 1 resNum += 0 + + if conect != None: + print("Hello") + writtenPairs = set() + + for src in sorted(conect): + if src not in serialMap: + continue + + srcOut = serialMap[src] + neighbors = [] + + for dst in sorted(conect[src]): + if dst not in serialMap: + continue + + pair = tuple(sorted((srcOut, serialMap[dst]))) + if pair in writtenPairs: + continue + + writtenPairs.add(pair) + neighbors.append(serialMap[dst]) + + # PDB CONECT lines allow up to 4 neighbors per line + for i in range(0, len(neighbors), 4): + chunk = neighbors[i:i+4] + pdbFile.write( + f"CONECT{srcOut:5d}" + "".join(f"{n:5d}" for n in chunk) + "\n" + ) pdbFile.write("END\n") def writeXYZ(data, filePath, strucType): diff --git a/TurtleMol/shiftUnitCell.py b/TurtleMol/shiftUnitCell.py index 60825a3..3ca2d79 100644 --- a/TurtleMol/shiftUnitCell.py +++ b/TurtleMol/shiftUnitCell.py @@ -1,97 +1,195 @@ '''This module is for replicating a unit cell if it is defined in a given pdb''' import numpy as np +from scipy.spatial import cKDTree +from collections import defaultdict import math import trimesh from .shiftBox import inBox +from .treeManager import PendingKDManager from .makeStruc import calcLatticeVectors, rotateUnitCell # Box -def unitCellBox(shape, dims, cellDims, cellAngles, og, radii, rotAngles=np.array([0, 0, 0]).all()): +def unitCellBox(shape, dims, cellDims, cellAngles, og, radii, rotAngles=np.array([0, 0, 0]).all(), conect=None): '''Duplicates unit cells to fill a given box''' - print('hello I am working') def _rebuildAtom(atom, xyz): """Preserve original tuple shape and trailing meta data""" return tuple([atom[0], xyz[0], xyz[1], xyz[2], *list(atom[4:])]) def _deduplicateAtomsPBC(atoms, latticeVec, tol=1e-3): - '''Wrap all atoms to canonical unit cell and remove duplicates outside cell''' - scale = 1.0/tol - seen = {} + """ + Deduplicate atoms under periodic boundary conditions using + minimum-image distance in fractional coordinates. + """ + coords = np.array([[a[1], a[2], a[3]] for a in atoms], dtype=float) + invLattice = np.linalg.inv(latticeVec) + + # Fractional coords in [0,1) + frac = coords @ invLattice + frac = frac % 1.0 + + n = len(atoms) + parent = list(range(n)) + + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + def union(a, b): + ra, rb = find(a), find(b) + if ra != rb: + parent[rb] = ra + + # Brute force is safest for correctness here. + # If needed, this can be optimized later. + for i in range(n): + for j in range(i + 1, n): + if atoms[i][0] != atoms[j][0]: + continue + + df = frac[i] - frac[j] + df -= np.round(df) # minimum-image fractional delta + dr = df @ latticeVec # back to Cartesian + dist = np.linalg.norm(dr) + + if dist < tol: + union(i, j) + unique = [] + kept_indices = [] + seen = set() - for atom in atoms: - key = ( - atom[0], - int(round(atom[1] * scale)), - int(round(atom[2] * scale)), - int(round(atom[3] * scale)), - tuple(atom[4:]), - ) - if key not in seen: - seen[key] = True - unique.append(atom) + for i in range(n): + r = find(i) + if r not in seen: + seen.add(r) + unique.append(atoms[i]) + kept_indices.append(i) - return unique + return unique, kept_indices + + def _filter_intra_image_conect(conect, kept_indices): + """ + Keep only bonds where both atoms survived canonical wrapping/dedup. + Assumes conect keys are 1-based indices matching original og order. + Returns: + baseConect using 1-based indices into canonicalOg + """ + if not conect: + return {} + + old_to_new = {old_idx + 1: new_idx + 1 for new_idx, old_idx in enumerate(kept_indices)} + baseConect = defaultdict(set) + + for src_old, nbrs in conect.items(): + if src_old not in old_to_new: + continue + src_new = old_to_new[src_old] + + for dst_old in nbrs: + if dst_old not in old_to_new: + continue + dst_new = old_to_new[dst_old] + + if src_new == dst_new: + continue + + baseConect[src_new].add(dst_new) + baseConect[dst_new].add(src_new) + + return dict(baseConect) + + def _replicate_conect(baseConect, atoms_per_cell, n_cells): + """ + Replicate intra-image connectivity into each duplicated cell. + baseConect uses 1-based indices inside one canonical cell. + """ + if not baseConect: + return {} + + newConect = defaultdict(set) + + for cell_idx in range(n_cells): + offset = cell_idx * atoms_per_cell + for src, nbrs in baseConect.items(): + src_new = src + offset + for dst in nbrs: + dst_new = dst + offset + newConect[src_new].add(dst_new) + newConect[dst_new].add(src_new) + + return dict(newConect) # Find the atom types in the tile atomNames = {atom[0] for atom in og} totalRadius = sum(radii[str.capitalize(name)] for name in atomNames) if not np.allclose(np.array(rotAngles), np.array([0, 0, 0])): - latticeVec = calcLatticeVectors(cellDims[0], cellDims[1], cellDims[2], cellAngles[0], cellAngles[1], cellAngles[2]) + latticeVec = calcLatticeVectors( + cellDims[0], cellDims[1], cellDims[2], + cellAngles[0], cellAngles[1], cellAngles[2] + ) og, cellInfo = rotateUnitCell(latticeVec, og, rotAngles) cellDims = [cellInfo['a'], cellInfo['b'], cellInfo['c']] cellAngles = [cellInfo['alpha'], cellInfo['beta'], cellInfo['gamma']] - latticeVec = calcLatticeVectors(cellDims[0], cellDims[1], cellDims[2], cellAngles[0], cellAngles[1], cellAngles[2]) + latticeVec = calcLatticeVectors( + cellDims[0], cellDims[1], cellDims[2], + cellAngles[0], cellAngles[1], cellAngles[2] + ) invLattice = np.linalg.inv(latticeVec) - alpha = np.radians(cellAngles[0]) - beta = np.radians(cellAngles[1]) - gamma = np.radians(cellAngles[2]) - - # Define the basis vectors a1 = latticeVec[0] a2 = latticeVec[1] a3 = latticeVec[2] - # Wrap original atoms into on canonical unit cell + # Wrap original atoms into one canonical unit cell wrappedOg = [] wrapTol = 1e-8 for atom in og: coord = np.array([atom[1], atom[2], atom[3]], dtype=float) - - # Cartesian to fraction for row based lattice vectors + + # Cartesian -> fractional for row-based lattice vectors frac = coord @ invLattice - # Wrap into [0,1] + # Wrap into [0,1) frac = frac % 1.0 frac[np.isclose(frac, 1.0, atol=wrapTol)] = 0.0 - - # Fractional to Cartesian + + # Fractional -> Cartesian wrappedCoord = frac @ latticeVec wrappedOg.append(_rebuildAtom(atom, wrappedCoord)) - canonicalOg = _deduplicateAtomsPBC(wrappedOg, latticeVec) - # Calculate how many times to duplicate the unit cell in a given dimension + # Deduplicate wrapped canonical cell + canonicalOg, kept_indices = _deduplicateAtomsPBC(wrappedOg, latticeVec, tol=0.15) + + # Preserve only intra-image conects among surviving canonical atoms + baseConect = _filter_intra_image_conect(conect, kept_indices) + + # Use ceil so the requested box is actually covered dupeCount = [max(1, math.ceil(dims[i] / cellDims[i])) for i in range(3)] - cellParams = f'CRYST1{dupeCount[0]*cellDims[0]:9.3f}{dupeCount[1]*cellDims[1]:9.3f}{dupeCount[2]*cellDims[2]:9.3f} {cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P 1 1' + + cellParams = ( + f'CRYST1{dupeCount[0]*cellDims[0]:9.3f}' + f'{dupeCount[1]*cellDims[1]:9.3f}' + f'{dupeCount[2]*cellDims[2]:9.3f} ' + f'{cellAngles[0]:0.2f} {cellAngles[1]:0.2f} {cellAngles[2]:0.2f} P 1 1' + ) filled = [] for dx in range(dupeCount[0]): for dy in range(dupeCount[1]): for dz in range(dupeCount[2]): - # Calculate the displacement for this duplication - disp = dx*a1 + dy*a2 + dz*a3 - + disp = dx * a1 + dy * a2 + dz * a3 currentCell = [] - + for atom in canonicalOg: newCoord = np.array([atom[1], atom[2], atom[3]], dtype=float) + disp shiftedCoord = np.array([ @@ -100,25 +198,16 @@ def _deduplicateAtomsPBC(atoms, latticeVec, tol=1e-3): shape.zCoord + newCoord[2] ], dtype=float) - # Check if the new atom fits within the box currentCell.append(_rebuildAtom(atom, shiftedCoord)) filled.append(currentCell) + # Wrap all atoms into final supercell box superLattice = np.array([ dupeCount[0] * a1, dupeCount[1] * a2, dupeCount[2] * a3 ]) - - print("dims =", dims) - print("cellDims =", cellDims) - print("dupeCount =", dupeCount) - print("a1 =", a1) - print("a2 =", a2) - print("a3 =", a3) - print("superLattice =\n", superLattice) - invSuper = np.linalg.inv(superLattice) wrappedFilled = [] @@ -147,7 +236,15 @@ def _deduplicateAtomsPBC(atoms, latticeVec, tol=1e-3): wrappedCell.append(_rebuildAtom(atom, finalCoord)) wrappedFilled.append(wrappedCell) - return wrappedFilled, "molecule", cellParams + + + atoms_per_cell = len(canonicalOg) + + newConect = _replicate_conect(baseConect, atoms_per_cell, len(wrappedFilled)) + + if conect is None: + return wrappedFilled, "molecule", cellParams + return wrappedFilled, "molecule", cellParams, newConect def unitCellSphere(shape, cellDims, cellAngles, og, radii, rotAngles=np.array([0, 0, 0]).all()): '''Duplicates unit cells to fill a given sphere''' diff --git a/TurtleMol/treeManager.py b/TurtleMol/treeManager.py index 795b5a5..f847d9a 100644 --- a/TurtleMol/treeManager.py +++ b/TurtleMol/treeManager.py @@ -31,7 +31,7 @@ def overlapsMolecule(self, mol, tol): for atom in mol: p = np.array([atom[1], atom[2], atom[3]], dtype=np.float64) - pr = float(self.radii[atom[0]]) + pr = float(self.radii[atom[0].title()]) # Check against comitted KDTree if self.kdTree is not None: From a8ecf4cb46003e1a553abf85da9994de0fceaf3f Mon Sep 17 00:00:00 2001 From: Dominick Filonowich Date: Wed, 5 Aug 2026 12:54:24 -0700 Subject: [PATCH 11/11] Documentation updates --- README.md | 5 +- docs/box.rst | 21 ++++++ docs/command-line.rst | 71 +++++++++++++++++++ docs/conf.py | 34 ++++------ docs/file-formats.rst | 33 +++++++++ docs/getting-started.rst | 50 ++++++++++++++ docs/index.rst | 128 +++++++++++------------------------ docs/input.rst | 143 ++++++++++++++++++++++----------------- docs/meshes.rst | 26 +++++++ docs/out.rst | 14 ++++ docs/python-api.rst | 91 +++++++++++++++++++++++++ docs/rho.rst | 20 ++++++ docs/sphere.rst | 19 ++++++ docs/troubleshooting.rst | 36 ++++++++++ 14 files changed, 519 insertions(+), 172 deletions(-) create mode 100644 docs/command-line.rst create mode 100644 docs/file-formats.rst create mode 100644 docs/getting-started.rst create mode 100644 docs/meshes.rst create mode 100644 docs/python-api.rst create mode 100644 docs/troubleshooting.rst diff --git a/README.md b/README.md index 45cdbd5..69e10ea 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,9 @@ Distributed under the MIT License. See [LICENSE](https://github.com/Dfilono/Turt ## Documentation -Documentation is in progress. +The complete user guide and Python API reference live in [`docs/`](docs/index.rst). +Build the HTML site locally with: + + python -m sphinx -W -b html docs docs/_build/html diff --git a/docs/box.rst b/docs/box.rst index e69de29..de379e0 100644 --- a/docs/box.rst +++ b/docs/box.rst @@ -0,0 +1,21 @@ +Boxes and cubes +=============== + +Use ``shape=box`` with ``Xlen``, ``Ylen``, and ``Zlen`` for a rectangular +volume. Use ``shape=cube`` with ``sideLength`` for equal edges. + +.. code-block:: text + + shape=box + Xlen=30 + Ylen=20 + Zlen=15 + structureFile=water.xyz + numMolecules=fill + tol=1.0 + outputFile=box.xyz + +The box begins at the origin. Grid filling places as many non-overlapping +copies as allowed by the volume and tolerance. Set a finite ``numMolecules`` +and ``randFill=True`` for random positions; increase ``maxAttempts`` if a dense +job stops before reaching its requested count. diff --git a/docs/command-line.rst b/docs/command-line.rst new file mode 100644 index 0000000..818e7f9 --- /dev/null +++ b/docs/command-line.rst @@ -0,0 +1,71 @@ +Command-line interface +====================== + +Run TurtleMol through its installed command or as a module: + +.. code-block:: console + + TurtleMol [options] + python -m TurtleMol [options] + +Use ``TurtleMol --help`` for the options supported by the installed version. + +Core options +------------ + +.. list-table:: + :header-rows: 1 + :widths: 27 18 55 + + * - Option + - Default + - Meaning + * - ``--structureFile`` + - required + - XYZ, PDB, or CJSON tile to repeat. + * - ``--outputFile`` + - none + - Destination XYZ, PDB, or CJSON file. + * - ``--shape`` + - ``box`` + - ``box``, ``cube``, ``sphere``, ``mesh``, or ``multimesh``. + * - ``--numMolecules`` + - ``1`` + - Number of copies. Input files also accept ``fill``. + * - ``--tol`` + - ``1.0`` + - Minimum separation in ångströms. + * - ``--density`` + - none + - Target density in g/mL; takes precedence over copy count. + * - ``--randomizeOrient`` + - false + - Randomize the orientation of molecular copies. + * - ``--randFill`` + - false + - Place copies randomly instead of on a grid. + * - ``--maxAttempts`` + - ``10000`` + - Attempt limit for random filling. + * - ``--atomRadius`` + - ``AtomicRadius`` + - ``AtomicRadius``, ``CovalentRadius``, or ``VanDerWaalsRadius``. + * - ``--baseStrucFile`` + - none + - Structure retained but not repeated. + +Shape options +------------- + +``box`` uses ``--Xlen``, ``--Ylen``, and ``--Zlen``. ``cube`` uses +``--sideLength``. ``sphere`` uses ``--radius`` and ``--center X Y Z``. +``mesh`` uses ``--mesh`` and optionally ``--meshScale``. + +.. note:: + + For reliable boolean values, especially false values, prefer an input file. + The current CLI applies Python's ``bool`` conversion, under which any + non-empty string is true. + +When ``--inputFile`` is supplied, other CLI values are not merged into it. +Missing keys receive defaults. Density takes precedence over ``numMolecules``. diff --git a/docs/conf.py b/docs/conf.py index 14a3d31..16b3c9e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,30 +1,26 @@ -# Configuration file for the Sphinx documentation builder. -# -# For the full list of built-in configuration values, see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html +'''Sphinx configuration for TurtleMol.''' -# -- Project information ----------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) project = 'TurtleMol' copyright = '2023, Dominick Filonowich' author = 'Dominick Filonowich' -html_title = 'TurtleMol' -html_logo = './images/logo.png' -release = '0.1.0' -# -- General configuration --------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration - -extensions = [] +try: + from TurtleMol import __version__ +except ImportError: + __version__ = 'development' +release = __version__ +version = __version__ +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] +autodoc_member_order = 'bysource' templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - - - -# -- Options for HTML output ------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output - html_theme = 'alabaster' +html_title = 'TurtleMol' +html_logo = 'images/logo.png' html_static_path = ['_static'] diff --git a/docs/file-formats.rst b/docs/file-formats.rst new file mode 100644 index 0000000..f605c9d --- /dev/null +++ b/docs/file-formats.rst @@ -0,0 +1,33 @@ +File formats +============ + +TurtleMol selects a format from the path extension (case-insensitive). + +XYZ +--- + +XYZ input must have an atom count, a comment line, then whitespace-separated +``element x y z`` records. Coordinates are interpreted as ångströms. XYZ does +not preserve bonds, residues, or unit-cell metadata. + +PDB +--- + +TurtleMol reads ``ATOM``, ``HETATM``, ``CRYST1``, and ``CONECT`` records. It +writes generated atoms as ``HETATM`` records and can preserve cell information +for unit-cell workflows. Element symbols should be present in columns 77-78; +the atom name is used as a fallback. + +CJSON +----- + +Chemical JSON input uses ``atoms.elements.number`` and flattened +``atoms.coords.3d`` arrays. An optional ``unitCell`` object may contain ``a``, +``b``, ``c``, ``alpha``, ``beta``, and ``gamma``. + +Meshes +------ + +Mesh files are loaded by trimesh. Common formats include STL, OBJ, and PLY. +Closed, watertight meshes give the most reliable inside/outside tests. See +:doc:`meshes` for mesh-specific controls. diff --git a/docs/getting-started.rst b/docs/getting-started.rst new file mode 100644 index 0000000..2fd9492 --- /dev/null +++ b/docs/getting-started.rst @@ -0,0 +1,50 @@ +Getting started +=============== + +Requirements +------------ + +TurtleMol requires Python 3.7 or newer. Its runtime dependencies include +NumPy, pandas, SciPy, trimesh, and rtree. + +Installation +------------ + +Install the released package from PyPI: + +.. code-block:: console + + python -m pip install TurtleMol + +To use the latest source checkout: + +.. code-block:: console + + git clone https://github.com/Dfilono/TurtleMol.git + cd TurtleMol + python -m pip install . + +Create a source molecule +------------------------ + +The input structure is the tile TurtleMol repeats. Save this as ``water.xyz``: + +.. code-block:: text + + 3 + water + O 0.000000 0.000000 0.000000 + H 0.957200 0.000000 0.000000 + H -0.239987 0.927297 0.000000 + +Generate a structure +-------------------- + +.. code-block:: console + + TurtleMol --structureFile water.xyz --shape cube --sideLength 20 \ + --numMolecules 100 --tol 1.0 --outputFile water-box.xyz + +The file extension selects XYZ, PDB, or CJSON format. Open the result in a +molecular viewer and check its boundaries and close contacts. The generated +structure is not geometry-optimized. diff --git a/docs/index.rst b/docs/index.rst index 588c976..9488fc2 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,101 +1,49 @@ -.. TURTLE documentation master file, created by - sphinx-quickstart on Mon Oct 16 13:06:21 2023. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +TurtleMol documentation +======================= -Welcome to TurtleMol's documentation! -======================================== +TurtleMol builds molecular starting structures by repeating an atom, molecule, +or crystallographic unit cell inside a box, sphere, or mesh. It can fill the +available volume, place a requested number of copies, or estimate the number of +copies from a target mass density. -Design, create, and generate unique, complex molecular structures of any shape and size! +TurtleMol creates *starting geometries*. Always inspect and energy-minimize +generated structures before using them in a simulation. -.. image:: https://github.com/Dfilono/TurtleMol/actions/workflows/python-package.yml/badge.svg - :target: https://github.com/Dfilono/TurtleMol/actions/workflows/python-package.yml - :alt: GitHub actions build status +Quick example +------------- -.. image:: https://codecov.io/gh/Dfilono/TurtleMol/branch/main/graph/badge.svg - :target: https://codecov.io/gh/Dfilono/TurtleMol - :alt: Codecov test coverage +.. code-block:: console -.. image:: https://img.shields.io/github/license/Dfilono/TurtleMol - :target: https://github.com/Dfilono/TurtleMol/blob/main/LICENSE + python -m pip install TurtleMol + TurtleMol --structureFile water.xyz --shape cube --sideLength 20 \ + --numMolecules 100 --tol 1.0 --outputFile water-box.xyz -.. image:: https://img.shields.io/github/repo-size/Dfilono/TurtleMol - :target: https://github.com/Dfilono/TurtleMol - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - -.. image:: https://img.shields.io/badge/linting-pylint-yellowgreen - :target: https://github.com/PyCQA/pylint - -Motivation -========== - -The goal of TurtleMol is to ease the process of -generating unique and complex molecular structures for computational chemistry. Available as a standalone python-package, -or as a plugin for `Avogadro2 `__, TurtleMol aims to quickly generate -the intial state of molecular strcutres that are ready for optimization via quamtum or classical calculations! - -Generating intial structure files for calculations can be a tedious process, one that TurtleMol aims to fix. -Large structures can be generated quickly, and are very tunable based on the need of the user! -Currently only basic shapes such as boxes and spheres are generatable, but more complex meshes are in the works! - -Approach -======== - -TurtleMol takes an input molecules (or molecules) and copies them into a grid filling out a user defined volume. -The number of molecules in the volume can be specially defined, calculated via a desired density, or for filling space. -The orientation of the molecules can be randomized so structures are closer to their equilibrium point, but will still need outside optimization. -Molecules can also be placed randomly instead of in a grid, allowing for a more disordered structure. - -Features -======== - -- Generate a box or sphere of molecules -- Generate a box or sphere of molecules around an existing molecular structure -- Fill a volume, or place a specfied number of molecules in space -- Randomly orient molecules to better represent an equilibrium structure -- Read/Write structures from XYZ and PDB formats - -Installation -============ - -You can install the latest development version of TURTLE from the `Github Repository `__ - -.. code-block:: bash - - git clone https://github.com/Dfilono/https://github.com/Dfilono/TurtleMol - cd TurtleMol - pip install . - -Or you can install it via PyPI - -.. code-block:: bash - - pip install TurtleMol - -Citation -======== - -If you find this code helpful, please consider referencing it! We don't currently have a released article to cite, -but any reference to our work helps acknowledge the effort put into developing and maintaining this code base, -provides support for further development! - -License -======= - -Distributed under the MIT License. See `LICENSE `__ for more information. - -.. image:: images/logo.png - :align: center +The ``TurtleMol`` command and ``python -m TurtleMol`` are equivalent. +.. toctree:: + :maxdepth: 2 + :caption: User guide + + getting-started + command-line + input + file-formats + box + sphere + meshes + rho + out + troubleshooting .. toctree:: - :hidden: + :maxdepth: 2 + :caption: Python API + + python-api - Input - Generate a Box - Generate a Sphere - Density - Outpute +Project links +------------- +* `Source code `_ +* `Issue tracker `_ +* `MIT license `_ diff --git a/docs/input.rst b/docs/input.rst index c070501..5f6f4db 100644 --- a/docs/input.rst +++ b/docs/input.rst @@ -1,62 +1,81 @@ -Input Parameters -================ - -The inputs for TurtleMol can be entered via the command line or an input file. Not all -parameters need to entered, TurtleMol will rely on default values we have predefined. Some of those -default values SHOULD be changed to ensure they meet the user's system, -and those will be marked in the following list of parameters. The units for all lengths -are in Angstroms. - -- shape: The shape of the object you would like to generate - - Current options: cube, box, sphere - - Default: box -- sideLength: The length of all sides in a cube - - Default: 1.0 -- XLen: The length of a non-cubical box (distance in the x-direction) - - Default: 1.0 -- YLen: The width of a non-cubical box (distance in the y-direction) - - Default: 1.0 -- ZLen: The height of a non-cubical box (distance in the z-direction) - - Default: 1.0 -- numMolecules: The number of molecules to place in the given volume - - Current options: - - fill: A special parameter to fill the volume with maximum amount of molecules - - Any integer - - Default: fill -- tol: The minimum distance between two molecules in the space - - Default: 1.0 -- structureFile: The path to the XYZ or PDB file where your system is defined. This is REQUIRED -- baseStrucFile: The path to the XYZ or PDB file of an additional structure you want at the center of the new system - - Default: None -- randomizeOrient: A boolean term that randomly orients the new molecules in the volume - - Options: True, False - - Default: False -- randFill: A boolean term that places molecules randomly in the volume rather than in a grid-like fashion. Only works when density or number of molecules is defined. - - Options: True, False - - Default: False -- density: Define the denisty of the system, and Turtle will calculate the number of molecules to place - - Default: None -- atomRadius: Choose what type of radius you want the atoms to have - - Options: AtomicRadius, CovalentRadius, VanDerWaalsRadius - -Important parameters to keep in mind include denisty and atomRadius. Results may be unphysical for low denisty molecular systems -if not specifically defined. - -To build an input file, simply write a .txt file with the parameter=value. For example: - -.. code-block:: - - shape=sphere - radius=5.0 - tol=0.5 - randomizeOrient=True - numMolecules=fill - structureFile=path/to/file.txt - -Spaces between parameters are not allowed, spaces may be placed around the = sign. - -To run TurtleMol, open command line and input the following: - -.. code-block:: - - python TurtleMol -i ./path/to/input/file.txt +Input files and parameters +========================== + +An input file is UTF-8 text containing one ``key=value`` pair per line. Key +names are case-sensitive. Do not add comments or blank lines: every line is +parsed as an assignment. + +.. code-block:: text + + shape=sphere + radius=15.0 + tol=0.5 + randomizeOrient=True + numMolecules=fill + structureFile=water.xyz + outputFile=water-sphere.pdb + +Run it with ``TurtleMol --inputFile run.txt``. + +Parameter reference +------------------- + +.. list-table:: + :header-rows: 1 + :widths: 22 18 60 + + * - Key + - Default + - Description + * - ``shape`` + - ``box`` + - ``box``, ``cube``, ``sphere``, ``mesh``, or ``multimesh``. + * - ``structureFile`` / ``outputFile`` + - required / none + - Input tile and output structure paths. + * - ``sideLength`` + - ``1.0`` + - Cube edge length in Å. + * - ``Xlen``, ``Ylen``, ``Zlen`` + - ``1.0`` + - Box dimensions in Å. + * - ``radius`` / ``sphereCenter`` + - ``1.0`` / ``[0,0,0]`` + - Sphere radius and center. Set list-valued options through Python; the + text input parser does not deserialize comma-separated lists. + * - ``numMolecules`` + - ``1`` + - Integer copy count or ``fill``. + * - ``tol`` + - ``1.0`` + - Minimum separation for overlap checks, in Å. + * - ``density`` + - none + - Target density in g/mL. Overrides count-based placement. + * - ``randomizeOrient`` / ``randFill`` + - ``False`` + - Randomize molecular orientations / positions. + * - ``maxAttempts`` + - ``10000`` + - Attempt limit for random placement. + * - ``atomRadius`` + - ``AtomicRadius`` + - Element radius used in overlap checks. + * - ``baseStrucFile`` / ``baseStrucCenter`` + - none / ``[0,0,0]`` + - Non-repeated structure and its desired center. + * - ``mesh`` / ``meshScale`` + - none / ``1.0`` + - Mesh path and uniform scale. + * - ``unitCell`` / ``angle`` + - none / ``[90,90,90]`` + - Cell lengths and angles, normally read from input. + * - ``hexagonal`` / ``rotAngles`` + - ``False`` / ``[0,0,0]`` + - Hexagonal packing and fixed tile rotation. + * - ``onSurface`` / ``alignNormal`` + - ``False`` + - Mesh surface placement and face-normal alignment. + +``scaleX``, ``scaleY``, ``scaleZ``, and ``padding`` are experimental. +``globalMatrixPath`` supplies transforms for multi-mesh generation. diff --git a/docs/meshes.rst b/docs/meshes.rst new file mode 100644 index 0000000..d17d456 --- /dev/null +++ b/docs/meshes.rst @@ -0,0 +1,26 @@ +Mesh volumes +============ + +Set ``shape=mesh`` and provide a mesh path. TurtleMol loads the mesh through +trimesh, scales it, translates its minimum bound to the origin, and places +copies inside it. + +.. code-block:: text + + shape=mesh + mesh=container.stl + meshScale=2.0 + structureFile=water.xyz + numMolecules=200 + randFill=True + maxAttempts=50000 + outputFile=mesh-fill.xyz + +Use a closed, watertight mesh. Holes, self-intersections, inconsistent normals, +or unexpected source units can make containment tests unreliable. Inspect the +scaled mesh and output together when diagnosing missing or misplaced copies. + +The Python parameter dictionary also supports ``onSurface`` and +``alignNormal`` for molecular tiles. Multi-mesh generation additionally needs +one tile, mesh, and global transformation matrix per component; it is an +advanced API workflow via :func:`TurtleMol.buildMultiMesh`. diff --git a/docs/out.rst b/docs/out.rst index e69de29..bfdaa6a 100644 --- a/docs/out.rst +++ b/docs/out.rst @@ -0,0 +1,14 @@ +Output +====== + +Set ``outputFile`` to a path ending in ``.xyz``, ``.pdb``, or ``.cjson``. +TurtleMol writes no structure file when the option is omitted. + +XYZ is the simplest and most portable output but contains only elements and +coordinates. PDB can include crystallographic cell and connectivity records in +unit-cell workflows. CJSON stores atomic numbers and a flattened coordinate +array, with optional unit-cell values. + +Generated structures may contain fewer copies than requested when boundary and +overlap constraints make placement impossible. Always validate the output atom +count and geometry before passing it to downstream software. diff --git a/docs/python-api.rst b/docs/python-api.rst new file mode 100644 index 0000000..8268051 --- /dev/null +++ b/docs/python-api.rst @@ -0,0 +1,91 @@ +Python API +========== + +TurtleMol exposes its primary geometry, generation, file, and transformation +helpers at package level. Begin with :func:`TurtleMol.defaultParams`, override +the values needed by your job, and pass the complete dictionary to a draw +function. + +.. code-block:: python + + import TurtleMol + + params = TurtleMol.defaultParams() + params.update({ + 'shape': 'cube', + 'sideLength': 20.0, + 'numMolecules': 100, + 'tol': 1.0, + 'randomizeOrient': True, + }) + + tile, unit_cell, connectivity = TurtleMol.readStrucFile('water.xyz') + if unit_cell: + params['unitCell'] = [unit_cell['a'], unit_cell['b'], unit_cell['c']] + params['angle'] = [unit_cell['alpha'], unit_cell['beta'], + unit_cell['gamma']] + + result = TurtleMol.drawMolBox(tile, None, params, + conect=connectivity) + molecules, structure_type, *metadata = result + TurtleMol.writeOutput(molecules, 'water-box.xyz', structure_type) + +Generation +---------- + +.. py:function:: defaultParams() + + Return a new dictionary containing every supported generation parameter. + The dictionary can be modified and passed to a draw function. +.. autofunction:: TurtleMol.drawMolBox +.. autofunction:: TurtleMol.drawMolSphere +.. autofunction:: TurtleMol.drawMolMesh +.. autofunction:: TurtleMol.buildMultiMesh + +File handling +------------- + +.. autofunction:: TurtleMol.getInput +.. autofunction:: TurtleMol.readStrucFile +.. autofunction:: TurtleMol.readPdb +.. autofunction:: TurtleMol.readMesh +.. autofunction:: TurtleMol.writeOutput +.. autofunction:: TurtleMol.writePdb +.. autofunction:: TurtleMol.writeXYZ +.. autofunction:: TurtleMol.getElementData + +Geometry +-------- + +.. autoclass:: TurtleMol.Box3d + :members: + +.. autoclass:: TurtleMol.Sphere3d + :members: + +.. autoclass:: TurtleMol.mesh3D + :members: + +Transformations and calculations +-------------------------------- + +.. autofunction:: TurtleMol.calcCenter +.. autofunction:: TurtleMol.reCenter +.. autofunction:: TurtleMol.shiftPoints +.. autofunction:: TurtleMol.Reorient +.. autofunction:: TurtleMol.calcDensity +.. autofunction:: TurtleMol.calcNumMol +.. autofunction:: TurtleMol.applyGlobalTransform +.. autofunction:: TurtleMol.computeCentroid +.. autofunction:: TurtleMol.applyTranslation +.. autofunction:: TurtleMol.alignToNormal +.. autofunction:: TurtleMol.alignVectors +.. autofunction:: TurtleMol.placeOnSurfaceNormal + +Return values +------------- + +Draw functions normally return ``(structures, structure_type)``. Unit-cell +paths append cell metadata, and box generation with connectivity may append an +updated connectivity mapping. Code that supports both modes can unpack the +first two values and collect the remainder, as in the example above. diff --git a/docs/rho.rst b/docs/rho.rst index e69de29..f84d4cf 100644 --- a/docs/rho.rst +++ b/docs/rho.rst @@ -0,0 +1,20 @@ +Density-based generation +======================== + +Set ``density`` in g/mL to let TurtleMol calculate a copy count from the tile's +molar mass and the target volume. Density mode takes precedence over +``numMolecules``. + +.. code-block:: text + + shape=cube + sideLength=30 + density=1.0 + structureFile=water.xyz + randomizeOrient=True + outputFile=water-density.xyz + +The calculation depends on recognized element symbols and the selected +geometric volume. The requested bulk density does not guarantee a relaxed or +physically realistic local structure; minimize and equilibrate the output with +appropriate simulation software. diff --git a/docs/sphere.rst b/docs/sphere.rst index e69de29..a2008d3 100644 --- a/docs/sphere.rst +++ b/docs/sphere.rst @@ -0,0 +1,19 @@ +Spherical volumes +================= + +Use ``shape=sphere`` and ``radius`` to define the volume. The default center is +the origin; the CLI accepts another center through ``--center X Y Z``. + +.. code-block:: text + + shape=sphere + radius=15 + structureFile=water.xyz + numMolecules=80 + randFill=True + randomizeOrient=True + outputFile=sphere.pdb + +Atoms are tested against the spherical boundary with their selected atomic +radii. A requested count may be impossible when the radius is small or the +separation is large. diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst new file mode 100644 index 0000000..b265e6c --- /dev/null +++ b/docs/troubleshooting.rst @@ -0,0 +1,36 @@ +Troubleshooting +=============== + +No output file +-------------- + +Confirm that ``outputFile`` is set and ends in ``.xyz``, ``.pdb``, or +``.cjson``. Also verify that ``structureFile`` exists and has a supported +extension. + +Too few molecules +----------------- + +The requested count may not fit. Increase the volume or ``maxAttempts``, or +reduce ``tol``, the copy count, or the selected atomic radius. Random placement +becomes progressively less likely to succeed as the volume fills. + +Unexpected command-line booleans +-------------------------------- + +Use an input file for boolean settings. With the current CLI parser, +``--randFill False`` is still a non-empty string and therefore evaluates true. + +Mesh placement fails +-------------------- + +Check that the mesh is watertight, has sensible units and scale, and contains +no self-intersections. The ``rtree`` dependency must also be available for +trimesh spatial queries. + +Unphysical contacts +------------------- + +Try a larger ``tol`` or a larger radius model such as +``VanDerWaalsRadius``. TurtleMol does not perform force-field optimization, so +the result should be minimized before simulation.