Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

<img src="https://github.com/Dfilono/TurtleMol/blob/main/docs/images/logo.png">
8 changes: 4 additions & 4 deletions TurtleMol/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)

Expand All @@ -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)

Expand Down
58 changes: 29 additions & 29 deletions TurtleMol/defaultParams.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 10 additions & 5 deletions TurtleMol/drawMol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -31,17 +31,22 @@ 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'],
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)
return filled, strucType, cellParams

originalPoints = shiftPoints(originalPoints, box)

if iparams['density']:
filled, strucType = placeMols(box, originalPoints, iparams['density'],
Expand Down
1 change: 0 additions & 1 deletion TurtleMol/examples/Argon/ArgonTest.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ sideLength=10
numMolecules=20
structureFile=argon.xyz
radius = 10
fromWall=0.25
outputFile=out.xyz
tol=0.5
89 changes: 47 additions & 42 deletions TurtleMol/makeStruc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -316,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.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)))

cellParams = {'a' : a,
'b' : b,
'c' : c,
'alpha' : alpha,
'beta' : beta,
'gamma' : gamma}


return rotatedAtoms, cellParams
# 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
28 changes: 25 additions & 3 deletions TurtleMol/mesh3D.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -55,7 +77,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])
Expand Down
Loading
Loading