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/topocoord.py ADDED
@@ -0,0 +1,1877 @@
1
+ """
2
+
3
+ .. module:: topocoords
4
+ :synopsis: Class for jointly handling Topology and Coordinate objects
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ from itertools import product
10
+ import pandas as pd
11
+ import logging
12
+ import numpy as np
13
+ from enum import Enum
14
+ import os
15
+ import shutil
16
+ from copy import deepcopy
17
+ from HTPolyNet.coordinates import Coordinates, GRX_ATTRIBUTES, GRX_GLOBALLY_UNIQUE, GRX_UNSET_DEFAULTS
18
+ from HTPolyNet.topology import Topology
19
+ from HTPolyNet.bondtemplate import BondTemplate,ReactionBond
20
+ from HTPolyNet.gromacs import grompp_and_mdrun,mdp_get, mdp_modify, gmx_energy_trace
21
+ import HTPolyNet.projectfilesystem as pfs
22
+
23
+ logger=logging.getLogger(__name__)
24
+
25
+ class BTRC(Enum):
26
+ """Bond test return codes: bond tests are applied to those bond-candidates that are within search radius of each other
27
+
28
+ :param Enum: inherits from Enum class
29
+ :type Enum: class
30
+ """
31
+ passed = 0
32
+ failed_pierce_ring = 1 # does this bond-candidate pierce a ring?
33
+ failed_short_circuit = 2 # does this bond-candidate result in short-circuit?
34
+ failed_bond_cycle = 3 # does this bond-candidate create a bondcycle on its own?
35
+ unset = 99
36
+
37
+ class TopoCoord:
38
+ """Container for Topology and Coordinates, along with methods that
39
+ use either or both of them
40
+ """
41
+ def __init__(self,topfilename='',grofilename='',grxfilename='',mol2filename='',system_name='htpolynet',**kwargs):
42
+ """Constructor method for TopoCoord.
43
+
44
+ :param topfilename: name of Gromacs-format topology file (top), defaults to ''
45
+ :type topfilename: str, optional
46
+ :param grofilename: name of Gromacs-format coordinate file (gro), defaults to ''
47
+ :type grofilename: str, optional
48
+ :param mol2filename: name of SYBYL MOL2-format coordinate/bonds file, defaults to ''
49
+ :type mol2filename: str, optional
50
+ """
51
+ wrap_coords=kwargs.get('wrap_coords',False)
52
+ # self.basefilenames={}
53
+ self.files={}
54
+ self.files['gro']=os.path.abspath(grofilename)
55
+ self.files['top']=os.path.abspath(topfilename)
56
+ self.files['grx']=os.path.abspath(grxfilename)
57
+ self.files['mol2']=os.path.abspath(mol2filename)
58
+ # self.basefilenames['gro']=grofilename
59
+ # self.basefilenames['top']=topfilename
60
+ # self.basefilenames['grx']=grxfilename
61
+ # self.basefilenames['mol2']=mol2filename
62
+ self.grxattr=[]
63
+ self.idx_lists={}
64
+ self.idx_lists['chain']=[]
65
+ self.idx_lists['cycle']=[]
66
+ if grofilename!='':
67
+ self.read_gro(grofilename,wrap_coords=wrap_coords)
68
+ else:
69
+ self.Coordinates=Coordinates() # empty
70
+ if topfilename!='':
71
+ self.read_top(topfilename)
72
+ else:
73
+ self.Topology=Topology(system_name=system_name) # empty
74
+ if mol2filename!='':
75
+ self.read_mol2(mol2filename,**kwargs)
76
+ if grxfilename!='':
77
+ self.read_gro_attributes(grxfilename)
78
+
79
+ @classmethod
80
+ def from_top_gro(cls,top,gro):
81
+ X=cls(topfilename=top,grofilename=gro)
82
+ return X
83
+
84
+ def make_bonds(self,pairs,explicit_sacH={}):
85
+ """Adds new bonds to the global topology
86
+
87
+ :param pairs: list of pairs of atom global indices indicating each new bond
88
+ :type pairs: list
89
+ :param skip_H: list of pairs of atom global indices to skip when identifying
90
+ the sacrificial H atoms; likely these are identified during molecule-building to
91
+ optimize mutual orientation and placement of the two reactant molecules, defaults
92
+ to []
93
+ :type skip_H: list, optional
94
+ :return: list of indexes of atoms that must now be deleted (sacrifical H's)
95
+ :rtype: list
96
+ """
97
+ idx_to_ignore=self.Coordinates.find_sacrificial_H(pairs,self.Topology,explicit_sacH=explicit_sacH)
98
+ logger.debug(f'idx_to_ignore {idx_to_ignore}')
99
+ self.Topology.add_bonds(pairs)
100
+ self.chainlist_update(pairs,msg='TopoCoord.make_bonds')
101
+ self.Topology.null_check(msg='add_bonds')
102
+ rename=False if len(explicit_sacH)>0 else False
103
+ idx_to_delete=self.Coordinates.find_sacrificial_H(pairs,self.Topology,explicit_sacH=explicit_sacH,rename=rename)
104
+ assert type(idx_to_delete)==list
105
+ return idx_to_delete
106
+
107
+ def add_restraints(self,pairdf,typ=6):
108
+ """Adds bonds of type typ to the topology from the dataframe pairdf
109
+
110
+ :param pairdf: ai, aj, initital-distance
111
+ :type pairdf: pandas.DataFrame
112
+ :param typ: bond type to add, defaults to 6 (non-topological restraint)
113
+ :type typ: int, optional
114
+ """
115
+ self.Topology.add_restraints(pairdf,typ=typ)
116
+
117
+ def delete_atoms(self,atomlist):
118
+ """Deletes atoms from both the Topology and Coordinates instances
119
+
120
+ :param atomlist: list of global indexes of atoms to delete
121
+ :type atomlist: list
122
+ :return: old-to-new atom global index mapper dictionary resulting from reindexing
123
+ remaining atoms to make sure global indexes are sequential
124
+ :rtype: dict
125
+ """
126
+ # logger.debug(f'delete_atoms: {atomlist}')
127
+ self.Coordinates.delete_atoms(atomlist)
128
+ idx_mapper=self.Topology.delete_atoms(atomlist)
129
+ assert type(idx_mapper)==dict
130
+ # logger.debug(f'idx_mapper: {idx_mapper}')
131
+ for list_name in ['chain','cycle']:
132
+ # logger.debug(f'remapping idxs in stale {list_name} lists: {self.idx_lists[list_name]}')
133
+ self.reset_idx_list_from_grx_attributes(list_name)
134
+ # self.remap_idx_list(list_name,idx_mapper)
135
+ # logger.debug(f'finished')
136
+ return idx_mapper
137
+
138
+ def count_H(self,idx):
139
+ """count_H Counts the number of hydrogens bound to atom with index idx;
140
+ any atom whose name begins with the character 'H' or 'h' is assumed to be a hydrogen!
141
+
142
+ :param idx: atom global index
143
+ :type idx: int
144
+ :return: number of H atoms bound to this atom
145
+ :rtype: int
146
+ """
147
+ aneigh=self.partners_of(idx)
148
+ aneighnames=[self.get_gro_attribute_by_attributes('atomName',{'globalIdx':y}) for y in aneigh]
149
+ anH=sum([int(x.upper().startswith('H')) for x in aneighnames])
150
+ return anH
151
+
152
+ def map_from_templates(self,bdf,moldict,overcharge_threshhold=0.1):
153
+ """Updates angles, pairs, dihedrals, atom types, and charges, based on product
154
+ templates associated with each bond in 'bdf'
155
+
156
+ :param bdf: dataframe, columns 'ai', 'aj', 'reactantName'
157
+ :type bdf: pandas.DataFrame
158
+ :param moldict: dictionary of template Molecules keyed by name
159
+ :type moldict: dict
160
+ :raises Exception: nan found in any attribute of any new system angle
161
+ :raises Exception: nan found in any attribute of any new system dihedral
162
+ :raises Exception: nan found in any attribute of any new system pair
163
+ that came along with a dihedral
164
+ :raises Exception: nan found in ai attribute of any template pair
165
+ :raises Exception: nan found in aj attribute of any template pair
166
+ :raises Exception: nan found in any system pair
167
+ """
168
+ atdf=self.Topology.D['atoms']
169
+ # ij=self.Topology.D['bondtypes'].set_index(['i','j'])
170
+ #mb=self.D['mol2_bonds']
171
+ # bmi=self.Topology.D['bonds'].set_index(['ai','aj']).sort_index().index
172
+ grodf=self.Coordinates.A
173
+ grodf['old_reactantName']=grodf['reactantName'].copy()
174
+ logger.debug(f'Mapping {bdf.shape[0]} bonds.')
175
+ premapping_total_charge=self.Topology.total_charge()
176
+ logger.debug(f'Must compensate for an overcharge of {premapping_total_charge:.4f}')
177
+ mapped_inst_atoms=[]
178
+ for b in bdf.itertuples():
179
+ logger.debug(f'Mapping bond {b}')
180
+ # for ln in b.to_string().split('\n'):
181
+ # logger.debug(f' -> {ln}')
182
+ bb=[b.ai,b.aj]
183
+ order=b.order
184
+ names=[self.get_gro_attribute_by_attributes('atomName',{'globalIdx':x}) for x in bb]
185
+ resnames=[self.get_gro_attribute_by_attributes('resName',{'globalIdx':x}) for x in bb]
186
+ logger.debug(f'{resnames}')
187
+ resids=[self.get_gro_attribute_by_attributes('resNum',{'globalIdx':x}) for x in bb]
188
+ # this is the product name of the reaction used to identify this bond
189
+ product_name=b.reactantName
190
+ if product_name in moldict:
191
+ P=moldict[product_name]
192
+ if P.is_reactant:
193
+ logger.debug(f'{P.name} is a reactant; updating \"reactantName\" attributes of {bb}')
194
+ # if the product of this reaction is also a reactant in a cure reaction, we should
195
+ # change the reactantName attribute of the two atoms to match this so either of
196
+ # these atoms can be found in a later bond search
197
+ for j in bb:
198
+ self.set_gro_attribute_by_attributes('reactantName',product_name,{'globalIdx':j})
199
+ else:
200
+ logger.debug(f'{P.name} is not a reactant; no update of \"reactantName\" attributes')
201
+ bystander_resids,bystander_resnames,bystander_atomidx,bystander_atomnames=self.get_bystanders(bb)
202
+ oneaway_resids,oneaway_resnames,oneaway_atomidx,oneaway_atomnames=self.get_oneaways(bb)
203
+ intraresidue=resids[0]==resids[1]
204
+ BT=BondTemplate(names,resnames,intraresidue,order,bystander_resnames,bystander_atomnames,oneaway_resnames,oneaway_atomnames)
205
+ RB=ReactionBond(bb,resids,order,bystander_resids,bystander_atomidx,oneaway_resids,oneaway_atomidx)
206
+ logger.debug(f'apparent bond template {str(BT)}')
207
+ logger.debug(f'apparent bond instance {str(RB)}')
208
+ T,rb,reverse_bond=find_template(BT,moldict)
209
+ if reverse_bond: RB.reverse()
210
+ temp_i_idx,temp_j_idx=rb.idx
211
+ d=T.TopoCoord.Topology.D['bonds']
212
+ # copy all bond records matching these two bonds; should be only one!!
213
+ d=d[((d.ai==temp_i_idx)&(d.aj==temp_j_idx))|
214
+ ((d.ai==temp_j_idx)&(d.aj==temp_i_idx))].copy()
215
+ assert d.shape[0]==1,f'Using {T.name} is sent inst-bond {i_idx}-{j_idx} which is claimed to map to {temp_i_idx}-{temp_j_idx}, but no such unique bond is found:\n{T.TopoCoord.Topology.D["bonds"].to_string()}'
216
+ ''' check passed '''
217
+ temp_angles,temp_dihedrals,temp_pairs=T.get_angles_dihedrals((temp_i_idx,temp_j_idx))
218
+ logger.debug(f'Mapping {temp_angles.shape[0]} angles, {temp_dihedrals.shape[0]} dihedrals, and {temp_pairs.shape[0]} pairs from template {T.name}')
219
+ # determine the set of unique atoms in template that must be mapped to instance -- it is all
220
+ # atoms involved in these bonded interactions
221
+ uniq_temp_idx=set()
222
+ for df in [temp_angles,temp_dihedrals,temp_pairs]:
223
+ for label in ['ai','aj','ak','al']:
224
+ if label in df:
225
+ uniq_temp_idx=uniq_temp_idx.union(set(df[label].to_list()))
226
+ logger.debug(f'Template atom indexes that must be mapped: {uniq_temp_idx}')
227
+ # get the bidirectional instance<->template mapping dictionaries
228
+ inst2temp,temp2inst=T.idx_mappers(self,RB.idx,RB.bystander_resids,RB.oneaway_resids,uniq_temp_idx)
229
+ # some hard checks on compatibility of the dicts
230
+ assert len(inst2temp)==len(temp2inst)
231
+ check=True
232
+ for k,v in inst2temp.items():
233
+ check = check and (k == temp2inst[v])
234
+ for k,v in temp2inst.items():
235
+ check = check and (k == inst2temp[v])
236
+ assert check,f'Error: bidirectional dicts are incompatible; bug\n{inst2temp}\b{temp2inst}'
237
+ # logger.debug(f'inst2temp {inst2temp}')
238
+ # logger.debug(f'temp2inst {temp2inst}')
239
+ i_idx,j_idx=bb
240
+ _temp_i_idx,_temp_j_idx=inst2temp[i_idx],inst2temp[j_idx]
241
+ assert temp_i_idx==_temp_i_idx,f'mapping mismatch -- bug'
242
+ assert temp_j_idx==_temp_j_idx,f'mapping mismatch -- bug'
243
+
244
+ need_new_bond_parameters=False
245
+ total_dcharge=0.0
246
+ temp_atdf=T.TopoCoord.Topology.D['atoms']
247
+ for temp_atom,inst_atom in temp2inst.items():
248
+ assert inst_atom in atdf['nr'].values,f'Error: mapped atom {inst_atom} not found in [ atoms ]'
249
+ inst_type,inst_charge,inst_name,inst_resn,inst_rnam=atdf[atdf['nr']==inst_atom][['type','charge','atom','resnr','residue']].values[0]
250
+ temp_type,temp_charge,temp_name,temp_resn,temp_rnam=temp_atdf[temp_atdf['nr']==temp_atom][['type','charge','atom','resnr','residue']].values[0]
251
+ # logger.debug(f'temp {temp_atom} {temp_name} {temp_rnam} {temp_resn} {temp_type} {temp_charge}')
252
+ # logger.debug(f'inst {inst_atom} {inst_name} {inst_rnam} {inst_resn} {inst_type} {inst_charge}')
253
+ if inst_type!=temp_type:
254
+ logger.debug(f'changing type of inst atom {inst_atom} ({inst_resn} {inst_rnam} {inst_name}) from {inst_type} to {temp_type}')
255
+ atdf.loc[atdf['nr']==inst_atom,'type']=temp_type
256
+ if inst_atom==b.ai or inst_atom==b.aj:
257
+ # changed type of one or both of the bond atoms
258
+ need_new_bond_parameters=True
259
+ if inst_charge!=temp_charge:
260
+ logger.debug(f'charge {inst_atom} ({inst_resn} {inst_rnam} {inst_name}) from {inst_charge} to {temp_charge}')
261
+ atdf.loc[atdf['nr']==inst_atom,'charge']=temp_charge
262
+ dcharge=temp_charge-inst_charge
263
+ total_dcharge+=dcharge
264
+ mapped_inst_atoms.extend(list(temp2inst.values()))
265
+ if need_new_bond_parameters:
266
+ self.Topology.reset_override_from_type('bonds','bondtypes',inst_idx=(b.ai,b.aj))
267
+
268
+ # get all angle, dihedrals, and pairs from template that result from the existence of the specified bond
269
+ # temp_angles,temp_dihedrals,temp_pairs=T.get_angles_dihedrals((temp_i_idx,temp_j_idx))
270
+ # logger.debug(f'Mapping {temp_angles.shape[0]} angles, {temp_dihedrals.shape[0]} dihedrals, and {temp_pairs.shape[0]} pairs from template {T.name}')
271
+ # map from template atom indicies to system atom indicies in angles
272
+ # logger.debug(f'Template angles:')
273
+ # for ln in temp_angles.to_string().split('\n'):
274
+ # logger.debug(ln)
275
+ inst_angles=temp_angles.copy()
276
+ inst_angles.ai=temp_angles.ai.map(temp2inst)
277
+ inst_angles.aj=temp_angles.aj.map(temp2inst)
278
+ inst_angles.ak=temp_angles.ak.map(temp2inst)
279
+ # logger.debug(f'Mapped instance angles:')
280
+ # for ln in inst_angles.to_string().split('\n'):
281
+ # logger.debug(ln)
282
+ # add new angles to the system topology
283
+ d=self.Topology.D['angles']
284
+ self.Topology.D['angles']=pd.concat((d,inst_angles),ignore_index=True)
285
+ # hard check for any nan's in any atom index attribute in any angle
286
+ d=self.Topology.D['angles']
287
+ check=True
288
+ for a in ['ai','aj','ak']:
289
+ check=check and d[a].isnull().values.any()
290
+ if check:
291
+ logger.error('NAN in angles')
292
+ raise Exception
293
+
294
+ # logger.debug(f'Template dihedrals:')
295
+ # for ln in temp_dihedrals.to_string().split('\n'):
296
+ # logger.debug(ln)
297
+ # map from template atom indicies to system atom indicies in dihedrals
298
+ inst_dihedrals=temp_dihedrals.copy()
299
+ inst_dihedrals.ai=temp_dihedrals.ai.map(temp2inst)
300
+ inst_dihedrals.aj=temp_dihedrals.aj.map(temp2inst)
301
+ inst_dihedrals.ak=temp_dihedrals.ak.map(temp2inst)
302
+ inst_dihedrals.al=temp_dihedrals.al.map(temp2inst)
303
+ # logger.debug(f'Mapped instance dihedrals:')
304
+ # for ln in inst_dihedrals.to_string().split('\n'):
305
+ # logger.debug(ln)
306
+ d=inst_dihedrals
307
+ check=False
308
+ for a in ['ai','aj','ak','al']:
309
+ check=check or d[a].isnull().values.any()
310
+ if check:
311
+ logger.error(f'a {a} NAN in dihedrals\n{inst_dihedrals.to_string()}')
312
+ raise Exception
313
+ # add new dihedrals to global topology
314
+ d=self.Topology.D['dihedrals']
315
+ self.Topology.D['dihedrals']=pd.concat((d,inst_dihedrals),ignore_index=True)
316
+ # hard check for no nans
317
+ d=self.Topology.D['dihedrals']
318
+ check=True
319
+ for a in ['ai','aj','ak','al']:
320
+ check=check and d[a].isnull().values.any()
321
+ if check:
322
+ logger.error('NAN in dihedrals')
323
+ raise Exception
324
+ d=self.Topology.D['pairs']
325
+ check=True
326
+ for a in ['ai','aj']:
327
+ check=check and d[a].isnull().values.any()
328
+ if check:
329
+ logger.error('NAN in pairs premapping')
330
+ raise Exception
331
+
332
+ # double-hard check to make sure pairs can be mapped
333
+ k=np.array(list(temp2inst.keys()))
334
+ v=np.array(list(temp2inst.values()))
335
+ if any(np.isnan(k)):
336
+ logger.error('null in temp2inst keys')
337
+ if any(np.isnan(v)):
338
+ logger.error('null in temp2inst values')
339
+ # logger.debug(f'temp_pairs:\n{temp_pairs.to_string()}')
340
+ isin=[not x in temp2inst for x in temp_pairs.ai]
341
+ if any(isin):
342
+ for ii,jj in enumerate(isin):
343
+ if jj:
344
+ logger.error(f'atom ai {temp_pairs.ai.iloc[ii]} not in temp2inst')
345
+ isin=[not x in temp2inst for x in temp_pairs.aj]
346
+ if any(isin):
347
+ for ii,jj in enumerate(isin):
348
+ if jj:
349
+ logger.error(f'atom aj {temp_pairs.aj.iloc[ii]} not in temp2inst')
350
+
351
+ # map all ai attributes of all template pairs to global ai
352
+ temp_pairs.ai=temp_pairs.ai.map(temp2inst)
353
+ # check AGAIN for nans (I am afraid of nans)
354
+ if temp_pairs.ai.isnull().values.any():
355
+ logger.error('NAN in pairs ai')
356
+ raise Exception
357
+ # map all aj attributes of all template pairs to global ai
358
+ temp_pairs.aj=temp_pairs.aj.map(temp2inst)
359
+ # check YET AGAIN for nans (eek!)
360
+ if temp_pairs.aj.isnull().values.any():
361
+ logger.error('NAN in pairs aj')
362
+ raise Exception
363
+ # add these pairs to the topology
364
+ # logger.debug(f'Concatenating this pairs to global pairs')
365
+ # for ln in temp_pairs.to_string().split('\n'):
366
+ # logger.debug(ln)
367
+ self.Topology.D['pairs']=pd.concat((d,temp_pairs),ignore_index=True)
368
+ d=self.Topology.D['pairs']
369
+ # check AGAIN for nans
370
+ check=True
371
+ for a in ['ai','aj']:
372
+ check=check and d[a].isnull().values.any()
373
+ if check:
374
+ logger.error('NAN in pairs post mapping')
375
+ raise Exception
376
+ # return temp_pairs
377
+ mapped_inst_atoms=list(set(mapped_inst_atoms))
378
+ logger.debug(f'System overcharge after mapping: {self.Topology.total_charge():.4f}')
379
+ self.adjust_charges(atoms=mapped_inst_atoms,overcharge_threshhold=overcharge_threshhold,msg=f'overcharge magnitude exceeds {overcharge_threshhold}')
380
+
381
+ def enumerate_1_4_pairs(self,at_idx):
382
+ """enumerate_1_4_pairs enumerate all 1-4 pair interactions resulting from new bonds in at_idx
383
+
384
+ :param at_idx: list of 2-tuples, each containing global indices of atoms that bond to each other
385
+ :type at_idx: list
386
+ :return: dataframe of all pairs
387
+ :rtype: pandas.DataFrame
388
+ """
389
+ pdf=self.Topology.D['pairs']
390
+ # each of these bonds results in 1-4 pair interactions
391
+ bl=self.Topology.bondlist
392
+ pai=[]
393
+ paj=[]
394
+ pri=[]
395
+ prj=[]
396
+ prsource=[]
397
+ for p in at_idx:
398
+ # determine all nj--nk pairs from j-k bond, where nj are neighbors of j not including k, and nk are neighbors of k not including j
399
+ # and all nnj--k pairs from all nj-j bonds, where nnj are next-nearest neighbors of j excluding j
400
+ # and all j--nnk pairs from all k-nk bonds, where nnk are next-nearest neighbors of k excluding k
401
+ j,k=p
402
+ nj=bl.partners_of(j)
403
+ nj.remove(k)
404
+ nnj=[]
405
+ for nn in nj:
406
+ t=bl.partners_of(nn)
407
+ t.remove(j)
408
+ nnj.append(t)
409
+ nk=bl.partners_of(k)
410
+ nk.remove(j)
411
+ nnk=[]
412
+ for nn in nk:
413
+ t=bl.partners_of(nn)
414
+ t.remove(k)
415
+ nnk.append(t)
416
+ logger.debug(f'{j} {nj} {k} {nk}')
417
+ logger.debug(f'{nnj} {nnk}')
418
+ for pp in product(nj,nk):
419
+ jj,kk=pp
420
+ pai.append(jj)
421
+ paj.append(kk)
422
+ pri.append(j)
423
+ prj.append(k)
424
+ prsource.append('c')
425
+ for nn in nnj:
426
+ for ii in nn:
427
+ pai.append(ii)
428
+ paj.append(k)
429
+ pri.append(j)
430
+ prj.append(k)
431
+ prsource.append('l')
432
+ for nn in nnk:
433
+ for ll in nn:
434
+ pai.append(j)
435
+ paj.append(ll)
436
+ pri.append(j)
437
+ prj.append(k)
438
+ prsource.append('r')
439
+
440
+ pi_df=pd.DataFrame({'ai':pai,'aj':paj,'source':prsource,'bi':pri,'bj':prj})
441
+ pi_df.drop_duplicates(inplace=True,ignore_index=True)
442
+ return pi_df
443
+
444
+
445
+ def update_topology_and_coordinates(self,bdf,template_dict={},write_mapper_to=None,**kwargs):
446
+ """update_topology_and_coordinates updates global topology and necessary atom attributes in the configuration to reflect formation of all bonds listed in `keepbonds`
447
+
448
+ :param bdf: bonds dataframe, columns 'ai', 'aj', 'reactantName'
449
+ :type bdf: pandas.DataFrame
450
+ :param template_dict: dictionary of molecule templates keyed on molecule name
451
+ :type template_dict: dict
452
+ :return: 3-tuple: new topology file name, new coordinate file name, list of bonds with atom indices updated to reflect any atom deletions
453
+ :rtype: 3-tuple
454
+
455
+ """
456
+ explicit_sacH=kwargs.get('explicit_sacH',{})
457
+ template_source=kwargs.get('template_source','internal')
458
+ overcharge_threshhold=kwargs.get('overcharge_threshhold',0.1)
459
+ logger.debug(f'begins.')
460
+ if bdf.shape[0]>0:
461
+ assert bdf['ai'].dtype==int
462
+ assert bdf['aj'].dtype==int
463
+ # pull out just the atom index pairs (first element of each tuple)
464
+ at_idx=[(int(x.ai),int(x.aj),x.order) for x in bdf.itertuples()]
465
+ logger.debug(f'Making {len(at_idx)} bonds.')
466
+ idx_to_delete=self.make_bonds(at_idx,explicit_sacH=explicit_sacH)
467
+ logger.debug(f'Deleting {len(idx_to_delete)} atoms.')
468
+ idx_mapper=self.delete_atoms(idx_to_delete) # will result in full reindexing
469
+ # logger.debug(f'null check')
470
+ self.Topology.null_check(msg='delete_atoms')
471
+ # reindex all atoms in the list of bonds sent in, and write it out
472
+ logger.debug(f'z-decrement, nreactions increment')
473
+ ri_bdf=bdf.copy()
474
+ ri_bdf.ai=ri_bdf.ai.map(idx_mapper)
475
+ ri_bdf.aj=ri_bdf.aj.map(idx_mapper)
476
+ at_idx=[(x.ai,x.aj) for x in ri_bdf.itertuples()]
477
+ for idx_pair in at_idx:
478
+ for idx in idx_pair:
479
+ self.decrement_gro_attribute_by_attributes('z',{'globalIdx':idx})
480
+ self.increment_gro_attribute_by_attributes('nreactions',{'globalIdx':idx})
481
+ if template_source=='internal':
482
+ logger.debug(f'calling map_from_templates')
483
+ self.map_from_templates(ri_bdf,template_dict,overcharge_threshhold=overcharge_threshhold)
484
+ logger.debug(f'1-4 pair update')
485
+ pi_df=self.enumerate_1_4_pairs(at_idx)
486
+ self.Topology.null_check(msg='update_topology_and_coordinates')
487
+ if write_mapper_to:
488
+ tdf=pd.DataFrame({'old':list(idx_mapper.keys()),'new':list(idx_mapper.values())})
489
+ tdf.to_csv(write_mapper_to,sep=' ',index=False)
490
+ logger.debug('finished')
491
+ return ri_bdf,pi_df
492
+
493
+ def read_top(self,topfilename):
494
+ """read_top Creates a new Topology member by reading from a Gromacs-style top file.
495
+ Just a wrapper for the read_gro method of Topology
496
+
497
+ :param topfilename: name of topology file
498
+ :type topfilename: str
499
+ """
500
+ self.files['top']=os.path.abspath(topfilename)
501
+ self.Topology=Topology.read_gro(topfilename)
502
+
503
+ def read_gro(self,grofilename,preserve_box=False,wrap_coords=False):
504
+ """read_gro Creates a new Coordinates member by reading from a Gromacs-style coordinates
505
+ file. Just a wrapper for the read_gro method of Coordinates
506
+
507
+ :param grofilename: name of gro file
508
+ :type grofilename: str
509
+ """
510
+ self.files['gro']=os.path.abspath(grofilename)
511
+ if preserve_box:
512
+ savebox=self.Coordinates.box.copy()
513
+ self.Coordinates=Coordinates.read_gro(grofilename,wrap_coords=wrap_coords)
514
+ if preserve_box:
515
+ self.Coordinates.box=savebox
516
+ # logger.debug(f'box: {self.Coordinates.box}')
517
+
518
+ def read_mol2(self,mol2filename,**kwargs):
519
+ """read_mol2 Creates a new Coordinates member by reading from a SYBYL-style MOL2 file.
520
+ A wrapper for read_mol2 from Coordinates, but also sets the 'mol2_bonds'
521
+ dataframe in the Topology if the parameter ignore_bonds is False. If
522
+ the mol2_bonds dataframe is created, and the Topology already has a 'bonds' dataframe, a consistency check is peformed.
523
+
524
+ :param mol2filename: name of mol2 file
525
+ :type mol2filename: str
526
+ """
527
+ ignore_bonds=kwargs.get('ignore_bonds',False)
528
+ overwrite_coordinates=kwargs.get('overwrite_coordinates',False)
529
+ self.files['mol2']=os.path.abspath(mol2filename)
530
+ temp_coords=Coordinates.read_mol2(mol2filename)
531
+ if self.Coordinates.empty or overwrite_coordinates:
532
+ save_box=self.Coordinates.box.copy()
533
+ self.Coordinates=temp_coords
534
+ self.Coordinates.box=save_box
535
+ temp_coords=self.Coordinates
536
+ if not ignore_bonds:
537
+ self.Topology.D['mol2_bonds']=temp_coords.mol2_bonds.copy()
538
+ if 'bonds' in self.Topology.D:
539
+ self.Topology.bond_source_check()
540
+
541
+ def swap_atom_names(self,ai,aj):
542
+ """swap_atom_names Swaps the names of the two atoms with global indicies ai and aj. This is used when
543
+ automatically selected which of several possible sacrificial H's will actually be
544
+ selected. Surviving H's are renamed so it always appears that the H with "least
545
+ important" name (lowest order if sorted) is the sacrificial H. Why do we do this? It
546
+ gives us perfect control of the names of the atoms that survive a bond.
547
+
548
+ :param ai: global index of first atom
549
+ :type ai: int
550
+ :param aj: global index of second atom
551
+ :type aj: int
552
+ """
553
+ T=self.Topology.D['atoms']
554
+ C=self.Coordinates.A
555
+ l1=T.columns=='atom'
556
+ l2=C.columns=='atomName'
557
+ iname=T.iloc[ai-1,l1].values[0]
558
+ jname=T.iloc[aj-1,l1].values[0]
559
+ # logger.debug(f'Swapping names of atoms {ai}({iname}) and {aj}({jname})')
560
+ tmpNm=T.iloc[ai-1,l1].values[0]
561
+ T.iloc[ai-1,l1]=T.iloc[aj-1,l1]
562
+ T.iloc[aj-1,l1]=tmpNm
563
+ C.iloc[ai-1,l2]=C.iloc[aj-1,l2]
564
+ C.iloc[aj-1,l2]=tmpNm
565
+
566
+ def read_top_gro(self,topfilename,grofilename):
567
+ """read_top_gro Wrapper for read_top and read_gro; generates new Topology and Coordinates members
568
+
569
+ :param topfilename: name of topology file
570
+ :type topfilename: str
571
+ :param grofilename: name of coordinates file (Gromacs format)
572
+ :type grofilename: str
573
+ """
574
+ self.read_top(topfilename)
575
+ self.read_gro(grofilename)
576
+
577
+ def write_top(self,topfilename):
578
+ """write_top Write a Gromacs-format topology file; this will only write an in-line version,
579
+ no itp; wrapper for Topology.to_file()
580
+
581
+ :param topfilename: name of file to write
582
+ :type topfilename: str
583
+ """
584
+ self.Topology.to_file(topfilename)
585
+ self.files['top']=os.path.abspath(topfilename)
586
+
587
+ def write_gro(self,grofilename,grotitle=''):
588
+ """write_gro Write a Gromacs-format coordinate file; wrapper for Coordinates.write_gro()
589
+
590
+ :param grofilename: name of file to write
591
+ :type grofilename: str
592
+ """
593
+ self.Coordinates.write_gro(grofilename,grotitle=grotitle)
594
+ self.files['gro']=os.path.abspath(grofilename)
595
+
596
+ def write_top_gro(self,topfilename,grofilename):
597
+ """write_top_gro Writes both a Gromacs top file and Gromacs coordinate file
598
+
599
+ :param topfilename: name of topology file to write
600
+ :type topfilename: str
601
+ :param grofilename: name of coordinate file to write
602
+ :type grofilename: str
603
+ """
604
+ self.write_top(topfilename)
605
+ self.write_gro(grofilename)
606
+
607
+ def return_bond_lengths(self,bdf):
608
+ """return_bond_lengths Return the length of all bonds in list bonds
609
+
610
+ :param bdf: bonds dataframe, 'ai','aj','reactantName'
611
+ :type bonds: pandas.DataFrame
612
+ :return: list of lengths parallel to bonds
613
+ :rtype: list of floats
614
+ """
615
+ return self.Coordinates.return_bond_lengths(bdf)
616
+
617
+ def add_length_attribute(self,bdf:pd.DataFrame,attr_name='length'):
618
+ """add_length_attribute computes bond lengths based on bonds indicated by the parallel 'ai' and 'aj' columns of the parameter dataframe bdf and stores result in a new column called attr_name
619
+
620
+ :param bdf: a pandas dataframe with 'ai' and 'aj' columns of atom indices indicating bonds
621
+ :type bdf: pd.DataFrame
622
+ :param attr_name: name of length attribute column, defaults to 'length'
623
+ :type attr_name: str, optional
624
+ """
625
+ self.Coordinates.add_length_attribute(bdf,attr_name=attr_name)
626
+
627
+ def copy_bond_parameters(self,bonds):
628
+ """Generate and return a copy of a bonds dataframe that contains all bonds
629
+ listed in bonds
630
+
631
+ :param bonds: list of bonds, each a 2-tuple of global atom indices
632
+ :type bonds: list
633
+ :return: bonds dataframe
634
+ :rtype: pandas.DataFrame
635
+ """
636
+ return self.Topology.copy_bond_parameters(bonds)
637
+
638
+ def remove_restraints(self,pairsdf):
639
+ """Remove all bonds represented in in pairdf.
640
+ These are interpreted as non-topological
641
+ restraints, so deleting these 'bonds' does
642
+ not influence angles or dihedrals
643
+
644
+ :param pairdf: dataframe of pairs ['ai','aj']
645
+ :type pairdf: pandas DataFrame
646
+ """
647
+ self.Topology.remove_restraints(pairsdf)
648
+
649
+ def attenuate_bond_parameters(self,bonds,i,n,minimum_distance=0.0,init_colname='initial_distance'):
650
+ """Alter the kb and b0 parameters for new crosslink bonds according to the values prior to
651
+ relaxation (stored in lengths), their equilibrium values, and the ratio stage/max_stages.
652
+ Let stage/max_stages be x, and 1/max_stages <= x <= 1. The spring constant for each
653
+ bond is multiplied by x and the distance is 1 xth of the way from its maximum value
654
+ to its equilibrium value.
655
+
656
+ :param bonds: bonds dataframe, 'ai', 'aj', 'initial_distance'
657
+ :type bonds: pandas.DataFrame
658
+ :param stage: index of stage in the series of post-bond-formation relaxation
659
+ :type stage: int
660
+ :param max_stages: total number of relaxation stages for this iteration
661
+ :type max_stages: int
662
+ :param minimum_distance: minimum bondlegth allowed, overriding type-specific b0
663
+ :type lengths: float
664
+ """
665
+ self.Topology.attenuate_bond_parameters(bonds,i,n,minimum_distance=minimum_distance,init_colname=init_colname)
666
+
667
+ def attenuate_pair_parameters(self,pairdf,i,n,draglimit_nm=0.3):
668
+ """Alter the kb and b0 parameters for new pre-crosslink pairs according
669
+ to the values prior to dragging (stored in pairdf['initial_distances']),
670
+ the desired lower limit of interatomic distance 'draglimit_nm',
671
+ and the ratio stage/max_stages.
672
+
673
+ :param pairdf: pairs dataframe (['ai'],['aj'],['initial_distance'])
674
+ :type pairdf: pandas.DataFrame
675
+ :param stage: index of stage in the series of pre-bond-formation dragging
676
+ :type stage: int
677
+ :param max_stages: total number of drag stages for this iteration
678
+ :type max_stages: int
679
+ :param draglimit_nm: lower limit of interatomic distance requested from drag
680
+ :type draglimit_nm: float
681
+ """
682
+ self.Topology.attenuate_pair_parameters(pairdf,i,n,minimum_distance=draglimit_nm)
683
+
684
+ def copy_coords(self,other):
685
+ """Copy coordinates and box size from other to self
686
+
687
+ :param other: a TopoCoord instance
688
+ :type other: TopoCoord
689
+ """
690
+ self.Coordinates.copy_coords(other.Coordinates)
691
+ self.Coordinates.box=other.Coordinates.box.copy()
692
+ self.files['gro']=os.path.abspath(other.files['gro'])
693
+
694
+ def restore_bond_parameters(self,saved):
695
+ """Retores saved bond parameters in df saved by overwriting
696
+
697
+ :param saved: [ bonds ] dataframe
698
+ :type saved: pandas.DataFrame
699
+ """
700
+ self.Topology.restore_bond_parameters(saved)
701
+
702
+ def set_grx_attributes(self,attributes=[]):
703
+ """set_grx_attributes override the global GRX_ATTRIBUTES
704
+
705
+ :param attributes: new GRX attributes to use, defaults to []
706
+ :type attributes: list, optional
707
+ """
708
+ if len(attributes)==0:
709
+ self.grxattr=GRX_ATTRIBUTES
710
+ else:
711
+ self.grxattr=attributes
712
+ logger.debug(f'grxattr set to {self.grxattr}')
713
+
714
+ def write_gro_attributes(self,attributes_list,grxfilename):
715
+ """write_gro_attributes Writes atomic attributes to a file
716
+
717
+ :param attributes_list: list of attributes to write
718
+ :type attributes_list: list
719
+ :param grxfilename: name of output file
720
+ :type grxfilename: str
721
+ """
722
+ self.Coordinates.write_atomset_attributes(attributes_list,grxfilename)
723
+ self.files['grx']=os.path.abspath(grxfilename)
724
+
725
+ def write_grx_attributes(self,grxfilename):
726
+ """write_grx_attributes Writes GRX attributes to a file
727
+
728
+ :param grxfilename: name of output file
729
+ :type grxfilename: str
730
+ """
731
+ self.write_gro_attributes(self.grxattr,grxfilename)
732
+
733
+ def read_gro_attributes(self,grxfilename,attribute_list=[]):
734
+ """Read attributes from file into self.Coordinates.A
735
+
736
+ :param grxfilename: name of input file
737
+ :type grxfilename: str
738
+ :param attribute_list: list of attributes to take, defaults to [] (take all)
739
+ :type attribute_list: list, optional
740
+ """
741
+ self.files['grx']=os.path.abspath(grxfilename)
742
+ logger.debug(f'Reading {grxfilename}')
743
+ attributes_read=self.Coordinates.read_atomset_attributes(grxfilename,attributes=attribute_list)
744
+ if 'chain' in attributes_read and 'chain_idx' in attributes_read:
745
+ self.reset_idx_list_from_grx_attributes('chain')
746
+ if 'cycle' in attributes_read and 'cycle_idx' in attributes_read:
747
+ self.reset_idx_list_from_grx_attributes('cycle')
748
+ if attributes_read!=self.grxattr:
749
+ self.grxattr=attributes_read
750
+
751
+ def set_gro_attribute(self,attribute,srs):
752
+ """set_gro_attribute sets attribute of atoms to srs (drillst through to Coordinates.set_atomset_attributes())
753
+
754
+ :param attribute: name of attribute
755
+ :type attribute: str
756
+ :param srs: scalar or list-like attribute values in same ordering as self.A
757
+ :type srs: scalar or list-like
758
+ """
759
+ self.Coordinates.set_atomset_attribute(attribute,srs)
760
+
761
+ def set_gro_attribute_by_attributes(self,att_name,att_value,attribute_dict):
762
+ """set_atom_attribute set the attributes named in name to values named in values (names||values) for the set of atoms specified in the attributes dict
763
+
764
+ :param name: list of names of attributes
765
+ :type name: list
766
+ :param value: list of values of attributes to be set
767
+ :type value: list
768
+ :param attributes: dictionary of attribute:value pairs that specify the set of atoms to be considered
769
+ :type attributes: dict
770
+ """
771
+ self.Coordinates.set_atom_attribute(att_name,att_value,attribute_dict)
772
+
773
+ def get_gro_attribute_by_attributes(self,att_name,attribute_dict):
774
+ """get_gro_attribute_by_attributes return values of attributes listed in name from atoms specified by attribute:value pairs in attribute_dict
775
+
776
+ :param att_name: list of attributes whose values are to be returned
777
+ :type att_name: list
778
+ :param attribute_dict: dictionary of attribute:value pairs that specify the set of atoms to be considered
779
+ :type attribute_dict: dict
780
+ :return: scalar or list of one or more return attribute values
781
+ :rtype: list if name is a list; scalar otherwise
782
+ """
783
+ return self.Coordinates.get_atom_attribute(att_name,attribute_dict)
784
+
785
+ def increment_gro_attribute_by_attributes(self,att_name,attribute_dict):
786
+ """increment_gro_attribute_by_attributes add one to attribute att_name of all atoms identified by attribute:value pairs in attribute_dict
787
+
788
+ :param att_name: name of attribute to increment
789
+ :type att_name: str
790
+ :param attribute_dict: attribute:value pairs that specify atoms to which to apply this incrementation
791
+ :type attribute_dict: dict
792
+ """
793
+ val=self.get_gro_attribute_by_attributes(att_name,attribute_dict)
794
+ val+=1
795
+ self.set_gro_attribute_by_attributes(att_name,val,attribute_dict)
796
+
797
+ def decrement_gro_attribute_by_attributes(self,att_name,attribute_dict):
798
+ """decrement_gro_attribute_by_attributes subtract one from attribute att_name of all atoms identified by attribute:value pairs in attribute_dict
799
+
800
+ :param att_name: name of attribute to increment
801
+ :type att_name: str
802
+ :param attribute_dict: attribute:value pairs that specify atoms to which to apply this incrementation
803
+ :type attribute_dict: dict
804
+ """
805
+ val=self.get_gro_attribute_by_attributes(att_name,attribute_dict)
806
+ val-=1
807
+ self.set_gro_attribute_by_attributes(att_name,val,attribute_dict)
808
+
809
+ def get_gro_attributelist_by_attributes(self,attribute_list,attribute_dict):
810
+ """get_atoms_w_attribute returns all rows of atoms dataframe and columns named in names of atoms identified by the attributes dict
811
+
812
+ :param attribute_list: list of attributes to be in the rows that are returned
813
+ :type sttribute_list: list
814
+ :param attribute_dict: dictionary of attribute:value pairs that specify the set of atoms to be considered
815
+ :type attribute_dict: dict
816
+ :return: a dataframe segment
817
+ :rtype: pd.DataFrame
818
+ """
819
+ return self.Coordinates.get_atoms_w_attribute(attribute_list,attribute_dict)
820
+
821
+ def get_R(self,idx):
822
+ """get_R return the cartesian position of atom with global index idx
823
+
824
+ :param idx: atom global index
825
+ :type idx: int
826
+ :return: position of atom
827
+ :rtype: numpy.ndarray(3,float)
828
+ """
829
+ return self.Coordinates.get_R(idx)
830
+
831
+ def rotate(self,R):
832
+ """rotate applies rotation matrix R to all atom positions
833
+
834
+ :param R: rotation matrix
835
+ :type R: numpy.ndarray((3,3),float)
836
+ """
837
+ self.Coordinates.rotate(R)
838
+
839
+ def translate(self,L):
840
+ """translate applies translation vector L to all atom positions
841
+
842
+ :param L: translation vector
843
+ :type L: numpy.ndarray(3,float)
844
+ """
845
+ self.Coordinates.translate(L)
846
+
847
+ def partners_of(self,i):
848
+ """partners_of return list of atom indices of bonded partners of atom i
849
+
850
+ :param i: global index of atom
851
+ :type i: int
852
+ :return: list of partner global indices
853
+ :rtype: list
854
+ """
855
+ return self.Topology.bondlist.partners_of(i)
856
+
857
+ def resid_partners_of(self,ri):
858
+ """resid_partners_of return list of resid partners of resid ri
859
+
860
+ :param ri: residue index
861
+ :type ri: int
862
+ :return: list of partner residue indices (two residues are partners if there is at least one interatomic bond joining them)
863
+ :rtype: list
864
+ """
865
+ result=[]
866
+ adf=self.Coordinates.A
867
+ radf=adf[adf['resNum']==ri]
868
+ for at in radf['globalIdx'].to_list():
869
+ bl=self.Topology.bondlist.partners_of(at)
870
+ for j in bl:
871
+ theirresid=adf.iloc[j-1]['resNum']
872
+ if theirresid!=ri and not theirresid in result:
873
+ result.append(theirresid)
874
+ return result
875
+
876
+ def interresidue_partners_of(self,i):
877
+ """interresidue_partners_of return list of atom indices that are bonded partners of atom i and are not in the residue of atom i
878
+
879
+ :param i: atom global index
880
+ :type i: int
881
+ :return: list of atom indices of atoms that are partners of i not in i's residue
882
+ :rtype: list
883
+ """
884
+ result=[]
885
+ bl=self.Topology.bondlist.partners_of(i)
886
+ # logger.debug(f'{i} partners {bl}')
887
+ myresid=self.Coordinates.A.iloc[i-1]['resNum']
888
+ for j in bl:
889
+ theirresid=self.Coordinates.A.iloc[j-1]['resNum']
890
+ if theirresid!=myresid:
891
+ result.append(j)
892
+ return result
893
+
894
+ def minimum_distance(self,other,self_excludes=[],other_excludes=[]):
895
+ """minimum_distance computes the distance of closest approach between self's Coordinates that other's Coordinates
896
+
897
+ :param other: another TopoCoord object
898
+ :type other: TopoCoord
899
+ :param self_excludes: list of global atom indices to ignore in self, defaults to []
900
+ :type self_excludes: list, optional
901
+ :param other_excludes: list of global atom indices to ignore in other, defaults to []
902
+ :type other_excludes: list, optional
903
+ :return: distance of closest approach: i.e., the distance between the two atoms, one from self and one from other, that are closest together
904
+ :rtype: float
905
+ """
906
+ return self.Coordinates.minimum_distance(other.Coordinates,self_excludes=self_excludes,other_excludes=other_excludes)
907
+
908
+ # def has_gro_attributes(self,attribute_list):
909
+ # return self.Coordinates.has_atom_attributes(attribute_list)
910
+
911
+ def are_bonded(self,i,j):
912
+ """are_bonded checks to see if atoms with indices i and j are bonded to each other
913
+
914
+ :param i: an atom global index
915
+ :type i: int
916
+ :param j: another atom global index
917
+ :type j: int
918
+ :return: True if atoms are bonded, False otherwise
919
+ :rtype: bool
920
+ """
921
+ return self.Topology.bondlist.are_bonded(i,j)
922
+
923
+ # def decrement_z(self,pairs):
924
+ # self.Coordinates.decrement_z(pairs)
925
+
926
+ def adjust_charges(self,atoms=[],overcharge_threshhold=0.1,netcharge=0.0,msg=''):
927
+ """adjust_charges adjust the partial charges on atoms in list 'atoms' if the absolute net charge exceeds 'netcharge' by the 'overcharge_threshhold'
928
+
929
+ :param atoms: list of atom indexes to consider, defaults to []
930
+ :type atoms: list, optional
931
+ :param overcharge_threshhold: absolute deviation from netcharge that triggers adjustment, defaults to 0.1
932
+ :type overcharge_threshhold: float, optional
933
+ :param netcharge: desired net charge, defaults to 0.0
934
+ :type netcharge: float, optional
935
+ :param msg: a little message to echo to console if adjustment is necessary, defaults to ''
936
+ :type msg: str, optional
937
+ """
938
+ self.Topology.adjust_charges(atoms=atoms,overcharge_threshhold=overcharge_threshhold,desired_charge=netcharge,msg=msg)
939
+
940
+ def gro_DataFrame(self,name):
941
+ """gro_DataFrame return the appropriate Coordinates dataframe based on the directive in 'name'
942
+
943
+ :param name: either 'atoms' or 'mol2_bonds'
944
+ :type name: str
945
+ :return: the desired dataframe
946
+ :rtype: pandas.DataFrame
947
+ """
948
+ if name=='atoms':
949
+ return self.Coordinates.A
950
+ elif name=='mol2_bonds':
951
+ return self.Coordinates.mol2_bonds
952
+ else:
953
+ return None
954
+
955
+ def overwrite_coords(self,other):
956
+ """overwrite_coords overwrite coordinates in self by those in other
957
+
958
+ :param other: another TopoCoord object
959
+ :type other: TopoCoord
960
+ """
961
+ # logger.debug(f'Overwriting {other.Coordinates.A.shape[0]} coordinates')
962
+ C=self.Coordinates.A
963
+ C=C.set_index('globalIdx')
964
+ # logger.debug(f'before update:\n{C.to_string()}')
965
+ B=other.Coordinates.A
966
+ B=B.set_index('globalIdx')
967
+ B=B[['posX','posY','posZ']].copy()
968
+ # logger.debug(f'new coordinates:\n{B.to_string()}')
969
+ C.update(B)
970
+ self.Coordinates.A=C.reset_index()
971
+ # logger.debug(f'after update:\n{self.Coordinates.A.to_string()}')
972
+
973
+ def linkcell_initialize(self,cutoff,ncpu=1,force_repopulate=True):
974
+ """linkcell_initialize Initialize the linkcell structure; a wrapper for Coordinates
975
+
976
+ :param cutoff: minimum value of cell side-length
977
+ :type cutoff: float
978
+ :param ncpu: number of processors to use in populating linkcell structure in parallel, default 1
979
+ :type ncpu: int
980
+ """
981
+ self.Coordinates.linkcell_initialize(cutoff,ncpu=ncpu,populate=True,force_repopulate=force_repopulate)
982
+
983
+ def linkcell_cleanup(self):
984
+ """linkcell_cleanup removes linkcell_idx attribute from Coordinate.A
985
+ """
986
+ self.Coordinates.A.drop(columns=['linkcell_idx'],inplace=True)
987
+
988
+ def atom_count(self):
989
+ """atom_count Check to be sure the Coordinate and Topology members contain the same number of
990
+ atoms
991
+
992
+ :return: the number of atoms
993
+ :rtype: int
994
+ """
995
+ assert self.Coordinates.A.shape[0]==self.Topology.D['atoms'].shape[0]
996
+ return self.Coordinates.A.shape[0]
997
+
998
+ def total_mass(self,units='SI'):
999
+ """total_mass Returns the total mass of the system. Just a wrapper.
1000
+
1001
+ :param units: units designation, defaults to 'SI' (other option is 'gromacs')
1002
+ :type units: str, optional
1003
+ :return: mass
1004
+ :rtype: float
1005
+ """
1006
+ return self.Topology.total_mass(units=units)
1007
+
1008
+ def total_volume(self,units='SI'):
1009
+ """total_volume returns total volume represented by the system's Coordinates
1010
+
1011
+ :param units: unit designation, defaults to 'SI'
1012
+ :type units: str, optional
1013
+ :return: box volume
1014
+ :rtype: float
1015
+ """
1016
+ return self.Coordinates.box_volume(units=units)
1017
+
1018
+ def density(self,units='SI'):
1019
+ """density returns system density
1020
+
1021
+ :param units: unit designation, defaults to 'SI'
1022
+ :type units: str, optional
1023
+ :return: density
1024
+ :rtype: float
1025
+ """
1026
+ return self.total_mass(units)/self.total_volume(units)
1027
+
1028
+ def wrap_coords(self):
1029
+ """wrap_coords wrap all coordinates into center periodic box
1030
+ """
1031
+ self.Coordinates.wrap_coords()
1032
+
1033
+ def inherit_grx_attributes_from_molecules(self,molecule_dict,initial_composition,globally_unique=GRX_GLOBALLY_UNIQUE,unset_defaults=GRX_UNSET_DEFAULTS,overall_default=0):
1034
+ """inherit_grx_attributes_from_molecules Copy non-Gromacs-standard atom attributes in list "attributes" from molecule templates in molecule_dict according to molecule counts in dict initial_composition.
1035
+
1036
+ :param attributes: list of labels of attributes to copy
1037
+ :type attributes: list
1038
+ :param molecule_dict: dictionary of available molecules (name:Molecule)
1039
+ :type molecule_dict: dict
1040
+ :param initial_composition: dictionary of initial composition (name:count)
1041
+ :type initial_composition: dict
1042
+ :param globally_unique: boolean list indicating attributes that must be globally unique, defaults to []
1043
+ :type globally_unique: list, optional
1044
+ :param unset_defaults: list of values, one per attribute, that signify UNSET, defaults to []
1045
+ :type unset_defaults: list, optional
1046
+ :param overall_default: default UNSET value for all attributes if unset_defaults is empty, defaults to 0
1047
+ :type overall_default: int, optional
1048
+ """
1049
+ # logger.debug(f'inherit grx {attributes} {unset_defaults} {globally_unique}')
1050
+ ''' set up the globally_unique and unset_defaults list if necessary '''
1051
+ if len(globally_unique)!=len(self.grxattr):
1052
+ globally_unique=[False for _ in range(len(self.grxattr))]
1053
+ if len(unset_defaults)!=len(self.grxattr):
1054
+ unset_defaults=[overall_default for _ in range(len(self.grxattr))]
1055
+
1056
+ ''' drop all attribute values from current global atom dataframe '''
1057
+ adf=self.Coordinates.A
1058
+ self.Coordinates.A=adf.drop(columns=[a for a in self.grxattr if a in adf])
1059
+
1060
+ logger.debug(f'{adf.shape[0]} atoms inheriting these attributes from molecular templates:')
1061
+ logger.debug(f' Attribute name Default value Globally unique?')
1062
+ for attname,defval,gu in zip(self.grxattr,unset_defaults,globally_unique):
1063
+ logger.debug(f' {attname:<15s} {str(defval):<13s} {gu}')
1064
+ if len(unset_defaults)==len(self.grxattr):
1065
+ att_running_maxval={}
1066
+ for k,v in zip(self.grxattr,unset_defaults):
1067
+ if type(v)==int or type(v)==float:
1068
+ att_running_maxval[k]=0
1069
+ else:
1070
+ att_running_maxval[k]='0'
1071
+ else:
1072
+ att_running_maxval={k:overall_default for k in self.grxattr}
1073
+
1074
+ attribute_lists={k:[] for k in self.grxattr}
1075
+ value_counts={k:0 for k in self.grxattr}
1076
+ mol_idx_counter=0
1077
+ for icdict in [cc for cc in initial_composition if 'count' in cc]:
1078
+ molecule=icdict['molecule']
1079
+ count=icdict['count']
1080
+ mol_adf=molecule_dict[molecule].TopoCoord.Coordinates.A
1081
+ logger.debug(f'Inheriting from {molecule}')
1082
+ for ln in mol_adf.head().to_string().split('\n'):
1083
+ logger.debug(ln)
1084
+ mol_attr_df=mol_adf[self.grxattr]
1085
+ for molecule_number in range(count):
1086
+ for i,k in enumerate(self.grxattr):
1087
+ tra=mol_attr_df[k].to_list()
1088
+ if k=='molecule':
1089
+ utra=[mol_idx_counter for _ in tra]
1090
+ mol_idx_counter+=1
1091
+ else:
1092
+ # nv=len(tra)-tra.count(unset_defaults[i])
1093
+ nuv=len(list(set([x for x in tra if x != unset_defaults[i]])))
1094
+ utra=[]
1095
+ for x in tra:
1096
+ if globally_unique[i] and (type(x)==int or type(x)==float):
1097
+ xx=x+value_counts[k] if x!=unset_defaults[i] else unset_defaults[i]
1098
+ else:
1099
+ xx=x
1100
+ utra.append(xx)
1101
+ value_counts[k]+=nuv
1102
+ attribute_lists[k].extend(utra)
1103
+
1104
+ for k,L in attribute_lists.items():
1105
+ self.Coordinates.A[k]=L
1106
+ logger.debug(f'postinherit adf columns {self.Coordinates.A.columns}')
1107
+
1108
+ def make_resid_graph(self,json_file=None):
1109
+ """make_resid_graph make a residue connectivity graph
1110
+
1111
+ :param json_file: name of output JSON file to write, defaults to None
1112
+ :type json_file: str, optional
1113
+ """
1114
+ self.Topology.make_resid_graph(json_file=json_file)
1115
+
1116
+ def maxspan(self):
1117
+ """maxspan Returns the maxspan of the Coordinates (dimensions of orthorhombic
1118
+ convex hull enclosing Coordinates). Just a wrapper.
1119
+
1120
+ :return: array of x-span, y-span, z-span
1121
+ :rtype: numpy.ndarray
1122
+ """
1123
+ return self.Coordinates.maxspan()
1124
+
1125
+ def minmax(self):
1126
+ """minmax returns the coordinates of the atoms at the lower-leftmost and upper-rightmost positions in the constellation of points in the atoms dataframe
1127
+
1128
+ :return: tuple of two points, lower-leftmost and upper-rightmost, respectively
1129
+ :rtype: tuple(np.ndarray(3,float),np.ndarray(3,float))
1130
+ """
1131
+ return self.Coordinates.minmax()
1132
+
1133
+ def checkbox(self):
1134
+ """checkbox checks that the entire constellation of points in the atoms dataframe fits within the designated box for this Configuration object
1135
+
1136
+ :return: True,True if both lower-leftmost and upper-rightmost points are within the box
1137
+ :rtype: tuple(bool,bool)
1138
+ """
1139
+ return self.Coordinates.checkbox()
1140
+
1141
+ def write_mol2(self,filename,molname='',element_names_as_types=False):
1142
+ """write_mol2 Writes a SYBYL MOL2-format file using Coordinates, with certain
1143
+ atom attributes borrowed from the Topology
1144
+
1145
+ :param filename: name of file to write
1146
+ :type filename: str
1147
+ :param molname: name of molecule to put in mol2 file, defaults to ''
1148
+ :type molname: str, optional
1149
+ """
1150
+ if molname=='':
1151
+ molname='This Molecule has no name'
1152
+ other_attributes=pd.DataFrame()
1153
+ if element_names_as_types:
1154
+ element_names=[x[0] for x in self.Topology.D['atoms']['atom']]
1155
+ other_attributes['type']=element_names
1156
+ else:
1157
+ other_attributes['type']=self.Topology.D['atoms']['type']
1158
+ other_attributes['charge']=self.Topology.D['atoms']['charge']
1159
+ self.files['mol2']=os.path.abspath(filename)
1160
+ # logger.debug(f'write_mol2, other_attributes:\n{other_attributes.to_string()}')
1161
+ if 'mol2_bonds' in self.Topology.D:
1162
+ self.Coordinates.write_mol2(filename,molname=molname,bondsDF=self.Topology.D['mol2_bonds'],other_attributes=other_attributes)
1163
+ else:
1164
+ self.Coordinates.write_mol2(filename,molname=molname,other_attributes=other_attributes)
1165
+
1166
+ def merge(self,other):
1167
+ """merge Merges the TopoCoord instance "other" to self
1168
+
1169
+ :param other: another TopoCoord instance
1170
+ :type other: TopoCoord
1171
+ :return: a shift tuple (returned by Coordinates.merge())
1172
+ :rtype: tuple
1173
+ """
1174
+ self.Topology.merge(other.Topology)
1175
+ shifts=self.Coordinates.merge(other.Coordinates)
1176
+ for name,idx_lists in other.idx_lists.items():
1177
+ # logger.debug(f'TopoCoord merge: list_name {name} lists {idx_lists}')
1178
+ for a_list in idx_lists:
1179
+ self.idx_lists[name].append([x+shifts[0] for x in a_list])
1180
+ self.reset_grx_attributes_from_idx_list(name)
1181
+ return shifts
1182
+
1183
+ def bondtest_df(self,df:pd.DataFrame,pbc=[1,1,1],show_piercings=True):
1184
+ """bondtest_df applies bond filters to all bonds in the dataframe;
1185
+
1186
+ :param df: dataframe of possible bonds; dataframe should have columns 'ai', 'aj' and 'r'; this method adds the column 'results'
1187
+ :type df: pd.DataFrame
1188
+ :param pbc: flags indicating dimensions in which pbc are used, defaults to [1,1,1]
1189
+ :type pbc: list, optional
1190
+ :param show_piercings: toggles diagnostic output for pierced rings, defaults to True
1191
+ :type show_piercings: bool, optional
1192
+ :return: input data frame with new 'results' column
1193
+ :rtype: pandas.DataFrame
1194
+ """
1195
+ if df.empty:
1196
+ return df
1197
+ results=[]
1198
+ for r in df.itertuples():
1199
+ result,dummy=self.bondtest((r.ai,r.aj,r.r),pbc=pbc,show_piercings=show_piercings)
1200
+ results.append(result)
1201
+ df['result']=results
1202
+ for ln in df[df['result']==BTRC.passed].to_string().split('\n'):
1203
+ logger.debug(ln)
1204
+ return df
1205
+
1206
+ def bondtest(self,b,pbc=[1,1,1],show_piercings=True):
1207
+ """Determine if bond b is to be allowed to form based on geometric and
1208
+ topological criteria
1209
+
1210
+ :param b: bond, tuple (ai,aj,rij)
1211
+ :type b: 2-tuple
1212
+ :param pbc: periodic boundary condition flags in each direction, defaults to [1,1,1]
1213
+ :type pbc: list, optional
1214
+ :param show_piercings: flag indicating you want to write gro files showing
1215
+ pierced rings
1216
+ :type show_piercings: bool
1217
+ :return: BTRC instance
1218
+ :rtype: BTRC enum
1219
+ """
1220
+ i,j,rij=b
1221
+ # i=int(i)
1222
+ # j=int(j)
1223
+ if self.makes_shortcircuit(i,j):
1224
+ return BTRC.failed_short_circuit,0
1225
+ if self.makes_cycle(i,j):
1226
+ return BTRC.failed_bond_cycle,0
1227
+ if self.pierces_ring(i,j,pbc=pbc,show_piercings=show_piercings):
1228
+ return BTRC.failed_pierce_ring,0
1229
+ # logger.debug(f'passed: {i:>7d} {j:>7d} {rij:>6.3f} nm')
1230
+ return BTRC.passed,rij
1231
+
1232
+ def pierces_ring(self,i,j,pbc=[1,1,1],show_piercings=True):
1233
+ """pierces_ring checks to see if bond i-j would pierce any covalent ring structure
1234
+
1235
+ :param i: global index of an atom
1236
+ :type i: int
1237
+ :param j: global index of another
1238
+ :type j: int
1239
+ :param pbc: flags indicating which dimensions have pbc applied, defaults to [1,1,1]
1240
+ :type pbc: list, optional
1241
+ :param show_piercings: toggles diagnostic output of ring piercings, defaults to True
1242
+ :type show_piercings: bool, optional
1243
+ :return: True if a ring is pierced; False otherwise
1244
+ :rtype: bool
1245
+ """
1246
+ adf=self.Coordinates.A
1247
+ LC=self.Coordinates.linkcell
1248
+ # at the current state, a linkcell is active under Coordinates
1249
+ # with spacing *greater* than the initial length of any bond.
1250
+ # so we can visit rings with one or more atom in a cell neighboring
1251
+ # the cells of the two atoms
1252
+ assert 'linkcell_idx' in adf,f'Error: atoms have no linkcell_idx attribute - bug!'
1253
+ i_lcidx=self.get_gro_attribute_by_attributes('linkcell_idx',{'globalIdx':i})
1254
+ j_lcidx=self.get_gro_attribute_by_attributes('linkcell_idx',{'globalIdx':j})
1255
+ joint_idx=[]
1256
+ for idx in LC.neighborlists[i_lcidx]+LC.neighborlists[j_lcidx]+[i_lcidx,j_lcidx]:
1257
+ if not idx in joint_idx:
1258
+ joint_idx.append(idx)
1259
+ cycle_tags=list(set(adf[(adf['cycle']!=-1)&(adf['linkcell_idx'].isin(joint_idx))]['cycle'].to_list()))
1260
+ B=adf.iloc[[i-1,j-1]].copy()
1261
+ saveB=B.copy()
1262
+ # logger.debug(f'bond {i} {j} subframe')
1263
+ # for ln in B.to_string().split('\n'):
1264
+ # logger.debug(ln)
1265
+ for c in cycle_tags:
1266
+ C=adf[adf['cycle']==c].copy()
1267
+ # logging.debug(f'ring {c} has {C.shape[0]} members')
1268
+ # assert 4<C.shape[0]<7
1269
+ saveC=C.copy()
1270
+ if self.Coordinates.pierces(B,C,pbc):
1271
+ if show_piercings:
1272
+ sub=self.Coordinates.subcoords(pd.concat([B,C]))
1273
+ sub.write_gro(f'ring-{i}-{j}'+'.gro')
1274
+ sub=self.Coordinates.subcoords(pd.concat([saveB,saveC]))
1275
+ sub.write_gro(f'ring-orig-{i}-{j}'+'.gro')
1276
+ logger.debug(f'Cycle {c} pierced by bond candidate {i}-{j}')
1277
+ for ln in sub.A.to_string().split('\n'):
1278
+ logger.debug(ln)
1279
+ return True
1280
+ return False
1281
+
1282
+ def makes_shortcircuit(self,i,j):
1283
+ """Determine whether atoms i and j, if bonded, would produce a short circuit,
1284
+ defined as an instance in which i and j belong to residues that are already
1285
+ bonded to each other
1286
+
1287
+ :param i: global index of first atom
1288
+ :type i: int
1289
+ :param j: global index of second atom
1290
+ :type j: int
1291
+ :return: True if a short circuit would happen, False otherwise
1292
+ :rtype: bool
1293
+ """
1294
+ i_resName,i_resNum,i_atomName,i_molNum=self.get_gro_attribute_by_attributes(['resName','resNum','atomName','molecule'],{'globalIdx':i})
1295
+ j_resName,j_resNum,j_atomName,j_molNum=self.get_gro_attribute_by_attributes(['resName','resNum','atomName','molecule'],{'globalIdx':j})
1296
+ '''
1297
+ In a cure reaction, atoms that react should be in different residues
1298
+ '''
1299
+ assert i_resNum!=j_resNum,f'shortcircuit test error {i}-{j} both in residue {i_resNum}?'
1300
+ i_neighbors=self.partners_of(i)
1301
+ j_neighbors=self.partners_of(j)
1302
+ # if i in j_neighbors or j in i_neighbors:
1303
+ # # logger.debug(f'atoms {i} and {j} already on each other\'s list of bonded partners')
1304
+ # return True
1305
+ '''
1306
+ Should never test a proposed bond that already exists
1307
+ '''
1308
+ assert not j in i_neighbors
1309
+ assert not i in j_neighbors
1310
+ '''
1311
+ Set up a DataFrame for heavy atoms in each molecule
1312
+ '''
1313
+ ADF=self.Coordinates.A
1314
+ R1DF=ADF[ADF['molecule']==i_molNum]
1315
+ R1DF=R1DF[[(not (b.startswith('H') or b.startswith('h'))) for b in R1DF['atomName']]]
1316
+ R2DF=ADF[ADF['molecule']==j_molNum]
1317
+ R2DF=R2DF[[(not (b.startswith('H') or b.startswith('h'))) for b in R2DF['atomName']]]
1318
+ assert R1DF.shape[0]>0
1319
+ assert R2DF.shape[0]>0
1320
+ '''
1321
+ Test to see if there exists any bond between these two molecules
1322
+ '''
1323
+ for i,j in product(R1DF['globalIdx'].to_list(),R2DF['globalIdx'].to_list()):
1324
+ if self.are_bonded(i,j):
1325
+ return True
1326
+ return False
1327
+
1328
+ def reset_grx_attributes_from_idx_list(self,list_name):
1329
+ """reset_grx_attributes_from_idx_list uses information in the "index lists" to repopulate appropriate GRX attributes. There are two index lists: one for cycles and the other for chains. Each index list is a list of lists; each element corresponds to a unique structure (cycle or chain) and is a list of global atom indices for atoms that make up that structural instance.
1330
+
1331
+ :param list_name: either 'cycle' or 'chain'
1332
+ :type list_name: str
1333
+ """
1334
+ self.set_gro_attribute(list_name,-1)
1335
+ self.set_gro_attribute(f'{list_name}_idx',-1)
1336
+ for i,c in enumerate(self.idx_lists[list_name]):
1337
+ for j,x in enumerate(c):
1338
+ self.set_gro_attribute_by_attributes(list_name,i,{'globalIdx':x})
1339
+ self.set_gro_attribute_by_attributes(f'{list_name}_idx',j,{'globalIdx':x})
1340
+
1341
+ def reset_idx_list_from_grx_attributes(self,list_name):
1342
+ """reset_idx_list_from_grx_attributes is the inverse of reset_grx_attributes_from_idx_list: it uses the GRX attributes to rebuild index lists.
1343
+
1344
+ :param list_name: either 'cycle' or 'chain'
1345
+ :type list_name: str
1346
+ """
1347
+ adf=self.Coordinates.A
1348
+ logger.debug(f'reset: columns {adf.columns}')
1349
+ tmp_dict={}
1350
+ for i,r in adf.iterrows():
1351
+ gix=r['globalIdx']
1352
+ cid=r[list_name]
1353
+ cix=r[f'{list_name}_idx']
1354
+ if cid!=-1:
1355
+ if not cid in tmp_dict:
1356
+ tmp_dict[cid]={}
1357
+ tmp_dict[cid][cix]=gix
1358
+ # logger.debug(f'{list_name} tmp_dict item count: {len(tmp_dict)}')
1359
+ # logger.debug(f'{tmp_dict}')
1360
+ if tmp_dict:
1361
+ consec_test=[a in tmp_dict for a in range(len(tmp_dict))]
1362
+ # logger.debug(f'{consec_test}')
1363
+ assert all(consec_test),f'{list_name} reset_idx_list for group attribute {list_name} has non-consecutive integer keys -- bug\n{[a in tmp_dict for a in range(len(tmp_dict))]}'
1364
+ ngroups=len(tmp_dict)
1365
+ self.idx_lists[list_name]=[[] for _ in range(ngroups)]
1366
+ for i in range(ngroups):
1367
+ for j in range(len(tmp_dict[i])):
1368
+ self.idx_lists[list_name][i].append(tmp_dict[i][j])
1369
+ # logger.debug(f'-> idx_lists[{list_name}]: {self.idx_lists[list_name]}')
1370
+
1371
+ def chainlist_update(self,new_bond_recs,msg=''):
1372
+ """chainlist_update updates the chain index lists due to generation of new bonds
1373
+
1374
+ :param new_bond_recs: list of bond records, each a tuple of two ints corresponding to atom indices
1375
+ :type new_bond_recs: list
1376
+ :param msg: a nice message (unused), defaults to ''
1377
+ :type msg: str, optional
1378
+ """
1379
+ chainlists=self.idx_lists['chain']
1380
+ if len(chainlists)==0: return
1381
+ # logger.debug(f'pre {msg} chainlists')
1382
+ # for i,c in enumerate(chainlists):
1383
+ # logger.debug(f' {i} {c}')
1384
+ for b in new_bond_recs:
1385
+ aidx,bidx=b[0],b[1]
1386
+ ar=self.get_gro_attribute_by_attributes('resNum',{'globalIdx':aidx})
1387
+ br=self.get_gro_attribute_by_attributes('resNum',{'globalIdx':bidx})
1388
+ if ar==br: continue # ignore intramolecular bonds
1389
+ # logger.debug(f'chainlist_update pair {aidx} {bidx}')
1390
+ ac=self.get_gro_attribute_by_attributes('chain',{'globalIdx':aidx})
1391
+ bc=self.get_gro_attribute_by_attributes('chain',{'globalIdx':bidx})
1392
+ logger.debug(f'ac {ac} bc {bc}')
1393
+ if ac==-1 or bc==-1:
1394
+ # neither of these newly bonded atoms is already in a chain, so
1395
+ # there is no possibility that this new bond can join two chains.
1396
+ continue
1397
+ # logger.debug(f'chain of bidx {bidx}: {chainlists[bc]}')
1398
+ # logger.debug(f'chain of aidx {aidx}: {chainlists[ac]}')
1399
+ aci=self.get_gro_attribute_by_attributes('chain_idx',{'globalIdx':aidx})
1400
+ bci=self.get_gro_attribute_by_attributes('chain_idx',{'globalIdx':bidx})
1401
+ logger.debug(f' -> {aidx}-{bidx}: ac {ac} #{len(chainlists[ac])} aci {aci} bc {bc} #{len(chainlists[bc])} bci {bci}')
1402
+ # one must be a head and the other a tail
1403
+ if aci==0: # a is a head
1404
+ if len(chainlists[bc])-1!=bci:
1405
+ logger.warning(f'Atom {bidx} has index {bci} in chain {bc} but that chain has {len(chainlists[bc])} elements, so it cannot be the tail of the chain. The tail appears to be atom {chainlists[bc][-1]}. So something is wrong, and I am not merging these chains.')
1406
+ logger.debug(f'chain of {aidx} {chainlists[ac]}')
1407
+ logger.debug(f'chain of {bidx} {chainlists[bc]}')
1408
+ continue
1409
+ c1=ac
1410
+ c2=bc
1411
+ elif bci==0: # b is a head
1412
+ if len(chainlists[ac])-1!=aci:
1413
+ logger.warning(f'Atom {aidx} has index {aci} in chain {ac} but that chain has {len(chainlists[ac])} elements, so it cannot be the tail of the chain. The tail appears to be atom {chainlists[ac][-1]}. So something is wrong, and I am not merging these chains.')
1414
+ logger.debug(f'chain of {aidx} {chainlists[ac]}')
1415
+ logger.debug(f'chain of {bidx} {chainlists[bc]}')
1416
+ continue
1417
+ c1=bc
1418
+ c2=ac
1419
+ else:
1420
+ logger.debug(f'Neither of {aidx} or {bidx} are heads of their respective chains.')
1421
+ logger.debug(f'This is most likely happening because of branching, which is permitted but')
1422
+ logger.debug(f'does not allow for merging of 1-D chains.')
1423
+ continue
1424
+ chainlists[c2].extend(chainlists[c1])
1425
+ for aidx in chainlists[c1]:
1426
+ self.set_gro_attribute_by_attributes('chain',c2,{'globalIdx':aidx})
1427
+ self.set_gro_attribute_by_attributes('chain_idx',chainlists[c2].index(aidx),{'globalIdx':aidx})
1428
+ # logger.debug(f'removing chain {c1}')
1429
+ chainlists.remove(chainlists[c1])
1430
+ # since we remove c1, all indices greater than c1 must decrement
1431
+ dec_us=np.array(self.Coordinates.A['chain'])
1432
+ bad_chain_idx=np.where(dec_us>c1)
1433
+ # logger.debug(f'bad_chain_idx: {bad_chain_idx}')
1434
+ # logger.debug(f'{dec_us[bad_chain_idx]}')
1435
+ dec_us[bad_chain_idx]-=1
1436
+ self.Coordinates.A['chain']=dec_us
1437
+ cnms=[]
1438
+ for c in self.idx_lists['chain']:
1439
+ cnms.append([self.get_gro_attribute_by_attributes('atomName',{'globalIdx':x}) for x in c])
1440
+ # logger.debug(f'post {msg} chains {self.idx_lists["chain"]} {cnms}')
1441
+
1442
+ def makes_cycle(self,aidx,bidx):
1443
+ """makes_cycle checks the current chain index lists to see if a bond between aidx and bidx (global atom indices) would generate a C-C' cycle
1444
+
1445
+ :param aidx: global index of an atom
1446
+ :type aidx: int
1447
+ :param bidx: global index of another atom
1448
+ :type bidx: int
1449
+ :return: True if a bond betwen aidx and bidx would form a C-C' cycle
1450
+ :rtype: bool
1451
+ """
1452
+ # is there a chain with aidx as head and bidx as tail, or vice versa?
1453
+ for c in self.idx_lists['chain']:
1454
+ if (aidx==c[0] and bidx==c[-1]) or (aidx==c[-1] and bidx==c[0]):
1455
+ return True
1456
+ return False
1457
+
1458
+ def cycle_collective(self,bdf:pd.DataFrame):
1459
+ """cycle_collective Check to see if, when considered as a collective, this
1460
+ set of bondrecs leads to one or more cyclic chain; if so, longest bonds that
1461
+ break cycles are removed from bondrecs list and resulting list is returned
1462
+
1463
+ :param bdf: bonds data frame
1464
+ :type bdf: pandas.DataFrame
1465
+ :return: list of bond records that results in no new cycles
1466
+ :rtype: list
1467
+ """
1468
+ def addlink(chainlist,i,j):
1469
+ i_cidx=(-1,-1)
1470
+ j_cidx=(-1,-1)
1471
+ for cidx,c in enumerate(chainlist):
1472
+ if i in c:
1473
+ i_cidx=(cidx,c.index(i))
1474
+ if j in c:
1475
+ j_cidx=(cidx,c.index(j))
1476
+ logger.debug(f'i {i_cidx} j {j_cidx}')
1477
+ if not (i_cidx==(-1,-1) or (j_cidx==(-1,-1))):
1478
+ # logger.debug(f'cycle_collective: {i} is in chain {i_cidx[0]} at {i_cidx[1]}')
1479
+ # logger.debug(f'cycle_collective: {j} is in chain {j_cidx[0]} at {j_cidx[1]}')
1480
+ if i_cidx[0]==j_cidx[0]:
1481
+ # cyclized!
1482
+ logger.debug(f'chain {i_cidx[0]} is cyclized!')
1483
+ return i_cidx[0],True
1484
+ old_head,old_tail=(i_cidx,j_cidx) if i_cidx[1]==0 else (j_cidx,i_cidx)
1485
+ chainlist[old_tail[0]].extend(chainlist[old_head[0]])
1486
+ # logger.debug(f'new chain {old_tail[0]} {chainlist[old_tail[0]]}')
1487
+ chainlist.remove(chainlist[old_head[0]])
1488
+ return old_tail[0],False
1489
+ else: # this bond involves one atom in a chain and another that is not; no way this can be a cyclization, but we have to return somthing
1490
+ return i_cidx[0] if i_cidx[0]!=-1 else j_cidx[0],False
1491
+
1492
+ # kb=bondrecs.copy()
1493
+ # logger.debug(f'checking set of {bdf.shape[0]} bonds for nascent cycles')
1494
+ new_bdf=bdf.copy()
1495
+ new_bdf['remove-to-uncyclize']=[False for _ in range(new_bdf.shape[0])]
1496
+ chains=deepcopy(self.idx_lists['chain'])
1497
+ assert id(chains) != id(self.idx_lists['chain'])
1498
+ if not chains:
1499
+ return new_bdf
1500
+ cyclized_chains={}
1501
+ chains_of_bonds=[]
1502
+ for i,r in bdf.iterrows():
1503
+ chain_idx,cyclized=addlink(chains,r.ai,r.aj)
1504
+ # logger.debug(f'bond {i} {r.ai}-{r.aj} ({r.reactantName}) adds to chain {chain_idx}')
1505
+ chains_of_bonds.append(chain_idx)
1506
+ if cyclized and not chain_idx in cyclized_chains:
1507
+ cyclized_chains[chain_idx]=[]
1508
+ assert len(chains_of_bonds)==bdf.shape[0]
1509
+ for i,r in bdf.iterrows():
1510
+ # logger.debug(f'compiling bonds of cyclized chains: bond {i}')
1511
+ cidx=chains_of_bonds[i]
1512
+ # logger.debug(f'compiling bonds of cyclized chains: cidx {chains_of_bonds[i]}')
1513
+ if cidx in cyclized_chains:
1514
+ cyclized_chains[cidx].append(i)
1515
+ for k,v in cyclized_chains.items():
1516
+ lb=v[-1] # last bondrec in list
1517
+ new_bdf.loc[lb,'remove-to-uncyclize']=True
1518
+ return new_bdf
1519
+
1520
+ def get_bystanders(self,atom_idx):
1521
+ """get_bystanders identify and return bystanders at a particular proposed bond specified by atom_idx
1522
+
1523
+ :param atom_idx: container of two global atom indices specifying a proposed bond
1524
+ :type atom_idx: container
1525
+ :return: 4-tuple of special bystander info containers
1526
+ :rtype: tuple
1527
+ """
1528
+ bystander_atomidx=[[int],[int]] # elements correspond to atoms in atom_idx
1529
+ bystander_atomnames=[[str],[str]]
1530
+ bystander_resids=[[int],[int]]
1531
+ bystander_resnames=[[str],[str]]
1532
+ for x in [0,1]:
1533
+ bystander_atomidx[x]=self.interresidue_partners_of(atom_idx[x])
1534
+ if atom_idx[1-x] in bystander_atomidx[x]: # if new bond has not yet formed
1535
+ bystander_atomidx[x].remove(atom_idx[1-x])
1536
+ bystander_atomnames[x]=[self.get_gro_attribute_by_attributes('atomName',{'globalIdx':y}) for y in bystander_atomidx[x]]
1537
+ bystander_resids[x]=[self.get_gro_attribute_by_attributes('resNum',{'globalIdx':y}) for y in bystander_atomidx[x]]
1538
+ bystander_resnames[x]=[self.get_gro_attribute_by_attributes('resName',{'globalIdx':y}) for y in bystander_atomidx[x]]
1539
+ return bystander_resids,bystander_resnames,bystander_atomidx,bystander_atomnames
1540
+
1541
+ def get_oneaways(self,atom_idx):
1542
+ """get_oneaways identify and return one-aways for a particular proposed bond specified by atom_idx
1543
+
1544
+ :param atom_idx: two-element container of atom indices specifying proposed bond
1545
+ :type atom_idx: list
1546
+ :return: tuple of oneaways-lists
1547
+ :rtype: tuple
1548
+ """
1549
+ resids=[self.get_gro_attribute_by_attributes('resNum',{'globalIdx':x}) for x in atom_idx]
1550
+ chains=[self.get_gro_attribute_by_attributes('chain',{'globalIdx':x}) for x in atom_idx]
1551
+ chain_idx=[self.get_gro_attribute_by_attributes('chain_idx',{'globalIdx':x}) for x in atom_idx]
1552
+ # logger.debug(f'chains {chains} chain_idx {chain_idx}')
1553
+ oneaway_resids=[None,None]
1554
+ oneaway_resnames=[None,None]
1555
+ oneaway_atomidx=[None,None]
1556
+ oneaway_atomnames=[None,None]
1557
+ # assert chain_idx[0]==0 or chain_idx[1]==0 # one must be a head
1558
+ if chains!=[-1,-1]:
1559
+ chainlists_idx=[self.idx_lists['chain'][chains[x]] for x in [0,1]]
1560
+ chainlists_atomnames=[]
1561
+ chainlists_resids=[]
1562
+ chainlists_resnames=[]
1563
+ for x in [0,1]:
1564
+ atomnamelist=[]
1565
+ residlist=[]
1566
+ resnamelist=[]
1567
+ for y in chainlists_idx[x]:
1568
+ rnum,rname,aname=self.get_gro_attribute_by_attributes(['resNum','resName','atomName'],{'globalIdx':y})
1569
+ residlist.append(rnum)
1570
+ resnamelist.append(rname)
1571
+ atomnamelist.append(aname)
1572
+ chainlists_atomnames.append(atomnamelist)
1573
+ chainlists_resids.append(residlist)
1574
+ chainlists_resnames.append(resnamelist)
1575
+ # logger.debug(f'chainlists_idx: {chainlists_idx}')
1576
+ # logger.debug(f'chainlists_atomnames: {chainlists_atomnames}')
1577
+ # logger.debug(f'chainlists_resids: {chainlists_resids}')
1578
+ # logger.debug(f'chainlists_resnames: {chainlists_resnames}')
1579
+ oa_chain_idx=[]
1580
+ if chain_idx[0]==0 or chain_idx[0]>chain_idx[1]:
1581
+ oa_chain_idx=[chain_idx[0]+2,chain_idx[1]-2]
1582
+ elif chain_idx[1]==0 or chain_idx[1]>chain_idx[0]:
1583
+ oa_chain_idx=[chain_idx[0]-2,chain_idx[1]+2]
1584
+ # logger.debug(f'oa_chain_idx {oa_chain_idx}')
1585
+ for i in range(len(oa_chain_idx)):
1586
+ if oa_chain_idx[i]<0:
1587
+ oa_chain_idx[i]=None
1588
+ oa_idx=[None,None]
1589
+ for i in [0,1]:
1590
+ try:
1591
+ oa_idx[i]=chainlists_idx[i][oa_chain_idx[i]]
1592
+ except:
1593
+ oa_idx[i]=None
1594
+ if oa_idx[i]:
1595
+ oneaway_atomidx[i]=chainlists_idx[i][oa_chain_idx[i]]
1596
+ oneaway_atomnames[i]=chainlists_atomnames[i][oa_chain_idx[i]]
1597
+ oneaway_resids[i]=chainlists_resids[i][oa_chain_idx[i]]
1598
+ oneaway_resnames[i]=chainlists_resnames[i][oa_chain_idx[i]]
1599
+ # logger.debug(f'result oneaway_resids {oneaway_resids} oneaway_resnames {oneaway_resnames}')
1600
+ # logger.debug(f'oneaway_atomidx {oneaway_atomidx} oneaway_atomnames {oneaway_atomnames}')
1601
+ return oneaway_resids,oneaway_resnames,oneaway_atomidx,oneaway_atomnames
1602
+
1603
+ def grab_files(self):
1604
+ """grab_files using absolute pathname information, grab the most up-to-date gromacs files for this system and deposit them into the cwd
1605
+ """
1606
+ cwd=os.getcwd()
1607
+ for ext in ['top','gro','grx']:
1608
+ filename=self.files[ext]
1609
+ logger.debug(f'{ext} grabbing {pfs.proj_abspath(filename)} into {pfs.cwd()}')
1610
+ if os.path.commonprefix([cwd,filename])!=cwd:
1611
+ shutil.copy(filename,cwd)
1612
+ self.files[ext]=os.path.abspath(os.path.basename(filename))
1613
+
1614
+ def grompp_and_mdrun(self,out,mdp,mylogger=logger.debug,**kwargs):
1615
+ """grompp_and_mdrun manages invoking a single Gromacs run using the current TopoCoord
1616
+
1617
+ :param out: output filename basename
1618
+ :type out: str
1619
+ :param mdp: name of mdp file
1620
+ :type mdp: str
1621
+ :param mylogger: a logger, defaults to logger.debug
1622
+ :type mylogger: logging.logger, optional
1623
+ :return: any message generated by gromacs.grompp_and_mdrun
1624
+ :rtype: str
1625
+ """
1626
+ wrap_coords=kwargs.get('wrap_coords',False)
1627
+ self.grab_files()
1628
+ # make sure required files exist in this directory
1629
+ top=os.path.basename(self.files['top']).replace('.top','')
1630
+ gro=os.path.basename(self.files['gro']).replace('.gro','')
1631
+ assert os.path.exists(f'{top}.top')
1632
+ assert os.path.exists(f'{gro}.gro')
1633
+ assert os.path.exists(f'{mdp}.mdp')
1634
+ mylogger(f'TopoCoord: running Gromacs {top}.top, {gro}.gro, {mdp}.mdp')
1635
+ msg=grompp_and_mdrun(gro=gro,top=top,out=out,mdp=mdp,**kwargs)
1636
+ self.copy_coords(TopoCoord(grofilename=f'{out}.gro',wrap_coords=wrap_coords))
1637
+ mylogger(f'after grompp_and_run: gro {self.files["gro"]}')
1638
+ return msg
1639
+
1640
+ def load_files(self,filenames:dict):
1641
+ """load_files load all gromacs files into TopoCoord
1642
+
1643
+ :param filenames: dictionary of extension:filename
1644
+ :type filenames: dict
1645
+ """
1646
+ for e,n in filenames.items():
1647
+ if not e in ['gro','top','grx','mol2']: continue
1648
+ bn,ext=os.path.splitext(n)
1649
+ logger.debug(f'bn {bn} ext {ext}')
1650
+ if ext=='.gro': self.read_gro(n)
1651
+ elif ext=='.top': self.read_top(n)
1652
+ elif ext=='.grx': self.read_gro_attributes(n)
1653
+ elif ext=='.mol2': self.read_mol2(n)
1654
+ else:
1655
+ logger.debug(f'Warning: file {n} has unknown file extension. Skipped.')
1656
+
1657
+ def center_coords(self,new_boxsize:np.ndarray=None):
1658
+ """center_coords center all coordinates in box
1659
+
1660
+ :param new_boxsize: new boxsize if desired, defaults to None
1661
+ :type new_boxsize: numpy.ndarray, optional
1662
+ """
1663
+ if type(new_boxsize)==np.ndarray:
1664
+ if new_boxsize.shape==(3,):
1665
+ box_vectors=new_boxsize*np.identity(3,dtype=float)
1666
+ elif new_boxsize.shape==(3,3):
1667
+ box_vectors=new_boxsize
1668
+ self.Coordinates.box=box_vectors
1669
+ center=self.Coordinates.box.diagonal()/2.0
1670
+ gc=self.Coordinates.geometric_center()
1671
+ addme=center-gc
1672
+ self.Coordinates.translate(addme)
1673
+
1674
+ def vacuum_minimize(self,outname='minimized',**kwargs):
1675
+ """vacuum_minimize the minimize analog to grompp_and_mdrun; performs an energy minimization using mdrun
1676
+
1677
+ :param outname: output file basename, defaults to 'minimized'
1678
+ :type outname: str, optional
1679
+ """
1680
+ pad=kwargs.get('pad',5)
1681
+ boxsize=np.array(self.maxspan())+pad*np.ones(3)
1682
+ logger.debug(f'{self.maxspan()} -> {boxsize}')
1683
+ self.center_coords(new_boxsize=boxsize)
1684
+ mdp_prefix='single-molecule-min'
1685
+ pfs.checkout(f'mdp/{mdp_prefix}.mdp')
1686
+ # gromacs_dict={'nt':1,'nb':'cpu','pme':'cpu','pmefft':'cpu','bonded':'cpu','update':'cpu'}
1687
+ self.grompp_and_mdrun(out=f'{outname}',
1688
+ mdp=mdp_prefix,boxSize=boxsize,single_molecule=True,wrap_coords=False) #,**gromacs_dict)
1689
+
1690
+ def vacuum_simulate(self,outname='simulated',**kwargs):
1691
+ """vacuum_simulate peform a vacuum MD simulation using mdrun
1692
+
1693
+ :param outname: output file basename, defaults to 'simulated'
1694
+ :type outname: str, optional
1695
+ """
1696
+ pad=kwargs.get('pad',5)
1697
+ boxsize=np.array(self.maxspan())+pad*np.ones(3)
1698
+ logger.debug(f'{self.maxspan()} -> {boxsize}')
1699
+ self.center_coords(new_boxsize=boxsize)
1700
+ mdp_prefix='single-molecule-nvt'
1701
+ pfs.checkout(f'mdp/{mdp_prefix}.mdp')
1702
+ nsamples=kwargs.get('nsamples',10)
1703
+ params=kwargs.get('params',{})
1704
+ T=params.get('temperature',300.0)
1705
+ ps=params.get('ps',0.0)
1706
+ nsteps=params.get('nsteps',-1)
1707
+ begin_at=params.get('begin_at',0.0)
1708
+ assert ps!=0.0 or nsteps!=-1
1709
+ dt=float(mdp_get(f'{mdp_prefix}.mdp','dt'))
1710
+ if ps!=0.0:
1711
+ nsteps=int(float(ps)/dt)
1712
+ else:
1713
+ ps=nsteps*dt
1714
+ sampling_duration_ps=ps-begin_at
1715
+ sampling_duration_nsteps=int(sampling_duration_ps/dt)
1716
+ sample_interval=sampling_duration_nsteps//nsamples
1717
+ logger.debug(f'nsteps {nsteps} begin_at {begin_at} ps {ps} sampling_duration_ps {sampling_duration_ps} ({sampling_duration_nsteps} steps) sample_interval {sample_interval}')
1718
+ # nsteps=nsamples*(sample_interval+1)
1719
+ # nsteps=mdp_get(f'{mdp_prefix}.mdp','nsteps')
1720
+ # nstxout=mdp_get(f'{mdp_prefix}.mdp','nstxout')
1721
+ mdp_modify(f'{mdp_prefix}.mdp',{'nsteps':nsteps,'nstxout':sample_interval,'ref_t':T})
1722
+ # gromacs_dict={'nt':1,'nb':'cpu','pme':'cpu','pmefft':'cpu','bonded':'cpu','update':'cpu'}
1723
+ self.grompp_and_mdrun(out=f'{outname}',
1724
+ mdp=mdp_prefix,boxSize=boxsize,single_molecule=True,wrap_coords=False) #,**gromacs_dict)
1725
+
1726
+ def equilibrate(self,deffnm='equilibrate',edict={},gromacs_dict={}):
1727
+ """equilibrate perform an MD simulation using mdrun
1728
+
1729
+ :param deffnm: output file basename, defaults to 'equilibrate'
1730
+ :type deffnm: str, optional
1731
+ :param edict: dictionary of simulation directives, defaults to {}
1732
+ :type edict: dict, optional
1733
+ :param gromacs_dict: dictionary of gromacs directives, defaults to {}
1734
+ :type gromacs_dict: dict, optional
1735
+ :return: list of edr files this equilibration generates
1736
+ :rtype: list
1737
+ """
1738
+ mod_dict={}
1739
+ edr_list=[]
1740
+ ens=edict['ensemble']
1741
+ repeat=edict.get('repeat',0)
1742
+ assert ens in ['min','npt','nvt'],f'Bad ensemble: {ens}'
1743
+ pfs.checkout(f'mdp/{ens}.mdp') # plain jane?
1744
+ if ens=='min':
1745
+ msg='minimization'
1746
+ else:
1747
+ msg=f'{ens} ensemble'
1748
+ if ens in ['nvt','npt']:
1749
+ dt=float(mdp_get(f'{ens}.mdp','dt'))
1750
+ mod_dict['ref_t']=edict['temperature']
1751
+ mod_dict['gen-temp']=edict['temperature']
1752
+ mod_dict['gen-vel']='yes'
1753
+ nsteps=edict.get('nsteps',0)
1754
+ if not nsteps:
1755
+ ps=edict.get('ps',0.0)
1756
+ if not ps: return
1757
+ nsteps=int(float(ps)/dt)
1758
+ else:
1759
+ ps=nsteps*dt
1760
+ mod_dict['nsteps']=nsteps
1761
+ msg+=f'; {ps:6.2f} ps, {float(edict["temperature"]):7.2f} K'
1762
+ if ens=='npt':
1763
+ mod_dict['ref_p']=edict['pressure']
1764
+ msg+=f', {float(edict["pressure"]):6.2f} bar'
1765
+ new_mdp=f'{deffnm}-{ens}'
1766
+ mdp_modify(f'{ens}.mdp',mod_dict,new_filename=f'{new_mdp}.mdp')
1767
+ logger.info(f'Running Gromacs: {msg}')
1768
+ self.grompp_and_mdrun(out=f'{deffnm}-{ens}',mdp=new_mdp,quiet=False,**gromacs_dict)
1769
+ edr_list=[f'{deffnm}-{ens}']
1770
+ if ens=='npt':
1771
+ box=self.Coordinates.box.diagonal()
1772
+ logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1773
+ gmx_energy_trace(f'{deffnm}-{ens}',['Density'],report_averages=True,**gromacs_dict)
1774
+ for rep in range(repeat):
1775
+ logger.info(f'Repeat {rep+1} out of {repeat}')
1776
+ this_deffnm=f'{deffnm}-repeat-{rep+1}-{ens}'
1777
+ self.grompp_and_mdrun(out=this_deffnm,mdp=new_mdp,quiet=False,**gromacs_dict)
1778
+ edr_list.append(this_deffnm)
1779
+ if ens=='npt':
1780
+ box=self.Coordinates.box.diagonal()
1781
+ logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1782
+ gmx_energy_trace(this_deffnm,['Density'],report_averages=True,**gromacs_dict)
1783
+ return edr_list
1784
+
1785
+ def get_resid_sets(self,atom_pair):
1786
+ """get_resid_sets identifies individual sets of separate resids owned by unbonded atoms i and j
1787
+
1788
+ :param atom_pair: tuple of i,j atom indices
1789
+ :type atom_pair: tuple
1790
+ :return: tuple containing the two apposing residue sets
1791
+ :rtype: tuple
1792
+ """
1793
+ # assertion: i and j are not bonded and they represent two separate sets of residues in this topocoord.
1794
+ i,j=atom_pair
1795
+ ri=self.get_gro_attribute_by_attributes('resNum',{'globalIdx':i})
1796
+ rj=self.get_gro_attribute_by_attributes('resNum',{'globalIdx':j})
1797
+ ci=self.Topology.local_resid_cluster(ri)
1798
+ cj=self.Topology.local_resid_cluster(rj)
1799
+ if set(ci)==set(cj):
1800
+ logger.debug(f'resid sets overlap: {i} {ri} : {ci} and {j} {rj} : {cj}')
1801
+ return []
1802
+ return [ci,cj]
1803
+
1804
+ def check_your_topology(self):
1805
+ """check_your_topology checks topology for duplicate 1-4 pair interactions and deletes them
1806
+ """
1807
+ T=self.Topology
1808
+ C=self.Coordinates
1809
+ aT={}
1810
+ pdf=T.D['pairs']
1811
+ aT['dx']=[]
1812
+ aT['dy']=[]
1813
+ aT['dz']=[]
1814
+ checked=[]
1815
+ drops=[]
1816
+ for i,r in pdf.iterrows():
1817
+ ai,aj=min([r.ai,r.aj]),max([r.ai,r.aj])
1818
+ assert ai!=aj
1819
+ if not (ai,aj) in checked:
1820
+ checked.append((ai,aj))
1821
+ else:
1822
+ # print(f'repeated pair {ai} {aj}')
1823
+ drops.append(i)
1824
+ ri=self.get_R(ai)
1825
+ rj=self.get_R(aj)
1826
+ D=C.mic(ri-rj,pbc=[1,1,1])
1827
+ aT['dx'],aT['dy'],aT['dz']=D
1828
+ print(f'{len(drops)} duplicate pairs detected')
1829
+ T.D['pairs']=pdf.drop(drops)
1830
+ pdf['dx']=aT['dx']
1831
+ pdf['dy']=aT['dy']
1832
+ pdf['dz']=aT['dz']
1833
+ print(pdf.sort_values(by='dx').head(3).to_string())
1834
+ print(pdf.sort_values(by='dy').head(3).to_string())
1835
+ print(pdf.sort_values(by='dz').head(3).to_string())
1836
+ self.write_top('checked.top')
1837
+
1838
+ def find_template(BT:BondTemplate,moldict):
1839
+ """find_template searches the dictionary of available molecules to identify a bond template that matches the passed-in template, returning the corresponding template molecule and reaction-bond
1840
+
1841
+ :param BT: bond template to search for
1842
+ :type BT: BondTemplate
1843
+ :param moldict: dictionary of available molecule
1844
+ :type moldict: MoleculeDict
1845
+ :raises Exception: if no matching template is found
1846
+ :return: template Molecule object, corresponding ReactionBond object from that template, and a boolean flag indicating whether or not the match required a symmetric-reversal of the template
1847
+ :rtype: tuple(Molecule,ReactionBond,bool)
1848
+ """
1849
+ use_T=None
1850
+ b_idx=-1
1851
+ reverse_bond=False
1852
+ for template_name,T in moldict.items():
1853
+ # if BT in T.bond_templates:
1854
+ # use_T=T
1855
+ # break
1856
+ use_T=None
1857
+ for b_idx in range(len(T.bond_templates)):
1858
+ bt=T.bond_templates[b_idx]
1859
+ # logger.debug(f'comparing to {T.name} {str(bt)}')
1860
+ if bt==BT:
1861
+ # logger.debug(f'TRUE')
1862
+ use_T=T
1863
+ break
1864
+ if bt.is_reverse_of(BT):
1865
+ # logger.debug(f'TRUE, but...')
1866
+ use_T=T
1867
+ reverse_bond=True
1868
+ # logger.debug(f'reversed bond instance {str(RB)}')
1869
+ if use_T!=None:
1870
+ break
1871
+ else:
1872
+ logger.error(f'No template is found for {str(BT)}')
1873
+ raise Exception('you have a bond for which I cannot find a template')
1874
+ logger.debug(f'Using template {use_T.name} and bond index {b_idx}')
1875
+ rb=use_T.reaction_bonds[b_idx]
1876
+ return use_T,rb,reverse_bond
1877
+