HTPolyNet 2.9.0__py3-none-any.whl → 2.10.0__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.
@@ -17,6 +17,7 @@ libraries keep working rather than silently re-parameterizing wholesale.
17
17
 
18
18
  Author: Cameron F. Abrams <cfa22@drexel.edu>
19
19
  """
20
+ import hashlib
20
21
  import json
21
22
  import logging
22
23
  import os
@@ -33,6 +34,30 @@ _KEY_FIELDS = (
33
34
  )
34
35
  """Fields that determine the parameters, with human-readable labels."""
35
36
 
37
+ FRCMOD_FIELD = 'frcmod'
38
+ """Record field holding a digest of the user frcmod files loaded after parmchk2's.
39
+
40
+ Written only when a molecule has any, so records of molecules without one are
41
+ unchanged; its absence means "none" when compared.
42
+ """
43
+
44
+
45
+ def frcmod_digest(frcmods):
46
+ """Returns a digest identifying a list of user frcmod files by content.
47
+
48
+ Args:
49
+ frcmods (list): (label, text) tuples, in load order
50
+
51
+ Returns:
52
+ str or None: hex digest, or None if the list is empty
53
+ """
54
+ if not frcmods:
55
+ return None
56
+ h = hashlib.sha256()
57
+ for label, text in frcmods:
58
+ h.update(label.encode('utf-8') + b'\0' + text.encode('utf-8') + b'\0')
59
+ return h.hexdigest()[:16]
60
+
36
61
 
37
62
  def build_key(ambertools=None):
38
63
  """Returns the provenance record describing a parameterization run under
@@ -49,8 +74,12 @@ def build_key(ambertools=None):
49
74
  """
50
75
  from ..external.ambertools import AMBERTOOLS_DEFAULTS
51
76
  ambertools = ambertools or {}
52
- return {field: ambertools.get(field, AMBERTOOLS_DEFAULTS[field])
53
- for field, _ in _KEY_FIELDS}
77
+ key = {field: ambertools.get(field, AMBERTOOLS_DEFAULTS[field])
78
+ for field, _ in _KEY_FIELDS}
79
+ digest = frcmod_digest(ambertools.get(FRCMOD_FIELD))
80
+ if digest:
81
+ key[FRCMOD_FIELD] = digest
82
+ return key
54
83
 
55
84
 
56
85
  def key_filename(prefix):
@@ -129,4 +158,8 @@ def describe_mismatch(stored, requested):
129
158
  continue
130
159
  if stored[field] != requested.get(field):
131
160
  diffs.append(f'{label} {stored[field]!r} cached, {requested.get(field)!r} requested')
161
+ # unlike the fields above, an absent frcmod digest is a statement: none was loaded
162
+ if stored.get(FRCMOD_FIELD) != requested.get(FRCMOD_FIELD):
163
+ diffs.append(f'user frcmod {stored.get(FRCMOD_FIELD) or "none"} cached, '
164
+ f'{requested.get(FRCMOD_FIELD) or "none"} requested')
132
165
  return diffs
htpolynet/core/runtime.py CHANGED
@@ -20,7 +20,7 @@ from ..core import projectfilesystem as pfs
20
20
  from ..core.configuration import Configuration
21
21
  from ..core.molecule import Molecule, MoleculeDict
22
22
  from ..core.topocoord import TopoCoord
23
- from ..core.topology import select_topology_type_option
23
+ from ..core.topology import conflicting_types, select_topology_type_option
24
24
  from ..cure.chain import ChainManager
25
25
  from ..cure.curecontroller import CureController, CureState
26
26
  from ..cure.expandreactions import bondchain_expand_reactions, generate_stereo_reactions, generate_symmetry_reactions, sibling_expand_reactions
@@ -150,6 +150,7 @@ class Runtime:
150
150
  self.restart=restart
151
151
  if restart:
152
152
  logger.info(f'Restarting in {pfs.proj()}')
153
+ self.frcmods=self._read_frcmods()
153
154
  self.molecules:MoleculeDict={}
154
155
  # molecules reused from a library entry that carries no provenance
155
156
  # record, collected for a stage-end summary; see generate_molecules
@@ -194,6 +195,66 @@ class Runtime:
194
195
  if k not in current:
195
196
  current[k]=v
196
197
 
198
+ def _read_frcmods(self):
199
+ """Reads the user frcmod file each constituent names, if any.
200
+
201
+ Returns:
202
+ dict: {constituent name: frcmod text}
203
+
204
+ Raises:
205
+ FileNotFoundError: if a named frcmod file does not exist
206
+ """
207
+ frcmods={}
208
+ for name,rec in (self.cfg.constituents or {}).items():
209
+ fn=(rec or {}).get('frcmod')
210
+ if not fn: continue
211
+ path=os.path.join(pfs.root(),fn)
212
+ if not os.path.isfile(path):
213
+ raise FileNotFoundError(f'frcmod {fn!r} for constituent {name} not found (looked for {path})')
214
+ with open(path) as f:
215
+ frcmods[name]=f.read()
216
+ logger.info(f'{name}: user frcmod {fn} will be loaded for {name} and every template containing it')
217
+ return frcmods
218
+
219
+ def _ambertools_for(self,M:Molecule):
220
+ """Returns the AmberTools directives for parameterizing M.
221
+
222
+ These are the configuration's, plus the user frcmod files of every
223
+ constituent residue M contains, so that a template built around a
224
+ monomer carries the same override as the monomer.
225
+
226
+ Args:
227
+ M (Molecule): molecule about to be parameterized, or checked against the cache
228
+
229
+ Returns:
230
+ dict: ambertools directives
231
+ """
232
+ amb=dict(self.cfg.ambertools or {})
233
+ residues=set(getattr(M,'sequence',None) or [M.name])
234
+ frc=[(n,t) for n,t in sorted(getattr(self,'frcmods',{}).items()) if n in residues]
235
+ if frc:
236
+ amb['frcmod']=frc
237
+ return amb
238
+
239
+ def _check_frcmod_type_conflicts(self):
240
+ """Refuses a set of molecules that a user frcmod leaves with conflicting bonded types.
241
+
242
+ Raises:
243
+ RuntimeError: if a type is parameterized differently in molecules built with and
244
+ without (or with different) user frcmod files
245
+ """
246
+ if not getattr(self,'frcmods',None): return
247
+ tops={n:(M.TopoCoord.Topology,paramcache.frcmod_digest(self._ambertools_for(M).get('frcmod')))
248
+ for n,M in self.molecules.items() if M.TopoCoord.Topology.D.get('atoms') is not None}
249
+ conflicts=conflicting_types(tops)
250
+ if not conflicts: return
251
+ for typename,key,a,b in conflicts[:10]:
252
+ logger.error(f'{typename} {"-".join(key[:-1])} (func {key[-1]}) differs between {a} and {b}')
253
+ raise RuntimeError(f'{len(conflicts)} bonded type(s) are parameterized differently in molecules built with and '
254
+ f'without a user frcmod. A system has one table per type, so the override cannot apply to '
255
+ f'some molecules and not others. Give the overridden atoms their own atom type, or apply '
256
+ f'the frcmod to every constituent that contains the type.')
257
+
197
258
  def _build_molecules_and_reactions(self):
198
259
  """Builds Molecule and Reaction objects from the parsed configuration.
