HTPolyNet 2.6.2__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
 
@@ -21,7 +21,7 @@ from ..core.molecule import MoleculeDict
21
21
  from ..core.topocoord import TopoCoord, BTRC
22
22
  from ..cure.reaction import ReactionList
23
23
  from ..cure.reaction import reaction_stage
24
- from ..external.gromacs import gromacs_distance, mdp_modify
24
+ from ..external.gromacs import gmx_energy_trace, gromacs_distance, mdp_modify
25
25
  from ..utils import checkpoint as cp
26
26
  from ..utils.stringthings import my_logger
27
27
 
@@ -54,6 +54,82 @@ def residue_functionality(adf):
54
54
  """
55
55
  return adf.groupby('resNum')[['z','nreactions']].sum().sum(axis=1)
56
56
 
57
+ def minimum_image_displacements(before,after,box):
58
+ """Per-atom displacement magnitudes across a window, under minimum image.
59
+
60
+ Args:
61
+ before (numpy.ndarray): (N,3) positions before the window, nm
62
+ after (numpy.ndarray): (N,3) positions after the window, nm
63
+ box (numpy.ndarray): (3,3) box matrix; only its diagonal is used
64
+
65
+ Returns:
66
+ numpy.ndarray: (N,) displacement magnitudes, nm; empty if N is 0
67
+ """
68
+ b=np.asarray(before,dtype=float).reshape(-1,3)
69
+ a=np.asarray(after,dtype=float).reshape(-1,3)
70
+ assert a.shape==b.shape,f'shape mismatch {b.shape} vs {a.shape}'
71
+ d=a-b
72
+ L=np.asarray(box,dtype=float)
73
+ L=L.diagonal() if L.ndim==2 else L.reshape(-1)
74
+ # an unset box would make every displacement nan; leave the raw
75
+ # displacement alone instead, which is right for a non-periodic snapshot
76
+ if d.size and np.all(L>0):
77
+ d=d-L*np.round(d/L)
78
+ return np.sqrt((d**2).sum(axis=1))
79
+
80
+ def varshney_criterion(displacements,search_radius):
81
+ """Summarizes reactive-species mobility against the bond-search capture radius.
82
+
83
+ Varshney sized the original 40 ps relaxation window on the requirement that
84
+ unreacted reactive species diffuse far enough during it to find new
85
+ partners. That requirement decays over a cure: as those species are bonded
86
+ into the growing network they become topologically constrained rather than
87
+ merely slow, and the fixed window silently stops satisfying the criterion it
88
+ was designed against. Nothing in the build reports this, so a window that
89
+ has stopped working looks exactly like one that still works.
90
+
91
+ 'crossing_fraction' is the share of still-reactive atoms that moved at least
92
+ one capture radius during the window; it is the quantity that decays.
93
+
94
+ Args:
95
+ displacements (numpy.ndarray): per-atom displacement magnitudes, nm, from :func:`minimum_image_displacements`
96
+ search_radius (float): bond-search capture radius, nm
97
+
98
+ Returns:
99
+ dict: 'n', 'rmsd', 'mean', 'max' (nm) and 'crossing_fraction'; all but 'n' are None when there are no reactive atoms left
100
+ """
101
+ r=np.asarray(displacements,dtype=float).reshape(-1)
102
+ if r.size==0:
103
+ return {'n':0,'rmsd':None,'mean':None,'max':None,'crossing_fraction':None}
104
+ return {
105
+ 'n':int(r.size),
106
+ 'rmsd':float(np.sqrt((r**2).mean())),
107
+ 'mean':float(r.mean()),
108
+ 'max':float(r.max()),
109
+ 'crossing_fraction':float((r>=search_radius).mean())
110
+ }
111
+
112
+ def _relax_stage_density(edr_pfx):
113
+ """Mean density over one relax stage's NPT segment, or None if unavailable.
114
+
115
+ Instrumentation must never be able to fail a build, so every failure path --
116
+ a missing edr, a gmx energy that will not run, an ensemble whose menu has no
117
+ Density -- returns None, and the stage reports '--' instead.
118
+
119
+ Args:
120
+ edr_pfx (str): edr basename, without the '.edr' extension
121
+
122
+ Returns:
123
+ float: mean density in kg/m^3, or None
124
+ """
125
+ try:
126
+ df=gmx_energy_trace(edr_pfx,['Density'])
127
+ except Exception as e:
128
+ logger.debug(f'no density available from {edr_pfx}: {e}')
129
+ return None
130
+ if df.empty or 'Density' not in df.columns: return None
131
+ return float(df['Density'].mean())
132
+
57
133
  def rank_bond_candidates(bdf,reaction_counts=None):
58
134
  """Orders bond candidates ahead of the greedy one-bond-per-residue downselection.
