HTPolyNet 2.7.0__py3-none-any.whl → 2.8.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.
@@ -1,16 +1,41 @@
1
1
  """Manages reading and parsing of YAML configuration files.
2
2
 
3
3
  Author: Cameron F. Abrams <cfa22@drexel.edu>
4
+
5
+ Configurations are validated against ``htpolynet/schema/base.yaml`` by
6
+ ycleptic, which also fills in every documented default. Before that, this
7
+ module read the file and ``.get()``-ed the keys it recognized, so an
8
+ unrecognized section or a misspelled key was discarded in silence -- a
9
+ ``desired_converson`` typo produced a default-value build and no message.
10
+
11
+ Keys whose *presence* changes behavior are declared ``required: false`` in the
12
+ schema so ycleptic leaves them absent rather than filling them in; see the
13
+ comments on ``densification.initial_boxsize``, ``reactive_atoms`` and
14
+ ``rename_atoms`` there.
4
15
  """
5
16
  import json
6
17
  import logging
7
18
  import os
8
19
 
20
+ from importlib.resources import as_file, files
21
+
9
22
  import yaml
10
23
 
24
+ from ycleptic.errors import YclepticError
25
+ from ycleptic.yclept import Yclept
26
+
11
27
  logger = logging.getLogger(__name__)
12
28
 
13
29
 
30
+ def schema_path():
31
+ """Context manager yielding a real path to the packaged base config.
32
+
33
+ Returns:
34
+ contextlib.AbstractContextManager: yields a pathlib.Path to base.yaml
35
+ """
36
+ return as_file(files('htpolynet').joinpath('schema/base.yaml'))
37
+
38
+
14
39
  class Configuration:
15
40
  """Pure data container for a build configuration file.
16
41
 
@@ -54,16 +79,44 @@ class Configuration:
54
79
  inst = cls()
55
80
  inst.cfgfile = filename
56
81
  if ext == '.json':
82
+ # ycleptic reads YAML; round-trip JSON through a temporary file so
83
+ # both formats get the same validation rather than only one
57
84
  with open(filename, 'r') as f:
58
- inst.basedict = json.load(f)
85
+ raw = json.load(f)
86
+ inst.basedict = inst._validate(raw)
59
87
  elif ext in ('.yaml', '.yml'):
60
88
  with open(filename, 'r') as f:
61
- inst.basedict = yaml.safe_load(f)
89
+ raw = yaml.safe_load(f)
90
+ inst.basedict = inst._validate(raw)
62
91
  else:
63
92
  raise Exception(f'Unknown config file extension {ext}')
64
93
  inst._parse()
65
94
  return inst
66
95
 
96
+ def _validate(self, raw):
97
+ """Validates a raw config against the packaged schema and fills defaults.
98
+
99
+ Args:
100
+ raw (dict): the configuration as read from disk
101
+
102
+ Raises:
103
+ Exception: with ycleptic's message, if the configuration is invalid
104
+
105
+ Returns:
106
+ dict: the validated configuration, with defaults filled in
107
+ """
108
+ import tempfile
109
+ with schema_path() as base:
110
+ with tempfile.TemporaryDirectory() as td:
111
+ userfile = os.path.join(td, 'user.yaml')
112
+ with open(userfile, 'w') as f:
113
+ yaml.dump(raw, f, default_flow_style=False, sort_keys=False)
114
+ try:
115
+ y = Yclept(basefile=str(base), userfile=userfile)
116
+ except YclepticError as e:
117
+ raise Exception(f'{self.cfgfile}: {e}') from None
118
+ return y['user']
119
+
67
120
  def _parse(self):
68
121
  """Populates named attributes from self.basedict."""
69
122
  self.title = self.basedict.get('Title', 'No title provided')
@@ -18,6 +18,7 @@ from ..core import projectfilesystem as pfs
18
18
  from ..core.bondtemplate import BondTemplate, ReactionBond
19
19
  from ..core.coordinates import Coordinates
20
20
  from ..core.topology import Topology
21
+ from ..utils.convergence import series_converged
21
22
  from ..external.gromacs import grompp_and_mdrun,mdp_get, mdp_modify, gmx_energy_trace
22
23
  from ..geometry.matrix4 import Matrix4
23
24
  from ..io.gro import GRX_ATTRIBUTES, GRX_GLOBALLY_UNIQUE, GRX_UNSET_DEFAULTS
@@ -1794,21 +1795,106 @@ class TopoCoord:
1794
1795
  logger.info(f'Running Gromacs: {msg}')
1795
1796
  self.grompp_and_mdrun(out=f'{deffnm}-{ens}',mdp=new_mdp,quiet=False,**gromacs_dict)
1796
1797
  edr_list=[f'{deffnm}-{ens}']
1798
+ density=None
1797
1799
  if ens=='npt':
1798
- box=self.Coordinates.box.diagonal()
1799
- logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1800
- gmx_energy_trace(f'{deffnm}-{ens}',['Density'],report_averages=True,**gromacs_dict)
1800
+ self._log_box()
1801
+ density=self._density_series(f'{deffnm}-{ens}',gromacs_dict)
1801
1802
  for rep in range(repeat):
1802
1803
  logger.info(f'Repeat {rep+1} out of {repeat}')
1803
1804
  this_deffnm=f'{deffnm}-repeat-{rep+1}-{ens}'
1804
1805
  self.grompp_and_mdrun(out=this_deffnm,mdp=new_mdp,quiet=False,**gromacs_dict)
1805
1806
  edr_list.append(this_deffnm)
1806
1807
  if ens=='npt':
1807
- box=self.Coordinates.box.diagonal()
1808
- logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1809
- gmx_energy_trace(this_deffnm,['Density'],report_averages=True,**gromacs_dict)
1808
+ self._log_box()
1809
+ density=self._density_series(this_deffnm,gromacs_dict)
1810
+ converge=edict.get('converge',{}) or {}
1811
+ if converge and ens=='npt':
1812
+ edr_list+=self._converge_density(deffnm,new_mdp,converge,density,gromacs_dict)
1813
+ elif converge:
1814
+ logger.warning(f'ignoring "converge" on a {ens} stage; density convergence needs npt')
1810
1815
  return edr_list
1811
1816
 
1817
+ def _log_box(self):
1818
+ """Logs the current box side lengths."""
1819
+ box=self.Coordinates.box.diagonal()
1820
+ logger.info(f'Current box side lengths: {box[0]:.3f} nm x {box[1]:.3f} nm x {box[2]:.3f} nm')
1821
+
1822
+ def _density_series(self,edr_pfx,gromacs_dict={}):
1823
+ """Density trace from one edr, as a plain array, or None.
1824
+
1825
+ Args:
1826
+ edr_pfx (str): edr basename, without the '.edr' extension
1827
+ gromacs_dict (dict): gromacs directives passed through to gmx energy
1828
+
1829
+ Returns:
1830
+ numpy.ndarray: the Density column in kg/m^3, or None if unavailable
1831
+ """
1832
+ try:
1833
+ df=gmx_energy_trace(edr_pfx,['Density'],report_averages=True,**gromacs_dict)
1834
+ except Exception as e:
1835
+ logger.debug(f'no density available from {edr_pfx}: {e}')
1836
+ return None
1837
+ if df.empty or 'Density' not in df.columns: return None
1838
+ return df['Density'].to_numpy(dtype=float)
1839
+
1840
+ def _converge_density(self,deffnm,mdp,converge,density,gromacs_dict={}):
1841
+ """Repeats an NPT stage until its density settles, or until a ceiling.
1842
+
1843
+ This is the fixed-``repeat`` mechanism with a measured stopping rule
1844
+ instead of a counted one. Densification is the right place for it:
1845
+ the 200 -> ~1100 kg/m^3 compaction is one-shot, involves a large volume
1846
+ change, and otherwise runs for however many steps someone guessed.
1847
+
1848
+ Each extension is a fresh ``mdrun``, so velocities are regenerated
1849
+ between segments exactly as ``repeat`` already does; the criterion is
1850
+ therefore applied to the *last* segment rather than to a concatenation
1851
+ of segments that do not share a velocity history.
1852
+
1853
+ A build that never settles says so, loudly, rather than silently
1854
+ reporting whatever density it reached.
1855
+
1856
+ Args:
1857
+ deffnm (str): output file basename of the stage being extended
1858
+ mdp (str): name of the mdp file to rerun
1859
+ converge (dict): 'tolerance' (kg/m^3), 'max_repeats', 'min_samples', 'drift_sems'
1860
+ density (numpy.ndarray): density trace of the stage just run, or None
1861
+ gromacs_dict (dict): gromacs directives
1862
+
1863
+ Returns:
1864
+ list: edr basenames of any extension segments run
1865
+ """
1866
+ tol=float(converge.get('tolerance',1.0))
1867
+ ceiling=int(converge.get('max_repeats',10))
1868
+ min_samples=int(converge.get('min_samples',50))
1869
+ drift_sems=float(converge.get('drift_sems',2.0))
1870
+ extra=[]
1871
+ for attempt in range(ceiling+1):
1872
+ if density is None:
1873
+ logger.warning('density convergence requested but no Density trace is available; not gating')
1874
+ return extra
1875
+ r=series_converged(density,tol,min_samples=min_samples,drift_sems=drift_sems)
1876
+ if r['converged']:
1877
+ logger.info(
1878
+ f'Density converged after {attempt} extension(s): '
1879
+ f'{r["mean"]:.1f} +/- {r["sem"]:.2f} kg/m^3 '
1880
+ f'(tau_int {r["tau_int"]:.0f} samples, drift {r["drift"]:+.2f})'
1881
+ )
1882
+ return extra
1883
+ if attempt==ceiling:
1884
+ logger.warning(
1885
+ f'Density did NOT converge after {ceiling} extension(s) -- {r["reason"]}. '
1886
+ f'The last window averaged {r["mean"]:.1f} kg/m^3; treat that as an '
1887
+ f'unsettled box, not as this system\'s density'
1888
+ )
1889
+ return extra
1890
+ logger.info(f'Density not settled ({r["reason"]}); extending, {attempt+1} of {ceiling}')
1891
+ this_deffnm=f'{deffnm}-converge-{attempt+1}-npt'
1892
+ self.grompp_and_mdrun(out=this_deffnm,mdp=mdp,quiet=False,**gromacs_dict)
1893
+ extra.append(this_deffnm)
1894
+ self._log_box()
1895
+ density=self._density_series(this_deffnm,gromacs_dict)
1896
+ return extra
1897
+
1812
1898
  def get_resid_sets(self,atom_pair):
1813
1899
  """Identifies individual sets of separate resids owned by unbonded atoms i and j.
