molfidget 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: molfidget
3
+ Version: 0.1.0
4
+ Summary: A molecular modeler of 3D printable models from the MOL/PDB format.
5
+ Author: Ryosuke Tajima
6
+ Author-email: tajima.ryosuke@techmagic.co.jp
7
+ Requires-Python: >=3.10,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Dist: manifold3d (>=3.1.0,<4.0.0)
13
+ Requires-Dist: pyglet (<2)
14
+ Requires-Dist: pyyaml (>=6.0.1,<7.0.0)
15
+ Requires-Dist: scipy (>=1.15.3,<2.0.0)
16
+ Requires-Dist: trimesh (>=4.6.9,<5.0.0)
File without changes
@@ -0,0 +1,443 @@
1
+ import argparse
2
+ import dataclasses
3
+ import os
4
+ import trimesh
5
+ import yaml
6
+ import numpy as np
7
+ from collections import OrderedDict as Orderdict
8
+ from dataclasses import dataclass
9
+
10
+ atom_radius_table = {
11
+ "C": 1.7,
12
+ "O": 1.52,
13
+ "H": 1.2,
14
+ "S": 1.8,
15
+ "N": 1.55,
16
+ }
17
+
18
+ atom_color_table = {
19
+ "C": [100, 100, 100, 255],
20
+ "O": [255, 0, 0, 255],
21
+ "H": [255, 255, 255, 255],
22
+ "S": [255, 255, 0, 255],
23
+ "N": [0, 0, 255, 255],
24
+ }
25
+
26
+ # Bond distance table in Angstroms for single, double, and triple bonds
27
+ bond_distance_table = {
28
+ frozenset(["C", "C"]): (1.54, 1.33, 1.20),
29
+ frozenset(["C", "O"]): (1.43, 1.23, 1.17),
30
+ frozenset(["C", "H"]): (1.09, 0.00, 0.00),
31
+ frozenset(["O", "O"]): (1.48, 1.2075, 1.28),
32
+ frozenset(["H", "O"]): (0.96, 0.00, 0.00),
33
+ frozenset(["C", "S"]): (1.81, 1.50, 1.40),
34
+ frozenset(["O", "S"]): (1.70, 1.45, 1.35),
35
+ frozenset(["H", "S"]): (1.34, 0.00, 0.00),
36
+ frozenset(["C", "N"]): (1.47, 1.34, 1.20),
37
+ frozenset(["N", "O"]): (1.40, 1.20, 1.15),
38
+ frozenset(["H", "N"]): (1.01, 0.00, 0.00),
39
+ frozenset(["N", "N"]): (1.45, 1.25, 1.10),
40
+ }
41
+
42
+ @dataclass
43
+ class ShapeConfig:
44
+ scale: float = 10.0 # Scale factor for the whole model
45
+ vdw_scale: float = 0.8 # Scale factor for van der Waals radius
46
+ shaft_radius: float = 0.3 # Radius of the shaft [Angstrom]
47
+ shaft_length: float = 0.3 # Length of the shaft [Angstrom]
48
+ stopper_radius: float = 0.4 # Radius of the stopper [Angstrom]
49
+ stopper_length: float = 0.2 # Length of the stopper [Angstrom]
50
+ hole_radius: float = 0.3 # Radius of the hole [Angstrom]
51
+ hole_length: float = 0.3 # Length of the hole [Angstrom]
52
+ chamfer_length: float = 0.1 # Length of the chamfer [Angstrom]
53
+ wall_thickness: float = 0.1 # Thickness of the wall [Angstrom]
54
+ shaft_gap: float = 0.03 # Gap between the shaft and the hole [Angstrom]
55
+ bond_gap: float = 0.0 # Gap between the bond plane [Angstrom]
56
+
57
+ slice_distance: float = 0.0 # Distance from the atom to the bond plane, calculated in Bond class
58
+
59
+ class Atom:
60
+ def __init__(self, id: int, name: str, x: float, y: float, z: float):
61
+ self.id = id
62
+ self.name = name[0]
63
+ if self.name not in atom_radius_table:
64
+ raise ValueError(f"Unknown atom {id}: name: {self.name}")
65
+ self.radius = atom_radius_table[self.name]
66
+ self.x = x
67
+ self.y = y
68
+ self.z = z
69
+ self.pairs = {}
70
+
71
+ def __repr__(self):
72
+ return f"{self.name}_{self.id}({self.x}, {self.y}, {self.z})"
73
+
74
+ def create_trimesh_model(self, config: ShapeConfig):
75
+ # Shpere mesh for the atom
76
+ mesh = trimesh.primitives.Sphere(radius=config.vdw_scale*self.radius, center=[0, 0, 0])
77
+ # Scrupt the sphere to represent bonds
78
+ for pair in self.pairs.values():
79
+ pair.update_slice_distance(config)
80
+ mesh = pair.sculpt_trimesh_model(mesh, config)
81
+ mesh.apply_translation([self.x, self.y, self.z])
82
+ mesh.visual.vertex_colors = atom_color_table[self.name]
83
+ return mesh
84
+
85
+ class Bond:
86
+ def __init__(self, atom1:Atom, atom2:Atom, type:str, shaft: bool):
87
+ '''
88
+ 結合を表すクラス
89
+ atom1(Atom): 原子1(分割したとき軸側になる)
90
+ atom2(Atom): 原子2(分割したとき穴側になる)
91
+ type(str): 結合の種類(single, double, triple)
92
+ shaft(bool): True: 軸側 / False 穴側
93
+ '''
94
+ self.atom1 = atom1
95
+ self.atom2 = atom2
96
+ self.type = type
97
+ self.shaft = shaft
98
+ self.atom_distance = np.linalg.norm(np.array([atom1.x - atom2.x, atom1.y - atom2.y, atom1.z - atom2.z]))
99
+ self.vector = np.array([atom2.x - atom1.x, atom2.y - atom1.y, atom2.z - atom1.z])
100
+ self.vector = self.vector / np.linalg.norm(self.vector)
101
+
102
+ def __repr__(self):
103
+ return f"Bond({self.atom1.id}, {self.atom2}, type={self.type})"
104
+
105
+ def update_slice_distance(self, config: ShapeConfig):
106
+ # Update the slice distance based on the configuration
107
+ r1 = config.vdw_scale * self.atom1.radius
108
+ r2 = config.vdw_scale * self.atom2.radius
109
+ self.slice_distance = (r1**2 - r2**2 + self.atom_distance**2)/(2*self.atom_distance)
110
+
111
+ def sculpt_trimesh_model(self, mesh: trimesh.Trimesh, config: ShapeConfig):
112
+ mesh = self.slice_by_bond_plane(mesh, config)
113
+
114
+ if self.type == "none":
115
+ return mesh
116
+
117
+ if self.shaft:
118
+ if self.type == "single":
119
+ # Create the cavity
120
+ cavity = self.create_cavity_shape(config)
121
+ cavity.apply_translation([0, 0, self.slice_distance])
122
+ rotation_matrix = trimesh.geometry.align_vectors([0, 0, 1], self.vector)
123
+ cavity.apply_transform(rotation_matrix)
124
+ mesh = trimesh.boolean.difference([mesh, cavity], check_volume=False)
125
+ # Create the shaft
126
+ shaft = self.create_rotate_shaft(config)
127
+ shaft.apply_translation([0, 0, self.slice_distance])
128
+ rotation_matrix = trimesh.geometry.align_vectors([0, 0, 1], self.vector)
129
+ shaft.apply_transform(rotation_matrix)
130
+ mesh = trimesh.boolean.union([mesh, shaft], check_volume=False)
131
+ else:
132
+ # Create the fixed shaft
133
+ shaft = self.create_fixed_shaft_shape(config)
134
+ shaft.apply_translation([0, 0, self.slice_distance - config.bond_gap])
135
+ rotation_matrix = trimesh.geometry.align_vectors([0, 0, 1], self.vector)
136
+ shaft.apply_transform(rotation_matrix)
137
+ mesh = trimesh.boolean.union([mesh, shaft], check_volume=False)
138
+ else:
139
+ hole = self.create_hole_shape(config)
140
+ hole.apply_translation([0, 0, self.slice_distance])
141
+ rotation_matrix = trimesh.geometry.align_vectors([0, 0, 1], self.vector)
142
+ hole.apply_transform(rotation_matrix)
143
+ mesh = trimesh.boolean.difference([mesh, hole], check_volume=False)
144
+ return mesh
145
+
146
+ def slice_by_bond_plane(self, mesh: trimesh.Trimesh, config: ShapeConfig):
147
+ box = trimesh.primitives.Box(extents=[self.atom1.radius*2, self.atom1.radius*2, self.atom1.radius*2])
148
+ box.apply_translation([0, 0, self.slice_distance-self.atom1.radius-config.bond_gap])
149
+ z_axis = np.array([0, 0, 1])
150
+ rotation_matrix = trimesh.geometry.align_vectors(z_axis, self.vector)
151
+ box.apply_transform(rotation_matrix)
152
+ mesh = trimesh.boolean.intersection([mesh, box], check_volume=False)
153
+ #mesh = trimesh.boolean.union([mesh, box], check_volume=False)
154
+ return mesh
155
+
156
+ def create_rotate_shaft(self, config):
157
+ # Create a shaft
158
+ # d1: Shaft length including the wall thickness and gap without chamfer
159
+ d1 = config.shaft_length + config.wall_thickness + config.shaft_gap
160
+ cylinder1 = trimesh.creation.cylinder(radius=config.shaft_radius, height=d1)
161
+ cylinder1.apply_translation([0, 0, -d1/2])
162
+ # Create the chamfer on the shaft
163
+ cylinder3 = trimesh.creation.cylinder(radius=config.shaft_radius, height=config.chamfer_length)
164
+ cylinder3.apply_translation([0, 0, config.chamfer_length/2])
165
+ cone1 = trimesh.creation.cone(radius=config.shaft_radius, height=2*config.shaft_radius, sections=32)
166
+ cone1 = trimesh.boolean.intersection([cone1, cylinder3], check_volume=False)
167
+ cylinder1 = trimesh.boolean.union([cylinder1, cone1], check_volume=False)
168
+ cylinder1.apply_translation([0, 0, config.shaft_length - config.chamfer_length])
169
+ # Create the stopper
170
+ cylinder2 = trimesh.creation.cylinder(radius=config.stopper_radius, height=config.stopper_length)
171
+ cylinder2.apply_translation([0, 0, - config.stopper_length/2 - config.wall_thickness - config.shaft_gap])
172
+ mesh = trimesh.boolean.union([cylinder1, cylinder2], check_volume=False)
173
+ return mesh
174
+
175
+ def create_cavity_shape(self, config):
176
+ eps = 0.01 # Small epsilon to avoid numerical issues
177
+ # Create the cavity shape for the shaft
178
+ d1 = config.wall_thickness + eps
179
+ cylinder1 = trimesh.creation.cylinder(radius=config.shaft_radius+config.shaft_gap, height=d1)
180
+ cylinder1.apply_translation([0, 0, -d1/2 + eps])
181
+ # Create the cavity for the stopper
182
+ d2 = config.stopper_length + 2*config.shaft_gap
183
+ cylinder2 = trimesh.creation.cylinder(radius=config.stopper_radius+config.shaft_gap, height=d2)
184
+ cylinder2.apply_translation([0, 0, -d2/2 - d1 + eps])
185
+ mesh = trimesh.boolean.union([cylinder1, cylinder2], check_volume=False)
186
+ return mesh
187
+
188
+ def create_fixed_shaft_shape(self, config):
189
+ eps = 0.01 # Small epsilon to avoid numerical issues
190
+ # Create a fixed shaft shape
191
+ d1 = config.shaft_length + config.bond_gap - config.chamfer_length
192
+ cylinder1 = trimesh.creation.cylinder(radius=config.shaft_radius, height=d1)
193
+ cylinder1.apply_translation([0, 0, -d1/2])
194
+ # Create the chamfer on the shaft
195
+ cylinder2 = trimesh.creation.cylinder(radius=config.shaft_radius, height=config.chamfer_length)
196
+ cylinder2.apply_translation([0, 0, config.chamfer_length/2])
197
+ cone1 = trimesh.creation.cone(radius=config.shaft_radius, height=2*config.shaft_radius, sections=32)
198
+ cone1 = trimesh.boolean.intersection([cone1, cylinder2], check_volume=False)
199
+ cylinder1 = trimesh.boolean.union([cylinder1, cone1], check_volume=False)
200
+ cylinder1.apply_translation([0, 0, config.shaft_length + config.bond_gap - config.chamfer_length - eps])
201
+ return cylinder1
202
+
203
+ def create_hole_shape(self, config):
204
+ # Create a hole shape for the shaft
205
+ eps = 0.01 # Small epsilon to avoid numerical issues
206
+ d1 = config.hole_length + eps
207
+ cylinder1 = trimesh.creation.cylinder(radius=config.hole_radius, height=d1)
208
+ cylinder1.apply_translation([0, 0, -d1/2 + eps])
209
+ return cylinder1
210
+
211
+ def atom_distance(atom1: Atom, atom2: Atom):
212
+ # Calculate the distance between two atoms
213
+ return float(np.linalg.norm(np.array([atom1.x - atom2.x, atom1.y - atom2.y, atom1.z - atom2.z])))
214
+
215
+ class Molecule:
216
+ def __init__(self):
217
+ # Dictionary to hold atoms by their ids
218
+ self.atoms = Orderdict()
219
+ # Group of atoms that can be merged
220
+ self.atom_groups = Orderdict()
221
+
222
+ def load_mol_file(self, file_name):
223
+ # Load a MOL file and populate the molecule with atoms and bonds
224
+ with open(file_name, 'r') as file:
225
+ lines = file.readlines()
226
+ # Fist line contains the name of the molecule
227
+ self.name = lines[0].strip()
228
+ counts = lines[3].split()
229
+ atom_count = int(counts[0])
230
+ bond_count = int(counts[1])
231
+ # Parse the atom lines
232
+ for i in range(atom_count):
233
+ data = lines[4 + i].strip().split()
234
+ x = float(data[0])
235
+ y = float(data[1])
236
+ z = float(data[2])
237
+ name = data[3]
238
+ self.atoms[i+1] = Atom(i+1, name, x, y, z)
239
+ print(f"Loaded atom: {self.atoms[i+1]}")
240
+ # Create the pairs of atoms based on the distances
241
+ self.create_pairs()
242
+ # Parse the bond lines
243
+ for i in range(bond_count):
244
+ data = lines[4 + atom_count + i].strip().split()
245
+ id1 = int(data[0])
246
+ id2 = int(data[1])
247
+ type = int(data[2])
248
+ if type == 1:
249
+ bond_type = "single"
250
+ elif type == 2:
251
+ bond_type = "double"
252
+ elif type == 3:
253
+ bond_type = "triple"
254
+ elif type == 4:
255
+ bond_type = "1.5"
256
+ else:
257
+ raise ValueError(f"Unknown bond type: {type}")
258
+ self.atoms[id1].pairs[id1, id2] = Bond(self.atoms[id1], self.atoms[id2], type=bond_type, shaft=id1 < id2)
259
+ self.atoms[id2].pairs[id1, id2] = Bond(self.atoms[id2], self.atoms[id1], type=bond_type, shaft=id2 < id1)
260
+ print(f"Loaded bond: {self.atoms[id1].name}_{id1} - {self.atoms[id2].name}_{id2}, type={bond_type}")
261
+
262
+ def load_pdb_file(self, file_name):
263
+ # Load a PDB file and populate the molecule with atoms and bonds
264
+ with open(file_name, 'r') as file:
265
+ for line in file:
266
+ # Do we have the name of the molecule somewhere?
267
+ if line.startswith("COMPND"):
268
+ self.name = line[10:].strip()
269
+ # Parse ATOM and HETATM lines to extract atom information
270
+ if line.startswith("ATOM") or line.startswith("HETATM"):
271
+ id = int(line[6:11].strip())
272
+ name = line[12:16].strip()
273
+ x = float(line[30:38])
274
+ y = float(line[38:46])
275
+ z = float(line[46:54])
276
+ self.atoms[id] = Atom(id, name, x, y, z)
277
+ # Create the atom pairs based on the atom distances
278
+ self.create_pairs()
279
+ # Find the bonds based on the atom pairs
280
+ self.find_bonds()
281
+
282
+ def create_pairs(self):
283
+ # Update the pairs of atoms based on the distance between them
284
+ for id1, atom1 in self.atoms.items():
285
+ for id2, atom2 in self.atoms.items():
286
+ if id1 == id2:
287
+ continue
288
+ if atom_distance(atom1, atom2) < atom1.radius + atom2.radius:
289
+ atom1.pairs[id1, id2] = Bond(atom1, atom2, type="none", shaft=id1 < id2)
290
+
291
+ def find_bonds(self):
292
+ # Update the bonds based on the distance between atoms
293
+ for id1, atom1 in self.atoms.items():
294
+ for id2, atom2 in self.atoms.items():
295
+ if id1 == id2:
296
+ continue
297
+ if frozenset([atom1.name, atom2.name]) not in bond_distance_table:
298
+ continue
299
+ # Check if the atoms are within triple bond distance
300
+ if atom_distance(atom1, atom2) < 1.05*bond_distance_table[frozenset([atom1.name, atom2.name])][2]:
301
+ atom1.pairs[id1, id2] = Bond(atom1, atom2, type="triple", shaft=id1 < id2)
302
+ # Check if the atoms are within double bond distance
303
+ elif atom_distance(atom1, atom2) < 1.05*bond_distance_table[frozenset([atom1.name, atom2.name])][1]:
304
+ atom1.pairs[id1, id2] = Bond(atom1, atom2, type="double", shaft=id1 < id2)
305
+ # Check if the atoms are within single bond distance
306
+ elif atom_distance(atom1, atom2) < 1.05*bond_distance_table[frozenset([atom1.name, atom2.name])][0]:
307
+ atom1.pairs[id1, id2] = Bond(atom1, atom2, type="single", shaft=id1 < id2)
308
+
309
+ def __repr__(self):
310
+ return f"Molecule({self.name}, {len(self.atoms)} atoms)"
311
+
312
+ # acces the center of the molecule
313
+ @property
314
+ def center(self):
315
+ # Get the center of the molecule
316
+ x = np.mean([atom.x for atom in self.atoms.values()])
317
+ y = np.mean([atom.y for atom in self.atoms.values()])
318
+ z = np.mean([atom.z for atom in self.atoms.values()])
319
+ return np.array([x, y, z])
320
+
321
+ def create_trimesh_scene(self, config: ShapeConfig):
322
+ # Create a trimesh model for the molecule
323
+ scene = trimesh.Scene()
324
+ for atom in self.atoms.values():
325
+ mesh = atom.create_trimesh_model(config)
326
+ scene.add_geometry(mesh)
327
+ # center the scene
328
+ scene.apply_translation(-self.center)
329
+ scene.apply_scale(config.scale)
330
+ return scene
331
+
332
+ def save_stl_files(self, config: ShapeConfig, output_dir: str ='output'):
333
+ os.makedirs(output_dir, exist_ok=True)
334
+ for atom in self.atoms.values():
335
+ mesh = atom.create_trimesh_model(config)
336
+ mesh.apply_scale(config.scale)
337
+ mesh.export(os.path.join(output_dir, f"{atom.name}_{atom.id}.stl"))
338
+
339
+ def merge_atoms(self):
340
+ counter = 0
341
+ for atom in self.atoms.values():
342
+ for pair in atom.pairs.values():
343
+ if pair.type == "none":
344
+ continue
345
+ if pair.atom1.name != pair.atom2.name:
346
+ continue
347
+ # Search group containing atom1 or atom2
348
+ group = next((g for g in self.atom_groups.values() if pair.atom1.id in g or pair.atom2.id in g), None)
349
+ if group is None:
350
+ # Create a new group if not found
351
+ self.atom_groups[f"group_{counter}"] = set()
352
+ self.atom_groups[f"group_{counter}"].add(pair.atom1.id)
353
+ self.atom_groups[f"group_{counter}"].add(pair.atom2.id)
354
+ counter += 1
355
+ else:
356
+ # Add the atoms to the existing group
357
+ group.add(pair.atom1.id)
358
+ group.add(pair.atom2.id)
359
+
360
+ print(f"Merged atoms into {len(self.atom_groups)} groups")
361
+ print("Groups:", self.atom_groups)
362
+
363
+ def save_group_stl_files(self, config: ShapeConfig, output_dir: str ='output'):
364
+ os.makedirs(output_dir, exist_ok=True)
365
+ for group_name, group in self.atom_groups.items():
366
+ # Merge the atoms and save as a single file
367
+ meshes = [self.atoms[id].create_trimesh_model(config) for id in group]
368
+ merged_mesh = trimesh.util.concatenate(meshes)
369
+ merged_mesh.apply_scale(config.scale)
370
+ merged_mesh.export(os.path.join(output_dir, f"{group_name}.stl"))
371
+
372
+ def main():
373
+ config = ShapeConfig()
374
+ # command line interface
375
+ parser = argparse.ArgumentParser(description="Molecule visualization and manipulation")
376
+ parser.add_argument("file_name", type=str, help="PDB or MOL file to load")
377
+ parser.add_argument('--config-file', type=str, help="Configuration yaml file")
378
+ parser.add_argument("--scale", type=float, default=config.scale, help="Scale of the molecule (default: %(default)s)")
379
+ parser.add_argument('--vdw-radius-scale', type=float, default=config.vdw_scale, help="Scale factor for van der Waals radius (default: %(default)s)")
380
+ parser.add_argument('--shaft-radius', type=float, default=config.shaft_radius, help="Radius of the shaft [Angstrom] (default: %(default)s)")
381
+ parser.add_argument('--shaft-length', type=float, default=config.shaft_length, help="Length of the shaft [Angstrom] (default: %(default)s)")
382
+ parser.add_argument('--stopper-radius', type=float, default=config.stopper_radius, help="Radius of the stopper [Angstrom] (default: %(default)s)")
383
+ parser.add_argument('--stopper-length', type=float, default=config.stopper_length, help="Length of the stopper [Angstrom] (default: %(default)s)")
384
+ parser.add_argument('--hole-radius', type=float, default=config.hole_radius, help="Radius of the hole [Angstrom] (default: %(default)s)")
385
+ parser.add_argument('--hole-length', type=float, default=config.hole_length, help="Length of the hole [Angstrom] (default: %(default)s)")
386
+ parser.add_argument('--chamfer-length', type=float, default=config.chamfer_length, help="Length of the chamfer [Angstrom] (default: %(default)s)")
387
+ parser.add_argument('--wall-thickness', type=float, default=config.wall_thickness, help="Thickness of the wall [Angstrom] (default: %(default)s)")
388
+ parser.add_argument('--shaft-gap', type=float, default=0.35, help="Gap between the shaft and the hole [mm] (default: %(default)s)")
389
+ parser.add_argument('--bond-gap', type=float, default=0.0, help="Gap between the bond plane [mm] (default: %(default)s)")
390
+ parser.add_argument('--output-dir', type=str, default='output', help="Output directory for STL files (default: %(default)s)")
391
+
392
+ args = parser.parse_args()
393
+
394
+ # Load configuration from a YAML file if provided
395
+ if args.config_file:
396
+ with open(args.config_file, 'r') as file:
397
+ config_data = yaml.safe_load(file)
398
+ config = ShapeConfig(**config_data)
399
+
400
+ config.scale = args.scale
401
+ config.vdw_scale = args.vdw_radius_scale
402
+ config.shaft_radius = args.shaft_radius
403
+ config.shaft_length = args.shaft_length
404
+ config.stopper_radius = args.stopper_radius
405
+ config.stopper_length = args.stopper_length
406
+ config.hole_radius = args.hole_radius
407
+ config.hole_length = args.hole_length
408
+ config.chamfer_length = args.chamfer_length
409
+ config.wall_thickness = args.wall_thickness
410
+ config.shaft_gap = min(0.05, args.shaft_gap / args.scale)
411
+ config.bond_gap = min(0.05, args.bond_gap / args.scale)
412
+
413
+ molecule = Molecule()
414
+
415
+ if args.file_name.endswith(".pdb"):
416
+ molecule.load_pdb_file(args.file_name)
417
+ elif args.file_name.endswith(".mol"):
418
+ molecule.load_mol_file(args.file_name)
419
+ else:
420
+ exit(f"Unsupported file format: {args.file_name}. Please provide a .pdb or .mol file.")
421
+
422
+ scene = molecule.create_trimesh_scene(config)
423
+ scene.show()
424
+ # Save the molecule as STL files
425
+ if not os.path.exists(args.output_dir):
426
+ os.makedirs(args.output_dir)
427
+ scene.export(os.path.join(args.output_dir, "molecule.stl"))
428
+ scene.export(os.path.join(args.output_dir, "molecule.ply"))
429
+
430
+ molecule.save_stl_files(config, output_dir=args.output_dir)
431
+ print(f"Loaded {len(molecule.atoms)} atoms from {args.file_name}")
432
+
433
+ molecule.merge_atoms()
434
+ molecule.save_group_stl_files(config, output_dir=args.output_dir)
435
+
436
+ # Save the configuration to a YAML file
437
+ config_data = dataclasses.asdict(config)
438
+ config_data["file_name"] = args.file_name
439
+ with open(os.path.join(args.output_dir, "config.yaml"), 'w') as file:
440
+ yaml.dump(config_data, file, default_flow_style=False)
441
+
442
+ if __name__ == "__main__":
443
+ main()
@@ -0,0 +1,22 @@
1
+ [tool.poetry]
2
+ name = "molfidget"
3
+ version = "0.1.0"
4
+ description = "A molecular modeler of 3D printable models from the MOL/PDB format."
5
+ authors = ["Ryosuke Tajima <tajima.ryosuke@techmagic.co.jp>"]
6
+
7
+ [tool.poetry.dependencies]
8
+ python = "^3.10"
9
+ scipy = "^1.15.3"
10
+ trimesh = "^4.6.9"
11
+ manifold3d = "^3.1.0"
12
+ pyglet = "<2"
13
+ pyyaml = "^6.0.1"
14
+
15
+ [tool.poetry.dev-dependencies]
16
+
17
+ [tool.poetry.scripts]
18
+ molfidget = "molfidget.molfidget:main"
19
+
20
+ [build-system]
21
+ requires = ["poetry-core>=1.0.0"]
22
+ build-backend = "poetry.core.masonry.api"