59
135
 
@@ -194,7 +270,11 @@ class CureController:
194
270
  },
195
271
  'relax': {
196
272
  'nstages': 6,
197
- '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,
198
278
  'cutoff_pad': 0.2,
199
279
  'equilibration': default_equilibration_sequence
200
280
  },
@@ -563,6 +643,63 @@ class CureController:
563
643
  """
564
644
  return f'{self.state.step.value}-{self.state.step}'
565
645
 
646
+ def _reactive_positions(self,TC:TopoCoord):
647
+ """Snapshots the positions of every atom that still has a reactive site.
648
+
649
+ 'z' is the count of a reactive atom's unused sites, so ``z > 0`` is the
650
+ set of species still looking for a partner -- the same selector the bond
651
+ search itself uses. Bonds only form during the topology update, so this
652
+ set is constant across one relax ladder and the snapshot can be compared
653
+ atom for atom with a later one.
654
+
655
+ Args:
656
+ TC (TopoCoord): global topology and coordinates
657
+
658
+ Returns:
659
+ tuple: (globalIdx array, (N,3) position array), or None if the atom dataframe carries no 'z' attribute or nothing is still reactive
660
+ """
661
+ adf=TC.Coordinates.A
662
+ if adf is None or not all(c in adf.columns for c in ('z','globalIdx','posX','posY','posZ')): return None
663
+ sel=adf[adf['z']>0]
664
+ if sel.shape[0]==0: return None
665
+ return sel['globalIdx'].to_numpy(),sel[['posX','posY','posZ']].to_numpy(dtype=float)
666
+
667
+ def _report_reactive_mobility(self,TC:TopoCoord,pre_reactive):
668
+ """Logs Varshney's criterion across the relax window just completed.
669
+
670
+ See :func:`varshney_criterion` for why this is worth reporting. It is
671
+ pure observation: any failure is logged and swallowed, because a
672
+ diagnostic must not be able to fail a build.
673
+
674
+ Args:
675
+ TC (TopoCoord): global topology and coordinates, as left by the relax ladder
676
+ pre_reactive (tuple): the snapshot returned by :meth:`_reactive_positions` before the ladder ran
677
+ """
678
+ try:
679
+ idx,before=pre_reactive
680
+ adf=TC.Coordinates.A.set_index('globalIdx')
681
+ after=adf.loc[idx,['posX','posY','posZ']].to_numpy(dtype=float)
682
+ r=minimum_image_displacements(before,after,TC.Coordinates.box)
683
+ stats=varshney_criterion(r,self.dicts['controls']['search_radius'])
684
+ except Exception as e:
685
+ logger.debug(f'could not report reactive mobility: {e}')
686
+ return
687
+ if not stats['n']: return
688
+ rcap=self.dicts['controls']['search_radius']
689
+ logger.info(
690
+ f'Reactive-species mobility over relax: rmsd {stats["rmsd"]:.3f} nm, '
691
+ f'max {stats["max"]:.3f} nm, {stats["crossing_fraction"]*100:.0f}% of '
692
+ f'{stats["n"]} crossed the {rcap:.2f} nm search radius'
693
+ )
694
+ if stats['crossing_fraction']<0.25:
695
+ logger.warning(
696
+ f'reactive-species mobility is low: only {stats["crossing_fraction"]*100:.0f}% of '
697
+ f'still-reactive atoms moved a full search radius during relax. The '
698
+ f'relax window is no longer satisfying the criterion it was sized '
699
+ f'against, so later bonds are being chosen from a nearly frozen '
700
+ f'neighborhood'
701
+ )
702
+
566
703
  def _distance_attenuation(self,TC:TopoCoord,mode='drag',gromacs_dict={}):
567
704
  """Manages the progressive attenuation of bond parameters for new bonds.
