HTPolyNet 1.0.7.2__py3-none-any.whl

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.
Files changed (93) hide show
  1. HTPolyNet/__init__.py +1 -0
  2. HTPolyNet/ambertools.py +94 -0
  3. HTPolyNet/analyze.py +258 -0
  4. HTPolyNet/banner.py +26 -0
  5. HTPolyNet/bondlist.py +206 -0
  6. HTPolyNet/bondtemplate.py +111 -0
  7. HTPolyNet/checkpoint.py +88 -0
  8. HTPolyNet/command.py +42 -0
  9. HTPolyNet/configuration.py +240 -0
  10. HTPolyNet/coordinates.py +1071 -0
  11. HTPolyNet/countTime.py +26 -0
  12. HTPolyNet/curecontroller.py +767 -0
  13. HTPolyNet/dataframetools.py +130 -0
  14. HTPolyNet/driver.py +250 -0
  15. HTPolyNet/expandreactions.py +154 -0
  16. HTPolyNet/gromacs.py +333 -0
  17. HTPolyNet/inputcheck.py +51 -0
  18. HTPolyNet/linkcell.py +322 -0
  19. HTPolyNet/molecule.py +1279 -0
  20. HTPolyNet/plot.py +607 -0
  21. HTPolyNet/postsim.py +444 -0
  22. HTPolyNet/projectfilesystem.py +483 -0
  23. HTPolyNet/reaction.py +282 -0
  24. HTPolyNet/resources/README.md +20 -0
  25. HTPolyNet/resources/__init__.py +0 -0
  26. HTPolyNet/resources/cfg/DGE-PAC-hi.yaml +115 -0
  27. HTPolyNet/resources/cfg/DGE-PAC-lo.yaml +115 -0
  28. HTPolyNet/resources/cfg/FDE-DFDA-hi.yaml +116 -0
  29. HTPolyNet/resources/cfg/FDE-DFDA-lo.yaml +116 -0
  30. HTPolyNet/resources/cfg/GMASTY-hi.yaml +158 -0
  31. HTPolyNet/resources/cfg/GMASTY-lo.yaml +158 -0
  32. HTPolyNet/resources/cfg/README.md +1 -0
  33. HTPolyNet/resources/cfg/STY.yaml +23 -0
  34. HTPolyNet/resources/cfg/pMSTY-hi.yaml +101 -0
  35. HTPolyNet/resources/cfg/pMSTY-lo.yaml +101 -0
  36. HTPolyNet/resources/cfg/pSTY-hi.yaml +101 -0
  37. HTPolyNet/resources/cfg/pSTY-lo.yaml +101 -0
  38. HTPolyNet/resources/example_depot/0-liquid-styrene.tgz +0 -0
  39. HTPolyNet/resources/example_depot/1-polystyrene.tgz +0 -0
  40. HTPolyNet/resources/example_depot/2-polymethylstyrene.tgz +0 -0
  41. HTPolyNet/resources/example_depot/3-bisgma-styrene-thermoset.tgz +0 -0
  42. HTPolyNet/resources/example_depot/4-pacm-dgeba-epoxy-thermoset.tgz +0 -0
  43. HTPolyNet/resources/example_depot/5-dfda-fde-epoxy-thermoset.tgz +0 -0
  44. HTPolyNet/resources/mdp/README.md +1 -0
  45. HTPolyNet/resources/mdp/drag-min.mdp +13 -0
  46. HTPolyNet/resources/mdp/drag-npt.mdp +36 -0
  47. HTPolyNet/resources/mdp/drag-nvt.mdp +31 -0
  48. HTPolyNet/resources/mdp/min.mdp +14 -0
  49. HTPolyNet/resources/mdp/npt.mdp +37 -0
  50. HTPolyNet/resources/mdp/nvt.mdp +29 -0
  51. HTPolyNet/resources/mdp/relax-min.mdp +13 -0
  52. HTPolyNet/resources/mdp/relax-npt.mdp +37 -0
  53. HTPolyNet/resources/mdp/relax-nvt.mdp +31 -0
  54. HTPolyNet/resources/mdp/single-molecule-min.mdp +12 -0
  55. HTPolyNet/resources/mdp/single-molecule-nvt.mdp +25 -0
  56. HTPolyNet/resources/molecules/inputs/DFA.pdb +62 -0
  57. HTPolyNet/resources/molecules/inputs/DGE.mol2 +115 -0
  58. HTPolyNet/resources/molecules/inputs/EMB.mol2 +50 -0
  59. HTPolyNet/resources/molecules/inputs/FDE.pdb +72 -0
  60. HTPolyNet/resources/molecules/inputs/GMA.mol2 +163 -0
  61. HTPolyNet/resources/molecules/inputs/PAC.mol2 +91 -0
  62. HTPolyNet/resources/molecules/inputs/STY.mol2 +44 -0
  63. HTPolyNet/resources/molecules/make-monomers.sh +64 -0
  64. HTPolyNet/resources/molecules/pics/DFA.png +0 -0
  65. HTPolyNet/resources/molecules/pics/DGE.png +0 -0
  66. HTPolyNet/resources/molecules/pics/EMB.png +0 -0
  67. HTPolyNet/resources/molecules/pics/FDE.png +0 -0
  68. HTPolyNet/resources/molecules/pics/GMA.png +0 -0
  69. HTPolyNet/resources/molecules/pics/PAC.png +0 -0
  70. HTPolyNet/resources/molecules/pics/STY.png +0 -0
  71. HTPolyNet/resources/molecules/sample-inputs/DFA.pdb +62 -0
  72. HTPolyNet/resources/molecules/sample-inputs/DGE.mol2 +115 -0
  73. HTPolyNet/resources/molecules/sample-inputs/EMB.mol2 +50 -0
  74. HTPolyNet/resources/molecules/sample-inputs/FDE.pdb +72 -0
  75. HTPolyNet/resources/molecules/sample-inputs/GMA.mol2 +163 -0
  76. HTPolyNet/resources/molecules/sample-inputs/PAC.mol2 +91 -0
  77. HTPolyNet/resources/molecules/sample-inputs/STY.mol2 +44 -0
  78. HTPolyNet/resources/tcl/readbonds.tcl +32 -0
  79. HTPolyNet/resources/tcl/readgrx.tcl +46 -0
  80. HTPolyNet/resources/tcl/render.tcl +74 -0
  81. HTPolyNet/ring.py +155 -0
  82. HTPolyNet/runtime.py +709 -0
  83. HTPolyNet/software.py +106 -0
  84. HTPolyNet/stringthings.py +39 -0
  85. HTPolyNet/topocoord.py +1877 -0
  86. HTPolyNet/topology.py +1288 -0
  87. HTPolyNet/unused_symmetry_stuff.py +291 -0
  88. HTPolyNet/utils.py +405 -0
  89. htpolynet-1.0.7.2.dist-info/METADATA +84 -0
  90. htpolynet-1.0.7.2.dist-info/RECORD +93 -0
  91. htpolynet-1.0.7.2.dist-info/WHEEL +4 -0
  92. htpolynet-1.0.7.2.dist-info/entry_points.txt +2 -0
  93. htpolynet-1.0.7.2.dist-info/licenses/LICENSE +21 -0
