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/runtime.py ADDED
@@ -0,0 +1,709 @@
1
+ """
2
+
3
+ .. module:: runtime
4
+ :synopsis: handles the HTPolyNet runtime workflow
5
+
6
+ .. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
7
+
8
+ """
9
+ import logging
10
+ import os
11
+ import shutil
12
+ import numpy as np
13
+ import random
14
+ from copy import deepcopy
15
+ from HTPolyNet.configuration import Configuration
16
+ from HTPolyNet.topology import select_topology_type_option
17
+ from HTPolyNet.topocoord import TopoCoord
18
+ import HTPolyNet.projectfilesystem as pfs
19
+ import HTPolyNet.software as software
20
+ from HTPolyNet.gromacs import insert_molecules, mdp_modify, mdp_get
21
+ import HTPolyNet.checkpoint as cp
22
+ from HTPolyNet.plot import trace
23
+ from HTPolyNet.molecule import Molecule, MoleculeDict
24
+ from HTPolyNet.reaction import is_reactant
25
+ from HTPolyNet.expandreactions import chain_expand_reactions
26
+ from HTPolyNet.reaction import reaction_stage
27
+ from HTPolyNet.curecontroller import CureController, CureState
28
+ from HTPolyNet.stringthings import my_logger
29
+
30
+ logger=logging.getLogger(__name__)
31
+
32
+ def logrotate(filename):
33
+ """logrotate renames any existing log file with name 'filename' using a pattern that
34
+ prevents overwriting any old logs
35
+
36
+ :param filename: name of log file
37
+ :type filename: str
38
+ """
39
+ if os.path.exists(filename):
40
+ n=1
41
+ while os.path.exists(f'#{n}#{filename}'):
42
+ n+=1
43
+ shutil.copyfile(filename,f'#{n}#{filename}')
44
+
45
+ _directives=['ps','nsteps','ncycles']
46
+ def _nonempty_directives(dirlist):
47
+ """_nonempty_directives checks the list of directives for existence of at least
48
+ one of the strings in the _directives list
49
+
50
+ :param dirlist: list of dictionaries
51
+ :type dirlist: lsit
52
+ :return: True if one of the strings in _directives is present in one of the dictionaries
53
+ :rtype: bool
54
+ """
55
+ amts=[]
56
+ for d in dirlist:
57
+ ta=[d.get(x,0) for x in _directives]
58
+ amts.append(any(ta))
59
+ return any(amts)
60
+
61
+ class Runtime:
62
+ """ Runtime class manages all aspects of a system build using HTPolyNet.
63
+ """
64
+ default_edict={ 'ensemble': 'npt', 'temperature': 300, 'pressure': 10, 'ps': 200, 'nsteps': -2, 'repeat': 0 }
65
+ runtime_defaults={
66
+ 'gromacs': {
67
+ 'gmx': 'gmx',
68
+ 'gmx_options': '-quiet -nobackup',
69
+ 'mdrun': 'gmx mdrun'
70
+ },
71
+ 'ambertools': {
72
+ 'charge_method': 'gas'
73
+ },
74
+ 'densification': {
75
+ 'initial_density': 200.0, # kg/m3
76
+ 'aspect_ratio': np.array([1.0,1.0,1.0]),
77
+ 'equilibration': [
78
+ { 'ensemble': 'min' },
79
+ { 'ensemble': 'nvt', 'temperature': 300, 'ps': 10 },
80
+ { 'ensemble': 'npt', 'temperature': 300, 'pressure': 10, 'ps': 200 }
81
+ ]
82
+ },
83
+ 'precure': {
84
+ 'preequilibration': {
85
+ 'ensemble': 'npt',
86
+ 'temperature': 300, # K
87
+ 'pressure': 1, # bar
88
+ 'ps': 100 # we should probably bring to a desired pressure after densification
89
+ },
90
+ 'anneal': {
91
+ 'ncycles': 0, # default none
92
+ 'initial_temperature': 300,
93
+ 'cycle_segments': [
94
+ { 'T': 300, 'ps': 0 },
95
+ { 'T': 600, 'ps': 20 },
96
+ { 'T': 600, 'ps': 20 },
97
+ { 'T': 300, 'ps': 20 },
98
+ { 'T': 300, 'ps': 20 }
99
+ ]
100
+ },
101
+ 'postequilibration': {
102
+ 'ensemble': 'npt',
103
+ 'temperature': 300, # K
104
+ 'pressure': 1, # bar
105
+ 'ps': 0 # default none
106
+ }
107
+ },
108
+ 'CURE': {},
109
+ 'postcure': {
110
+ 'anneal': {
111
+ 'ncycles': 0, # default none
112
+ 'initial_temperature': 300,
113
+ 'cycle_segments': [
114
+ { 'T': 300, 'ps': 0 },
115
+ { 'T': 600, 'ps': 20 },
116
+ { 'T': 600, 'ps': 20 },
117
+ { 'T': 300, 'ps': 20 },
118
+ { 'T': 300, 'ps': 20 }
119
+ ]
120
+ },
121
+ 'postequilibration': {
122
+ 'ensemble': 'npt',
123
+ 'temperature': 300, # K
124
+ 'pressure': 1, # bar
125
+ 'ps': 0 # default none
126
+ }
127
+ }
128
+ }
129
+
130
+ def __init__(self,cfgfile='',restart=False):
131
+ """__init__ generates a new Runtime object based on the cfg file
132
+
133
+ :param cfgfile: name of YAML cfg file
134
+ :type cfgfile: str, optional
135
+ :param restart: flag indicating if this is a restart
136
+ :type restart: bool
137
+
138
+ """
139
+ my_logger(software.to_string(),logger.info)
140
+ self.cfgfile=cfgfile
141
+ if cfgfile=='':
142
+ logger.error('HTPolyNet requires a configuration file.')
143
+ raise RuntimeError('HTPolyNet requires a configuration file')
144
+ logger.info(f'Configuration: {cfgfile}')
145
+ self.cfg=Configuration.read(os.path.join(pfs.root(),cfgfile))
146
+ """ Fill in any default values """
147
+ for k,default_values in self.runtime_defaults.items():
148
+ if not k in self.cfg.parameters:
149
+ self.cfg.parameters[k]=default_values
150
+ if type(default_values)==dict:
151
+ for kk,vv in default_values.items():
152
+ if not kk in self.cfg.parameters[k]:
153
+ self.cfg.parameters[k][kk]=vv
154
+ software.set_gmx_preferences(self.cfg.parameters)
155
+ self.TopoCoord=TopoCoord(system_name='htpolynet')
156
+ self.cfg.parameters['restart']=restart
157
+ if self.cfg.parameters['restart']:
158
+ logger.info(f'Restarting in {pfs.proj()}')
159
+ self.molecules:MoleculeDict={}
160
+ cure_dict=self.cfg.parameters.get('CURE',{})
161
+ if cure_dict:
162
+ logger.debug('Setting up cure controller')
163
+ self.cc=CureController(cure_dict)
164
+ self.ncpu=self.cfg.parameters.get('ncpu',os.cpu_count())
165
+
166
+ def generate_molecules(self,force_parameterization=False,force_checkin=False):
167
+ """generate_molecules manages creation and parameterization of all monomers
168
+ and oligomer templates
169
+
170
+ :param force_parameterization: forces AmberTools to run parameterizations, defaults to False
171
+ :type force_parameterization: bool, optional
172
+ :param force_checkin: forces HTPolyNet to overwrite molecule library, defaults to False
173
+ :type force_checkin: bool, optional
174
+ """
175
+ GAFF_dict=self.cfg.parameters.get('GAFF',{})
176
+ self.molecules={}
177
+ ''' configuration.parse() generated a list of Molecules implied by configuration; assume
178
+ they are all unparameterized '''
179
+ for mname,M in self.cfg.molecules.items():
180
+ M.set_origin('unparameterized')
181
+ pfs.go_to('molecules/parameterized')
182
+ my_logger(f'Templates in {pfs.cwd()}',logger.info)
183
+ ''' Each molecule implied by the cfg is 'generated' here, either by
184
+ reading from the library or direct parameterization. In some cases,
185
+ the molecule is to be generated by a reaction; if so, it's
186
+ `generator` attribute will be a Reaction instance '''
187
+ ess='' if len(self.cfg.molecules)==1 else 's'
188
+ logger.info(f'{len(self.cfg.molecules)} molecule{ess} detected in {self.cfgfile}')
189
+ replns=[f'{msg:>30s}: {count:<5d}' for msg,count in self.cfg.molecule_report.items()]
190
+ for ln in replns:
191
+ logger.info(ln)
192
+ ml=list(self.cfg.molecules.keys())
193
+ logger.debug(f'Generating: {ml}')
194
+ for mname,M in self.cfg.molecules.items():
195
+ self._generate_molecule(M,force_parameterization=force_parameterization,force_checkin=force_checkin)
196
+ self.molecules[mname]=M
197
+ ''' Generate any required template products that result from reactions in which the bond generated creates
198
+ dihedrals that span more than just the two monomers that are connected '''
199
+ new_reactions,new_molecules=chain_expand_reactions(self.molecules)
200
+ if len(new_molecules)>0:
201
+ ess='' if len(new_molecules)==1 else 's'
202
+ logger.info(f'{len(new_molecules)} molecule{ess} implied by chaining')
203
+ ml=list(new_molecules.keys())
204
+ # logger.info(ml)
205
+ self.cfg.reactions.extend(new_reactions)
206
+ make_molecules={k:v for k,v in new_molecules.items() if k not in self.molecules}
207
+ for mname,M in make_molecules.items():
208
+ # logger.debug(f'Generating {mname}:')
209
+ self._generate_molecule(M,force_parameterization=force_parameterization,force_checkin=force_checkin)
210
+ assert M.get_origin()!='unparameterized'
211
+ self.molecules[mname]=M
212
+ logger.debug(f'Generated {mname}')
213
+
214
+ for M in self.molecules:
215
+ self.molecules[M].is_reactant=is_reactant(M,self.cfg.reactions,stage=reaction_stage.cure)
216
+
217
+ resolve_type_discrepancies=GAFF_dict.get('resolve_type_discrepancies',[])
218
+ if not resolve_type_discrepancies:
219
+ resolve_type_discrepancies=self.cfg.parameters.get('resolve_type_discrepancies',[])
220
+ if resolve_type_discrepancies:
221
+ for resolve_directive in resolve_type_discrepancies:
222
+ logger.info(f'Resolving type discrepancies for directive {resolve_directive}')
223
+ self._type_consistency_check(typename=resolve_directive['typename'],funcidx=resolve_directive.get('funcidx',4),selection_rule=resolve_directive['rule'])
224
+
225
+ ess='' if len(self.molecules)==1 else 's'
226
+ logger.info(f'Generated {len(self.molecules)} molecule template{ess}')
227
+ if self.cfg.initial_composition:
228
+ cmp_msg=", ".join([(x["molecule"]+" "+str(x["count"])) for x in self.cfg.initial_composition if x["count"]>0])
229
+ logger.info(f'Initial composition is {cmp_msg}')
230
+ self.cfg.calculate_maximum_conversion()
231
+ logger.info(f'100% conversion is {self.cfg.maxconv} bonds')
232
+
233
+ logger.debug(f'Reaction bond(s) in each molecular template:')
234
+ for M in self.molecules.values():
235
+ if len(M.reaction_bonds)>0:
236
+ logger.debug(f'Bond {M.name}:')
237
+ for b in M.reaction_bonds:
238
+ logger.debug(f' {str(b)}')
239
+
240
+ logger.debug(f'Bond template(s) in each molecular template:')
241
+ for M in self.molecules.values():
242
+ if len(M.bond_templates)>0:
243
+ logger.debug(f'Template {M.name}:')
244
+ for b in M.bond_templates:
245
+ logger.debug(f' {str(b)}')
246
+
247
+ for k,v in self.cfg.parameters.get('constituents',{}).items():
248
+ relaxdict=v.get('relax',{})
249
+ if relaxdict:
250
+ self.molecules[k].relax(relaxdict)
251
+
252
+ @cp.enableCheckpoint
253
+ def do_initialization(self,inpfnm='init'):
254
+ """do_initialization manages creation of the global system topology file
255
+ and the execution of 'gmx insert-molecules' to create the initial
256
+ simulation box
257
+
258
+ :param inpfnm: basename for output files, defaults to 'init'
259
+ :type inpfnm: str, optional
260
+ :return: dictionary of Gromacs files
261
+ :rtype: dict
262
+ """
263
+ my_logger(f'Initialization in {pfs.cwd()}',logger.info)
264
+ top=self._initialize_topology(inpfnm)
265
+ gro,grx=self._initialize_coordinates(inpfnm)
266
+ return {'top':top,'gro':gro,'grx':grx}
267
+
268
+ @cp.enableCheckpoint
269
+ def do_densification(self,deffnm='densified'):
270
+ """do_densification manages execution of gmx mdrun to perform minimization
271
+ and NPT MD simulation of the initial liquid system. Final coordinates are
272
+ loaded into the global TopoCoord.
273
+
274
+ :param inpfnm: input file name prefix, defaults to 'init'
275
+ :type inpfnm: str, optional
276
+ :param deffnm: deffnm prefix fed to gmx mdrun, defaults to 'npt-1'
277
+ :type deffnm: str, optional
278
+ :return: dictionary of Gromacs file names
279
+ :rtype: dict
280
+ """
281
+ my_logger(f'Densification in {pfs.cwd()}',logger.info)
282
+ densification_dict=self.cfg.parameters.get('densification',{})
283
+ assert len(densification_dict)>0,'"densification" directives missing'
284
+ equilibration=densification_dict.get('equilibration',[])
285
+ assert len(equilibration)>0,'equilibration directives missing'
286
+ TC=self.TopoCoord
287
+ infiles=[TC.files[x] for x in ['gro','top','grx']]
288
+ assert all([os.path.exists(x) for x in infiles]),f'One or more of {infiles} not found'
289
+ self._do_equilibration_series(equilibration,deffnm=f'{deffnm}',plot_pfx='densification')
290
+ logger.info(f'Densified coordinates in {pfs.cwd()}/{os.path.basename(TC.files["gro"])}')
291
+ return {c:os.path.basename(x) for c,x in TC.files.items() if c!='mol2'}
292
+
293
+ @cp.enableCheckpoint
294
+ def do_precure(self):
295
+ """do_precure manages execution of mdrun to perform any pre-cure MD simulation(s).
296
+
297
+ :return: dictionary of Gromacs file names
298
+ :rtype: dict
299
+ """
300
+ self._do_pap(pfx='precure')
301
+ return {c:os.path.basename(x) for c,x in self.TopoCoord.files.items() if c!='mol2'}
302
+
303
+ def do_cure(self):
304
+ """do_cure manages CURE algorithm execution.
305
+
306
+ :return: only returns None if CURE cannot execute
307
+ :rtype: None
308
+ """
309
+ if not hasattr(self,'cc'):
310
+ logger.debug(f'no cure controller')
311
+ return # no cure controller
312
+ cc=self.cc
313
+ TC=self.TopoCoord
314
+ RL=self.cfg.reactions
315
+ MD=self.molecules
316
+ gromacs_dict=self.cfg.parameters.get('gromacs',{})
317
+ pfs.go_proj()
318
+ ''' read cure state or initialize new cure '''
319
+ if os.path.exists('systems/cure_state.yaml'):
320
+ cc.state=CureState.from_yaml('systems/cure_state.yaml')
321
+ my_logger(f'Connect-Update-Relax-Equilibrate (CURE) resumes',logger.info)
322
+ my_logger(f'at iteration {cc.state.iter} and {cc.state.cum_nxlinkbonds} bonds',logger.info)
323
+ else:
324
+ cc.setup(max_nxlinkbonds=self.cfg.maxconv,desired_nxlinkbonds=int(self.cfg.maxconv*cc.dicts['controls']['desired_conversion']),max_search_radius=float(min(TC.Coordinates.box.diagonal()/2)))
325
+ cc.state.iter=1
326
+ my_logger('Connect-Update-Relax-Equilibrate (CURE) begins',logger.info)
327
+ cure_finished=cc.is_cured()
328
+ if cure_finished:
329
+ logger.debug('cure finished even before loop')
330
+ return
331
+ ''' perform CURE iterations '''
332
+ logger.info(f'Attempting to form {cc.state.desired_nxlinkbonds} bonds')
333
+ while not cure_finished:
334
+ pfs.go_to(f'systems/iter-{cc.state.iter}')
335
+ cc.do_iter(TC,RL,MD,gromacs_dict=gromacs_dict)
336
+ cure_finished=cc.is_cured()
337
+ if not cure_finished:
338
+ cure_finished=cc.next_iter()
339
+ ''' perform capping if necessary '''
340
+ my_logger(f'Capping begins',logger.info)
341
+ pfs.go_to(f'systems/capping')
342
+ cc.do_capping(TC,RL,MD,gromacs_dict=gromacs_dict)
343
+ my_logger('Connect-Update-Relax-Equilibrate (CURE) ends',logger.info)
344
+
345
+ @cp.enableCheckpoint
346
+ def do_postcure(self):
347
+ """do_postcure manages execution of mdrun to perform any post-cure MD simulation(s).
348
+
349
+ :return: dictionary of Gromacs file names
350
+ :rtype: dict
351
+ """
352
+ self._do_pap(pfx='postcure')
353
+ return {c:os.path.basename(x) for c,x in self.TopoCoord.files.items() if c!='mol2'}
354
+
355
+ @cp.enableCheckpoint
356
+ def save_data(self,result_name='final'):
357
+ """save_data writes 'gro', 'top', and 'grx' files for system
358
+
359
+ :param result_name: output file basename, defaults to 'final'
360
+ :type result_name: str, optional
361
+ :return: dictionary of Gromacs file basenames
362
+ :rtype: dict
363
+ """
364
+ TC=self.TopoCoord
365
+ my_logger(f'Final data to {pfs.cwd()}',logger.info)
366
+ TC.write_grx_attributes(f'{result_name}.grx')
367
+ TC.write_gro(f'{result_name}.gro')
368
+ TC.write_top(f'{result_name}.top')
369
+ return {c:os.path.basename(x) for c,x in TC.files.items() if c!='mol2'}
370
+
371
+ def do_workflow(self,**kwargs):
372
+ """do_workflow manages runtime for one entire system-build workflow
373
+ """
374
+ force_parameterization=kwargs.get('force_parameterization',False)
375
+ force_checkin=kwargs.get('force_checkin',False)
376
+ TC=self.TopoCoord
377
+ pfs.go_proj()
378
+ self.generate_molecules(
379
+ force_parameterization=force_parameterization, # force antechamber/GAFF parameterization
380
+ force_checkin=force_checkin # force check-in to system libraries
381
+ )
382
+ pfs.go_proj()
383
+ last_data=cp.read_checkpoint()
384
+ logger.debug(f'Checkpoint last_data {last_data}')
385
+ TC.load_files(last_data)
386
+ pfs.go_to(f'systems/init')
387
+ self.do_initialization()
388
+ pfs.go_to(f'systems/densification')
389
+ self.do_densification()
390
+ pfs.go_to(f'systems/precure')
391
+ self.do_precure()
392
+ self.do_cure()
393
+ pfs.go_to(f'systems/postcure')
394
+ self.do_postcure()
395
+ pfs.go_to(f'systems/final-results')
396
+ self.save_data()
397
+ pfs.go_proj()
398
+
399
+ def _generate_molecule(self,M:Molecule,**kwargs):
400
+ """_generate_molecule generates and parameterizes a single molecule based on the partially
401
+ complete instance in parameter M
402
+
403
+ :param M: partially-complete molecule instance (populated by config reader)
404
+ :type M: Molecule
405
+ """
406
+ if M.origin!='unparameterized' and M.origin!='symmetry_product': return
407
+ mname=M.name
408
+ checkin=pfs.checkin
409
+ force_parameterization=kwargs.get('force_parameterization',False)
410
+ force_checkin=kwargs.get('force_checkin',False)
411
+ ''' Either perform a fresh parameterization or fetch parameterization files '''
412
+ if force_parameterization or not M.previously_parameterized():
413
+ logger.debug(f'Parameterization of {mname} requested -- can we generate {mname}?')
414
+ generatable=(not M.generator) or (all([m in self.molecules for m in M.generator.reactants.values()]))
415
+ if generatable:
416
+ logger.debug(f'Generating {mname}')
417
+ M.generate(available_molecules=self.molecules,**self.cfg.parameters)
418
+ for ex in ['mol2','top','itp','gro','grx']:
419
+ checkin(f'molecules/parameterized/{mname}.{ex}',overwrite=force_checkin)
420
+ M.set_origin('newly parameterized')
421
+ else:
422
+ logger.debug(f'Error: could not generate {mname}')
423
+ logger.debug(f'not ({mname}.generator) = {bool(not M.generator)}')
424
+ if M.generator:
425
+ logger.debug(f'reactants {list(M.generator.reactants.values())}')
426
+ return
427
+ else:
428
+ logger.debug(f'Fetching parameterized {mname}')
429
+ exts=pfs.fetch_molecule_files(mname)
430
+ logger.debug(f'fetched {mname} exts {exts}')
431
+ M.load_top_gro(f'{mname}.top',f'{mname}.gro',mol2filename='',wrap_coords=False)
432
+ M.TopoCoord.read_gro_attributes(f'{mname}.grx')
433
+ M.set_sequence_from_coordinates()
434
+ if M.generator:
435
+ M.prepare_new_bonds(available_molecules=self.molecules)
436
+ M.set_origin('previously parameterized')
437
+
438
+ ''' Generate any stereoisomers and/or conformers '''
439
+ M.generate_stereoisomers()
440
+ M.generate_conformers()
441
+
442
+ def _type_consistency_check(self,typename='dihedraltypes',funcidx=4,selection_rule='stiffest'):
443
+ """_type_consistency_check checks current topology for any inconsistencies and corrects them
444
+
445
+ :param typename: type of Gromacs interaction to check, defaults to 'dihedraltypes'
446
+ :type typename: str, optional
447
+ :param funcidx: function type of interaction, defaults to 4
448
+ :type funcidx: int, optional
449
+ :param selection_rule: one-word designation for correction mechanism, defaults to 'stiffest'
450
+ :type selection_rule: str, optional
451
+ """
452
+ logger.debug(f'Consistency check of {typename} func {funcidx} on all {len(self.molecules)} molecules requested')
453
+ mnames=list(self.molecules.keys())
454
+ types_duplicated=[]
455
+ for i in range(len(mnames)):
456
+ logger.debug(f'{mnames[i]}...')
457
+ for j in range(i+1,len(mnames)):
458
+ mol1topo=self.molecules[mnames[i]].TopoCoord.Topology
459
+ mol2topo=self.molecules[mnames[j]].TopoCoord.Topology
460
+ this_duptypes=mol1topo.report_duplicate_types(mol2topo,typename=typename,funcidx=funcidx)
461
+ logger.debug(f'...{mnames[j]} {len(this_duptypes)}')
462
+ for d in this_duptypes:
463
+ if not d in types_duplicated:
464
+ types_duplicated.append(d)
465
+ logger.debug(f'Duplicated {typename}: {types_duplicated}')
466
+ options={}
467
+ for t in types_duplicated:
468
+ logger.debug(f'Duplicate {t}:')
469
+ options[t]=[]
470
+ for i in range(len(mnames)):
471
+ moltopo=self.molecules[mnames[i]].TopoCoord.Topology
472
+ this_type=moltopo.report_type(t,typename='dihedraltypes',funcidx=4)
473
+ if len(this_type)>0 and not this_type in options[t]:
474
+ options[t].append(this_type)
475
+ logger.debug(f'{mnames[i]} reports {this_type}')
476
+ logger.debug(f'Conflicting options for this type: {options[t]}')
477
+ selected_type=select_topology_type_option(options[t],typename,rule=selection_rule)
478
+ logger.debug(f'Under selection rule "{selection_rule}", preferred type is {selected_type}')
479
+ for i in range(len(mnames)):
480
+ logger.debug(f'resetting {mnames[i]}')
481
+ TC=self.molecules[mnames[i]].TopoCoord
482
+ moltopo=TC.Topology
483
+ moltopo.reset_type(typename,t,selected_type)
484
+
485
+ def _initialize_topology(self,inpfnm='init'):
486
+ """_initialize_topology creates a full gromacs topology that includes all directives necessary
487
+ for an initial liquid simulation. This will NOT use any #include's;
488
+ all types will be explicitly in-lined.
489
+
490
+ :param inpfnm: input file basename, defaults to 'init'
491
+ :type inpfnm: str, optional
492
+ :return: name of top file
493
+ :rtype: str
494
+ """
495
+ # if cp.passed('initialize_topology'): return
496
+ if os.path.isfile(f'{inpfnm}.top'):
497
+ logger.debug(f'{inpfnm}.top already exists in {pfs.cwd()} but we will rebuild it anyway!')
498
+
499
+ ''' for each monomer named in the cfg, either parameterize it or fetch its parameterization '''
500
+ TC=self.TopoCoord
501
+ already_merged=[]
502
+ for item in self.cfg.initial_composition:
503
+ M=self.molecules[item['molecule']]
504
+ N=item['count']
505
+ if not N: continue
506
+ t=deepcopy(M.TopoCoord.Topology)
507
+ logger.debug(f'Merging {N} copies of {M.name}\'s topology into global topology')
508
+ t.adjust_charges(atoms=t.D['atoms']['nr'].to_list(),desired_charge=0.0,overcharge_threshhold=0.1,msg='')
509
+ t.rep_ex(N)
510
+ TC.Topology.merge(t)
511
+ already_merged.append(M.name)
512
+ for othermol,M in self.molecules.items():
513
+ if not othermol in already_merged:
514
+ logger.debug(f'Merging types from {othermol}\'s topology into global topology')
515
+ TC.Topology.merge_types(M.TopoCoord.Topology)
516
+ logger.info(f'Topology "{inpfnm}.top" in {pfs.cwd()}')
517
+ TC.write_top(f'{inpfnm}.top')
518
+ return f'{inpfnm}.top'
519
+
520
+ def _initialize_coordinates(self,inpfnm='init'):
521
+ """_initialize_coordinates builds initial top and gro files for initial liquid simulation
522
+
523
+ :param inpfnm: input file basename, defaults to 'init'
524
+ :type inpfnm: str, optional
525
+ :return: 'gro' and 'grx' file names
526
+ :rtype: tuple
527
+ """
528
+ densification_dict=self.cfg.parameters.get('densification',{})
529
+ # logger.debug(f'{densification_dict}')
530
+ TC=self.TopoCoord
531
+ if not densification_dict:
532
+ densification_dict['aspect_ratio']=self.cfg.parameters.get('aspect_ratio',np.array([1.,1.,1.]))
533
+ if 'initial_density' in self.cfg.parameters:
534
+ densification_dict['initial_density']=self.cfg.parameters['initial_density']
535
+ if 'initial_boxsize' in self.cfg.parameters:
536
+ densification_dict['initial_boxsize']=self.cfg.parameters['initial_boxsize']
537
+ dspec=['initial_density' in densification_dict,'initial_boxsize' in densification_dict]
538
+ # logger.debug(f'{dspec} {any(dspec)} {not all(dspec)}')
539
+ assert any(dspec),'Neither "initial_boxsize" nor "initial_density" are specfied'
540
+ assert not all(dspec),'Cannot specify both "initial_boxsize" and "initial_density"'
541
+ if 'initial_boxsize' in densification_dict:
542
+ boxsize=densification_dict['initial_boxsize']
543
+ else:
544
+ mass_kg=TC.total_mass(units='SI')
545
+ V0_m3=mass_kg/densification_dict['initial_density']
546
+ ar=densification_dict.get('aspect_ratio',np.array([1.,1.,1.]))
547
+ assert ar[0]==1.,f'Error: parameter aspect_ratio must be a 3-element-list with first element 1'
548
+ ar_yx=ar[1]*ar[2]
549
+ L0_m=(V0_m3/ar_yx)**(1./3.)
550
+ L0_nm=L0_m*1.e9
551
+ boxsize=np.array([L0_nm,L0_nm,L0_nm])*ar
552
+ logger.info(f'Initial density: {densification_dict["initial_density"]} kg/m^3')
553
+ logger.info(f'Total mass: {mass_kg:.3e} kg')
554
+ logger.info(f'Box aspect ratio: {" x ".join([str(x) for x in ar])}')
555
+ logger.info(f'Initial box side lengths: {boxsize[0]:.3f} nm x {boxsize[1]:.3f} nm x {boxsize[2]:.3f} nm')
556
+
557
+ clist=[cc for cc in self.cfg.initial_composition if 'count' in cc]
558
+ c_togromacs={}
559
+ for cc in clist:
560
+ M=self.cfg.molecules[cc['molecule']]
561
+ tc=cc['count']
562
+ if not tc: continue
563
+ if len(M.conformers)>0:
564
+ nconf=len(M.conformers)
565
+ if tc<nconf:
566
+ c_togromacs.update({u:1 for u in random.sample(M.conformers,tc)})
567
+ else:
568
+ q,r=divmod(tc,nconf)
569
+ logger.debug(f'divmod({nconf},{tc}) gives {q}, {r}')
570
+ c_togromacs.update({u:q for u in M.conformers})
571
+ k=0
572
+ while r:
573
+ c_togromacs[M.conformers[k]]+=1
574
+ k+=1
575
+ r-=1
576
+ for gro in M.conformers:
577
+ pfs.checkout(f'molecules/parameterized/{gro}.gro',altpath=[pfs.subpath('molecules')])
578
+ else:
579
+ ''' assuming racemic mixture of any stereoisomers '''
580
+ total_isomers=len(M.stereoisomers)+1
581
+ count_per_isomer=tc//total_isomers
582
+ leftovers=tc%total_isomers
583
+ c_togromacs[M.name]=count_per_isomer
584
+ if leftovers>0:
585
+ c_togromacs[M.name]+=1
586
+ leftovers-=1
587
+ pfs.checkout(f'molecules/parameterized/{M.name}.gro',altpath=[pfs.subpath('molecules')])
588
+ for isomer in M.stereoisomers:
589
+ c_togromacs[isomer]=count_per_isomer
590
+ if leftovers>0:
591
+ c_togromacs[isomer]+=1
592
+ leftovers-=1
593
+ pfs.checkout(f'molecules/parameterized/{isomer}.gro',altpath=[pfs.subpath('molecules')])
594
+ logger.debug(f'Sending to insert_molecules: {c_togromacs}')
595
+ msg=insert_molecules(c_togromacs,boxsize,inpfnm,inputs_dir='../../molecules/parameterized',**self.cfg.parameters)
596
+ TC.read_gro(f'{inpfnm}.gro')
597
+ TC.atom_count()
598
+ TC.set_grx_attributes()
599
+ TC.inherit_grx_attributes_from_molecules(self.cfg.molecules,self.cfg.initial_composition)
600
+ for list_name in ['cycle','chain']:
601
+ TC.reset_idx_list_from_grx_attributes(list_name)
602
+ TC.make_resid_graph()
603
+ TC.write_grx_attributes(f'{inpfnm}.grx')
604
+ logger.info(f'Coordinates "{inpfnm}.gro" in {pfs.cwd()}')
605
+ logger.info(f'Extended attributes "{inpfnm}.grx" in {pfs.cwd()}')
606
+ return f'{inpfnm}.gro',f'{inpfnm}.grx'
607
+
608
+ def _do_equilibration(self,edict={},deffnm='equilibrate',plot_pfx=''):
609
+ """_do_equilibration manages execution of TopoCoord.equilibrate using
610
+ the directive passed in parameter 'edict'
611
+
612
+ :param edict: equilibration directives, defaults to {}
613
+ :type edict: dict, optional
614
+ :param deffnm: mdrun default file basename, defaults to 'equilibrate'
615
+ :type deffnm: str, optional
616
+ :param plot_pfx: basename for any output plots, defaults to ''
617
+ :type plot_pfx: str, optional
618
+ """
619
+ gromacs_dict=self.cfg.parameters.get('gromacs',{})
620
+ TC=self.TopoCoord
621
+ for k in edict.keys():
622
+ if not k in self.default_edict:
623
+ logger.debug(f'ignoring unknown equilibration directive "{k}"')
624
+ edr_list=TC.equilibrate(deffnm,edict,gromacs_dict)
625
+ ens=edict['ensemble']
626
+ if ens=='npt' and plot_pfx!='':
627
+ trace('Density',edr_list,outfile=os.path.join(pfs.proj(),f'plots/{plot_pfx}-density.png'))
628
+
629
+ def _do_equilibration_series(self,eq_stgs=[],deffnm='equilibrate',plot_pfx=''):
630
+ """_do_equilibration_series manages a series of equilibrations
631
+
632
+ :param eq_stgs: list of stage designations, defaults to []
633
+ :type eq_stgs: list, optional
634
+ :param deffnm: mdrun default file basename, defaults to 'equilibrate'
635
+ :type deffnm: str, optional
636
+ :param plot_pfx: basename for any output plots, defaults to ''
637
+ :type plot_pfx: str, optional
638
+ """
639
+ if not eq_stgs: return
640
+ for stg in eq_stgs:
641
+ self._do_equilibration(stg,deffnm,plot_pfx)
642
+
643
+ def _do_pap(self,pfx='precure'):
644
+ """_do_pap manages a preanneal-anneal-postanneal series of MD simulations
645
+
646
+ :param pfx: either 'precure' or 'postcure', defaults to 'precure'
647
+ :type pfx: str, optional
648
+ """
649
+ if not pfx: return
650
+ assert pfx in ['precure','postcure']
651
+ pap_dict=self.cfg.parameters.get(pfx,{})
652
+ if not pap_dict: return
653
+ preequil=pap_dict.get('preequilibration',{})
654
+ anneal=pap_dict.get('anneal',{})
655
+ postequil=pap_dict.get('postequilibration',{})
656
+ if not any([preequil,anneal,postequil]): return
657
+ if not _nonempty_directives([x for x in [preequil,anneal,postequil] if x]): return
658
+ my_logger(f'{pfx.capitalize()} in {pfs.cwd()}',logger.info)
659
+ if preequil: self._do_equilibration(preequil,deffnm='preequilibration',plot_pfx=f'{pfx}-preequilibration')
660
+ if anneal and _nonempty_directives([anneal]):
661
+ self._do_anneal(anneal,deffnm='annealed')
662
+ trace('Temperature',['annealed'],outfile=os.path.join(pfs.proj(),f'plots/{pfx}-anneal-T.png'))
663
+ if postequil: self._do_equilibration(postequil,deffnm='postequilibration',plot_pfx=f'{pfx}-postequilibration')
664
+
665
+ def _do_anneal(self,anneal_dict={},deffnm='anneal'):
666
+ """_do_anneal manages execution of an annealing MD simulation
667
+
668
+ :param anneal_dict: annealing directives, defaults to {}
669
+ :type anneal_dict: dict, optional
670
+ :param deffnm: mdrun default file basename, defaults to 'anneal'
671
+ :type deffnm: str, optional
672
+ :raises Exception: If no run duration is indicated in the any of the annealing segments
673
+ """
674
+ if not anneal_dict: return
675
+ ncycles=anneal_dict.get('ncycles',0)
676
+ if not ncycles: return
677
+ mdp_pfx='nvt' # assume all annealing run at NVT
678
+ TC=self.TopoCoord
679
+ gromacs_dict=self.cfg.parameters.get('gromacs',{})
680
+ pfs.checkout(f'mdp/{mdp_pfx}.mdp')
681
+ timestep=float(mdp_get(f'{mdp_pfx}.mdp','dt'))
682
+ cycle_segments=anneal_dict.get('cycle_segments',[])
683
+ temps=[str(r['T']) for r in cycle_segments]
684
+ durations=[r.get('ps',0) for r in cycle_segments]
685
+ if not any(durations):
686
+ durations=['{:.2f}'.format(r.get('nsteps',)*timestep) for r in cycle_segments]
687
+ if not any(durations):
688
+ raise Exception(f'No "ps" or "nsteps" found.')
689
+ cycle_duration=sum(durations)
690
+ total_duration=cycle_duration*ncycles
691
+ nsteps=int(total_duration/timestep)
692
+ cum_time=durations.copy()
693
+ for i in range(1,len(cum_time)):
694
+ cum_time[i]+=cum_time[i-1]
695
+ logger.info(f'Annealing: {len(durations)} points for {ncycles} cycles over {total_duration} ps')
696
+ mod_dict={
697
+ 'ref_t':anneal_dict.get('initial_temperature',300.0),
698
+ 'gen-temp':anneal_dict.get('initial_temperature',300.0),
699
+ 'gen-vel':'yes',
700
+ 'annealing-npoints':len(cycle_segments),
701
+ 'annealing-temp':' '.join(temps),
702
+ 'annealing-time':' '.join([f'{x:.2f}' for x in cum_time]),
703
+ 'annealing':'periodic' if ncycles>1 else 'single',
704
+ 'nsteps':nsteps
705
+ }
706
+ mdp_modify(f'{mdp_pfx}.mdp',mod_dict)
707
+ msg=TC.grompp_and_mdrun(out=deffnm,mdp=mdp_pfx,quiet=False,**gromacs_dict)
708
+ logger.info(f'Annealed coordinates in {deffnm}.gro')
709
+