568
705
 
@@ -591,7 +728,7 @@ class CureController:
591
728
  pmaxL,pminL,pmeanL=pdf['current_lengths'].max(),pdf['current_lengths'].min(),pdf['current_lengths'].mean()
592
729
  logger.debug(f'1-4 distances lengths avg/min/max: {pmeanL:.3f}/{pminL:.3f}/{pmaxL:.3f}')
593
730
  roptions.append(pmaxL)
594
- logger.info(' Stage Max-distance (nm) Max-1-4-distance (nm)')
731
+ logger.info(' Stage Max-distance (nm) Max-1-4-distance (nm) Density (kg/m3)')
595
732
  rcommon=max(roptions)
596
733
  for stg_dict in d['equilibration']:
597
734
  ensemble=stg_dict['ensemble']
@@ -605,6 +742,15 @@ class CureController:
605
742
  mdp_modify(f'{impfx}.mdp',mdp_mods_dict,add_if_missing=(ensemble!='min'))
606
743
  this_nstages=int(maxL/d['increment'])
607
744
  this_firststage=self.state.current_stage[mode]
745
+ # Varshney's criterion is measured across the whole relax window, so a
746
+ # build resuming mid-ladder cannot report it -- the window it would
747
+ # measure is only the tail. Skip rather than report a partial number.
748
+ pre_reactive=None
749
+ if mode=='relax':
750
+ if this_firststage==0:
751
+ pre_reactive=self._reactive_positions(TC)
752
+ else:
753
+ logger.debug(f'resuming at stage {this_firststage}; skipping the mobility report')
608
754
  logger.debug(f'{self.state.step} {this_nstages} {this_firststage}')
609
755
  saveT=TC.Topology.copy_bond_parameters(self.bonds_df)
610
756
  for i in range(this_firststage,this_nstages):
@@ -615,11 +761,17 @@ class CureController:
615
761
  TC.Topology.attenuate_bond_parameters(self.bonds_df,i,this_nstages,init_colname='initial_distance')
616
762
  stagepfx=f'{opfx}-stage-{i+1}'
617
763
  TC.write_top(f'{stagepfx}.top')
764
+ stage_density=None
618
765
  for stg_dict in d['equilibration']:
619
766
  ensemble=stg_dict['ensemble']
620
767
  impfx=f'{statename}-{ensemble}' # e.g., drag-min, drag-nvt, drag-npt
621
768
  TC.grompp_and_mdrun(out=f'{stagepfx}-{ensemble}',mdp=f'{impfx}',**gromacs_dict)
622
769
  # logger.debug(f'{TC.files["gro"]}')
770
+ # the relax stages are the only above-Tg constant-pressure time in
771
+ # a cure, and until now nothing looked at the density they produce.
772
+ # Drag runs under restraints, so its density is not comparable.
773
+ if mode=='relax' and ensemble=='npt':
774
+ stage_density=_relax_stage_density(f'{stagepfx}-npt')
623
775
  TC.Topology.restore_bond_parameters(saveT)
624
776
  TC.add_length_attribute(nbdf,attr_name='current_lengths')
625
777
  maxL,minL,meanL=nbdf['current_lengths'].max(),nbdf['current_lengths'].min(),nbdf['current_lengths'].mean()
@@ -630,10 +782,13 @@ class CureController:
630
782
  TC.add_length_attribute(pdf,attr_name='current_lengths')