HTPolyNet/molecule.py ADDED
@@ -0,0 +1,1279 @@
1
+ """
2
+
3
+ .. module:: molecule
4
+ :synopsis: manages generation of molecular templates
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import os
10
+ import pandas as pd
11
+ import numpy as np
12
+ import logging
13
+ import shutil
14
+ from itertools import chain, product
15
+ from copy import deepcopy
16
+
17
+ import HTPolyNet.projectfilesystem as pfs
18
+ from HTPolyNet.topocoord import TopoCoord
19
+ from HTPolyNet.bondtemplate import BondTemplate,BondTemplateList,ReactionBond,ReactionBondList
20
+ from HTPolyNet.coordinates import dfrotate, GRX_ATTRIBUTES
21
+ from HTPolyNet.ambertools import GAFFParameterize
22
+ from HTPolyNet.gromacs import mdp_modify,gro_from_trr
23
+ from HTPolyNet.command import Command
24
+ from HTPolyNet.reaction import Reaction, ReactionList, reaction_stage, generate_product_name, reactant_resid_to_presid
25
+
26
+ logger=logging.getLogger(__name__)
27
+
28
+ def _rotmat(axis,radians):
29
+ """_rotmat generates a rotation matrix that rotates coordinates around axis by radians
30
+
31
+ :param axis: 0=x,1=y,2=z
32
+ :type axis: int
33
+ :param radians: angle measure
34
+ :type radians: float
35
+ :return: rotation matrix
36
+ :rtype: np.ndarray(3,float)
37
+ """
38
+ R=np.identity(3)
39
+ sr=np.sin(radians)
40
+ cr=np.cos(radians)
41
+ if axis==2:
42
+ R[0][0]=cr
43
+ R[0][1]=-sr
44
+ R[1][0]=sr
45
+ R[1][1]=cr
46
+ elif axis==1:
47
+ R[0][0]=cr
48
+ R[0][2]=sr
49
+ R[2][0]=-sr
50
+ R[2][2]=cr
51
+ elif axis==0:
52
+ R[1][1]=cr
53
+ R[1][2]=-sr
54
+ R[2][1]=sr
55
+ R[2][2]=cr
56
+ return R
57
+
58
+ def yield_bonds(R:Reaction,TC:TopoCoord,resid_mapper):
59
+ """yield_bonds for each bond pattern in the reaction R, yield the specific bond represented by this pattern in the molecule's topology
60
+
61
+ :param R: a Reaction
62
+ :type R: Reaction
63
+ :param TC: molecule topology and coordinates
64
+ :type TC: TopoCoord
65
+ :param resid_mapper: dictionary that maps in-reactant resids to in-product resids
66
+ :type resid_mapper: dict
67
+ :yield: a reaction bond
68
+ :rtype: ReactionBond
69
+ """
70
+ nreactants=len(R.reactants)
71
+ for bondrec in R.bonds:
72
+ atom_keys=bondrec['atoms']
73
+ order=bondrec['order']
74
+ assert len(atom_keys)==2
75
+ atomrecs=[R.atoms[x] for x in atom_keys]
76
+ atom_names=[x['atom'] for x in atomrecs]
77
+ in_reactant_resids=[x['resid'] for x in atomrecs]
78
+ if nreactants==1:
79
+ in_product_resids=[resid_mapper[0][in_reactant_resids[x]] for x in [0,1]]
80
+ else:
81
+ in_product_resids=[resid_mapper[x][in_reactant_resids[x]] for x in [0,1]]
82
+ atom_idx=[TC.get_gro_attribute_by_attributes('globalIdx',{'resNum':in_product_resids[x],'atomName':atom_names[x]}) for x in [0,1]]
83
+ bystander_resids,bystander_resnames,bystander_atomidx,bystander_atomnames=TC.get_bystanders(atom_idx)
84
+ oneaway_resids,oneaway_resnames,oneaway_atomidx,onewaway_atomnames=TC.get_oneaways(atom_idx)
85
+ yield ReactionBond(atom_idx,in_product_resids,order,bystander_resids,bystander_atomidx,oneaway_resids,oneaway_atomidx)
86
+
87
+ def yield_bonds_as_df(R:Reaction,TC:TopoCoord,resid_mapper):
88
+ """yield_bonds_as_df returns a pandas DataFrame identifying all reaction bonds obtained by matching the reaction template bonds to instances in the molecule topology
89
+
90
+ :param R: a Reaction
91
+ :type R: Reaction
92
+ :param TC: molecule topology and coordinates
93
+ :type TC: TopoCoord
94
+ :param resid_mapper: dictionary that maps in-reactant resids to in-product resids
95
+ :type resid_mapper: dict
96
+ :return: dataframe with all reaction bonds
97
+ :rtype: pd.DataFrame
98
+ """
99
+ bdf=pd.DataFrame()
100
+ nreactants=len(R.reactants)
101
+ for bondrec in R.bonds:
102
+ atom_keys=bondrec['atoms']
103
+ order=bondrec['order']
104
+ assert len(atom_keys)==2
105
+ atomrecs=[R.atoms[x] for x in atom_keys]
106
+ atom_names=[x['atom'] for x in atomrecs]
107
+ in_reactant_resids=[x['resid'] for x in atomrecs]
108
+ if nreactants==1:
109
+ in_product_resids=[resid_mapper[0][in_reactant_resids[x]] for x in [0,1]]
110
+ else:
111
+ in_product_resids=[resid_mapper[x][in_reactant_resids[x]] for x in [0,1]]
112
+ ai,aj=[TC.get_gro_attribute_by_attributes('globalIdx',{'resNum':in_product_resids[x],'atomName':atom_names[x]}) for x in [0,1]]
113
+ ri,rj=in_product_resids
114
+ row_dict={'ai':[ai],'aj':[aj],'ri':[ri],'rj':[rj],'order':[order],'reactantName':[R.product]}
115
+ bdf=pd.concat((bdf,pd.DataFrame(row_dict)),ignore_index=True)
116
+ return bdf
117
+
118
+ class Molecule:
119
+ def __init__(self,name='',generator:Reaction=None,origin:str=None):
120
+ self.name=name
121
+ self.parentname=name # stereoisomer parent
122
+ self.TopoCoord=TopoCoord()
123
+ self.generator:Reaction=generator
124
+ self.sequence=[]
125
+ self.origin=origin
126
+ self.reaction_bonds:ReactionBondList=[]
127
+ self.bond_templates:BondTemplateList=[]
128
+ self.symmetry_relateds=[]
129
+ self.stereocenters=[] # list of atomnames
130
+ self.stereoisomers:dict(str,Molecule)={}
131
+ self.nconformers=0
132
+ self.conformers_dict={}
133
+ self.conformers=[] # just a list of gro file basenames
134
+ self.zrecs=[]
135
+ self.is_reactant=False
136
+
137
+ @classmethod
138
+ def New(cls,mol_name,generator:Reaction,molrec={}):
139
+ """New generates a new, partially populated Molecule based on directives in the configuration input
140
+
141
+ :param mol_name: name of molecule
142
+ :type mol_name: str
143
+ :param generator: reaction that generates this molecule, if applicable
144
+ :type generator: Reaction
145
+ :param molrec: dictionary of directive for this molecule, defaults to {}
146
+ :type molrec: dict, optional
147
+ :return: a new Molecule object
148
+ :rtype: Molecule
149
+ """
150
+ M=cls(name=mol_name)
151
+ M.generator=generator
152
+ if not molrec: return M
153
+ M.symmetry_relateds=molrec.get('symmetry_equivalent_atoms',[])
154
+ M.stereocenters=molrec.get('stereocenters',[])
155
+ # expand list of stereocenters if any are in symmetry sets
156
+ extra_stereocenters=[]
157
+ for stc in M.stereocenters:
158
+ for sc in M.symmetry_relateds:
159
+ if stc in sc:
160
+ sc_copy=sc.copy()
161
+ sc_copy.remove(stc)
162
+ if not sc_copy in extra_stereocenters:
163
+ extra_stereocenters.extend(sc_copy)
164
+ M.stereocenters.extend(extra_stereocenters)
165
+ logger.debug(f'{M.name} stereocenters: {M.stereocenters}')
166
+ # generate shells for new stereoisomers
167
+ M.create_new_stereoisomers()
168
+ logger.debug(f'{M.name} stereoisomers: {[s.name for s in M.stereoisomers.values()]}')
169
+ M.conformers_dict=molrec.get('conformers',{})
170
+ logger.debug(f'{M.name} conformers_dict {M.conformers_dict}')
171
+ return M
172
+
173
+ def set_origin(self,value):
174
+ """set_origin sets the value of the origin member
175
+
176
+ :param value: value
177
+ :type value: anything
178
+ """
179
+ self.origin=value
180
+
181
+ def get_origin(self):
182
+ """get_origin returns the value of the origin member
183
+
184
+ :return: value of origin member
185
+ :rtype: anything
186
+ """
187
+ return self.origin
188
+
189
+ def update_zrecs(self,zrecs,moldict):
190
+ """update_zrecs updates the "z-records" based on z's declared in the input configuration file
191
+
192
+ :param zrecs: zrecs extracted from configuration file for this molecule
193
+ :type zrecs: dict
194
+ :param moldict: dictionary of available molecules
195
+ :type moldict: dicts
196
+ """
197
+ def replace_if_greater(rec,D,matchattr=[],maxattr=[]):
198
+ if not matchattr or not maxattr: return
199
+ for r in D:
200
+ matched=all([r[a]==rec[a] for a in matchattr])
201
+ if matched:
202
+ replace=all([r[a]<rec[a] for a in maxattr])
203
+ if replace:
204
+ D.remove(r)
205
+ D.append(rec)
206
+ return True
207
+ return False
208
+ logger.debug(f'Update zrecs in {self.name} from {zrecs}')
209
+ seq=self.sequence
210
+ for zr in zrecs:
211
+ resid=zr['resid']-1
212
+ rname=seq[resid]
213
+ target=moldict[rname]
214
+ logger.debug(f'{target.name} {target.zrecs} ->')
215
+ found=replace_if_greater(zr,target.zrecs,matchattr=['resid','atom'],maxattr=['z'])
216
+ if not found: target.zrecs.append(zr)
217
+ logger.debug(f'-> {target.name} {target.zrecs}')
218
+
219
+ def determine_sequence(self,moldict):
220
+ """determine_sequence recursively determine the sequence of a molecule using the network of reactions that must be executed to generate it from primitives
221
+
222
+ :param moldict: dictionary of available molecules
223
+ :type moldict: dict
224
+ :return: list of resnames in order of sequence
225
+ :rtype: list
226
+ """
227
+ if not self.generator: return [self.parentname]
228
+ R:Reaction=self.generator
229
+ thisseq=[]
230
+ for rid,rname in R.reactants.items():
231
+ parentname=moldict[rname].parentname
232
+ thisseq.extend(moldict[parentname].determine_sequence(moldict))
233
+ # logger.debug(thisseq)
234
+ return thisseq
235
+
236
+ def set_sequence_from_moldict(self,moldict):
237
+ """set_sequence_from_moldict set the sequence of this molecule using the recursive determine_sequence method
238
+
239
+ :param moldict: dictionary of available molecules
240
+ :type moldict: dict
241
+ :return: self
242
+ :rtype: Molecule
243
+ """
244
+ self.sequence=self.determine_sequence(moldict)
245
+ return self
246
+
247
+ def set_sequence_from_coordinates(self):
248
+ """set_sequence Establish the sequence-list (residue names in order) based on resNum attributes in atom list
249
+ """
250
+ adf=self.TopoCoord.gro_DataFrame('atoms')
251
+ trial_sequence=[]
252
+ current_resid=0
253
+ for i,r in adf.iterrows():
254
+ ri=r['resNum']
255
+ rn=r['resName']
256
+ if ri!=current_resid:
257
+ current_resid=ri
258
+ trial_sequence.append(rn)
259
+ assert trial_sequence==self.sequence,f'trial {trial_sequence} seq {self.sequence}'
260
+ return self
261
+
262
+ def create_new_stereoisomers(self):
263
+ """create_new_stereoisomers generate new molecules to hold stereoisomers of self
264
+
265
+ :return: None if no action taken
266
+ :rtype: none
267
+ """
268
+ if self.generator: return # we only consider stereoisomers on monomers
269
+ if not self.stereocenters: return
270
+ basename=self.name+'-S'
271
+ b=[[0,1] for _ in range(len(self.stereocenters))]
272
+ sseq=product(*b)
273
+ next(sseq) # skip the unmodified; it's the base molecule
274
+ for x in sseq:
275
+ s=''.join([str(_) for _ in x])
276
+ mname=f'{basename}{s}'
277
+ self.stereoisomers[mname]=Molecule.New(mname,None)
278
+ self.stereoisomers[mname].parentname=self.name
279
+
280
+ def initialize_molecule_cycles(self):
281
+ """initialize_molecule_cycles assigns cycle indexes to all atoms
282
+ """
283
+ TC=self.TopoCoord
284
+ TC.idx_lists['cycle']=[]
285
+ cycle_dict=TC.Topology.detect_cycles()
286
+ for l,cs_of_l in cycle_dict.items():
287
+ TC.idx_lists['cycle'].extend(cs_of_l)
288
+ logger.debug('Resetting cycle and cycle_idx')
289
+ TC.reset_grx_attributes_from_idx_list('cycle')
290
+ logger.debug('Done')
291
+
292
+ def initialize_monomer_grx_attributes(self):
293
+ """initialize_monomer_grx_attributes initializes all GRX attributes of atoms in molecule
294
+ """
295
+ logger.debug(f'{self.name}')
296
+ TC=self.TopoCoord
297
+ TC.set_gro_attribute('z',0)
298
+ TC.set_gro_attribute('nreactions',0)
299
+ TC.set_gro_attribute('molecule',1)
300
+ TC.set_gro_attribute('molecule_name',self.name)
301
+ for att in ['sea_idx','chain','chain_idx','cycle','cycle_idx']:
302
+ TC.set_gro_attribute(att,-1)
303
+ # set symmetry class indices
304
+ sea_idx=1
305
+ logger.debug(f'{self.name}: symmetry_relateds {self.symmetry_relateds}')
306
+ for s in self.symmetry_relateds:
307
+ # logger.debug(f'sea_idx {sea_idx} set for set {s}')
308
+ for atomName in s:
309
+ # logger.debug(f'{atomName} {sea_idx}')
310
+ TC.set_gro_attribute_by_attributes('sea_idx',sea_idx,{'atomName':atomName})
311
+ sea_idx+=1
312
+ # set z and nreactions
313
+ idx=[]
314
+ for zr in self.zrecs:
315
+ an=zr['atom']
316
+ rnum=zr['resid']
317
+ if rnum!=1: continue
318
+ z=zr['z']
319
+ logger.debug(f'{self.name} setting z for {an} {rnum} {z}')
320
+ TC.set_gro_attribute_by_attributes('z',z,{'atomName':an,'resNum':rnum})
321
+ idx.append(TC.get_gro_attribute_by_attributes('globalIdx',{'atomName':an,'resNum':rnum}))
322
+ for sr in self.symmetry_relateds:
323
+ # logger.debug(f'{self.name}: setting z for {an}, considering sr {sr}')
324
+ if an in sr:
325
+ for bn in sr:
326
+ if bn==an: continue
327
+ # logger.debug(f'{self.name}: setting z for {bn}')
328
+ idx.append(TC.get_gro_attribute_by_attributes('globalIdx',{'atomName':bn,'resNum':rnum}))
329
+ TC.set_gro_attribute_by_attributes('z',z,{'atomName':bn,'resNum':rnum})
330
+
331
+ # set chain, chain_idx
332
+ TC.idx_lists['chain']=[]
333
+ pairs=product(idx,idx)
334
+ for i,j in pairs:
335
+ if i<j:
336
+ iname=TC.get_gro_attribute_by_attributes('atomName',{'globalIdx':i})
337
+ jname=TC.get_gro_attribute_by_attributes('atomName',{'globalIdx':j})
338
+ if TC.are_bonded(i,j) and iname.startswith('C') and jname.startswith('C'):
339
+ # this monomer has two carbon atoms capable of reacting
340
+ # that are bound to each other -- this means that
341
+ # the two originated as a double-bond.
342
+ # *If* there is one with three hydrogens
343
+ # (remember this is an activated monomer)
344
+ # then it is the "tail"; the other is the "head".
345
+ i_nH=TC.count_H(i)
346
+ j_nH=TC.count_H(j)
347
+ if i_nH==3 and j_nH!=3:
348
+ # i is the tail
349
+ entry=[j,i]
350
+ elif i_nH!=3 and j_nH==3:
351
+ # j is the tail
352
+ entry=[i,j]
353
+ else:
354
+ logger.warning(f'In molecule {self.name}, cannot identify bonded reactive head and tail atoms\nAssuming {j} is head and {i} is tail')
355
+ entry=[j,i]
356
+ # logger.debug(f'Adding {entry} to chainlist of {self.name}')
357
+ TC.idx_lists['chain'].append(entry)
358
+ TC.reset_grx_attributes_from_idx_list('chain')
359
+ # set cycle, cycle_idx
360
+ self.initialize_molecule_cycles()
361
+
362
+ def previously_parameterized(self):
363
+ """previously_parameterized if a gro file exists in the project molecule/parameterized directory for this molecule, return True
364
+
365
+ :return: True if gro file found
366
+ :rtype: bool
367
+ """
368
+ rval=True
369
+ for ext in ['gro']:
370
+ rval=rval and pfs.exists(os.path.join('molecules/parameterized',f'{self.name}.{ext}'))
371
+ return rval
372
+
373
+ def parameterize(self,outname='',input_structure_format='mol2',**kwargs):
374
+ """parameterize manages GAFF parameterization of this molecule
375
+
376
+ :param outname: output file basename, defaults to ''
377
+ :type outname: str, optional
378
+ :param input_structure_format: input structure format, defaults to 'mol2' ('pdb' is other possibility)
379
+ :type input_structure_format: str, optional
380
+ """
381
+ assert os.path.exists(f'{self.name}.{input_structure_format}'),f'Cannot parameterize molecule {self.name} without {self.name}.{input_structure_format} as input'
382
+ if outname=='':
383
+ outname=f'{self.name}'
384
+ GAFFParameterize(self.name,outname,input_structure_format=input_structure_format,**kwargs)
385
+ self.load_top_gro(f'{outname}.top',f'{outname}.gro',mol2filename=f'{outname}.mol2',wrap_coords=False)
386
+
387
+ def minimize(self,outname='',**kwargs):
388
+ """minimize manages invocation of vacuum minimization
389
+
390
+ :param outname: output file basename, defaults to ''
391
+ :type outname: str, optional
392
+ """
393
+ if outname=='':
394
+ outname=f'{self.name}'
395
+ self.TopoCoord.vacuum_minimize(outname,**kwargs)
396
+
397
+ def relax(self,relax_dict):
398
+ """relax manages invocation of MD relaxations
399
+
400
+ :param relax_dict: dictionary of simulation directives
401
+ :type relax_dict: dict
402
+ """
403
+ deffnm=relax_dict.get('deffnm',f'{self.name}-relax')
404
+ nsteps=relax_dict.get('nsteps',10000)
405
+ temperature=relax_dict.get('temperature',10000)
406
+ n=self.name
407
+ boxsize=np.array(self.TopoCoord.maxspan())+2*np.ones(3)
408
+ self.center_coords(new_boxsize=boxsize)
409
+ mdp_prefix='single-molecule-nvt'
410
+ pfs.checkout(f'mdp/{mdp_prefix}.mdp')
411
+ mdp_modify(f'{mdp_prefix}.mdp',{'nsteps':nsteps,'gen-vel':'yes','ref_t':temperature,'gen-temp':temperature})
412
+ logger.info(f'In vacuo equilibration of {self.name}.gro for {nsteps} steps at {temperature} K')
413
+ self.TopoCoord.grompp_and_mdrun(out=deffnm,mdp=mdp_prefix,boxSize=boxsize)
414
+
415
+ def center_coords(self,new_boxsize:np.ndarray=None):
416
+ """center_coords wrapper for the TopoCoord.center_coords method
417
+
418
+ :param new_boxsize: new box size, defaults to None
419
+ :type new_boxsize: np.ndarray, optional
420
+ """
421
+ self.TopoCoord.center_coords(new_boxsize)
422
+
423
+ def generate(self,outname='',available_molecules={},**kwargs):
424
+ """generate manages generating topology and coordinates for self
425
+
426
+ :param outname: output file basename, defaults to ''
427
+ :type outname: str, optional
428
+ :param available_molecules: dictionary of available molecules, defaults to {}
429
+ :type available_molecules: dict, optional
430
+ """
431
+ logger.debug(f'{self.name}.generate() begins')
432
+ if outname=='': outname=f'{self.name}'
433
+ do_minimization=True
434
+ GAFF_dict=kwargs.get('GAFF',{})
435
+ if GAFF_dict: do_minimization=GAFF_dict.get('minimize_molecules',True)
436
+ do_parameterization=False
437
+ if self.generator:
438
+ R=self.generator
439
+ if R.stage in [reaction_stage.cure,reaction_stage.param,reaction_stage.cap]: do_parameterization=True
440
+ self.TopoCoord=TopoCoord()
441
+ logger.debug(f'Using reaction {R.name} ({str(R.stage)}) to generate {self.name} parent {self.parentname}')
442
+ isf='mol2'
443
+ resid_mapper=[]
444
+ for ri in R.reactants.values():
445
+ logger.debug(f'Adding {ri}')
446
+ new_reactant=deepcopy(available_molecules[ri])
447
+ new_reactant.TopoCoord.write_mol2(filename=f'{self.name}-reactant{ri}-prebonding.mol2',molname=self.name)
448
+ rnr=len(new_reactant.sequence)
449
+ shifts=self.TopoCoord.merge(new_reactant.TopoCoord)
450
+ # for ln in self.TopoCoord.Coordinates.A.head().to_string().split('\n'): logger.debug(ln)
451
+ resid_mapper.append({k:v for k,v in zip(range(1,rnr+1),range(1+shifts[2],1+rnr+shifts[2]))})
452
+ # logger.debug(f'{self.name}: resid_mapper {resid_mapper}')
453
+ # logger.debug(f'{self.TopoCoord.idx_lists}')
454
+ # logger.debug(f'\n{self.TopoCoord.Coordinates.A.to_string()}')
455
+ # logger.debug(f'composite prebonded molecule in box {self.TopoCoord.Coordinates.box}')
456
+ self.TopoCoord.write_mol2(filename=f'{self.name}-prebonding.mol2',molname=self.name)
457
+ self.set_sequence_from_coordinates()
458
+ # bonds_to_make=list(yield_bonds(R,self.TopoCoord,resid_mapper))
459
+ bdf=yield_bonds_as_df(R,self.TopoCoord,resid_mapper)
460
+ # logger.debug(f'Generation of {self.name}: composite molecule has {len(self.sequence)} resids')
461
+ # logger.debug(f'generation of {self.name}: composite molecule:\n{composite_mol.TopoCoord.Coordinates.A.to_string()}')
462
+ self.make_bonds(bdf,available_molecules,R.stage)
463
+ # self.TopoCoord.set_gro_attribute('reactantName',R.product)
464
+ self.TopoCoord.set_gro_attribute('sea_idx',-1) # turn off symmetry-equivalence for multimers
465
+ self.TopoCoord.set_gro_attribute('molecule',1)
466
+ self.TopoCoord.set_gro_attribute('molecule_name',self.name)
467
+ self.write_gro_attributes(GRX_ATTRIBUTES,f'{R.product}.grx')
468
+ # if pfs.exists(f'molecules/inputs/{self.name}.mol2'): # an override structure is present
469
+ # logger.debug(f'Using override input molecules/inputs/{self.name}.{isf} as a generator')
470
+ # pfs.checkout(f'molecules/inputs/{self.name}.{isf}')
471
+ # else:
472
+ self.TopoCoord.write_mol2(filename=f'{self.name}.mol2',molname=self.name)
473
+ if not do_parameterization:
474
+ self.TopoCoord.write_gro(f'{self.name}.gro',grotitle=self.name)
475
+ self.TopoCoord.write_top(f'{self.name}.top')
476
+ # if pfs.exists(f'molecules/inputs/{self.name}.pdb'): # an override structure is present
477
+ # isf='pdb'
478
+ # logger.debug(f'Using override input molecules/inputs/{self.name}.{isf} as a generator')
479
+ # pfs.checkout(f'molecules/inputs/{self.name}.{isf}')
480
+ else:
481
+ # this molecule was not assigned a generator: implies it is a monomer and must have a parameterization
482
+ input_structure_formats=['mol2','pdb']
483
+ isf=None
484
+ for isf in input_structure_formats:
485
+ if pfs.exists(f'molecules/inputs/{self.name}.{isf}'):
486
+ logger.debug(f'Using input molecules/inputs/{self.name}.{isf} as a generator')
487
+ pfs.checkout(f'molecules/inputs/{self.name}.{isf}')
488
+ break
489
+ assert isf,'Error: no valid input structure file found'
490
+ do_parameterization=True
491
+
492
+ reactantName=self.name
493
+ if do_parameterization:
494
+ self.parameterize(outname,input_structure_format=isf,**kwargs)
495
+ else:
496
+ if self.name!=self.parentname:
497
+ logger.info(f'Built {self.name} using topology of {self.parentname}; copying {self.parentname}.top to {self.name}.top')
498
+ self.load_top_gro(f'{self.parentname}.top',f'{self.name}.gro',wrap_coords=False)
499
+ shutil.copy(f'{self.parentname}.top',f'{self.name}.top')
500
+ shutil.copy(f'{self.parentname}.grx',f'{self.name}.grx')
501
+
502
+ if do_minimization:
503
+ self.minimize(outname,**kwargs)
504
+ self.set_sequence_from_coordinates()
505
+ if not self.generator:
506
+ self.TopoCoord.set_gro_attribute('reactantName',reactantName)
507
+ self.initialize_monomer_grx_attributes()
508
+ self.write_gro_attributes(GRX_ATTRIBUTES,f'{reactantName}.grx')
509
+ else:
510
+ if do_parameterization or self.name!=self.parentname:
511
+ grx=f'{reactantName}.grx'
512
+ if (os.path.exists(grx)):
513
+ self.TopoCoord.read_gro_attributes(grx)
514
+ #self.reset_chains_from_attributes()
515
+ # logger.debug(f'{self.name} gro\n{self.TopoCoord.Coordinates.A.to_string()}')
516
+ self.prepare_new_bonds(available_molecules=available_molecules)
517
+ # for ln in self.TopoCoord.Coordinates.A.head().to_string().split('\n'): logger.debug(ln)
518
+ logger.info(f'{self.name}: {self.get_molecular_weight():.2f} g/mol')
519
+ logger.debug('Done.')
520
+
521
+ def get_molecular_weight(self):
522
+ """get_molecular_weight returns the molecular weight of self
523
+
524
+ :return: _description_
525
+ :rtype: _type_
526
+ """
527
+ mass=self.TopoCoord.total_mass(units='gromacs') # g
528
+ return mass
529
+
530
+ def prepare_new_bonds(self,available_molecules={}):
531
+ """prepare_new_bonds populates the bond templates and reaction bonds for self
532
+
533
+ :param available_molecules: dictionary of available molecules, defaults to {}
534
+ :type available_molecules: dict, optional
535
+ """
536
+ # logger.debug(f'set_reaction_bonds: molecules {list(available_molecules.keys())}')
537
+ R=self.generator
538
+ if not R:
539
+ return
540
+ self.reaction_bonds=[]
541
+ self.bond_templates=[]
542
+ TC=self.TopoCoord
543
+ # logger.debug(f'prepare_new_bonds {self.name}: chainlists {TC.idx_lists["chain"]}')
544
+ for bondrec in R.bonds:
545
+ atom_keys=bondrec['atoms']
546
+ order=bondrec['order']
547
+ assert len(atom_keys)==2
548
+ atomrecs=[R.atoms[x] for x in atom_keys]
549
+ atom_names=[x['atom'] for x in atomrecs]
550
+ reactant_keys=[x['reactant'] for x in atomrecs]
551
+ in_reactant_resids=[x['resid'] for x in atomrecs]
552
+ if reactant_keys[0]==reactant_keys[1]: # this is an intraresidue bond
553
+ reactant_names=[R.reactants[reactant_keys[0]]]
554
+ else:
555
+ reactant_names=[R.reactants[x] for x in reactant_keys]
556
+ reactant_sequences=[available_molecules[x].sequence for x in reactant_names]
557
+ product_sequence=[]
558
+ for seq in reactant_sequences:
559
+ product_sequence.extend(seq)
560
+ # logger.debug(f'product_sequence {product_sequence}')
561
+ sequence_residue_idx_origins=[0,0]
562
+ if len(reactant_sequences)==2:
563
+ sequence_residue_idx_origins[1]=len(reactant_sequences[0])
564
+ in_product_resids=[in_reactant_resids[x]+sequence_residue_idx_origins[x] for x in [0,1]]
565
+ # logger.debug(f'in_product_resids {in_product_resids}')
566
+ in_product_resnames=[product_sequence[in_product_resids[x]-1] for x in [0,1]]
567
+ atom_idx=[TC.get_gro_attribute_by_attributes('globalIdx',{'resNum':in_product_resids[x],'atomName':atom_names[x]}) for x in [0,1]]
568
+ # logger.debug(f'{R.name} names {atom_names} in_product_resids {in_product_resids} idx {atom_idx}')
569
+ bystander_resids,bystander_resnames,bystander_atomidx,bystander_atomnames=TC.get_bystanders(atom_idx)
570
+ oneaway_resids,oneaway_resnames,oneaway_atomidx,oneaway_atomnames=TC.get_oneaways(atom_idx)
571
+ # logger.debug(f'{self.name} bystanders {bystander_resids} {bystander_resnames} {bystander_atomidx} {bystander_atomnames}')
572
+ # logger.debug(f'{self.name} oneaways {oneaway_resids} {oneaway_resnames} {oneaway_atomidx} {oneaway_atomnames}')
573
+ self.reaction_bonds.append(ReactionBond(atom_idx,in_product_resids,order,bystander_resids,bystander_atomidx,oneaway_resids,oneaway_atomidx))
574
+ intraresidue=in_product_resids[0]==in_product_resids[1]
575
+ self.bond_templates.append(BondTemplate(atom_names,in_product_resnames,intraresidue,order,bystander_resnames,bystander_atomnames,oneaway_resnames,oneaway_atomnames))
576
+
577
+ def idx_mappers(self,otherTC:TopoCoord,other_bond,bystanders,oneaways,uniq_atom_idx:set):
578
+ """idx_mappers computes the mapping dictionary from molecule template index to instance index in the other TopoCoord
579
+
580
+ :param otherTC: the other TopoCoord
581
+ :type otherTC: TopoCoord
582
+ :param other_bond: 2 atom indices of the bond in the other TopoCoord
583
+ :type other_bond: list-like container of length 2
584
+ :param bystanders: bystander lists, one for each reacting atom
585
+ :type bystanders: lists
586
+ :param oneaways: oneaways, one for each atom in the bond
587
+ :type oneaways: list (2)
588
+ :param uniq_atom_idx: set of unique atoms in template that must be mapped to instance
589
+ :type uniq_atom_idx: set
590
+ :raises Exception: if there is a buggy double-counting of one or more indexes
591
+ :return: two-way dictionaries of index mappers instance<->template
592
+ :rtype: tuple of two dictionaries
593
+ """
594
+ assert len(other_bond)==2
595
+ assert len(bystanders)==2
596
+ assert len(oneaways)==2
597
+ ut=uniq_atom_idx.copy()
598
+ logger.debug(f'Template name {self.name}')
599
+ i_idx,j_idx=other_bond
600
+ i_resName,i_resNum,i_atomName=otherTC.get_gro_attribute_by_attributes(['resName','resNum','atomName'],{'globalIdx':i_idx})
601
+ j_resName,j_resNum,j_atomName=otherTC.get_gro_attribute_by_attributes(['resName','resNum','atomName'],{'globalIdx':j_idx})
602
+ logger.debug(f'i_idx {i_idx} i_resName {i_resName} i_resNum {i_resNum} i_atomName {i_atomName}')
603
+ logger.debug(f'j_idx {j_idx} j_resName {j_resName} j_resNum {j_resNum} j_atomName {j_atomName}')
604
+ # identify the template bond represented by the other_bond parameter
605
+ ij=[]
606
+ for RB,BT in zip(self.reaction_bonds,self.bond_templates):
607
+ temp_resids=RB.resids
608
+ temp_iname,temp_jname=BT.names
609
+ temp_iresname,temp_jresname=BT.resnames
610
+ temp_bystander_resids=RB.bystander_resids
611
+ temp_oneaway_resids=RB.oneaway_resids
612
+ # logger.debug(f'temp_iresname {temp_iresname} temp_iname {temp_iname}')
613
+ # logger.debug(f'temp_jresname {temp_jresname} temp_jname {temp_jname}')
614
+ if (i_atomName,i_resName)==(temp_iname,temp_iresname):
615
+ ij=[0,1]
616
+ break # found it -- stop looking
617
+ elif (i_atomName,i_resName)==(temp_jname,temp_jresname):
618
+ ij=[1,0]
619
+ break
620
+ assert len(ij)==2,f'Mappers using template {self.name} unable to map from instance bond {i_resName}-{i_resNum}-{i_atomName}---{j_resName}-{j_resNum}-{j_atomName}'
621
+ inst_resids=[i_resNum,j_resNum]
622
+ inst_resids=[inst_resids[ij[x]] for x in [0,1]]
623
+ inst_bystander_resids=[bystanders[ij[x]] for x in [0,1]]
624
+ inst_oneaway_resids=[oneaways[ij[x]] for x in [0,1]]
625
+ assert all([len(inst_bystander_resids[x])==len(temp_bystander_resids[x]) for x in [0,1]]),f'Error: bystander count mismatch'
626
+ # use dataframe merges to create globalIdx maps
627
+ instdf=otherTC.Coordinates.A
628
+ tempdf=self.TopoCoord.Coordinates.A
629
+ inst2temp={}
630
+ temp2inst={}
631
+ # logger.debug(f'inst resids from {[i_resNum,j_resNum,*inst_bystanders]}')
632
+ # logger.debug(f'temp resids from {[temp_iresid,temp_jresid,*temp_bystanders]}')
633
+ for inst,temp in zip([*inst_resids,*inst_bystander_resids[0],*inst_bystander_resids[1],*inst_oneaway_resids],
634
+ [*temp_resids,*temp_bystander_resids[0],*temp_bystander_resids[1],*temp_oneaway_resids]):
635
+ if inst and temp: # None's in the bystander lists and oneaways lists should be ignored
636
+ logger.debug(f'map inst resid {inst} to template resid {temp}')
637
+ idf=instdf[instdf['resNum']==inst][['globalIdx','atomName']].copy()
638
+ # logger.debug(f'idf res {inst}:\n{idf.to_string()}')
639
+ tdf=tempdf[tempdf['resNum']==temp][['globalIdx','atomName']].copy()
640
+ # logger.debug(f'tdf res {temp}:\n{tdf.to_string()}')
641
+ tdf=tdf.merge(idf,on='atomName',how='inner',suffixes=('_template','_instance'))
642
+ # logger.debug(f'merged\n{tdf.to_string()}')
643
+ for i,r in tdf.iterrows():
644
+ temp_idx=r['globalIdx_template']
645
+ inst_idx=r['globalIdx_instance']
646
+ # logger.debug(f't {temp_idx} <-> i {inst_idx}')
647
+ # only map template atoms that are identified in the passed in set
648
+ if temp_idx in ut:
649
+ ut.remove(temp_idx)
650
+ temp2inst[temp_idx]=inst_idx
651
+ inst2temp[inst_idx]=temp_idx
652
+ if temp_idx in temp2inst and temp2inst[temp_idx]!=inst_idx:
653
+ raise Exception(f'Error: temp_idx {temp_idx} already claimed in temp2inst; bug')
654
+ assert len(inst2temp)==len(temp2inst),f'Error: could not establish two-way dict of atom globalIdx'
655
+ return (inst2temp,temp2inst)
656
+
657
+ def get_angles_dihedrals(self,bond):
658
+ """get_angles_dihedrals returns copies of selections from the Topology interaction-type dataframes that contain the two atoms indicated in the bond
659
+
660
+ :param bond: 2-element list-like container of ints
661
+ :type bond: list-like container
662
+ :raises Exception: dies if a NaN is found in any selection
663
+ :return: tuple of the three dataframe selection copies for angles, dihedrals, and 1-4 pairs
664
+ :rtype: tuple
665
+ """
666
+ ai,aj=bond
667
+ d=self.TopoCoord.Topology.D['angles']
668
+ ad=d[((d.ai==ai)&(d.aj==aj))|
669
+ ((d.ai==aj)&(d.aj==ai))|
670
+ ((d.aj==ai)&(d.ak==aj))|
671
+ ((d.aj==aj)&(d.ak==ai))].copy()
672
+ d=self.TopoCoord.Topology.D['dihedrals']
673
+ td=d[((d.ai==ai)&(d.aj==aj))|
674
+ ((d.ai==aj)&(d.aj==ai))|
675
+ ((d.aj==ai)&(d.ak==aj))|
676
+ ((d.aj==aj)&(d.ak==ai))|
677
+ ((d.ak==ai)&(d.al==aj))|
678
+ ((d.ak==aj)&(d.al==ai))].copy()
679
+ check=True
680
+ for a in ['ai','aj','ak','al']:
681
+ check=check and td[a].isnull().values.any()
682
+ if check:
683
+ logger.error('NAN in molecule/dihedrals')
684
+ raise Exception
685
+
686
+ d=self.TopoCoord.Topology.D['pairs']
687
+ paird=pd.DataFrame()
688
+ for ai,al in zip(td.ai,td.al):
689
+ tpair=d[((d.ai==ai)&(d.aj==al))|
690
+ ((d.ai==al)&(d.aj==ai))].copy()
691
+ paird=pd.concat((paird,tpair),ignore_index=True)
692
+ check=True
693
+ for a in ['ai','aj']:
694
+ check=check and paird[a].isnull().values.any()
695
+ if check:
696
+ logger.error('NAN in molecule/pairs')
697
+ raise Exception
698
+ return ad,td,paird
699
+
700
+ def get_resname(self,internal_resid):
701
+ """get_resname returns the residue name at position internal_resid in the molecule's sequence
702
+
703
+ :param internal_resid: molecule-internal residue index
704
+ :type internal_resid: int
705
+ :return: residue name
706
+ :rtype: str
707
+ """
708
+ return self.sequence[internal_resid-1]
709
+
710
+ # def inherit_attribute_from_reactants(self,attribute,available_molecules,increment=True,no_increment_if_negative=True):
711
+ # """inherit_attribute_from_reactants populate certain atom attributes in molecule from its constituent reactants
712
+
713
+ # :param attribute: _description_
714
+ # :type attribute: _type_
715
+ # :param available_molecules: _description_
716
+ # :type available_molecules: _type_
717
+ # :param increment: _description_, defaults to True
718
+ # :type increment: bool, optional
719
+ # :param no_increment_if_negative: _description_, defaults to True
720
+ # :type no_increment_if_negative: bool, optional
721
+ # """
722
+ # adf=self.TopoCoord.Coordinates.A
723
+ # ordered_attribute_idx=[]
724
+ # curr_max=0
725
+ # # logger.debug(f'{self.name}({adf.shape[0]}) inheriting {attribute} from {self.sequence}')
726
+ # # logger.debug(f'available molecules {list(available_molecules.keys())}')
727
+ # for i,r in enumerate(self.sequence):
728
+ # '''
729
+ # for this residue number, read the list of unique atom names
730
+ # '''
731
+ # namesinres=list(adf[adf['resNum']==(i+1)]['atomName'])
732
+ # '''
733
+ # access coordinates of standalone residue template with this name 'r' on the list of available molecules
734
+ # '''
735
+ # rdf=available_molecules[r].TopoCoord.Coordinates.A
736
+ # '''
737
+ # get the attribute values from residue template
738
+ # '''
739
+ # x=list(rdf[rdf['atomName'].isin(namesinres)][attribute])
740
+ # # logger.debug(f'{r}->{len(x)}')
741
+ # '''
742
+ # increment these attribute value based on residue number in this molecule
743
+ # '''
744
+ # if increment:
745
+ # i_x=[]
746
+ # for y in x:
747
+ # if y>0 or (y<0 and not no_increment_if_negative):
748
+ # i_x.append(y+curr_max)
749
+ # else:
750
+ # i_x.append(y)
751
+ # curr_max=max(i_x)
752
+ # ordered_attribute_idx.extend(i_x)
753
+ # assert len(ordered_attribute_idx)==adf.shape[0]
754
+ # adf[attribute]=ordered_attribute_idx
755
+
756
+ def merge(self,other):
757
+ """merge merges TopoCoord from other into self's TopoCoord
758
+
759
+ :param other: another Molecule
760
+ :type other: Molecule
761
+ :return: a shift tuple (returned by Coordinates.merge())
762
+ :rtype: tuple
763
+ """
764
+ shifts=self.TopoCoord.merge(other.TopoCoord)
765
+ return shifts
766
+
767
+ def load_top_gro(self,topfilename,grofilename,mol2filename='',**kwargs):
768
+ """load_top_gro generate a new TopoCoord member object for this molecule by reading in a Gromacs topology file and a Gromacs gro file
769
+
770
+ :param topfilename: Gromacs topology file
771
+ :type topfilename: str
772
+ :param grofilename: Gromacs gro file
773
+ :type grofilename: str
774
+ :param mol2filename: alternative coordinate mol2 file, defaults to ''
775
+ :type mol2filename: str, optional
776
+ """
777
+ self.TopoCoord=TopoCoord(topfilename=topfilename,grofilename=grofilename,mol2filename=mol2filename,**kwargs)
778
+
779
+ def set_gro_attribute(self,attribute,srs):
780
+ """set_gro_attribute sets attribute of atoms to srs (drillst through to Coordinates.set_atomset_attributes())
781
+
782
+ :param attribute: name of attribute
783
+ :type attribute: str
784
+ :param srs: scalar or list-like attribute values in same ordering as self.A
785
+ :type srs: scalar or list-like
786
+ """
787
+ self.TopoCoord.set_gro_attribute(attribute,srs)
788
+
789
+ def read_gro_attributes(self,grxfilename,attribute_list=[]):
790
+ """Read attributes from file into self.TopoCoord.Coordinates.A
791
+
792
+ :param grxfilename: name of input file
793
+ :type grxfilename: str
794
+ :param attribute_list: list of attributes to take, defaults to [] (take all)
795
+ :type attribute_list: list, optional
796
+ """
797
+ self.TopoCoord.read_gro_attributes(grxfilename,attribute_list=attribute_list)
798
+
799
+ def write_gro_attributes(self,attribute_list,grxfilename):
800
+ """Writes atomic attributes to a file
801
+
802
+ :param attributes_list: list of attributes to write
803
+ :type attributes_list: list
804
+ :param grxfilename: name of output file
805
+ :type grxfilename: str
806
+ """
807
+ self.TopoCoord.write_gro_attributes(attribute_list,grxfilename)
808
+
809
+ def make_bonds(self,bdf:pd.DataFrame,moldict,stage):
810
+ """make_bonds adds new bonds to the molecule's topology and deletes any sacrificial hydrogens
811
+
812
+ :param bdf: pandas dataframe identifying new bonds
813
+ :type bdf: pd.DataFrame
814
+ :param moldict: dictionary of available molecular templates
815
+ :type moldict: dict
816
+ :param stage: enumerated parameter indicating reaction_stage
817
+ :type stage: reaction_stage(Enum)
818
+ """
819
+ TC=self.TopoCoord
820
+ explicit_sacrificial_Hs={}
821
+ for i,r in bdf.iterrows():
822
+ aname,bname=[TC.get_gro_attribute_by_attributes('atomName',{'globalIdx':x}) for x in [r.ai,r.rj]]
823
+ logger.debug(f'generating {self.name} bond {r.ri}:{aname}:{r.ai}-{r.rj}:{bname}:{r.aj} order {r.order}')
824
+ if r.ri!=r.rj:
825
+ resid_sets=TC.get_resid_sets([r.ai,r.aj])
826
+ hxi,hxj=self.transrot(r.ai,r.ri,r.aj,r.rj,connected_resids=resid_sets[1])
827
+ explicit_sacrificial_Hs[i]=[hxi,hxj]
828
+ if stage in [reaction_stage.cure, reaction_stage.param, reaction_stage.cap]:
829
+ template_source='ambertools'
830
+ else:
831
+ template_source='internal' # signals that a template molecule should be identified to parameterize this bond
832
+ TC.update_topology_and_coordinates(bdf,moldict,explicit_sacH=explicit_sacrificial_Hs,template_source=template_source)
833
+ self.initialize_molecule_cycles()
834
+
835
+ def transrot(self,at_idx,at_resid,from_idx,from_resid,connected_resids=[]):
836
+ """transrot given a composite molecule, translate and rotate the piece downstream of the yet-to-be created bond specified by (at_idx,at_resid) and (from_idx,from_resid) to minimize steric overlaps and identify the best two sacrificial hydrogens
837
+
838
+ :param at_idx: global index of left-hand atom in new bond
839
+ :type at_idx: int
840
+ :param at_resid: global index of left-hand residue
841
+ :type at_resid: int
842
+ :param from_idx: global index of right-hand atom in new
843
+ :type from_idx: int
844
+ :param from_resid: global index of right-hand residue
845
+ :type from_resid: int
846
+ :param connected_resids: list of all other resids attached to right-hand residue that should move with it, defaults to []
847
+ :type connected_resids: list, optional
848
+ :return: 2-tuple containing global indices
849
+ :rtype: tuple
850
+ """
851
+ # Rotate and translate
852
+ if at_resid==from_resid:
853
+ return # should never happen but JIC
854
+ logger.debug(f'{self.name} connected resids {connected_resids}')
855
+ TC=self.TopoCoord
856
+ ATC=TopoCoord()
857
+ BTC=TopoCoord()
858
+ C=TC.gro_DataFrame('atoms')
859
+ ATC.Coordinates.A=C[C['resNum']==at_resid].copy()
860
+ bresids=connected_resids.copy()
861
+ bresids.append(from_resid)
862
+ BTC.Coordinates.A=C[C['resNum'].isin(bresids)].copy()
863
+ for ln in BTC.Coordinates.A.to_string().split('\n'): logger.debug(ln)
864
+ NONROT=C[~C['resNum'].isin(bresids)].shape[0]
865
+ logger.debug(f'{self.TopoCoord.Coordinates.A.shape[0]} atoms')
866
+ logger.debug(f'holding {at_resid} ({NONROT})')
867
+ logger.debug(f'rotating/translating {bresids} ({BTC.Coordinates.A.shape[0]})')
868
+ assert self.TopoCoord.Coordinates.A.shape[0]==(NONROT+BTC.Coordinates.A.shape[0])
869
+ mypartners=TC.partners_of(at_idx)
870
+ otpartners=TC.partners_of(from_idx)
871
+ logger.debug(f'Partners of {at_idx} {mypartners}')
872
+ logger.debug(f'Partners of {from_idx} {otpartners}')
873
+ myHpartners={k:v for k,v in zip(mypartners,[C[C['globalIdx']==i]['atomName'].values[0] for i in mypartners]) if v.startswith('H')}
874
+ otHpartners={k:v for k,v in zip(otpartners,[C[C['globalIdx']==i]['atomName'].values[0] for i in otpartners]) if v.startswith('H')}
875
+ myHighestH={k:v for k,v in myHpartners.items() if v==max([k for k in myHpartners.values()],key=lambda x: int(x.split('H')[1] if x.split('H')[1]!='' else '0'))}
876
+ otHighestH={k:v for k,v in otHpartners.items() if v==max([k for k in otHpartners.values()],key=lambda x: int(x.split('H')[1] if x.split('H')[1]!='' else '0'))}
877
+ assert len(myHighestH)==1
878
+ assert len(otHighestH)==1
879
+ logger.debug(f'Highest-named H partner of {at_idx} is {myHighestH}')
880
+ logger.debug(f'Highest-named H partner of {from_idx} is {otHighestH}')
881
+ assert len(myHpartners)>0,f'Error: atom {at_idx} does not have a deletable H atom!'
882
+ assert len(otHpartners)>0,f'Error: atom {from_idx} does not have a deletable H atom!'
883
+
884
+ Ri=TC.get_R(at_idx)
885
+ Rj=TC.get_R(from_idx)
886
+ overall_maximum=(-1.e9,-1,-1)
887
+ coord_trials={}
888
+ for myH,myHnm in myHpartners.items(): # keys are globalIdx's, values are names
889
+ coord_trials[myH]:dict[TopoCoord]={}
890
+ Rh=TC.get_R(myH)
891
+ Rih=Ri-Rh
892
+ Rih*=1.0/np.linalg.norm(Rih)
893
+ for otH,otHnm in otHpartners.items():
894
+ # logger.debug(f'{self.name}: Considering {myH} {otH}')
895
+ coord_trials[myH][otH]=deepcopy(BTC)
896
+ # logger.debug(f'\n{coord_trials[myH][otH].Coordinates.A.to_string()}')
897
+ Rk=coord_trials[myH][otH].get_R(otH)
898
+ # logger.debug(f'{self.name}: otH {otH} Rk {Rk}')
899
+ Rkj=Rk-Rj
900
+ Rkj*=1.0/np.linalg.norm(Rkj)
901
+ #Rhk=Rh-Rk
902
+ #rhk=np.linalg.norm(Rhk)
903
+ cp=np.cross(Rkj,Rih)
904
+ c=np.dot(Rkj,Rih)
905
+ v=np.array([[0,-cp[2],cp[1]],[cp[2],0,-cp[0]],[-cp[1],cp[0],0]])
906
+ v2=np.dot(v,v)
907
+ I=np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
908
+ # R is the rotation matrix that will rotate donb to align with accb
909
+ R=I+v+v2/(1.+c)
910
+ # logger.debug(f'{self.name}: R:\n{R}')
911
+ # rotate translate all donor atoms!
912
+ coord_trials[myH][otH].rotate(R)
913
+ Rk=coord_trials[myH][otH].get_R(otH)
914
+ # overlap the two H atoms by translation
915
+ Rik=Rh-Rk
916
+ coord_trials[myH][otH].translate(Rik)
917
+ minD=TC.minimum_distance(coord_trials[myH][otH],self_excludes=[myH],other_excludes=[otH])
918
+ logger.debug(f'{self.name}: minD {minD}')
919
+ if minD>overall_maximum[0]:
920
+ overall_maximum=(minD,myH,otH)
921
+ logger.debug(f'{self.name}: overall_maximum {overall_maximum}')
922
+ minD,myH,otH=overall_maximum
923
+ BTC=coord_trials[myH][otH]
924
+ TC.overwrite_coords(BTC)
925
+ TC.swap_atom_names(myH,list(myHighestH.keys())[0])
926
+ TC.swap_atom_names(otH,list(otHighestH.keys())[0])
927
+ return myH,otH
928
+
929
+ def atoms_w_same_attribute_as(self,find_dict={},same_attribute='',return_attribute=''):
930
+ """atoms_w_same_attribute_as returns a list of atom attributes named in the return_attribute parameter from atoms that share an attribute named in the same_attribute parameter with the atom identified by the find_dict parameter
931
+
932
+ :param find_dict: dictionary of attribute:value pairs that should uniquely identify an atom, defaults to {}
933
+ :type find_dict: dict, optional
934
+ :param same_attribute: name of attribute used to screen atoms, defaults to ''
935
+ :type same_attribute: str, optional
936
+ :param return_attribute: attribute value to return a list of from the screened atoms, defaults to ''
937
+ :type return_attribute: str, optional
938
+ :return: list of attribute values
939
+ :rtype: list
940
+ """
941
+ att_val=self.TopoCoord.get_gro_attribute_by_attributes(same_attribute,find_dict)
942
+ return self.TopoCoord.get_gro_attributelist_by_attributes(return_attribute,{same_attribute:att_val})
943
+
944
+ def flip_stereocenter(self,idx):
945
+ """flip_stereocenter flips stereochemistry of atom at idx
946
+
947
+ :param idx: global index of atom
948
+ :type idx: int
949
+ """
950
+ TC=self.TopoCoord
951
+ A=TC.Coordinates.A
952
+ logger.debug(f'{self.name} flipping on {idx}')
953
+ ligand_idx=self.TopoCoord.Topology.bondlist.partners_of(idx)
954
+ if len(ligand_idx)!=4:
955
+ logger.debug(f'Atom {idx} cannot be a stereocenter; it only has {len(ligand_idx)} ligands.')
956
+ return
957
+ # determine the two lightest ligands
958
+ branches={}
959
+ for n in ligand_idx:
960
+ bl=deepcopy(self.TopoCoord.Topology.bondlist)
961
+ branches[n]=bl.half_as_list([idx,n],3)
962
+ ligand_idx.sort(key=lambda x: len(branches[x]))
963
+ a=ligand_idx[0]
964
+ aset=list(set(list(chain.from_iterable(branches[a]))))
965
+ b=ligand_idx[1]
966
+ bset=list(set(list(chain.from_iterable(branches[b]))))
967
+ # translate origin to location of stereocenter
968
+ O=TC.get_R(idx)
969
+ TC.translate(-1*O)
970
+ rO=TC.get_R(idx)
971
+ ra=TC.get_R(a)
972
+ rb=TC.get_R(b)
973
+ adf=A[A['globalIdx'].isin(aset)]
974
+ bdf=A[A['globalIdx'].isin(bset)]
975
+ # rotate the two branches to swap them
976
+ rOa=rO-ra
977
+ rOa*=1.0/np.linalg.norm(rOa)
978
+ rOb=rO-rb
979
+ rOb*=1.0/np.linalg.norm(rOb)
980
+ cp=np.cross(rOa,rOb)
981
+ c=np.dot(rOa,rOb)
982
+ v=np.array([[0,-cp[2],cp[1]],[cp[2],0,-cp[0]],[-cp[1],cp[0],0]])
983
+ v2=np.dot(v,v)
984
+ I=np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
985
+ R=I+v+v2/(1.+c)
986
+ dfrotate(adf,R)
987
+ A.loc[A['globalIdx'].isin(aset),['posX','posY','posZ']]=adf[['posX','posY','posZ']]
988
+ cp=np.cross(rOb,rOa)
989
+ v=np.array([[0,-cp[2],cp[1]],[cp[2],0,-cp[0]],[-cp[1],cp[0],0]])
990
+ v2=np.dot(v,v)
991
+ R=I+v+v2/(1.+c)
992
+ dfrotate(bdf,R)
993
+ A.loc[A['globalIdx'].isin(bset),['posX','posY','posZ']]=bdf[['posX','posY','posZ']]
994
+ # translate back to original coordinate frame
995
+ TC.translate(O)
996
+
997
+ def rotate_bond(self,a,b,deg):
998
+ """rotate_bond rotates all atoms in molecule on b-side of a-b bond by deg degrees
999
+
1000
+ :param a: index of a
1001
+ :type a: int
1002
+ :param b: index of b
1003
+ :type b: int
1004
+ :param deg: angle of rotation (degrees)
1005
+ :type deg: float
1006
+ """
1007
+ TC=self.TopoCoord
1008
+ A=TC.Coordinates.A
1009
+ branch=TopoCoord()
1010
+ bl=deepcopy(self.TopoCoord.Topology.bondlist)
1011
+ branchidx=bl.half_as_list((a,b),99)
1012
+ ra=TC.get_R(a)
1013
+ rb=TC.get_R(b)
1014
+ Rab=ra-rb
1015
+ rab=Rab/np.linalg.norm(Rab)
1016
+ O=rb
1017
+ TC.translate(-1*O)
1018
+ branch.Coordinates.A=A[A['globalIdx'].isin(branchidx)].copy()
1019
+ # do stuff
1020
+ rx,ry,rz=rab
1021
+ caz=rx/(rx**2+ry**2)**(1/2)
1022
+ saz=ry/(rx**2+ry**2)**(1/2)
1023
+ az=np.acos(caz)
1024
+ if saz<0:
1025
+ az=2*np.pi-az
1026
+ R1=_rotmat(2,az)
1027
+ ay=np.acos(rab/rz) # (must live on 0<ay<pi bc polar angle)
1028
+ R2=_rotmat(1,ay)
1029
+ R3=_rotmat(2,deg/180.*np.pi)
1030
+ R4=_rotmat(1,-ay)
1031
+ R5=_rotmat(2,-az)
1032
+ R=np.matmult(R2,R1)
1033
+ R=np.matmult(R3,R)
1034
+ R=np.matmult(R4,R)
1035
+ R=np.matmult(R5,R)
1036
+ branch.rotate(R)
1037
+ bdf=branch.Coordinates.A
1038
+ A.loc[A['globalIdx'].isin(branchidx),['posX','posY','posZ']]=bdf[['posX','posY','posZ']]
1039
+ TC.translate(O)
1040
+
1041
+ # def sea_of(self,idx):
1042
+ # clu=self.atoms_w_same_attribute_as(find_dict={'globalIdx':idx},
1043
+ # same_attribute='sea_idx',
1044
+ # return_attribute='globalIdx')
1045
+ # return list(clu)
1046
+
1047
+ def generate_stereoisomers(self):
1048
+ """generate_stereoisomers generates list of Molecule shells, one for each stereoisomer
1049
+
1050
+ :return: only returns if no stereoisomers need to be generated
1051
+ :rtype: None
1052
+ """
1053
+ if self.TopoCoord.Topology.D['atoms'].shape[0]==0: return # self has not yet acquired topology/coordinates
1054
+ if len(self.stereoisomers)==0: return
1055
+ flip=[[0,1] for _ in range(len(self.stereocenters))]
1056
+ st_idx=[self.TopoCoord.get_gro_attribute_by_attributes('globalIdx',{'atomName':n}) for n in self.stereocenters]
1057
+ P=product(*flip)
1058
+ next(P) # one with no flips is the original molecule, so skip it
1059
+ for p in P:
1060
+ si_name=self.name+'-S'+''.join([str(_) for _ in p])
1061
+ if not si_name in self.stereoisomers:
1062
+ logger.debug(f'{si_name} not found in dict of stereoisomers of {self.name}')
1063
+ logger.debug(f'Stereocenter sequence {p} generates stereoisomer {si_name}')
1064
+ M=self.stereoisomers[si_name]
1065
+ M.origin=self.origin
1066
+ M.TopoCoord=deepcopy(self.TopoCoord)
1067
+ fsc=[st_idx[i] for i in range(len(self.stereocenters)) if p[i]]
1068
+ for f in fsc:
1069
+ M.flip_stereocenter(f)
1070
+ M.TopoCoord.write_gro(f'{si_name}.gro')
1071
+
1072
+ def generate_conformers(self):
1073
+ """generate_conformers generates this molecule's conformer instances using either gromacs or obabel
1074
+ """
1075
+ # only generates gro files
1076
+ default_gromacs_params={'ensemble': 'nvt', 'temperature': 600, 'ps': 100, 'begin_at': 50}
1077
+ # if self.nconformers==0: return
1078
+ cd=self.conformers_dict
1079
+ if not cd: return
1080
+ logger.debug(f'{self.name} conformer_dict {cd}')
1081
+ self.nconformers=cd['count']
1082
+ minimize=cd.get('minimize',False)
1083
+ generator=cd.get('generator',{})
1084
+ if generator=='obabel' and not minimize:
1085
+ logger.debug(f'Confomers generated by obabel should be energy-minimized. Indicate "mimimize: True" in the confomers directive for {self.name}')
1086
+ minimize=True
1087
+ if not generator: return
1088
+ logger.info(f'Generating {self.nconformers*(1+len(self.stereoisomers))} conformers for {self.name}')
1089
+ gronames=[f'{self.name}']
1090
+ nd=cd.get('nzeros',2)
1091
+ for si in self.stereoisomers:
1092
+ gronames.append(f'{si}')
1093
+ for gro in gronames:
1094
+ pfx=f'{gro}-C'
1095
+ if generator['name']=='obabel':
1096
+ compfile=f'{gro}-obabel-confs.gro'
1097
+ c=Command(f'obabel -igro {gro}.gro -O {compfile} --conformer --nconf {self.nconformers} --writeconformers')
1098
+ out,err=c.run()
1099
+ c=Command(f'wc -l {compfile}')
1100
+ out,err=c.run()
1101
+ tok=out.split()
1102
+ lpf=int(tok[0])//self.nconformers
1103
+ c=Command(f'split -d -n {nd} -l {lpf} {compfile} {pfx} --additional-suffix=".gro"')
1104
+ out,err=c.run()
1105
+ elif generator['name']=='gromacs':
1106
+ params=generator.get('params',default_gromacs_params)
1107
+ begin_at=params.get('begin_at',0.0)
1108
+ compfile=f'{gro}-gromacs-confs'
1109
+ TC=self.TopoCoord if gro==self.name else self.stereoisomers[gro].TopoCoord
1110
+ TC.vacuum_simulate(outname=f'{compfile}',nsamples=cd['count'],params=params)
1111
+ gro_from_trr(compfile,nzero=nd,outpfx=pfx,b=begin_at)
1112
+ # os.remove(f'{gro}-confs.gro')
1113
+ fmt=r'{A}{B:0'+str(nd)+r'd}' # the trjconv command in gro_from_trr must generate these files
1114
+ cfnl=[fmt.format(A=pfx,B=x) for x in range(self.nconformers)]
1115
+ for mname in cfnl:
1116
+ assert os.path.exists(f'{mname}.gro'),f'Error: Conformer coordinates file {mname}.gro not found'
1117
+ logger.debug(f'Conformer coordinate filenames {cfnl}')
1118
+ self.conformers.extend(cfnl)
1119
+ if minimize:
1120
+ saveTC=deepcopy(self.TopoCoord)
1121
+ for mname in self.conformers:
1122
+ self.TopoCoord.read_gro(f'{mname}.gro')
1123
+ logger.info(f'Minimizing conformer {mname}')
1124
+ self.TopoCoord.vacuum_minimize(outname=f'{mname}')
1125
+ self.TopoCoord=saveTC
1126
+
1127
+ MoleculeDict = dict[str,Molecule]
1128
+ MoleculeList = list[Molecule]
1129
+
1130
+ def generate_stereo_reactions(RL:ReactionList,MD:MoleculeDict):
1131
+ """generate_stereo_reactions scans the list of reactions and generates any additional reactions in which all possible stereoisomers are reactants
1132
+
1133
+ :param RL: list of Reactions
1134
+ :type RL: ReactionList
1135
+ :param MD: dictionary of available Molecules
1136
+ :type MD: MoleculeDict
1137
+ :return: number of new reactions/molecular products created
1138
+ :rtype: int
1139
+ """
1140
+ # any reaction with one or more reactant with one or more stereoisomers
1141
+ # generates new "build" reactions using the stereoisomer as a reactant
1142
+ # in place
1143
+ adds=0
1144
+ terminal_reactions=[]
1145
+ for R in RL:
1146
+ if R.stage not in [reaction_stage.param,reaction_stage.build]: continue
1147
+ Prod=MD[R.product]
1148
+ logger.debug(f'Stereos for {R.name} ({str(R.stage)})')
1149
+ reactant_stereoisomers={k:[r]+list(MD[r].stereoisomers.keys()) for k,r in R.reactants.items()}
1150
+ for k,v in reactant_stereoisomers.items():
1151
+ assert all([m in MD for m in v]) # all stereoisomers must be in the dict of molecules
1152
+ logger.debug(reactant_stereoisomers)
1153
+ reactant_keys=list(R.reactants.keys())
1154
+ isomer_lists=list(reactant_stereoisomers.values())
1155
+ combos=product(*isomer_lists)
1156
+ next(combos)
1157
+ # new_reactions=[]
1158
+ sidx=1
1159
+ for c in combos:
1160
+ nR=deepcopy(R)
1161
+ nR.name=R.name+f'S-{sidx}'
1162
+ nR.product=R.product+f'S-{sidx}'
1163
+ nR.stage=reaction_stage.build
1164
+ nR.reactants={k:v for k,v in zip(reactant_keys,c)}
1165
+ # MD[R.product].stereoisomers[nR.product]=Molecule.NewCopy(MD[R.product],nR.product)
1166
+ # add resulting product to global molecule dict so that it will be generated
1167
+ MD[nR.product]=Molecule.New(nR.product,nR)
1168
+ adds+=1
1169
+ MD[nR.product].sequence=MD[R.product].sequence
1170
+ MD[nR.product].parentname=R.product
1171
+ Prod.stereoisomers[nR.product]=MD[nR.product]
1172
+ logger.debug(c)
1173
+ # new_reactions.append(nR)
1174
+ sidx+=1
1175
+ terminal_reactions.append(nR)
1176
+ RL.extend(terminal_reactions)
1177
+ return adds
1178
+
1179
+ def generate_symmetry_reactions(RL:ReactionList,MD:MoleculeDict):
1180
+ """generate_symmetry_reactions scans reaction list to generate any new reactions implied by symmetry-equivalent atoms
1181
+
1182
+ :param RL: list of Reactions
1183
+ :type RL: ReactionList
1184
+ :param MD: dict of available molecules
1185
+ :type MD: MoleculeDict
1186
+ :return: number of new reactions/molecular products created
1187
+ :rtype: int
1188
+ """
1189
+ jdx=1
1190
+ terminal_reactions=[]
1191
+ tail_adds=0
1192
+ for R in RL:
1193
+ if R.stage not in [reaction_stage.param,reaction_stage.cure,reaction_stage.cap]: continue
1194
+ Prod=MD[R.product]
1195
+ logger.debug(f'Symmetry versions for {R.name} ({str(R.stage)})\n{str(R)}')
1196
+ # thisR_extra_reactions=[]
1197
+ # thisR_extra_molecules={}
1198
+ # logger.debug(f' Product {R.product} resname sequence {prod_seq_resn}')
1199
+ sra_by_reactant={k:MD[rname].symmetry_relateds for k,rname in R.reactants.items()}
1200
+ logger.debug(f' sra_by_reactant: {sra_by_reactant}')
1201
+ atom_options=[]
1202
+ for atom_key,atom_rec in R.atoms.items():
1203
+ this_atom_options=[]
1204
+ art=atom_rec['reactant']
1205
+ target_atom_name=atom_rec['atom']
1206
+ if art in sra_by_reactant:
1207
+ logger.debug(f'art {art} {sra_by_reactant[art]}')
1208
+ if len(sra_by_reactant[art])==0: sra_by_reactant[art]=[[target_atom_name]]
1209
+ for symm_set in sra_by_reactant[art]:
1210
+ if target_atom_name in symm_set:
1211
+ for atom_name in symm_set:
1212
+ this_atom_options.append([atom_key,atom_name])
1213
+ atom_options.append(this_atom_options)
1214
+ logger.debug(f' atom options: {atom_options}')
1215
+ if len(R.reactants)>1:
1216
+ olist=list(product(*atom_options))
1217
+ else:
1218
+ olist=list(zip(*atom_options))
1219
+ idx=1
1220
+ R.symmetry_versions=olist
1221
+ logger.debug(f'olist {olist}')
1222
+ if len(olist)==1: continue
1223
+ for P in olist[1:]:
1224
+ newR=deepcopy(R)
1225
+ newR.name=R.name+f'-S{idx}'
1226
+ logger.debug(f'Permutation {P}:')
1227
+ for pp in P:
1228
+ atomKey,atomName=pp
1229
+ newR.atoms[atomKey]['atom']=atomName
1230
+ pname=generate_product_name(newR)
1231
+ if len(pname)==0:
1232
+ pname=R.product+f'-{idx}'
1233
+ newR.product=pname
1234
+ newR.stage=R.stage
1235
+ logger.debug(f'Primary:')
1236
+ for ln in str(newR).split('\n'): logger.debug(ln)
1237
+ terminal_reactions.append(newR)
1238
+ MD[newR.product]=Molecule(name=newR.product,generator=newR)
1239
+ MD[newR.product].set_origin('symmetry_product')
1240
+ MD[newR.product].set_sequence_from_moldict(MD)
1241
+ for rR in [x for x in RL if R.product in x.reactants.values()]:
1242
+ reactantKey=list(rR.reactants.keys())[list(rR.reactants.values()).index(R.product)]
1243
+ logger.debug(f' New product {newR.product} must replace reactant {reactantKey}:{R.product} in {rR.name}')
1244
+ nooR=deepcopy(rR)
1245
+ nooR.stage=rR.stage
1246
+ nooR.name=rR.name+f'-{reactantKey}:S{jdx}'
1247
+ nooR.reactants[reactantKey]=newR.product
1248
+ # update any atom names to reflect origin of this reactant
1249
+ for naK,naRec in {k:v for k,v in nooR.atoms.items() if v['reactant']==reactantKey}.items():
1250
+ na_resid=naRec['resid'] # resid of reactant atom in target reactant
1251
+ na_name=naRec['atom']
1252
+ for p in P:
1253
+ oaK,oa_name=p
1254
+ oaRec=R.atoms[oaK]
1255
+ oa_reactatnName=R.reactants[oaRec['reactant']]
1256
+ oa_resid=oaRec['resid']
1257
+ oa_resid_in_o_product=reactant_resid_to_presid(R,oa_reactatnName,oa_resid,RL)
1258
+ # this atom is an atom in the permutation the resid in product matches
1259
+ if na_resid == oa_resid_in_o_product:
1260
+ nooR.atoms[naK]['resid']=oa_resid_in_o_product
1261
+ nooR.atoms[naK]['atom']=oa_name
1262
+ noor_pname=generate_product_name(nooR)
1263
+ if noor_pname in MD: continue
1264
+ if len(noor_pname)==0:
1265
+ noor_pname=rR.product+f'-{jdx}'
1266
+ nooR.product=noor_pname
1267
+ logger.debug(f'Secondary:')
1268
+ for ln in str(nooR).split('\n'): logger.debug(ln)
1269
+ jdx+=1
1270
+ RL.append(nooR)
1271
+ tail_adds+=1
1272
+ MD[nooR.product]=Molecule.New(nooR.product,nooR)
1273
+ MD[nooR.product].set_origin('symmetry_product')
1274
+ MD[nooR.product].set_sequence_from_moldict(MD)
1275
+ idx+=1
1276
+ logger.debug(f'Symmetry expansion of reaction {R.name} ends')
1277
+
1278
+ RL.extend(terminal_reactions)
1279
+ return len(terminal_reactions)+tail_adds