199
260
 
@@ -331,6 +392,8 @@ class Runtime:
331
392
  self.molecules[mname]=M
332
393
  logger.debug(f'Generated {mname}')
333
394
 
395
+ self._check_frcmod_type_conflicts()
396
+
334
397
  for M in self.molecules:
335
398
  self.molecules[M].is_reactant=is_reactant(M,self.reactions,stage=reaction_stage.cure)
336
399
 
@@ -781,7 +844,7 @@ class Runtime:
781
844
  list: descriptions of the differing directives; empty if the cached
782
845
  parameterization agrees with this run or carries no record
783
846
  """
784
- requested = paramcache.build_key(self.cfg.ambertools)
847
+ requested = paramcache.build_key(self._ambertools_for(M))
785
848
  # Discard any record left in the project directory by an earlier run so
786
849
  # that what we check is the record belonging to the library entry that
787
850
  # previously_parameterized() just found.
@@ -829,7 +892,7 @@ class Runtime:
829
892
  generatable=(not M.generator) or (all([m in self.molecules for m in M.generator.reactants.values()]))
830
893
  if generatable:
831
894
  logger.debug(f'Generating {mname}')
832
- M.generate(available_molecules=self.molecules,gaff=self.cfg.gaff,ambertools=self.cfg.ambertools)
895
+ M.generate(available_molecules=self.molecules,gaff=self.cfg.gaff,ambertools=self._ambertools_for(M))
833
896
  self._checkin_parameterization(mname, force_checkin)
834
897
  M.origin='newly parameterized'
835
898
  else:
@@ -899,7 +962,7 @@ class Runtime:
899
962
  # assert it matches what falls out of the merged dataframe).
900
963
  M.set_sequence_from_moldict(self.molecules)
901
964
  M.generate(available_molecules=self.molecules,
902
- gaff=self.cfg.gaff, ambertools=self.cfg.ambertools)
965
+ gaff=self.cfg.gaff, ambertools=self._ambertools_for(M))
903
966
  self._checkin_parameterization(mname, True)
904
967
  M.origin='newly parameterized (stale cache refreshed)'
905
968
  else:
@@ -137,6 +137,49 @@ _GromacsTopologyDirectiveDefaults_ = {
137
137
  'defaults': [1, 2, 'yes', 0.5, 0.83333333]
138
138
  }
139
139
 
140
+ def conflicting_types(topologies, typenames=('bondtypes', 'angletypes', 'dihedraltypes')):
141
+ """Finds bonded types that two groups of topologies parameterize differently.
142
+
143
+ A merged topology keeps one table per type, shared by every molecule in
144
+ it, so a type with different parameters in two molecules cannot be
145
+ honored for both: drop_duplicates keeps both sets, and GROMACS applies
146
+ them together. A user frcmod loaded for some molecules and not others is
147
+ the usual way to create one.
148
+
149
+ Args:
150
+ topologies (dict): {name: (Topology, group)}; types are compared only between topologies
151
+ whose groups differ, e.g. a digest of the frcmod files each was built with
152
+ typenames (tuple): type sections to compare
153
+
154
+ Returns:
155
+ list: (typename, type key, name of one topology, name of another) tuples, one per conflicting
156
+ type; the key is the atom types followed by the function number
157
+ """
158
+ seen = {}
159
+ conflicts = []
160
+ for name, (T, group) in topologies.items():
161
+ for typename in typenames:
162
+ df = T.D.get(typename)
163
+ if df is None or df.empty:
164
+ continue
165
+ hashables = _GromacsTopologyHashables_[typename]
166
+ params = [c for c in df.columns if c not in hashables]
167
+ rows = {}
168
+ for r in df.itertuples(index=False):
169
+ r = r._asdict()
170
+ t = tuple(r[h] for h in hashables)
171
+ # a proper and an improper can share atom types; they are different types
172
+ key = (*min(t, t[::-1]), int(r['func']) if 'func' in r else 0)
173
+ rows.setdefault(key, []).append(tuple(round(float(r[p]), 4) if isinstance(r[p], (int, float)) else r[p]
174
+ for p in params))
175
+ for key, values in rows.items():
176
+ values = tuple(sorted(values))
177
+ first = seen.setdefault((typename, key), (name, group, values))
178
+ if first[1] != group and first[2] != values:
179
+ conflicts.append((typename, key, first[0], name))
180
+ return conflicts
181
+
182
+
140
183
  def select_topology_type_option(options, typename='dihedraltypes', rule='stiffest'):
141
184
  """Selects from a list of topological interaction options of type typename using the provided rule.
