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
@@ -0,0 +1,767 @@
1
+ """
2
+
3
+ .. module:: curecontroller
4
+ :synopsis: Manages execution of the CURE algorithm
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import pandas as pd
10
+ from enum import Enum
11
+ import yaml
12
+ import numpy as np
13
+ import os
14
+ from itertools import product
15
+ from HTPolyNet.topocoord import TopoCoord, BTRC
16
+ from HTPolyNet.gromacs import gromacs_distance, mdp_modify
17
+ from HTPolyNet.configuration import ReactionList
18
+ from HTPolyNet.molecule import MoleculeDict
19
+ from HTPolyNet.reaction import reaction_stage
20
+ from multiprocessing import Pool
21
+ from functools import partial
22
+ import HTPolyNet.projectfilesystem as pfs
23
+ from HTPolyNet.stringthings import my_logger
24
+ import HTPolyNet.checkpoint as cp
25
+ from HTPolyNet.plot import trace
26
+
27
+ import logging
28
+
29
+ logger=logging.getLogger(__name__)
30
+
31
+ class cure_step(Enum):
32
+ """Enumerated CURE step
33
+ """
34
+ cure_bondsearch=0
35
+ cure_drag=1
36
+ cure_update=2
37
+ cure_relax=3
38
+ cure_equilibrate=4
39
+ cap_bondsearch=5
40
+ cap_update=6 # dragging is not needed/allowed in capping since these are likely intramolecular bonds...
41
+ cap_relax=7
42
+ cap_equilibrate=8
43
+ finished=9
44
+ unknown=99
45
+ def __str__(self):
46
+ return self.name
47
+ def basename(self):
48
+ name=str(self)
49
+ if 'cap_' in name:
50
+ return name[len('cap_'):]
51
+ if 'cure_' in name:
52
+ return name[len('cure_'):]
53
+
54
+ class CureState:
55
+ def __init__(self):
56
+ """__init__ generates a new, initialized CureState object
57
+ """
58
+ self.iter=0
59
+ self.max_nxlinkbonds=0
60
+ self.cum_nxlinkbonds=0
61
+ self.desired_nxlinkbonds=0
62
+ self.max_search_radius=0.0
63
+ self.max_radidx=0
64
+ self.step=cure_step.unknown
65
+ self.curr_nxlinkbonds=0
66
+
67
+ self.current_stage={}
68
+ self.current_stage['drag']=0
69
+ self.current_stage['relax']=0
70
+
71
+ self.current_radidx=0
72
+ self.current_radius=0.0
73
+
74
+ self.bonds_file=''
75
+
76
+ def _to_yaml(self,filename='../cure_state.yaml'):
77
+ """_to_yaml writes CureState object to YAML file
78
+
79
+ :param filename: name of output YAML file, defaults to '../cure_state.yaml'
80
+ :type filename: str, optional
81
+ """
82
+ with open(filename,'w') as f:
83
+ f.write(yaml.dump(self))
84
+
85
+ @classmethod
86
+ def from_yaml(cls,filename='cure_state.yaml'):
87
+ """from_yaml returns a new CureState object generated by reading in the YAML file
88
+
89
+ :param filename: input file name, defaults to 'cure_state.yaml'
90
+ :type filename: str, optional
91
+ :return: new CureState object returned by yaml.load
92
+ :rtype: CureState
93
+ """
94
+ with open(filename,'r') as f:
95
+ yaml_string=f.read()
96
+ return yaml.load(yaml_string,Loader=yaml.Loader)
97
+
98
+ def reset(self):
99
+ """reset resets this CureState object to begin a new CURE iteration
100
+ """
101
+ self.iter=1
102
+ self.step=cure_step.cure_bondsearch
103
+ self.curr_nxlinkbonds=0
104
+ self.current_stage['drag']=0
105
+ self.current_stage['relax']=0
106
+ self.current_radidx=0
107
+ self.current_radius=0.0
108
+ self.bonds_file=''
109
+
110
+ class CureController:
111
+ default_equilibration_sequence = [ { 'ensemble': 'min' },
112
+ { 'ensemble': 'nvt', 'temperature': 600, 'nsteps': 1000 },
113
+ { 'ensemble': 'npt', 'temperature': 600, 'pressure': 1, 'nsteps': 2000 }
114
+ ]
115
+ curedict_defaults={
116
+ 'output': {
117
+ 'bonds_file': 'bonds.csv'
118
+ },
119
+ 'controls': {
120
+ 'max_conversion_per_iteration': 1.0,
121
+ 'search_radius': 0.5,
122
+ 'radial_increment': 0.05,
123
+ 'late_threshold': 0.85,
124
+ 'max_iterations': 100,
125
+ 'desired_conversion': 0.5,
126
+ 'ncpu' : os.cpu_count()
127
+ },
128
+ 'drag': {
129
+ 'limit': 0.0,
130
+ 'kb': 300000.0, # kJ/mol/nm
131
+ 'trigger_distance': 0.0,
132
+ 'nstages': 0,
133
+ 'increment': 0.0,
134
+ 'cutoff_pad': 0.2,
135
+ 'equilibration': default_equilibration_sequence
136
+ },
137
+ 'relax': {
138
+ 'nstages': 6,
139
+ 'increment': 0.0,
140
+ 'cutoff_pad': 0.2,
141
+ 'equilibration': default_equilibration_sequence
142
+ },
143
+ 'equilibrate': {
144
+ 'temperature': 300,
145
+ 'pressure': 1,
146
+ 'nsteps': 50000,
147
+ 'ensemble': 'npt'
148
+ },
149
+ 'gromacs': {
150
+ 'rdefault': 0.9
151
+ }
152
+ }
153
+
154
+ def __init__(self,curedict={}):
155
+ """__init__ generates a new CureController object populated from directives in curedict
156
+
157
+ :param curedict: dictionary of cure directives, defaults to {}
158
+ :type curedict: dict, optional
159
+ """
160
+ self.state=CureState()
161
+ self.bonds_df:pd.DataFrame=None
162
+ self.bonds_are='nonexistent!'
163
+ self.search_failed=False
164
+ self.dicts={}
165
+ for k,v in self.curedict_defaults.items():
166
+ self.dicts[k]=curedict.get(k,v) # loads entire default if dict is just missing
167
+ if type(v)==dict: # assign subitem defaults if their keys are missing
168
+ for kk,vv in v.items():
169
+ if not kk in self.dicts[k]:
170
+ self.dicts[k][kk]=vv
171
+
172
+ self.dragging_enabled=False
173
+ d=self.dicts['drag']
174
+ if (d['nstages']>0 or d['increment']>0.0) and d['limit']>0.0:
175
+ self.dragging_enabled=True
176
+
177
+ def setup(self,max_nxlinkbonds=0,desired_nxlinkbonds=0,max_search_radius=0.0):
178
+ """setup sets up this CureController object
179
+
180
+ :param max_nxlinkbonds: maximum allowable number of bonds, defaults to 0
181
+ :type max_nxlinkbonds: int, optional
182
+ :param desired_nxlinkbonds: desired number of bonds, defaults to 0
183
+ :type desired_nxlinkbonds: int, optional
184
+ :param max_search_radius: maximum search radius (nm), defaults to 0.0
185
+ :type max_search_radius: float, optional
186
+ """
187
+ st=self.state
188
+ st.max_nxlinkbonds=max_nxlinkbonds
189
+ st.desired_nxlinkbonds=desired_nxlinkbonds
190
+ st.max_search_radius=max_search_radius
191
+ d=self.dicts['controls']
192
+ st.max_radidx=int((st.max_search_radius-d['search_radius'])/d['radial_increment'])
193
+
194
+ @cp.enableCheckpoint
195
+ def do_iter(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,gromacs_dict={}):
196
+ """do_iter performs one CURE iteration
197
+
198
+ :param TC: TopoCoord object; all topological and coordinate information is in here
199
+ :type TC: TopoCoord
200
+ :param RL: ReactionList object; list of all reaction types
201
+ :type RL: ReactionList
202
+ :param MD: MoleculeDict object; dictionary of all molecules, keyed by name
203
+ :type MD: MoleculeDict
204
+ :param gromacs_dict: dictionary of custom gromacs parameters, defaults to {}
205
+ :type gromacs_dict: dict, optional
206
+ :return: dictionary of resulting output file names
207
+ :rtype: dict
208
+ """
209
+ my_logger(f'Iteration {self.state.iter} begins',logger.info,fill='~')
210
+ TC.grab_files() # copy files locally
211
+ self.state.step=cure_step.cure_bondsearch
212
+ self._do_bondsearch(TC,RL,MD)
213
+ self._do_preupdate_dragging(TC,gromacs_dict)
214
+ self._do_topology_update(TC,MD)
215
+ self._do_relax(TC,gromacs_dict)
216
+ self._do_equilibrate(TC,gromacs_dict)
217
+ self.state.cum_nxlinkbonds+=self.bonds_df.shape[0]
218
+ logger.info(f'Iteration {self.state.iter} current conversion {self._curr_conversion():.3f} or {self.state.cum_nxlinkbonds} bonds')
219
+ return {c:os.path.basename(x) for c,x in TC.files.items() if c!='mol2'}
220
+
221
+ @cp.enableCheckpoint
222
+ def do_capping(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,gromacs_dict={}):
223
+ """do_capping manages generation of all capping bonds
224
+
225
+ :param TC: TopoCoord object containing all topology and coordinate information
226
+ :type TC: TopoCoord
227
+ :param RL: ReactionList object containing all reaction types
228
+ :type RL: ReactionList
229
+ :param MD: MoleculeDict object containing all molecule information
230
+ :type MD: MoleculeDict
231
+ :param gromacs_dict: dictionary of custom gromacs parameters, defaults to {}
232
+ :type gromacs_dict: dict, optional
233
+ :return: dictionary of resulting output files, keyed by extension ('gro', 'top', 'grx')
234
+ :rtype: dict
235
+ """
236
+ self._do_cap_bondsearch(TC,RL,MD)
237
+ self._do_topology_update(TC,MD)
238
+ self._do_relax(TC)
239
+ self._do_equilibrate(TC,gromacs_dict)
240
+ return {c:os.path.basename(x) for c,x in TC.files.items() if c!='mol2'}
241
+
242
+ def is_cured(self):
243
+ """is_cured returns True if system is cured
244
+
245
+ :return: True if system is cured; False otherwise
246
+ :rtype: bool
247
+ """
248
+ st=self.state
249
+ logger.debug(f'search_failed? {self.search_failed}')
250
+ logger.debug(f'cumxlinks {st.cum_nxlinkbonds} maxxlinks {st.max_nxlinkbonds}: {(st.cum_nxlinkbonds>=st.max_nxlinkbonds)}')
251
+ finished=self.search_failed or (st.cum_nxlinkbonds>=st.desired_nxlinkbonds)
252
+ if finished:
253
+ st.step=cure_step.cap_bondsearch
254
+ return finished
255
+
256
+ def _curr_conversion(self):
257
+ """_curr_conversion returns current conversion expressed as a fraction of the maximum number of possible bonds
258
+
259
+ :return: conversion
260
+ :rtype: float
261
+ """
262
+ if not self.state.max_nxlinkbonds: return 0
263
+ return float(self.state.cum_nxlinkbonds)/self.state.max_nxlinkbonds
264
+
265
+ def reset(self):
266
+ """reset resets this CureController object by resetting its CureState, its bonds dataframe, and its search_failed member
267
+ """
268
+ self.state.reset()
269
+ self.bonds_df=pd.DataFrame()
270
+ self.bonds_are='nonexistent!'
271
+ self.search_failed=False
272
+
273
+ def next_iter(self):
274
+ """next_iter resets this CureController for the next CURE iteration
275
+
276
+ :return: True if new iteration index exceeds the maximum number of iterations allowed by runtime
277
+ :rtype: bool
278
+ """
279
+ i=self.state.iter+1
280
+ self.reset()
281
+ self.state.iter=i
282
+ return self.state.iter>=self.dicts['controls']['max_iterations']
283
+
284
+ def _do_bondsearch(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,reentry=False):
285
+ """_do_bondsearch manages the search for new bonds
286
+
287
+ :param TC: TopoCoord object containing all topology and coordinate information
288
+ :type TC: TopoCoord
289
+ :param RL: ReactionList containing all reaction types
290
+ :type RL: ReactionList
291
+ :param MD: MoleculeDict object containing all molecular templates, keyed by name
292
+ :type MD: MoleculeDict
293
+ :param reentry: True if we are restarting a bondsearch in this directory, defaults to False
294
+ :type reentry: bool, optional
295
+ """
296
+ if self.state.step!=cure_step.cure_bondsearch: return
297
+ opfx=self._pfx()
298
+ d=self.dicts['controls']
299
+ self.state.current_radius=d['search_radius']+self.state.current_radidx*d['radial_increment']
300
+ logger.info(f'Bond search using radius {self.state.current_radius} nm initiated')
301
+ curr_conversion=self._curr_conversion()
302
+ apply_probabilities=curr_conversion<d['late_threshold']
303
+ bond_limit=int(d['max_conversion_per_iteration']*self.state.max_nxlinkbonds)
304
+ bond_target=int((d['desired_conversion']-curr_conversion)*self.state.max_nxlinkbonds)
305
+ bond_limit=min([bond_limit,bond_target])
306
+ logger.debug(f'Iteration limited to at most {bond_limit} new bonds')
307
+ # TODO: new branch: multisearch:
308
+ # calc and store distances once outside this loop
309
+ # have a controller that runs loop until a select number
310
+ # of bonds has been formed, or we've maxed out the radius
311
+ # raw_bdf=self.make_candidates(TC,RL,MD,...)
312
+ ''' execute search radius updating until at lesast one bond is identified '''
313
+ nbonds=0
314
+ while nbonds==0 and self.state.current_radidx<self.state.max_radidx:
315
+ # test_bdf=raw_bdf[raw_bdf['r']<self.current_radius]
316
+ # result_bdf=self.apply_filters(TC,RL,MD,...)
317
+ nbdf=self._searchbonds(TC,RL,MD,stage=reaction_stage.cure,abs_max=bond_limit,apply_probabilities=apply_probabilities,reentry=reentry)
318
+ nbonds=nbdf.shape[0]
319
+ # nbonds+=result_bdf.shape[0]
320
+ # if nbonds<PARAMETER:
321
+ if nbonds==0:
322
+ self.state.current_radidx+=1
323
+ self.state.current_radius+=d['radial_increment']
324
+ logger.info(f'Radius increased to {self.state.current_radius} nm')
325
+ if nbonds>0:
326
+ ess='' if nbonds==1 else 's'
327
+ logger.info(f'Iteration {self.state.iter} will generate {nbdf.shape[0]} new bond{ess}')
328
+ pairs=pd.DataFrame() # empty placeholder
329
+ ''' compute all lengths '''
330
+ TC.add_length_attribute(nbdf,attr_name='initial_distance')
331
+ ''' register all new bonds '''
332
+ self._register_bonds(nbdf,pairs,f'{opfx}-bonds.csv',bonds_are='identified')
333
+ ''' declare intention to go to dragging or topology-update '''
334
+ self.state.step=cure_step.cure_drag if self.dragging_enabled else cure_step.cure_update
335
+ else:
336
+ self.search_failed=True
337
+ ''' declare intention to proceed to bond capping '''
338
+ self.state.step=cure_step.cap_bondsearch
339
+ self.state._to_yaml()
340
+ logger.debug(f'next: {self.state.step}')
341
+
342
+ def _do_preupdate_dragging(self,TC:TopoCoord,gromacs_dict={}):
343
+ """_do_preupdate_dragging manages the preupdate dragging CURE step
344
+
345
+ :param TC: the global system topology and coordinates
346
+ :type TC: TopoCoord
347
+ :param gromacs_dict: dictionary of optional gromacs directives, defaults to {}
348
+ :type gromacs_dict: dict, optional
349
+ """
350
+ if self.state.step!=cure_step.cure_drag: return
351
+ nbdf=self.bonds_df
352
+ assert nbdf.shape[0]>0
353
+ d=self.dicts['drag']
354
+ nogos=[not self.dragging_enabled,nbdf['initial_distance'].max()<d['trigger_distance']]
355
+ logger.debug(f'{nogos} {any(nogos)}')
356
+ if any(nogos):
357
+ logger.debug(f'No dragging is necessary')
358
+ else:
359
+ self._distance_attenuation(TC,mode='drag',gromacs_dict=gromacs_dict)
360
+ self.state.step=cure_step.cure_update
361
+ self.state._to_yaml()
362
+ logger.debug(f'next: {self.state.step}')
363
+
364
+ def _do_relax(self,TC:TopoCoord,gromacs_dict={}):
365
+ """_do_relax manages relaxation steps within the CURE algorithm
366
+
367
+ :param TC: global topology and coordinates
368
+ :type TC: TopoCoord
369
+ :param gromacs_dict: dictionary of optional gromacs directives, defaults to {}
370
+ :type gromacs_dict: dict, optional
371
+ """
372
+ if self.state.step!=cure_step.cure_relax and self.state.step!=cure_step.cap_relax: return
373
+ nbdf=self.bonds_df
374
+ if nbdf.shape[0]==0: # no bonds identified
375
+ if self.state.step==cure_step.cure_relax:
376
+ self.state.step=cure_step.cap_bondsearch # drop out of CURE loop
377
+ else:
378
+ self.state.step=cure_step.finished
379
+ return
380
+ self._distance_attenuation(TC,mode='relax',gromacs_dict=gromacs_dict)
381
+ if self.state.step==cure_step.cure_relax:
382
+ self.state.step=cure_step.cure_equilibrate
383
+ else:
384
+ self.state.step=cure_step.cap_equilibrate
385
+ self.state._to_yaml()
386
+ logger.debug(f'next: {self.state.step}')
387
+
388
+ def _do_topology_update(self,TC:TopoCoord,MD:MoleculeDict):
389
+ """_do_topology_update manages the topology update in CURE
390
+
391
+ :param TC: global system topology and coordinates
392
+ :type TC: TopoCoord
393
+ :param MD: dictionary of all molecular templates
394
+ :type MD: MoleculeDict
395
+ """
396
+ if self.state.step!=cure_step.cure_update and self.state.step!=cure_step.cap_update: return
397
+ opfx=self._pfx()
398
+ logger.debug(f'Topology update')
399
+ bonds_df,pairs_df=TC.update_topology_and_coordinates(self.bonds_df,template_dict=MD,write_mapper_to=f'{opfx}-idx-mapper.csv')
400
+ TC.add_length_attribute(bonds_df,attr_name='initial_distance')
401
+ TC.add_length_attribute(pairs_df,attr_name='initial_distance')
402
+ self._register_bonds(bonds_df,pairs_df,f'{opfx}-bonds.csv',bonds_are='unrelaxed')
403
+ TC.write_gro(f'{opfx}.gro')
404
+ TC.write_top(f'{opfx}.top')
405
+ TC.write_grx_attributes(f'{opfx}.grx')
406
+ if self.state.step==cure_step.cure_update:
407
+ self.state.step=cure_step.cure_relax
408
+ else:
409
+ self.state.step=cure_step.cap_relax
410
+ self.state._to_yaml()
411
+
412
+ def _do_equilibrate(self,TC:TopoCoord,gromacs_dict={}):
413
+ """_do_equilibrate manages pre- and post-cure equilibration runs
414
+
415
+ :param TC: global system topology and coordinates
416
+ :type TC: TopoCoord
417
+ :param gromacs_dict: dictionary of optional gromacs directives, defaults to {}
418
+ :type gromacs_dict: dict, optional
419
+ """
420
+ if self.state.step!=cure_step.cure_equilibrate and self.state.step!=cure_step.cap_equilibrate: return
421
+ d=self.dicts['equilibrate']
422
+ opfx=self._pfx()
423
+ edr_list=TC.equilibrate(deffnm=f'{opfx}',edict=d,gromacs_dict=gromacs_dict) #,plot_pfx=f'iter-{self.state.iter}-{str(self.state.step)}')
424
+ ens=d['ensemble']
425
+ if ens=='npt':
426
+ plot_pfx=f'iter-{self.state.iter}-{str(self.state.step)}'
427
+ trace('Density',edr_list,outfile=os.path.join(pfs.proj(),f'plots/{plot_pfx}-density.png'))
428
+ if self.state.step==cure_step.cure_equilibrate:
429
+ # go to next iteration -- this whole method is skipped if nbonds==0 in relax
430
+ self.state.step=cure_step.cure_bondsearch # if not self.search_failed else state.cap_bondsearch
431
+ elif self.state.step==cure_step.cap_equilibrate:
432
+ self.state.step=cure_step.finished
433
+ self.state._to_yaml()
434
+
435
+ def _do_cap_bondsearch(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict):
436
+ """_do_cap_bondsearch manages the post-cure capping reaction bond search
437
+
438
+ :param TC: global system topology and coordinates
439
+ :type TC: TopoCoord
440
+ :param RL: list of all reactions
441
+ :type RL: ReactionList
442
+ :param MD: dictionary of all molecular templates
443
+ :type MD: MoleculeDict
444
+ """
445
+ if self.state.step!=cure_step.cap_bondsearch: return
446
+ opfx=self._pfx()
447
+ # multi: nbdf=self.make_cadidates(...,stage='cap')
448
+ nbdf=self._searchbonds(TC,RL,MD,stage=reaction_stage.cap)
449
+ nbonds=nbdf.shape[0]
450
+ ess='' if nbonds==1 else 's'
451
+ logger.info(f'Capping will generate {nbdf.shape[0]} new bond{ess}')
452
+ if nbonds>0:
453
+ cwd=pfs.go_to(f'systems/capping')
454
+ pairs=pd.DataFrame() # empty placeholder
455
+ TC.add_length_attribute(nbdf,attr_name='initial_distance')
456
+ self._register_bonds(nbdf,pairs,f'{opfx}-bonds.csv',bonds_are='identified')
457
+ self.state.step=cure_step.cap_update
458
+ else:
459
+ self.state.step=cure_step.finished
460
+ self.state._to_yaml()
461
+
462
+ def _write_bonds_df(self,bondsfile='bonds.csv'):
463
+ """_write_bonds_df writes all bonds in the bonds dataframe to a CSV file
464
+
465
+ :param bondsfile: name of csv file to write, defaults to 'bonds.csv'
466
+ :type bondsfile: str, optional
467
+ """
468
+ self.bonds_df.to_csv(bondsfile,sep=' ',mode='w',index=False,header=True,doublequote=False)
469
+
470
+ def _read_bonds_df(self,bonds_file_override=''):
471
+ """_read_bonds_df reads bonds into bonds dataframe from a CSV file
472
+
473
+ :param bonds_file_override: name of file to read from (overrides default), defaults to ''
474
+ :type bonds_file_override: str, optional
475
+ """
476
+ infile=self.dicts['output']['bonds_file'] if not bonds_file_override else bonds_file_override
477
+ assert os.path.exists(infile),f'Error: {infile} not found'
478
+ self.bonds_df=pd.read_csv(infile,sep='\s+',header=0)
479
+ self.dicts['output']['bonds_file']=os.path.abspath(infile)
480
+
481
+ def _register_bonds(self,bonds,pairs,bonds_file,bonds_are='unrelaxed'):
482
+ """_register_bonds registers the bonds, 1-4 pairs from the input parameters
483
+
484
+ :param bonds: dataframe of bonds
485
+ :type bonds: pd.DataFrame
486
+ :param pairs: dataframe of 1-4 pairs
487
+ :type pairs: pd.DataFrame
488
+ :param bonds_file: file to which bonds are written
489
+ :type bonds_file: str
490
+ :param bonds_are: a little flag to remind us the state of these bonds, defaults to 'unrelaxed'
491
+ :type bonds_are: str, optional
492
+ """
493
+ self.bonds_df=bonds
494
+ self.pairs_df=pairs
495
+ self.bonds_are=bonds_are
496
+ self.state.bonds_file=bonds_file
497
+ self._write_bonds_df(bonds_file)
498
+ self.dicts['output']['bonds_file']=os.path.abspath(bonds_file)
499
+
500
+ def _pfx(self):
501
+ """_pfx generates a little string that can be used as a state-specific filename prefix
502
+
503
+ :return: the little string
504
+ :rtype: str
505
+ """
506
+ return f'{self.state.step.value}-{self.state.step}'
507
+
508
+ def _distance_attenuation(self,TC:TopoCoord,mode='drag',gromacs_dict={}):
509
+ """_distance_attenuation manages the progressive attenuation of bond parameters for new bonds
510
+
511
+ :param TC: global system topology and coordinates
512
+ :type TC: TopoCoord
513
+ :param mode: string indicating whether this is prebonding or postbonding attentuation; defaults to 'drag' (prebonding); other option is 'relax' (postbonding)
514
+ :type mode: str, optional
515
+ :param gromacs_dict: dictionary of optional gromacs directives, defaults to {}
516
+ :type gromacs_dict: dict, optional
517
+ """
518
+ assert mode in ['drag','relax']
519
+ statename=self.state.step.basename()
520
+ opfx=self._pfx()
521
+ nbdf=self.bonds_df.copy()
522
+ pdf=self.pairs_df.copy()
523
+ d=self.dicts[mode]
524
+ nbdf['current_lengths']=nbdf['initial_distance'].copy()
525
+ maxL,minL,meanL=nbdf['current_lengths'].max(),nbdf['current_lengths'].min(),nbdf['current_lengths'].mean()
526
+ logger.debug(f'Lengths avg/min/max: {meanL:.3f}/{minL:.3f}/{maxL:.3f}')
527
+ ess='' if nbdf.shape[0]==1 else 's'
528
+ logger.info(f'Step "{str(self.state.step)}" initiated on {nbdf.shape[0]} distance{ess} (max {maxL:.3f} nm)')
529
+ roptions=[self.dicts['gromacs']['rdefault'],maxL]
530
+ if mode=='drag':
531
+ TC.add_restraints(nbdf,typ=6)
532
+ logger.info(' Stage Max-distance (nm)')
533
+ else:
534
+ pdf['current_lengths']=pdf['initial_distance'].copy()
535
+ pmaxL,pminL,pmeanL=pdf['current_lengths'].max(),pdf['current_lengths'].min(),pdf['current_lengths'].mean()
536
+ logger.debug(f'1-4 distances lengths avg/min/max: {pmeanL:.3f}/{pminL:.3f}/{pmaxL:.3f}')
537
+ roptions.append(pmaxL)
538
+ logger.info(' Stage Max-distance (nm) Max-1-4-distance (nm)')
539
+ rcommon=max(roptions)
540
+ for stg_dict in d['equilibration']:
541
+ ensemble=stg_dict['ensemble']
542
+ impfx=f'{statename}-{ensemble}' # e.g., drag-min, drag-nvt, drag-npt
543
+ pfs.checkout(f'mdp/{impfx}.mdp')
544
+ mdp_mods_dict={'rvdw':rcommon,'rcoulomb':rcommon,'rlist':rcommon}
545
+ if ensemble!='min':
546
+ mdp_mods_dict.update({'gen-temp':stg_dict['temperature'],'ref_t':stg_dict['temperature'],'gen-vel':'yes','nsteps':stg_dict['nsteps']})
547
+ if ensemble=='npt':
548
+ mdp_mods_dict['ref_p']=stg_dict['pressure']
549
+ mdp_modify(f'{impfx}.mdp',mdp_mods_dict,add_if_missing=(ensemble!='min'))
550
+ this_nstages=int(maxL/d['increment'])
551
+ this_firststage=self.state.current_stage[mode]
552
+ logger.debug(f'{self.state.step} {this_nstages} {this_firststage}')
553
+ saveT=TC.copy_bond_parameters(self.bonds_df)
554
+ for i in range(this_firststage,this_nstages):
555
+ self.state.current_stage[mode]=i
556
+ if mode=='drag':
557
+ TC.attenuate_bond_parameters(self.bonds_df,i,this_nstages,minimum_distance=d['limit'],init_colname='initial_distance')
558
+ else:
559
+ TC.attenuate_bond_parameters(self.bonds_df,i,this_nstages,init_colname='initial_distance')
560
+ stagepfx=f'{opfx}-stage-{i+1}'
561
+ TC.write_top(f'{stagepfx}.top')
562
+ for stg_dict in d['equilibration']:
563
+ ensemble=stg_dict['ensemble']
564
+ impfx=f'{statename}-{ensemble}' # e.g., drag-min, drag-nvt, drag-npt
565
+ TC.grompp_and_mdrun(out=f'{stagepfx}-{ensemble}',mdp=f'{impfx}',**gromacs_dict)
566
+ # logger.debug(f'{TC.files["gro"]}')
567
+ TC.restore_bond_parameters(saveT)
568
+ TC.add_length_attribute(nbdf,attr_name='current_lengths')
569
+ maxL,minL,meanL=nbdf['current_lengths'].max(),nbdf['current_lengths'].min(),nbdf['current_lengths'].mean()
570
+ logger.debug(f'Distances avg/min/max: {meanL:.3f}/{minL:.3f}/{maxL:.3f}')
571
+ if mode=='drag':
572
+ logger.info(f'{i+1:>10d} {maxL:>17.3f}')
573
+ else:
574
+ TC.add_length_attribute(pdf,attr_name='current_lengths')
575
+ pmaxL,pminL,pmeanL=pdf['current_lengths'].max(),pdf['current_lengths'].min(),pdf['current_lengths'].mean()
576
+ logger.debug(f'1-4 distances lengths avg/min/max: {pmeanL:.3f}/{pminL:.3f}/{pmaxL:.3f}')
577
+ logger.info(f'{i+1:>10d} {maxL:>17.3f} {pmaxL:>21.3f}')
578
+ self.state._to_yaml()
579
+ if mode=='drag':
580
+ TC.remove_restraints(self.bonds_df)
581
+ TC.write_top(f'{opfx}-complete.top')
582
+ self._register_bonds(nbdf,pdf,f'{opfx}-{mode}-bonds.csv',bonds_are=('relaxed' if mode=='relax' else 'dragged'))
583
+ self.state.current_stage[mode]=0
584
+ self.state._to_yaml()
585
+
586
+ # TODO: move to searchbonds.by; split into make_candidates() and apply_filters()
587
+ def _searchbonds(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,stage=reaction_stage.cure,abs_max=0,apply_probabilities=False,reentry=False):
588
+ """_searchbonds manages the search for bonds
589
+
590
+ :param TC: global system topology and coordinates
591
+ :type TC: TopoCoord
592
+ :param RL: list of all reactions
593
+ :type RL: ReactionList
594
+ :param MD: dictionary of all molecular templates
595
+ :type MD: MoleculeDict
596
+ :param stage: which reaction stage, defaults to reaction_stage.cure, other choice is reaction_stage.cap
597
+ :type stage: reaction_stage, optional
598
+ :param abs_max: upper limit to number of new bonds allowed, defaults to 0, signifying no limit
599
+ :type abs_max: int, optional
600
+ :param apply_probabilities: if true, bond probabilities are applied, defaults to False
601
+ :type apply_probabilities: bool, optional
602
+ :param reentry: if true, existing linkcell data stored on disk is used, defaults to False
603
+ :type reentry: bool, optional
604
+ :return: the dataframe of proposed bonds
605
+ :rtype: pd.DataFrame
606
+ """
607
+ adf=TC.gro_DataFrame('atoms')
608
+ gro=TC.files['gro']
609
+ ncpu=self.dicts['controls']['ncpu']
610
+ if stage==reaction_stage.cure:
611
+ TC.linkcell_initialize(self.state.current_radius,ncpu=ncpu,force_repopulate=reentry)
612
+ raset=adf[adf['z']>0] # this view will be used for downselecting to potential A-B partners
613
+ bdf=pd.DataFrame()
614
+ Rlist=[x for x in RL if (x.stage==stage and x.probability>0.0)]
615
+ logger.debug(f'reactioncount {len(Rlist)} atomscount {raset.shape[0]}')
616
+ for R in Rlist:
617
+ logger.debug(f'Reaction {R.name} with {len(R.bonds)} bond(s)')
618
+ prob=R.probability
619
+ for bond in R.bonds:
620
+ A=R.atoms[bond['atoms'][0]]
621
+ B=R.atoms[bond['atoms'][1]]
622
+ order=bond['order']
623
+ aname=A['atom']
624
+ areactantname_template=R.reactants[A['reactant']]
625
+ aresid_template=A['resid']
626
+ aresname=MD[areactantname_template].get_resname(aresid_template)
627
+ az=A['z']
628
+ bname=B['atom']
629
+ breactantname_template=R.reactants[B['reactant']]
630
+ bresid_template=B['resid']
631
+ bresname=MD[breactantname_template].get_resname(bresid_template)
632
+ bz=B['z']
633
+ if stage==reaction_stage.cap:
634
+ assert areactantname_template==breactantname_template,f'Error: capping reaction {R.name} lists a bond whose atoms are in different reactants'
635
+ assert aresname==bresname,f'Error: capping reaction {R.name} lists a bond whose atoms are in different residues'
636
+
637
+ Aset=raset[(raset['atomName']==aname)&(raset['resName']==aresname)&(raset['z']==az)&(raset['reactantName']==areactantname_template)]
638
+ Bset=raset[(raset['atomName']==bname)&(raset['resName']==bresname)&(raset['z']==bz)&(raset['reactantName']==breactantname_template)]
639
+ logger.debug(f'Aset {Aset.shape[0]} atoms')
640
+ logger.debug(f'Bset {Bset.shape[0]} atoms')
641
+ alist=list(zip(Aset['globalIdx'].to_list(),Aset['resNum'].to_list(),Aset['molecule'].to_list()))
642
+ blist=list(zip(Bset['globalIdx'].to_list(),Bset['resNum'].to_list(),Bset['molecule'].to_list()))
643
+ all_possible_pairs=list(product(alist,blist))
644
+
645
+ idf=pd.DataFrame({'ai': [int(x[0][0]) for x in all_possible_pairs],
646
+ 'ri': [int(x[0][1]) for x in all_possible_pairs],
647
+ 'mi': [int(x[0][2]) for x in all_possible_pairs],
648
+ 'aj': [int(x[1][0]) for x in all_possible_pairs],
649
+ 'rj': [int(x[1][1]) for x in all_possible_pairs],
650
+ 'mj': [int(x[1][2]) for x in all_possible_pairs],
651
+ 'prob': [prob for _ in all_possible_pairs],
652
+ 'reactantName': [R.product for _ in all_possible_pairs],
653
+ 'order': [order for _ in all_possible_pairs]})
654
+ if stage==reaction_stage.cure:
655
+ # exclude atom pairs that have same resid or molid
656
+ idf=idf[(idf['ri']!=idf['rj'])&(idf['mi']!=idf['mj'])].copy()
657
+ logger.debug(f'Examining {idf.shape[0]} bond-candidates of order {order}')
658
+ if idf.shape[0]>0:
659
+ ess='' if idf.shape[0]!=1 else 's'
660
+ bondtestoutcomes={k:0 for k in BTRC}
661
+ p=Pool(processes=ncpu)
662
+ idf_split=np.array_split(idf,ncpu)
663
+ packets=[(i,idf_split[i]) for i in range(ncpu)]
664
+ logger.debug(f'Decomposed dataframe lengths: {", ".join([str(x.shape[0]) for x in idf_split])}')
665
+ results=p.map(partial(gromacs_distance,gro=gro,new_column_name='r'),packets)
666
+ p.close()
667
+ p.join()
668
+ # reassemble final dataframe:
669
+ # logger.debug(f'Checking dataframe lengths: {", ".join([str(x.shape[0]) for x in results])}')
670
+ idf=pd.concat(results,ignore_index=True)
671
+ # gromacs_distance(idf,gro,new_column_name='r') # use "gmx distance" to very quickly get all lengths
672
+ logger.debug(f'{idf.shape[0]} bond-candidate length{ess} avg/min/max: {idf["r"].mean():0.3f}/{idf["r"].min():0.3f}/{idf["r"].max():0.3f}')
673
+ idf=idf[idf['r']<self.state.current_radius].copy().reset_index(drop=True)
674
+ ess='' if idf.shape[0]!=1 else 's'
675
+ logger.debug(f'{idf.shape[0]} bond-candidate{ess} with lengths below {self.state.current_radius} nm')
676
+ p=Pool(processes=ncpu)
677
+ idf_split=np.array_split(idf,ncpu)
678
+ # logger.debug(f'Decomposed dataframe lengths: {", ".join([str(x.shape[0]) for x in idf_split])}')
679
+ results=p.map(partial(TC.bondtest_df),idf_split)
680
+ p.close()
681
+ p.join()
682
+ # reassemble final dataframe:
683
+ # logger.debug(f'Checking dataframe lengths: {", ".join([str(x.shape[0]) for x in results])}')
684
+ idf=pd.concat(results,ignore_index=True)
685
+ if not idf.empty:
686
+ logger.debug(f'Bond-candidate test outcomes:')
687
+ for k in bondtestoutcomes:
688
+ bondtestoutcomes[k]=idf[idf['result']==k].shape[0]
689
+ logger.debug(f' {str(k)}: {bondtestoutcomes[k]}')
690
+ idf=idf[idf['result']==BTRC.passed].copy()
691
+ elif stage==reaction_stage.cap:
692
+ idf=idf[idf['ri']==idf['rj']].copy()
693
+ logger.debug(f'Examining {idf.shape[0]} bond-candidates of order {order}')
694
+ if not idf.empty:
695
+ bdf=pd.concat((bdf,idf),ignore_index=True)
696
+ # logger.debug('Filtered (by single-bond tests) bonds:')
697
+ # for ln in bdf.to_string().split('\n'):
698
+ # logger.debug(ln)
699
+
700
+ if stage==reaction_stage.cure and bdf.shape[0]>0:
701
+ bdf=bdf.sort_values('r',axis=0,ignore_index=True).reset_index(drop=True)
702
+ bdf['allowed']=[True for x in range(bdf.shape[0])]
703
+ unique_atomidx=set(bdf.ai.to_list()).union(set(bdf.aj.to_list()))
704
+ unique_resids=set(bdf.ri.to_list()).union(set(bdf.rj.to_list()))
705
+ for i,r in bdf.iterrows():
706
+ if r.ai in unique_atomidx:
707
+ unique_atomidx.remove(r.ai)
708
+ else:
709
+ # logger.debug(f'Disallowing bond {i} due to repeated atom index {r.ai}')
710
+ bdf.loc[i,'allowed']=False
711
+ if r.aj in unique_atomidx:
712
+ unique_atomidx.remove(r.aj)
713
+ else:
714
+ # logger.debug(f'Disallowing bond {i} due to repeated atom index {r.aj}')
715
+ bdf.loc[i,'allowed']=False
716
+ if r.ri in unique_resids:
717
+ unique_resids.remove(r.ri)
718
+ else:
719
+ # logger.debug(f'Disallowing bond {i} due to repeated residue index {r.ri}')
720
+ bdf.loc[i,'allowed']=False
721
+ if r.rj in unique_resids:
722
+ unique_resids.remove(r.rj)
723
+ else:
724
+ # logger.debug(f'Disallowing bond {i} due to repeated residue index {r.rj}')
725
+ bdf.loc[i,'allowed']=False
726
+
727
+ logger.debug(f'{bdf[bdf["allowed"]==False].shape[0]} out of {bdf.shape[0]} bonds disallowed due to repeated atom indexes or residue indexes')
728
+
729
+ bdf=bdf[bdf['allowed']==True].copy().reset_index(drop=True)
730
+ # logger.debug('Allowed bonds:')
731
+ # for ln in bdf.to_string().split('\n'):
732
+ # logger.debug(ln)
733
+
734
+ bdf=TC.cycle_collective(bdf)
735
+ logger.debug(f'{bdf[bdf["remove-to-uncyclize"]==True].shape[0]} out of {bdf.shape[0]} bonds removed to break nascent cycles')
736
+ bdf=bdf[bdf['remove-to-uncyclize']==False].copy().reset_index(drop=True)
737
+ # logger.debug('Non-cyclizing bonds:')
738
+ # for ln in bdf.to_string().split('\n'):
739
+ # logger.debug(ln)
740
+
741
+ ''' roll the dice '''
742
+ bdf['lucky']=[True for _ in range(bdf.shape[0])]
743
+ if apply_probabilities:
744
+ for i,r in bdf.iterrows():
745
+ x=np.random.random()
746
+ if x>r.prob:
747
+ bdf.loc[i,'lucky']=False
748
+
749
+ logger.debug(f'{bdf[bdf["lucky"]==True].shape[0]} bonds survive probability application')
750
+ bdf=bdf[bdf['lucky']==True].copy().reset_index(drop=True)
751
+ # logger.debug('Lucky bonds:')
752
+ # for ln in bdf.to_string().split('\n'):
753
+ # logger.debug(ln)
754
+
755
+ ''' apply the stated limit '''
756
+ if abs_max>-1:
757
+ if abs_max<bdf.shape[0]:
758
+ bdf=bdf.loc[:abs_max].copy().reset_index(drop=True)
759
+ logger.debug(f'Limiting to {bdf.shape[0]} allowed bonds')
760
+ logger.debug('Final bonds:')
761
+ for ln in bdf.to_string().split('\n'):
762
+ logger.debug(ln)
763
+
764
+ if stage==reaction_stage.cure:
765
+ TC.linkcell_cleanup()
766
+
767
+ return bdf