631
783
  pmaxL,pminL,pmeanL=pdf['current_lengths'].max(),pdf['current_lengths'].min(),pdf['current_lengths'].mean()
632
784
  logger.debug(f'1-4 distances lengths avg/min/max: {pmeanL:.3f}/{pminL:.3f}/{pmaxL:.3f}')
633
- logger.info(f'{i+1:>10d} {maxL:>17.3f} {pmaxL:>21.3f}')
785
+ dstr='--' if stage_density is None else f'{stage_density:.1f}'
786
+ logger.info(f'{i+1:>10d} {maxL:>17.3f} {pmaxL:>21.3f} {dstr:>15}')
634
787
  self.state._to_yaml()
635
788
  if mode=='drag':
636
789
  TC.Topology.remove_restraints(self.bonds_df)
790
+ if pre_reactive is not None:
791
+ self._report_reactive_mobility(TC,pre_reactive)
637
792
  TC.write_top(f'{opfx}-complete.top')
638
793
  self._register_bonds(nbdf,pdf,f'{opfx}-{mode}-bonds.csv',bonds_are=('relaxed' if mode=='relax' else 'dragged'))
639
794
  self.state.current_stage[mode]=0
@@ -401,7 +401,8 @@ def _choose_cap_placement(o_xyz, ref_xyz, neighbors, box, oc_len=0.136,
401
401
  # ---------------------------------------------------------------------------
402
402
 
403
403
 
404
- def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, placement=None):
404
+ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, placement=None,
405
+ bond_histogram=None):
405
406
  """Summarize crosslinker completion and log it.
406
407
 
407
408
  A crosslinker survives this repair only if every one of its sites is
@@ -417,9 +418,20 @@ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, plac
417
418
  n_incomplete (int): how many of them are being dismantled
418
419
  log (bool): emit the summary message; False when there is nothing to summarize
419
420
  placement (dict): cap-placement summary from :func:`_report_placements`, merged into the result
421
+ bond_histogram (dict): how many crosslinkers carried 0, 1, ... bonds
422
+ *before* repair dismantled any of them, keyed by bond count. This
423
+ is the distribution ``n_complete`` is the top bin of, and it is the
424
+ only record of it: repair rewrites the topology, and the final
425
+ structure does not say which cap came from which ring. Without it
426
+ the independence assumption behind
427
+ ``crosslinker conversion = bond conversion ** f`` can only be
428
+ tested through its ``n_complete`` consequence. Zero-filled
429
+ through the full bond count, so the top bin is always present
430
+ and always equals ``n_complete``; that is checked here.
420
431
 
421
432
  Returns:
422
- dict: n_crosslinkers, n_complete, n_dismantled, crosslinker_conversion
433
+ dict: n_crosslinkers, n_complete, n_dismantled, crosslinker_conversion,
434
+ and prerepair_bond_counts when a histogram was supplied
423
435
  """
424
436
  n_complete = n_crosslinkers - n_incomplete
425
437
  chi = n_complete / n_crosslinkers if n_crosslinkers else 0.0
@@ -436,6 +448,24 @@ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, plac
436
448
  'n_dismantled': n_incomplete,
437
449
  'crosslinker_conversion': chi,
438
450
  }
451
+ if bond_histogram is not None:
452
+ out['prerepair_bond_counts'] = {int(k): int(v) for k, v in sorted(bond_histogram.items())}
453
+ # the histogram and the completion count are computed independently, so
454
+ # they are each other's check: the top bin IS the surviving population
455
+ binned = sum(out['prerepair_bond_counts'].values())
456
+ top = out['prerepair_bond_counts'].get(max(out['prerepair_bond_counts'], default=0), 0)
457
+ if binned != n_crosslinkers or top != n_complete:
458
+ logger.warning(
459
+ f'triazine_to_cyanate_cap: pre-repair histogram disagrees with the '
460
+ f'completion count ({binned} binned vs {n_crosslinkers} residues, '
461
+ f'{top} in the top bin vs {n_complete} complete); one of the two '
462
+ f'is wrong and the reported conversion cannot be trusted'
463
+ )
464
+ if log:
465
+ spread = ', '.join(f'{k}:{v}' for k, v in out['prerepair_bond_counts'].items())
466
+ logger.info(
467
+ f'triazine_to_cyanate_cap: pre-repair bonds per {residue_name} -- {spread}'
468
+ )
439
469
  if placement:
440
470
  out.update(placement)
441
471
  return out
@@ -472,16 +502,22 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
472
502
  cl_residues = _find_crosslinker_residues(TC, cl['residue'])
473
503
  if not cl_residues:
474
504
  logger.info(f'triazine_to_cyanate_cap: no {cl["residue"]} residues found; nothing to do')
475
- return _completion_stats(cl['residue'], 0, 0, log=False)
505
+ return _completion_stats(cl['residue'], 0, 0, log=False,
506
+ bond_histogram={n: 0 for n in range(full_bond_count + 1)})
476
507
 
477
508
  incomplete_plans = [] # list of dicts, one per incomplete triazine
478
509
  h_to_delete = set() # global H indices, batched for final deletion
510
+ # how many bonds each crosslinker carries before anything is dismantled;
511
+ # repair destroys this distribution, so it has to be counted here or not
512
+ # at all. Zero-filled so the reported shape does not depend on the box.
513
+ bond_histogram = {n: 0 for n in range(full_bond_count + 1)}
479
514
 
480
515
  for resnum, atoms_by_name in cl_residues.items():
481
516
  ring_c = [atoms_by_name[n] for n in ring_c_names]
482
517
  ring_n = [atoms_by_name[n] for n in ring_n_names]
483
518
  bonded_o = [_bonded_bridge_o(TC, c, bridge_residue, bridge_o_names) for c in ring_c]
484
519
  k = sum(1 for o in bonded_o if o is not None)
520
+ bond_histogram[k] = bond_histogram.get(k, 0) + 1
485
521
  if k >= full_bond_count:
486
522
  continue
487
523
  # plan dismantle
@@ -511,7 +547,8 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
511
547
  f'triazine_to_cyanate_cap: all {len(cl_residues)} {cl["residue"]} '
512
548
  f'residues are fully bonded; nothing to do'
513
549
  )
514
- return _completion_stats(cl['residue'], len(cl_residues), 0)
550
+ return _completion_stats(cl['residue'], len(cl_residues), 0,
551
+ bond_histogram=bond_histogram)
515
552
 
516
553
  total_caps = sum(len(p['caps']) for p in incomplete_plans)
517
554
  free_caps_planned = sum(1 for p in incomplete_plans for c in p['caps'] if c['bonded_o'] is None)
@@ -679,7 +716,8 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
679
716
  )
680
717
 
681
718
  return _completion_stats(cl['residue'], len(cl_residues), len(incomplete_plans),
682
- placement=placement_summary)
719
+ placement=placement_summary,
720
+ bond_histogram=bond_histogram)
683
721
 
684
722
 
685
723
  # ---------------------------------------------------------------------------
@@ -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
@@ -6,7 +6,8 @@ nstxout = 500
6
6
  nstvout = 0
7
7
  nstenergy = 500
8
8
  nstlog = 500
9
- constraints = all-bonds
9
+ constraints = h-bonds ; not all-bonds; see CHANGELOG 2.7.0
10
+ lincs_order = 8 ; GROMACS default 4 is marginal here
10
11
  nstlist = 10
11
12
  rlist = 1.0
12
13
  rcoulomb = 1.0
@@ -5,7 +5,8 @@ nstxout = 500
5
5
  nstvout = 0
6
6
  nstenergy = 500
7
7
  nstlog = 500
8
- constraints = all-bonds
8
+ constraints = h-bonds ; not all-bonds; see CHANGELOG 2.7.0
9
+ lincs_order = 8 ; GROMACS default 4 is marginal here
9
10
  nstlist = 10
10
11
  rlist = 1.0
11
12
  rcoulomb = 1.0