142
185
 
@@ -28,6 +28,15 @@ invocations below and the provenance record written beside their output; see
28
28
  """
29
29
 
30
30
 
31
+ def leapsafe(name):
32
+ """Returns a tleap-safe file stem for name.
33
+
34
+ tleap reads a bare filename containing 'e' after a digit as a number, so
35
+ names are hashed, as GAFFParameterize does for its own files.
36
+ """
37
+ return 'u' + hashlib.shake_128(name.encode('utf-8')).hexdigest(8).replace('e', 'x')
38
+
39
+
31
40
  def GAFFParameterize(inputPrefix, outputPrefix, input_structure_format='mol2', ambertools=None):
32
41
  """Manages execution of antechamber, parmchk2, and tleap to generate GAFF parameters,
33
42
  then converts the result to Gromacs gro/top files via parmed.
@@ -36,7 +45,9 @@ def GAFFParameterize(inputPrefix, outputPrefix, input_structure_format='mol2', a
36
45
  inputPrefix (str): basename of input structure file
37
46
  outputPrefix (str): basename of output files
38
47
  input_structure_format (str): format of input structure file, defaults to 'mol2'; 'pdb' is other option
39
- ambertools (dict | None): ambertools configuration directives, defaults to None
48
+ ambertools (dict | None): ambertools configuration directives, defaults to None; an
49
+ ``frcmod`` entry, a list of (label, text) tuples, names user frcmod files that
50
+ tleap loads after parmchk2's, so their parameters take precedence
40
51
 
41
52
  Raises:
42
53
  parmed.exceptions.GromacsError: if parmed fails to convert tleap output
@@ -65,6 +76,13 @@ def GAFFParameterize(inputPrefix, outputPrefix, input_structure_format='mol2', a
65
76
  f' -at {atomtype} -i {new_structin} -o {mol2out} -pf Y -nc {netcharge} -eq 1 -pl 10', quiet=False)
66
77
  logger.debug(f'AmberTools> Antechamber generated {mol2out}')
67
78
  run(f'parmchk2 -i {mol2out} -o {frcmodout} -f mol2 -s {atomtype}', quiet=False)
79
+ user_frcmods = []
80
+ for label, text in ambertools.get('frcmod') or []:
81
+ fn = f'{leapsafe(label)}-user.frcmod'
82
+ with open(fn, 'w') as f:
83
+ f.write(text)
84
+ user_frcmods.append(fn)
85
+ logger.info(f'AmberTools> loading user frcmod for {label} into {outputPrefix}')
68
86
 
69
87
  # Antechamber ignores SUBSTRUCTURE records, so patch the antechamber output
70
88
  # mol2 with the original resName/resNum before passing it to tleap.
@@ -92,6 +110,8 @@ def GAFFParameterize(inputPrefix, outputPrefix, input_structure_format='mol2', a
92
110
  # fires, and we abort even though tleap would have completed once
93
111
  # the frcmod was loaded.
94
112
  f'loadamberparams {leapprefix}.frcmod',
113
+ # user files last, so they override both GAFF and parmchk2's guesses
114
+ *[f'loadamberparams {fn}' for fn in user_frcmods],
95
115
  f'mymol = loadmol2 {leapprefix}.mol2',
96
116
  'check mymol',
97
117
  f'saveamberparm mymol {leapprefix}-tleap.top {leapprefix}-tleap.crd',
@@ -102,6 +122,8 @@ def GAFFParameterize(inputPrefix, outputPrefix, input_structure_format='mol2', a
102
122
  run(f'tleap -f {inputPrefix}-tleap.in', override=('Error!', 'Unspecified tleap error'))
103
123
 
104
124
  os.remove(f'{leapprefix}.frcmod')
125
+ for fn in user_frcmods:
126
+ os.remove(fn)
105
127
  shutil.move(f'{leapprefix}.mol2', mol2out)
106
128
  shutil.move(f'{leapprefix}-tleap.top', f'{outputPrefix}-tleap.top')
107
129
  shutil.move(f'{leapprefix}-tleap.crd', f'{outputPrefix}-tleap.crd')
@@ -192,6 +192,18 @@ attributes:
192
192
  - name: symmetry_equivalent_atoms
193
193
  type: list
194
194
  text: Sets of symmetry-equivalent atom names, if any.
195
+ - name: frcmod
196
+ type: str
197
+ required: false
198
+ text: >
199
+ Path, relative to the configuration file, to an Amber frcmod file of
200
+ parameter overrides for this molecule. tleap loads it after GAFF and
201
+ parmchk2, so its entries win. It is loaded for this molecule and for
202
+ every template containing it, and it is part of each parameterization's
203
+ cache record, so editing the file re-parameterizes them. A system
204
+ keeps one table per bonded type, so an overridden type must not also
205
+ occur, unoverridden, in a molecule without this residue; setup stops if
206
+ it does.
195
207
  - name: conformers
196
208
  type: dict
197
209
  required: false
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.9.0
3
+ Version: 2.10.0
4
4
  Summary: Automated MD System Builder for Amorphous Network Polymers
5
5
  Project-URL: Source, https://github.com/cameronabrams/htpolynet
6
6
  Project-URL: Documentation, https://htpolynet.readthedocs.io/
@@ -10,18 +10,18 @@ htpolynet/core/bondtemplate.py,sha256=_1vYMugonDuogysu15IsbpthvxYb6uJKC5ao7pQcWv
10
10
  htpolynet/core/configuration.py,sha256=RKnsVz_SX7GrCxuL-1rXP9AQ23EcFyiQSYeLiG6CHc4,5191
11
11
  htpolynet/core/coordinates.py,sha256=CGTHkdfw2ikc2ANacA5akRhZ9tOyM2IbELwQ2FVcKRw,23878
12
12
  htpolynet/core/molecule.py,sha256=MXTdgKXFc7JnCvFhorCaTBQNXrdhKhC9gALtBge4Ff0,52787
13
- htpolynet/core/paramcache.py,sha256=3MTG96F4vtT5w-pn1RWNmXic0QKB7WVcwCrD-BSY3B0,4508
13
+ htpolynet/core/paramcache.py,sha256=A99VVqf1SdcdzoW5tEkRnN_GEPMjnw-1yy0J-S6FzJI,5660
14
14
  htpolynet/core/projectfilesystem.py,sha256=2U_EToZxN7yUGWu9BIRABVsYdp1AKkOuManwuFBz89k,20983
15
- htpolynet/core/runtime.py,sha256=uCTc-1-4UZsr_ygHnGl54mM4n7OPkzK1plkWuEfCXbg,58575
15
+ htpolynet/core/runtime.py,sha256=DOYay4BcLab2p-Eeti45kWMozEol-8fYsYB5mZQixCY,61529
16
16
  htpolynet/core/topocoord.py,sha256=GfxOf04jAMYB6_vgj87kG9lXR0LVXwDHWetG5sv5AIA,109249
17
- htpolynet/core/topology.py,sha256=OZHb6_t52IxrVDSjCKQuvOG3xZkE1zM0Ft0rmTLgzWk,58393
17
+ htpolynet/core/topology.py,sha256=fRp3a-ILNsrjCyIuJrs7p1NYnH4Y6waKLm_CEQK7IUw,60531
18
18
  htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
19
  htpolynet/cure/chain.py,sha256=-d5BFE5xUKjFdNkxLfSnCnZIRSJCtr7xuxYzNHBeSgU,5344
20
20
  htpolynet/cure/curecontroller.py,sha256=ulj9wpXRIEH6AAUSS23ssCMYvPKiOOL748fKK0jVjJI,58056
21
21
  htpolynet/cure/expandreactions.py,sha256=LDVefyrCZI2QSqrTsrVIPYP6g_w-LiUsYZkN3lUAM74,19977
22
22
  htpolynet/cure/reaction.py,sha256=S-w60HocYknKnGbq1_uwLpKTL5Fte_o7zxwk3FbyQ1I,10557
23
23
  htpolynet/external/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
- htpolynet/external/ambertools.py,sha256=W3Ut9z7XovJcrxfgkL8eyP-Q0tKmyK1awfAcEafNxB0,5307
24
+ htpolynet/external/ambertools.py,sha256=NkZ0fP6iqwMnMk2jMD3-EaiGCmutHb1MVFOTFJiQ7WI,6286
25
25
  htpolynet/external/command.py,sha256=KYmWV8P4nuw_ciE16WazviorxjGj5un_z7dL62n0TG0,2480
26
26
  htpolynet/external/gromacs.py,sha256=KEtHA4TuHaSA_nFXoz2NyrX3JUr9a733-KkOv5BE4Lc,12848
27
27
  htpolynet/external/slurm.py,sha256=FvnKyNqFXgDe5bdTDB4Kcn9KU4mxq9Gcw675SzU-4w0,4082
@@ -87,7 +87,7 @@ htpolynet/resources/molecules/sample-inputs/STY.mol2,sha256=r1NqpovL6L7E96Kkyc6U
87
87
  htpolynet/resources/tcl/readbonds.tcl,sha256=l_bh7eMjbxVi44UMPMi32bFntZltij92KmKfXC1qDz4,972
88
88
  htpolynet/resources/tcl/readgrx.tcl,sha256=A1KvyIpFC_lwfze3XOqTCPqLIkq7HwmqJ96lZH42W0U,1731
89
89
  htpolynet/resources/tcl/render.tcl,sha256=KUszYxzWtfuL7OXdtdk8n6eAQbz8DJfKJrGbb0pOdrI,2379
90
- htpolynet/schema/base.yaml,sha256=BklXkmZfT0adlCxv9hNGvkKunUhVx4aWYoPVnl21Jkk,36222
90
+ htpolynet/schema/base.yaml,sha256=g3TzYK8iCkGkzp-2uU3358ux51n4NrsPmOLqDaZ4zf0,36879
91
91
  htpolynet/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
92
92
  htpolynet/utils/banner.py,sha256=hdw6xoHNAo9p6X33LmhW5qyb67qAaQ3hmLnct3ZuDy0,906
93
93
  htpolynet/utils/checkpoint.py,sha256=QTZIJ8K777T6o-mNpjPdelTqrpT0amLlQcgpHBiq5V0,2924
@@ -98,8 +98,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
98
98
  htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
99
99
  htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
100
100
  htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
101
- htpolynet-2.9.0.dist-info/METADATA,sha256=csJ0C3IGcPfIQYAECEMBpvWVvMAwc4Vt9-vVY7qUddg,6588
102
- htpolynet-2.9.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
103
- htpolynet-2.9.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
104
- htpolynet-2.9.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
105
- htpolynet-2.9.0.dist-info/RECORD,,
101
+ htpolynet-2.10.0.dist-info/METADATA,sha256=tnzImfyZ92r2NecCZeltVxO4wkElSF5ZCgrnQkNauMM,6589
102
+ htpolynet-2.10.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
103
+ htpolynet-2.10.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
104
+ htpolynet-2.10.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
105
+ htpolynet-2.10.0.dist-info/RECORD,,