1814
1900
 
@@ -121,10 +121,19 @@ _GromacsTopologyHashables_ = { # attributes/columns that should always have valu
121
121
  'dihedraltypes': ['i', 'j', 'k', 'l']
122
122
  }
123
123
 
124
+ # htpolynet writes an entire build as ONE moleculetype, on purpose: a cured
125
+ # network is a single covalently connected molecule, and leftover monomers
126
+ # ride along in the same block. The name used to default to the string
127
+ # 'None', which reads to a user like an unset field or a bug -- and users who
128
+ # hit GROMACS's "inconsistent shifts" warning under trjconv -pbc whole go
129
+ # looking at exactly this line. The name must match between [ moleculetype ]
130
+ # and [ molecules ], so both defaults change together.
131
+ _WHOLE_SYSTEM_MOLECULETYPE_ = 'whole_system'
132
+
124
133
  _GromacsTopologyDirectiveDefaults_ = {
125
134
  'system': ['A_generic_system'],
126
- 'molecules': ['None', 1],
127
- 'moleculetype': ['None', 3],
135
+ 'molecules': [_WHOLE_SYSTEM_MOLECULETYPE_, 1],
136
+ 'moleculetype': [_WHOLE_SYSTEM_MOLECULETYPE_, 3],
128
137
  'defaults': [1, 2, 'yes', 0.5, 0.83333333]
129
138
  }
130
139
 
@@ -270,7 +270,11 @@ class CureController:
270
270
  },
271
271
  'relax': {
272
272
  'nstages': 6,
273
- 'increment': 0.0,
273
+ # not 0.0: _distance_attenuation derives its stage count as
274
+ # int(maxL/increment) with no guard, so a config that omits this
275
+ # key used to raise ZeroDivisionError at the first relax. Drag
276
+ # can default to 0.0 because its own 0.0 limit disables it.
277
+ 'increment': 0.08,
274
278
  'cutoff_pad': 0.2,
275
279
  'equilibration': default_equilibration_sequence
276
280
  },
@@ -54,6 +54,9 @@ densification:
54
54
  temperature: 300.0
55
55
  pressure: 10.0
56
56
  ps: 200.0
57
+ converge:
58
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
59
+ max_repeats: 6 # hitting this is reported as a failure to converge
57
60
  precure:
58
61
  preequilibration:
59
62
  ensemble: npt
@@ -36,6 +36,9 @@ densification:
36
36
  temperature: 300
37
37
  pressure: 10
38
38
  ps: 200
39
+ converge:
40
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
41
+ max_repeats: 6 # hitting this is reported as a failure to converge
39
42
  precure:
40
43
  preequilibration:
41
44
  ensemble: npt
@@ -51,6 +51,9 @@ densification:
51
51
  pressure: 10
52
52
  ps: 100
53
53
  repeat: 8
54
+ converge:
55
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
56
+ max_repeats: 6 # hitting this is reported as a failure to converge
54
57
  precure:
55
58
  preequilibration:
56
59
  ensemble: npt
@@ -44,6 +44,9 @@ densification:
44
44
  temperature: 300
45
45
  pressure: 10
46
46
  ps: 300
47
+ converge:
48
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
49
+ max_repeats: 6 # hitting this is reported as a failure to converge
47
50
  precure:
48
51
  preequilibration:
49
52
  ensemble: npt
@@ -43,6 +43,9 @@ densification:
43
43
  temperature: 300
44
44
  pressure: 10
45
45
  ps: 300
46
+ converge:
47
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
48
+ max_repeats: 6 # hitting this is reported as a failure to converge
46
49
  precure:
47
50
  preequilibration:
48
51
  ensemble: npt
@@ -106,6 +106,9 @@ densification:
106
106
  pressure: 10
107
107
  ps: 100
108
108
  repeat: 50
109
+ converge:
110
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
111
+ max_repeats: 6 # hitting this is reported as a failure to converge
109
112
  precure:
110
113
  preequilibration:
111
114
  ensemble: npt
@@ -97,6 +97,9 @@ densification:
97
97
  pressure: 10
98
98
  ps: 100
99
99
  repeat: 4
100
+ converge:
101
+ tolerance: 1.0 # kg/m3; stop when the mean density is this well known
102
+ max_repeats: 6 # hitting this is reported as a failure to converge
100
103
  precure:
101
104
  preequilibration:
102
105
  ensemble: npt