HTPolyNet 2.11.2__py3-none-any.whl → 2.11.4__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.
@@ -472,9 +472,38 @@ def resolve_user_library(pathname, default='lib'):
472
472
  return default if os.path.isdir(default) else None
473
473
 
474
474
 
475
+ def _note_if_shadowing(filename, source):
476
+ """Says so when a file of your own replaces one htpolynet ships.
477
+
478
+ Overriding a packaged file is supported and often the point. The trap is that a
479
+ copy taken from an older version keeps that version's settings, silently, for as
480
+ long as it stays on the search path -- so a setting the packaged file has since
481
+ gained never reaches the run, and nothing says which file was used.
482
+
483
+ Seen 2026-09-24: an `npt.mdp` copied from 2.6.2 and edited in one place stayed on a
484
+ study's path across four upgrades. From 2.7.0 the packaged file sets
485
+ ``lincs_order = 8``, because at ``dt = 0.002`` GROMACS' default of 4 is marginal and
486
+ was fatal on one chemistry in 7 of 7 builds. The stale copy reverted every run to
487
+ order 4, and the resulting instability was written up for weeks as a property of the
488
+ systems being built.
489
+ """
490
+ try:
491
+ if _SYSTEM_LIBRARY_ and _SYSTEM_LIBRARY_._root.joinpath(filename).exists():
492
+ logger.warning(
493
+ f'{filename} was taken from your {source} and replaces the copy '
494
+ f'htpolynet ships. That is supported -- but if it was copied from an '
495
+ f'older version it still carries that version\'s settings. Compare it '
496
+ f'against the packaged file after any upgrade.')
497
+ except Exception:
498
+ pass
499
+
500
+
475
501
  def checkout(filename, altpath=[]):
476
502
  """Copies a file to cwd; searches user library, then user cache, then system library.
477
503
 
504
+ A file found in the user library or cache shadows the packaged one, and
505
+ :func:`_note_if_shadowing` says so, because a stale copy is otherwise invisible.
506
+
478
507
  Args:
479
508
  filename (str): path relative to library root
480
509
  altpath (list): extra search directories, defaults to []
@@ -484,8 +513,10 @@ def checkout(filename, altpath=[]):
484
513
  """
485
514
  if _PFS_ and _PFS_.userlibrary and _PFS_.userlibrary.checkout(
486
515
  filename, searchpath=[_PFS_.rootPath, _PFS_.projPath], altpath=altpath):
516
+ _note_if_shadowing(filename, 'user library')
487
517
  return True
488
518
  if _USER_CACHE_.checkout(filename):
519
+ _note_if_shadowing(filename, 'user cache')
489
520
  return True
490
521
  return _SYSTEM_LIBRARY_.checkout(filename)
491
522
 
htpolynet/core/runtime.py CHANGED
@@ -14,6 +14,7 @@ from copy import deepcopy
14
14
 
15
15
  import networkx as nx
16
16
  import numpy as np
17
+ import pandas as pd
17
18
 
18
19
  from networkx.algorithms import isomorphism
19
20
 
@@ -31,7 +32,7 @@ from ..cure.reaction import (Reaction, ReactionList, parse_reaction_list, extrac
31
32
  is_reactant, is_ring_closing, reaction_stage)
32
33
  from ..core.productsplice import nearer_site_atoms
33
34
  from ..cure.ringcontroller import RingController, RingCureState
34
- from ..cure.triplesearch import reactive_sites, triple_bonds_dataframe
35
+ from ..cure.triplesearch import bonds_by_atom, reactive_sites, triple_bonds_dataframe
35
36
  from ..external import software as software
36
37
  from ..external.gromacs import insert_molecules, mdp_modify, mdp_get
37
38
  from ..external.smiles_input import materialize_smiles_inputs
@@ -694,7 +695,11 @@ class Runtime:
694
695
  adf = TC.Coordinates.A
695
696
  positions = {int(r.globalIdx): np.array([r.posX, r.posY, r.posZ])
696
697
  for r in adf.itertuples()}
697
- sites, chosen = rc.search(adf, positions, TC.Coordinates.box.diagonal(), resname, groups)
698
+ # a ring that closes around an existing bond threads that monomer through
699
+ # it for good; CURE refuses the mirror image of this and the ring cure did not
700
+ bonds_of = bonds_by_atom(TC.Topology.D['bonds'])
701
+ sites, chosen = rc.search(adf, positions, TC.Coordinates.box.diagonal(), resname,
702
+ groups, bonds_of=bonds_of)
698
703
  if not chosen:
699
704
  if rc.widen():
700
705
  break
@@ -704,12 +709,17 @@ class Runtime:
704
709
  work = rc.close_rings(TC, bdf, gromacs_dict=gromacs_dict)
705
710
  # a ring the ladder could not pull shut would be bonded long and stay that way
706
711
  bdf, chosen = rc.accept(bdf, work, chosen)
712
+ # now that the loop is nearly ring-sized, ask what it actually encloses
713
+ bdf, chosen = rc.reject_threaded(TC, bdf, chosen)
707
714
  if not chosen:
708
715
  rc.state.iter += 1
709
716
  continue
710
717
  rc.form_rings(TC, bdf, sites, chosen, template, template_resids,
711
718
  name_translations=name_translations, atom_names=arm)
712
719
  rc.relax(TC, gromacs_dict=gromacs_dict)
720
+ # the cold half of the cycle: relax ends hot and expanded, and without this
721
+ # the box only ever grows
722
+ rc.equilibrate(TC, gromacs_dict=gromacs_dict)
713
723
  rc.record(chosen)
714
724
  TC.write_gro(f'ring-{rc.state.iter}.gro')
715
725
  TC.write_top(f'ring-{rc.state.iter}.top')
@@ -718,7 +728,14 @@ class Runtime:
718
728
  rc.state.iter += 1
719
729
  pfs.go_proj()
720
730
  rc.state.to_yaml(statefile)
731
+ # the last batch of rings never sees another closure ladder, so it reaches
732
+ # postcure carrying whatever the ladder left in it
733
+ pfs.go_to(pfs.Dirs.systems_iter(rc.state.iter))
734
+ TC.grab_files()
735
+ rc.settle(TC, gromacs_dict=gromacs_dict)
736
+ pfs.go_proj()
721
737
  self._report_molecule_charges('after ring cure')
738
+ self._report_overlong_bonds('after ring cure')
722
739
  my_logger(f'Ring cure ends: {rc.state.rings} ring(s), conversion '
723
740
  f'{rc.state.conversion:.3f}', logger.info)
724
741
  return {c: os.path.basename(x) for c, x in TC.files.items() if c != 'mol2'}
@@ -839,6 +856,7 @@ class Runtime:
839
856
  if dropped:
840
857
  logger.info(f'Pruned {dropped} stale [ pairs ] entries left over from cure-induced path shortening')
841
858
  self._report_molecule_charges(f'in {result_name}')
859
+ self._report_overlong_bonds(f'in {result_name}')
842
860
  TC.write_grx_attributes(f'{result_name}.grx')
843
861
  TC.write_gro(f'{result_name}.gro')
844
862
  TC.write_top(f'{result_name}.top')
@@ -877,6 +895,62 @@ class Runtime:
877
895
  f'moved between molecules, which parameterization does not intend.')
878
896
  return charged
879
897
 
898
+ def _report_overlong_bonds(self, when, limit=0.2, show=5):
899
+ """Logs any bond too long to be a bond in the structure being handed on.
900
+
901
+ A crosslinked network can finish a build carrying a bond stretched far past what
902
+ chemistry allows, and nothing else reports it: the topology is valid, every
903
+ molecule is neutral, and the run completes. htpolynet-study measured a C-C at
904
+ 3.20 A in two of five *final* structures, unchanged to two decimals by a 160 ps
905
+ anneal -- a monomer held stretched by network tension from a ring closure it was
906
+ not part of. Ring bonds themselves always relaxed; these did not. Anything
907
+ computed from such a structure inherits it, so it should at least be said out
908
+ loud. See ROADMAP.md for the mechanism and why there is no fix yet.
909
+
910
+ Lengths use the minimum-image convention, so a bond spanning a periodic boundary
911
+ is measured across the boundary rather than counted as long.
912
+
913
+ Args:
914
+ when (str): stage label for the message, e.g. 'in final'
915
+ limit (float): longest credible bond, in nm. The longest ordinary single
916
+ bond between light elements is C-S at about 0.182 nm, so 0.2 is
917
+ generous: this is meant to catch a bond that is not a bond any more,
918
+ not to police a strained one.
919
+ show (int): how many of the worst to name individually
920
+
921
+ Returns:
922
+ pandas.DataFrame: the offending bonds, longest first
923
+ """
924
+ TC = self.TopoCoord
925
+ D = getattr(getattr(TC, 'Topology', None), 'D', None) or {}
926
+ bonds = D.get('bonds')
927
+ if bonds is None or bonds.empty:
928
+ return pd.DataFrame()
929
+ work = bonds[['ai', 'aj']].copy()
930
+ TC.add_length_attribute(work, attr_name='length')
931
+ long = work[work['length'] > limit].sort_values('length', ascending=False)
932
+ if long.empty:
933
+ logger.info(f'Bond lengths {when}: no bond among {work.shape[0]} exceeds {limit} nm')
934
+ return long
935
+ A = TC.Coordinates.A.set_index('globalIdx')
936
+
937
+ def label(i):
938
+ try:
939
+ r = A.loc[int(i)]
940
+ return f'{r.atomName}({int(i)}) of {r.resName}{int(r.resNum)}'
941
+ except Exception:
942
+ return str(int(i))
943
+
944
+ ess = '' if long.shape[0] == 1 else 's'
945
+ worst = '; '.join(f'{label(r.ai)}-{label(r.aj)} at {r.length * 10:.2f} A'
946
+ for r in long.head(show).itertuples())
947
+ logger.warning(f'Bond lengths {when}: {long.shape[0]} bond{ess} of {work.shape[0]} exceed '
948
+ f'{limit} nm, which is longer than any real bond between these elements. '
949
+ f'Worst: {worst}. A bond this long survives minimization and annealing -- '
950
+ f'it is held by the surrounding network, not by thermal motion -- and every '
951
+ f'property computed from this structure carries it. See ROADMAP.md.')
952
+ return long
953
+
880
954
  def _write_vmd_viz_files(self, result_name='final'):
881
955
  """Writes a PSF (real bond topology for VMD) and a TCL helper that
882
956
  trims bonds spanning periodic boundaries so VMD doesn't render the
@@ -19,13 +19,16 @@ What one iteration does:
19
19
  Author: Cameron F. Abrams <cfa22@drexel.edu>
20
20
  """
21
21
  import logging
22
+ import os
22
23
 
23
24
  import numpy as np
24
25
  import yaml
25
26
 
27
+ from ..analysis.plot import trace
26
28
  from ..core import projectfilesystem as pfs
27
29
  from ..core.productsplice import map_product_from_template
28
- from ..cure.triplesearch import (candidate_triples, reactive_sites, residue_map,
30
+ from ..cure.triplesearch import (bonds_by_atom, candidate_triples, drop_threaded,
31
+ reactive_sites, residue_map, ring_threading_bonds,
29
32
  select_disjoint, site_name_maps)
30
33
  from ..external.gromacs import mdp_modify
31
34
  from ..repair.topology_surgery import neutralize_touched_fragments
@@ -33,6 +36,21 @@ from ..repair.topology_surgery import neutralize_touched_fragments
33
36
  logger = logging.getLogger(__name__)
34
37
 
35
38
 
39
+ def _ring_atoms(bdf, triple):
40
+ """The six atoms of one formed ring, in cyclic order.
41
+
42
+ ``triple_bonds_dataframe`` writes a triple's three new bonds in the cycle order
43
+ ``candidate_triples`` chose -- (a,b), (b,c), (c,a) -- as (donor of the first group,
44
+ acceptor of the second). Each group's own donor and acceptor are already bonded to
45
+ each other, so reading the rows out as ai, aj, ai, aj, ai, aj walks the ring.
46
+ """
47
+ rows = bdf[bdf['triple'] == triple]
48
+ ring = []
49
+ for r in rows.itertuples():
50
+ ring.extend((int(r.ai), int(r.aj)))
51
+ return ring
52
+
53
+
36
54
  def _triple_key(donors):
37
55
  """A ring's identity, in terms that survive from one iteration to the next.
38
56
 
@@ -92,10 +110,17 @@ class RingController:
92
110
  'desired_conversion': 0.95,
93
111
  'max_rings_per_iteration': 0,
94
112
  'min_rings_per_iteration': 4,
113
+ 'reject_threaded_rings': True,
114
+ 'prefilter_threaded_candidates': False,
95
115
  'same_molecule': False,
96
116
  'same_residue': False,
97
117
  'relax': [{'ensemble': 'min'},
98
- {'ensemble': 'nvt', 'temperature': 300, 'nsteps': 2000}],
118
+ {'ensemble': 'nvt', 'temperature': 600, 'nsteps': 1000},
119
+ {'ensemble': 'npt', 'temperature': 600, 'pressure': 1, 'nsteps': 2000}],
120
+ 'settle': [{'ensemble': 'min'},
121
+ {'ensemble': 'nvt', 'temperature': 300, 'nsteps': 2500}],
122
+ 'equilibrate': {'ensemble': 'npt', 'temperature': 300, 'pressure': 1,
123
+ 'nsteps': 50000, 'repeat': 0},
99
124
  'closure': {'nstages': 8, 'target': 0.15, 'kb': 300000.0, 'max_accept': 0.30,
100
125
  'equilibration': [{'ensemble': 'min'},
101
126
  {'ensemble': 'nvt', 'temperature': 600, 'nsteps': 1000}]},
@@ -169,7 +194,7 @@ class RingController:
169
194
  floor = min(floor, int(self.dicts['max_rings_per_iteration']))
170
195
  return max(1, floor)
171
196
 
172
- def search(self, adf, positions, box, resname, groups):
197
+ def search(self, adf, positions, box, resname, groups, bonds_of=None):
173
198
  """Finds and packs this iteration's rings, widening the radius until it has enough.
174
199
 
175
200
  Args:
@@ -178,6 +203,8 @@ class RingController:
178
203
  box (array-like): box diagonal
179
204
  resname (str): residue carrying the reactive groups
180
205
  groups (iterable): (donor, acceptor) atom-name pairs
206
+ bonds_of (dict): atom -> the bonds it belongs to, for threading rejection;
207
+ omit it to skip that check
181
208
 
182
209
  Returns:
183
210
  tuple: (sites, chosen) -- the groups considered and the rings accepted
@@ -188,10 +215,22 @@ class RingController:
188
215
  cands = candidate_triples(sites, positions, self.radius, box,
189
216
  same_molecule=self.dicts['same_molecule'],
190
217
  same_residue=self.dicts['same_residue'])
218
+ if self.dicts['prefilter_threaded_candidates'] and bonds_of:
219
+ cands, threaded = drop_threaded(cands, sites, positions, bonds_of, box)
220
+ if threaded:
221
+ logger.info(f'Iteration {self.state.iter}: rejected {threaded} '
222
+ f'candidate ring(s) that would close around an existing '
223
+ f'bond')
191
224
  allowed = self._drop_declined(cands, sites)
192
225
  chosen = select_disjoint(allowed, max_triples=self.dicts['max_rings_per_iteration'])
193
226
  passed = len(cands) - len(allowed)
194
- logger.info(f'Iteration {self.state.iter}: {len(sites)} unreacted group(s), '
227
+ # concentration, not count, is what decides whether a fixed radius finds
228
+ # enough candidates -- log it or the widening looks arbitrary in a cure
229
+ # whose box is moving
230
+ volume = float(np.prod(np.asarray(box, dtype=float)))
231
+ conc = len(sites) / volume if volume > 0 else float('nan')
232
+ logger.info(f'Iteration {self.state.iter}: {len(sites)} unreacted group(s) '
233
+ f'({conc:.4f} per nm^3), '
195
234
  f'{len(cands)} candidate ring(s) within {self.radius:.3f} nm'
196
235
  + (f' ({passed} passed over as already failed)' if passed else '')
197
236
  + f', {len(chosen)} accepted')
@@ -320,19 +359,92 @@ class RingController:
320
359
  f'{worst[n]:.3f} nm from closing (limit {limit:.3f} nm); its '
321
360
  f'groups stay unreacted, and this combination waits until '
322
361
  f'nothing untried is in reach')
362
+ return self._keep_rings(bdf, chosen, keep)
363
+
364
+ def _keep_rings(self, bdf, chosen, keep):
365
+ """Reduces a bond table and its ring list to `keep`, renumbered contiguously.
366
+
367
+ ``form_rings`` zips its residue and name maps against the triple column, so a
368
+ gap would silently misalign them.
369
+ """
370
+ if len(keep) == len(chosen):
371
+ return bdf, chosen
323
372
  renumber = {old: new for new, old in enumerate(keep)}
324
373
  bdf = bdf[bdf['triple'].isin(keep)].copy()
325
374
  bdf['triple'] = [renumber[t] for t in bdf['triple']]
326
375
  return bdf.reset_index(drop=True), [chosen[n] for n in keep]
327
376
 
377
+ def reject_threaded(self, TC, bdf, chosen):
378
+ """Drops a ring that has an existing bond through it, at the geometry it will
379
+ actually be formed at.
380
+
381
+ This is the authoritative threading test, and it runs here rather than at
382
+ candidate time because here the question is unambiguous: the ladder has pulled
383
+ the loop down to nearly its final size, so what is inside it now is what the
384
+ triazine will enclose.
385
+
386
+ The candidate-time screen surveys a much larger region. A formed triazine has a
387
+ circumscribed radius of about 1.37 A, near enough rigid across 233 of them, while
388
+ a candidate loop is three groups a search radius apart -- nine times the enclosed
389
+ area at a 1.0 nm radius and over twenty at 1.6 nm, which is where a cure spends
390
+ its late iterations. Threading would be preserved through the shrink if nothing
391
+ moved, but the ladder runs six stages of NVT at 600 K and bonds move while the
392
+ loop contracts, so a bond inside the candidate loop need not still be inside at
393
+ closure. Hence a cheap screen there, off by default, and the real test here.
394
+
395
+ Args:
396
+ TC (TopoCoord): the system
397
+ bdf (pandas.DataFrame): this iteration's bonds, three rows per ring
398
+ chosen (list): the rings that survived the closure ladder
399
+
400
+ Returns:
401
+ tuple: (bdf, chosen) keeping only the rings nothing is threaded through
402
+ """
403
+ if not self.dicts['reject_threaded_rings'] or not chosen:
404
+ return bdf, chosen
405
+ A = TC.Coordinates.A
406
+ positions = {int(r.globalIdx): np.array([r.posX, r.posY, r.posZ])
407
+ for r in A.itertuples()}
408
+ bonds_of = bonds_by_atom(TC.Topology.D['bonds'])
409
+ box = TC.Coordinates.box.diagonal()
410
+ keep = []
411
+ for n in range(len(chosen)):
412
+ ring = _ring_atoms(bdf, n)
413
+ threading = ring_threading_bonds(ring, positions, bonds_of, box)
414
+ if threading:
415
+ ai, aj = threading[0]
416
+ logger.info(f'Iteration {self.state.iter}: declining a ring that would '
417
+ f'close around bond {ai}-{aj}; threading it would trap that '
418
+ f'monomer for good, since escaping needs a bond to break')
419
+ continue
420
+ keep.append(n)
421
+ return self._keep_rings(bdf, chosen, keep)
422
+
328
423
  def relax(self, TC, gromacs_dict=None):
329
- """Eases a freshly closed ring's bonds in before anything else runs.
424
+ """Eases a freshly closed ring's bonds in, and lets the box respond.
330
425
 
331
426
  A ring bond is formed at whatever length the closure ladder reached, a good way
332
427
  short of the 1.34 A it wants, so the system is strained the moment the bonds
333
428
  exist. CURE relaxes its new bonds for the same reason; without it here, the
334
429
  strain is still there when postcure MD starts, and that run dies.
335
430
 
431
+ These stages mirror CURE's ``relax.equilibration`` exactly, and the whole
432
+ sequence is above Tg rather than only its last stage. The NVT ran at 300 K
433
+ until 2.11.4, which cooled the network between the closure ladder at 600 K and
434
+ the next ladder at 600 K, and would have handed the barostat a configuration
435
+ equilibrated cold -- a good way to measure no densification and conclude the
436
+ constant-pressure stage does not work.
437
+
438
+ The last stage is constant-pressure, and above Tg, because a cure that never
439
+ runs NPT cannot densify. Before this, every ring-cure stage was NVT: measured
440
+ over 22 iterations of a 233-triazine build the box stayed at 5.241 nm to four
441
+ decimals and the density at 1155.9 kg/m3 from first ring to last, with the
442
+ entire volume change deferred to a single postcure NPT. CURE's density climbs
443
+ through its cure, from about 1085 to 1170. Cure shrinkage -- 0.0324 ml/g for
444
+ BADCy by Snow -- cannot be reproduced at constant volume by construction, and a
445
+ network formed in a box that cannot respond builds up internal stress with
446
+ nowhere to put it.
447
+
336
448
  Args:
337
449
  TC (TopoCoord): the system
338
450
  gromacs_dict (dict): gromacs directives
@@ -341,6 +453,96 @@ class RingController:
341
453
  gromacs_dict or {})
342
454
  logger.info(f'Iteration {self.state.iter}: new ring bonds relaxed')
343
455
 
456
+ def equilibrate(self, TC, gromacs_dict=None):
457
+ """Equilibrates the system at the end of an iteration, as CURE does.
458
+
459
+ Identical in shape and in defaults to ``CURE.equilibrate``: NPT at 300 K and
460
+ 1 bar for 50000 steps of 2 fs, once per iteration, after :meth:`relax`. It runs
461
+ through the same :meth:`TopoCoord.equilibrate` that the pairwise cure uses, so
462
+ it picks up the plain ``npt.mdp`` with its constraints and 2 fs step, the box
463
+ log, and the density series, rather than reimplementing any of that.
464
+
465
+ This is the stage that makes the box *cycle*. :meth:`relax` ends hot and
466
+ constant-pressure, which expands; without something cold to pull it back the box
467
+ only ever grows. Measured with `relax` alone and no equilibration, a ring cure's
468
+ box expands thermally for six iterations to +28% in volume and then comes back
469
+ down as the network forms, the two legs nearly cancelling: path 0.4104 nm for a
470
+ net of -0.0038 nm. A cure is not just shrinkage -- the hot stages enlarge the
471
+ box and the cold stage pulls it back -- which is why path length rather than net
472
+ is the statistic to look at, and why the surrogate route travels three to nine
473
+ times further in box length than it ends up moving.
474
+
475
+ Running hot without this stage is not a disaster; it reaches the same
476
+ conversion. It is untrustworthy, because 2 ps at 600 K does not equilibrate, so
477
+ what the box does mixes network formation with thermal relaxation that has not
478
+ finished. It also costs iterations: ``search_radius`` is an absolute length and
479
+ does not scale with the box, so an expanded box encloses fewer groups per sphere
480
+ and a triple is harder to find -- 25 iterations against 22 for the same
481
+ conversion.
482
+
483
+ It is also the expensive stage, about 99 s against a 280 s iteration, so it is
484
+ the first place to look when a ring cure is too slow. Whether 100 ps is the
485
+ right number for either route has never been measured; see ROADMAP.md.
486
+
487
+ Args:
488
+ TC (TopoCoord): the system
489
+ gromacs_dict (dict): gromacs directives
490
+
491
+ Returns:
492
+ list: the edr basenames produced, empty if equilibration is disabled
493
+ """
494
+ d = self.dicts['equilibrate']
495
+ if not d:
496
+ return []
497
+ edr_list = TC.equilibrate(deffnm=f'ringequil-{self.state.iter}', edict=d,
498
+ gromacs_dict=gromacs_dict or {}) or []
499
+ if d.get('ensemble') == 'npt' and edr_list:
500
+ trace('Density', edr_list,
501
+ outfile=os.path.join(pfs.proj(),
502
+ f'plots/ring-iter-{self.state.iter}-density.png'),
503
+ yunits=r'kg/m$^3$')
504
+ logger.info(f'Iteration {self.state.iter}: equilibrated')
505
+ return edr_list
506
+
507
+ def settle(self, TC, gromacs_dict=None):
508
+ """Relaxes the network one last time before the cure hands it on.
509
+
510
+ Every batch of rings but the last is relaxed twice: once by :meth:`relax` as
511
+ soon as its bonds exist, and again -- much harder -- by the next iteration's
512
+ closure ladder, which is eight minimizations and 16 ps at 600 K against relax's
513
+ one minimization and 4 ps at 300 K. The final batch only ever gets the first,
514
+ and whatever the cure ends on goes straight into postcure.
515
+
516
+ Measured by htpolynet-study on three 2.11.1 builds, all of which ended on a
517
+ ring-forming iteration, so all of which had been relaxed: bond energy entering
518
+ the anneal tracked how many rings that last iteration formed -- 1, 1 and 4 rings
519
+ for 18849, 26113 and 35959 kJ/mol, against 13619 +/- 226 for a route that enters
520
+ already relaxed. An inventory of one such structure found five bonds beyond
521
+ 2.0 A: one triazine's three ring bonds at 2.24 A, and two monomers whose own
522
+ backbones the ladder had stretched to 2.34 and 3.20 A while pulling their two
523
+ arms toward different rings. Nothing after the restraints come off relieves
524
+ either, and the strain then has to be absorbed by a 500 K anneal, which is where
525
+ 11 of 20 builds died.
526
+
527
+ Unconditional on purpose. The cure has four ways to end -- target reached,
528
+ iterations exhausted, radius exhausted, every ring declined -- and which of them
529
+ leaves strain behind is not worth reasoning about per exit when the remedy is
530
+ this cheap.
531
+
532
+ Args:
533
+ TC (TopoCoord): the system
534
+ gromacs_dict (dict): gromacs directives
535
+ """
536
+ stages = self.dicts['settle']
537
+ if not stages:
538
+ return False
539
+ TC.write_top(f'ringsettle-{self.state.iter}.top')
540
+ TC.write_gro(f'ringsettle-{self.state.iter}.gro')
541
+ self._run_stages(TC, f'ringsettle-{self.state.iter}', stages, gromacs_dict or {})
542
+ logger.info(f'Ring cure settled after {self.state.rings} ring(s); the network is '
543
+ f'relaxed before postcure rather than at 500 K')
544
+ return True
545
+
344
546
  def _run_stages(self, TC, deffnm, stages, gromacs_dict):
345
547
  """Runs one equilibration sequence, as the cure's ladders do."""
346
548
  for stage in stages:
@@ -348,9 +550,12 @@ class RingController:
348
550
  mdp = f'relax-{ensemble}' if ensemble != 'min' else 'relax-min'
349
551
  pfs.checkout(pfs.Dirs.mdp_file(mdp))
350
552
  if ensemble != 'min':
351
- mdp_modify(f'{mdp}.mdp', {'ref_t': stage.get('temperature', 300),
352
- 'gen-temp': stage.get('temperature', 300),
353
- 'gen-vel': 'yes', 'nsteps': stage.get('nsteps', 1000)})
553
+ mods = {'ref_t': stage.get('temperature', 300),
554
+ 'gen-temp': stage.get('temperature', 300),
555
+ 'gen-vel': 'yes', 'nsteps': stage.get('nsteps', 1000)}
556
+ if ensemble == 'npt':
557
+ mods['ref_p'] = stage.get('pressure', 1)
558
+ mdp_modify(f'{mdp}.mdp', mods)
354
559
  TC.grompp_and_mdrun(out=f'{deffnm}-{ensemble}', mdp=mdp, **gromacs_dict)
355
560
 
356
561
  def form_rings(self, TC, bdf, sites, chosen, template, template_resids, name_translations=None,
@@ -155,6 +155,140 @@ def candidate_triples(sites, positions, radius, box, same_molecule=False, same_r
155
155
  return out
156
156
 
157
157
 
158
+ def _segment_pierces_triangle(p0, p1, a, b, c, eps=1e-12):
159
+ """Moller-Trumbore, restricted to a segment rather than an infinite ray."""
160
+ e1, e2, d = b - a, c - a, p1 - p0
161
+ h = np.cross(d, e2)
162
+ det = float(np.dot(e1, h))
163
+ if abs(det) < eps:
164
+ return False
165
+ inv = 1.0 / det
166
+ s = p0 - a
167
+ u = inv * float(np.dot(s, h))
168
+ if u < 0.0 or u > 1.0:
169
+ return False
170
+ q = np.cross(s, e1)
171
+ v = inv * float(np.dot(d, q))
172
+ if v < 0.0 or u + v > 1.0:
173
+ return False
174
+ t = inv * float(np.dot(e2, q))
175
+ return 0.0 < t < 1.0
176
+
177
+
178
+ def ring_threading_bonds(ring, positions, bonds_of, box, margin=0.3):
179
+ """Existing bonds that pass through the loop a candidate ring would close.
180
+
181
+ The loop is triangulated as a fan from its centroid rather than treated as a plane,
182
+ because at candidate time it is not a triazine yet -- it is three reactive groups up
183
+ to a search radius apart, and markedly non-planar.
184
+
185
+ Testing it at this size is the right thing to do even though the ring ends up much
186
+ smaller. Threading is topological: the closure ladder shrinks the loop continuously,
187
+ so a bond inside it stays inside and a bond outside cannot get in. The test is
188
+ therefore asking the question at the moment the trap would be set.
189
+
190
+ Args:
191
+ ring (list): the six atoms of the prospective ring, in cyclic order
192
+ positions (dict): global atom index -> position, in nm
193
+ bonds_of (dict): global atom index -> list of (ai, aj) bonds it belongs to
194
+ box (array-like): box diagonal, in nm
195
+ margin (float): how far beyond the loop's own radius to look for bonds, in nm.
196
+ Bonds are gathered by endpoint, so this has to exceed the longest bond in
197
+ the system or one could cross the loop with both ends outside the search.
198
+ 0.3 nm is generous: the longest real bond here is about 0.18 nm, and even
199
+ the pathological stretched ones top out near 0.32 nm
200
+
201
+ Returns:
202
+ list: the (ai, aj) bonds found threading it
203
+ """
204
+ box = np.asarray(box, dtype=float)
205
+ anchor = np.asarray(positions[ring[0]], dtype=float)
206
+ # every point brought into the anchor's periodic image; a centroid of raw wrapped
207
+ # coordinates is what produces false positives here
208
+ P = np.array([anchor + _mic(np.asarray(positions[i], dtype=float) - anchor, box)
209
+ for i in ring])
210
+ O = P.mean(axis=0)
211
+ reach = float(np.linalg.norm(P - O, axis=1).max()) + margin
212
+ ring_set = set(ring)
213
+
214
+ ids = np.fromiter(positions.keys(), dtype=int, count=len(positions))
215
+ pts = np.array([positions[i] for i in ids], dtype=float)
216
+ within = np.linalg.norm(_mic(pts - O, box), axis=1) <= reach
217
+ nearby = set()
218
+ for j in ids[within]:
219
+ if int(j) not in ring_set:
220
+ nearby.update(bonds_of.get(int(j), ()))
221
+
222
+ seen, out = set(), []
223
+ for ai, aj in nearby:
224
+ if ai in ring_set or aj in ring_set:
225
+ continue
226
+ key = (min(ai, aj), max(ai, aj))
227
+ if key in seen:
228
+ continue
229
+ seen.add(key)
230
+ p0 = anchor + _mic(np.asarray(positions[ai], dtype=float) - anchor, box)
231
+ # keep the bond contiguous: its far end is imaged against its near end
232
+ p1 = p0 + _mic(np.asarray(positions[aj], dtype=float)
233
+ - np.asarray(positions[ai], dtype=float), box)
234
+ for k in range(len(P)):
235
+ if _segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]):
236
+ out.append((ai, aj))
237
+ break
238
+ return out
239
+
240
+
241
+ def bonds_by_atom(bonds):
242
+ """Inverts a bond table into {atom: [(ai, aj), ...]}, for threading lookups."""
243
+ out = {}
244
+ for r in bonds.itertuples():
245
+ ai, aj = int(r.ai), int(r.aj)
246
+ out.setdefault(ai, []).append((ai, aj))
247
+ out.setdefault(aj, []).append((ai, aj))
248
+ return out
249
+
250
+
251
+ def drop_threaded(candidates, sites, positions, bonds_of, box):
252
+ """Removes candidate rings that would close around an existing bond.
253
+
254
+ CURE refuses a bond that pierces a ring; the ring cure has the converse problem and
255
+ refused nothing. Measured over ten builds: six carried a threaded triazine, and the
256
+ threading bonds were the same bonds found stretched past 2 A -- 15 stretched, 13
257
+ threading, none threading without being stretched. 10 of 11 were pre-existing
258
+ monomer backbones, so the ring closes around a monomer that was already there and
259
+ traps it. It cannot relax out afterwards; escaping needs a bond to break.
260
+
261
+ Returns:
262
+ tuple: (kept candidates, number dropped)
263
+ """
264
+ if not bonds_of:
265
+ return candidates, 0
266
+ kept = []
267
+ dropped = 0
268
+ for cand in candidates:
269
+ ring = ring_atom_order(cand, sites)
270
+ if ring_threading_bonds(ring, positions, bonds_of, box):
271
+ dropped += 1
272
+ continue
273
+ kept.append(cand)
274
+ return kept, dropped
275
+
276
+
277
+ def ring_atom_order(candidate, sites):
278
+ """The six atoms of a candidate ring, in cyclic order.
279
+
280
+ A triple is (score, order, bonds) with `order` the three groups in ring order; each
281
+ group contributes its donor and the acceptor that the previous group's donor reaches,
282
+ and a group's own donor and acceptor are already bonded to each other.
283
+ """
284
+ score, order, bonds = candidate
285
+ ring = []
286
+ for a, b in bonds:
287
+ ring.append(int(sites.at[a, 'donor']))
288
+ ring.append(int(sites.at[b, 'acceptor']))
289
+ return ring
290
+
291
+
158
292
  def select_disjoint(candidates, max_triples=0):
159
293
  """Chooses triples so that no group is used twice, shortest total bonds first.
160
294
 
@@ -543,13 +543,6 @@ attributes:
543
543
  Minimum amount in nm by which the target distance is decreased
544
544
  per stage; with `limit`, this sets the stage count.
545
545
  default: 0.0
546
- - name: max_accept
547
- type: float
548
- text: >
549
- Refuse to form a ring whose pairs are still further apart than this after
550
- the closure ladder, in nm. The groups stay unreacted and are offered
551
- again next iteration. 0 accepts any ring.
552
- default: 0.30
553
546
  - name: nstages
554
547
  type: int
555
548
  text: Explicit stage count, as an alternative to deriving one from `increment`.
@@ -828,6 +821,28 @@ attributes:
828
821
  min_bonds_per_iteration, counted in rings. Clamped against the rings still
829
822
  needed to reach desired_conversion.
830
823
  default: 4
824
+ - name: reject_threaded_rings
825
+ type: bool
826
+ text: >
827
+ Refuse a ring that would close around an existing bond, tested after the
828
+ closure ladder and before the bonds are formed. CURE refuses a new bond that
829
+ pierces an existing ring; this is the converse, and without it a triazine can
830
+ form around a monomer that was already there and trap it. A threaded monomer
831
+ cannot relax out -- escaping needs a bond to break -- and it is the same
832
+ monomer that shows up stretched past 2 A in the final structure. Set false
833
+ to reproduce pre-2.11.4 behavior.
834
+ default: true
835
+ - name: prefilter_threaded_candidates
836
+ type: bool
837
+ text: >
838
+ Also apply the threading test at candidate time, to avoid spending a closure
839
+ ladder on a ring that is already threaded. Off by default because a
840
+ candidate loop is three groups a search radius apart and encloses far more
841
+ area than the triazine it becomes -- roughly nine times at a 1.0 nm radius
842
+ and over twenty at 1.6 nm, which is where late iterations run -- so it
843
+ rejects rings the ladder would have closed cleanly. Enable it to trade
844
+ conversion for wall time, or to measure the difference.
845
+ default: false
831
846
  - name: same_molecule
832
847
  type: bool
833
848
  text: >
@@ -842,6 +857,82 @@ attributes:
842
857
  Allow two groups of one residue in a ring, which for a dicyanate is both
843
858
  arms into one triazine.
844
859
  default: false
860
+ - name: relax
861
+ type: list
862
+ list_defaults: replace
863
+ text: >
864
+ MD stages run after each iteration's rings are formed, easing the new bonds
865
+ in. The constant-pressure stage is what lets the box respond as the network
866
+ forms: with NVT only, a cure runs at fixed volume from first ring to last and
867
+ cannot reproduce cure shrinkage at all. It is above Tg for the same reason
868
+ CURE's relaxation is -- a glassy network will not densify in 2 ps, and these
869
+ stages mirror CURE's `relax.equilibration` exactly. The NVT is above Tg too:
870
+ cooling here would put a cold configuration under the barostat and sit
871
+ between two 600 K closure ladders.
872
+ default:
873
+ - ensemble: min
874
+ - ensemble: nvt
875
+ temperature: 600
876
+ nsteps: 1000
877
+ - ensemble: npt
878
+ temperature: 600
879
+ pressure: 1
880
+ nsteps: 2000
881
+ value_attributes: *cure_md_record
882
+ - name: equilibrate
883
+ type: dict
884
+ text: >
885
+ The equilibration run at the end of every ring-cure iteration, identical in
886
+ shape and defaults to `CURE.equilibrate`. This is the cold half of the
887
+ cycle: `relax` ends hot and constant-pressure, which expands the box, and
888
+ without something cold to pull it back the box only grows. Like CURE's, it
889
+ uses a 2 fs timestep with constraints, not the 1 fs of relax.
890
+ attributes:
891
+ - name: ensemble
892
+ type: str
893
+ text: min (minimization), nvt, or npt.
894
+ choices: [min, nvt, npt]
895
+ default: npt
896
+ - name: temperature
897
+ type: float
898
+ text: Temperature in K.
899
+ default: 300
900
+ - name: pressure
901
+ type: float
902
+ text: Pressure in bar.
903
+ default: 1
904
+ - name: nsteps
905
+ type: int
906
+ text: >
907
+ Duration in timesteps. 50000 of the 2 fs step is 100 ps, matching CURE.
908
+ Whether 100 ps is the right number has never been measured for either
909
+ route; see ROADMAP.md.
910
+ default: 50000
911
+ - name: ps
912
+ type: float
913
+ text: >
914
+ Duration in picoseconds. `nsteps` wins when both are set, and it has a
915
+ default, so this takes effect only if `nsteps` is set to 0.
916
+ - name: repeat
917
+ type: int
918
+ text: Times to repeat this simulation in series; 0 runs it once.
919
+ default: 0
920
+ - name: settle
921
+ type: list
922
+ list_defaults: replace
923
+ value_attributes: *cure_md_record
924
+ text: >
925
+ Equilibration run once at the end of the cure, before postcure. Every
926
+ batch of rings but the last is relaxed again by the next iteration's
927
+ closure ladder; the last one is not, and reaches postcure still carrying
928
+ the strain the ladder left -- stretched ring bonds, and monomers whose
929
+ backbones were pulled while their arms went to different rings. An empty
930
+ list skips it.
931
+ default:
932
+ - ensemble: min
933
+ - ensemble: nvt
934
+ temperature: 300
935
+ nsteps: 2500
845
936
  - name: closure
846
937
  type: dict
847
938
  text: >
@@ -860,6 +951,27 @@ attributes:
860
951
  type: float
861
952
  text: Restraint stiffness, in kJ/mol/nm^2.
862
953
  default: 300000.0
954
+ - name: max_accept
955
+ type: float
956
+ text: >
957
+ Refuse to form a ring whose pairs are still further apart than this after
958
+ the closure ladder, in nm. The groups stay unreacted and are offered
959
+ again next iteration, though that combination of them is passed over
960
+ while any untried ring is in reach. 0 accepts any ring.
961
+ default: 0.30
962
+ - name: equilibration
963
+ type: list
964
+ list_defaults: replace
965
+ text: >
966
+ The MD records run at each stage of the ladder, with the restraints in
967
+ place. Constant-volume on purpose: NPT while restraints are actively
968
+ pulling groups together is not a stable combination.
969
+ default:
970
+ - ensemble: min
971
+ - ensemble: nvt
972
+ temperature: 600
973
+ nsteps: 1000
974
+ value_attributes: *cure_md_record
863
975
 
864
976
  - name: postcure_repair
865
977
  type: list
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.11.2
3
+ Version: 2.11.4
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/
@@ -12,8 +12,8 @@ htpolynet/core/coordinates.py,sha256=CGTHkdfw2ikc2ANacA5akRhZ9tOyM2IbELwQ2FVcKRw
12
12
  htpolynet/core/molecule.py,sha256=j0I0qsk5mRTg8QMysxJz6U9HxgTRpRSzHEgJ_SRT-jQ,63012
13
13
  htpolynet/core/paramcache.py,sha256=37S88gRXZ5_xAdWyUE-Q3Etxc5HMv8L_RHrykkq9YAs,6966
14
14
  htpolynet/core/productsplice.py,sha256=asFVCW8G_rcMIizvO2Sh98MpOsFqzP1kIX1JySei_p8,12816
15
- htpolynet/core/projectfilesystem.py,sha256=2U_EToZxN7yUGWu9BIRABVsYdp1AKkOuManwuFBz89k,20983
16
- htpolynet/core/runtime.py,sha256=yBDfo0-ExUKFmfycWNi-ldnV249yR_j_dkUCkZG0sx8,72385
15
+ htpolynet/core/projectfilesystem.py,sha256=KLpKlAaAG02bl6jZEZkYYTyjnHSrO5yAFAwI0uTMmDE,22630
16
+ htpolynet/core/runtime.py,sha256=yKSSmaiUmRfJYYSrhqYvpxsD0RWCrYU8cWGl9GKn3v0,76493
17
17
  htpolynet/core/topocoord.py,sha256=jUgFg9TuUdSm14wo_464xX6dC4okJMrj1FbIzmaoA0Q,110520
18
18
  htpolynet/core/topology.py,sha256=ASyNbyWxw4bvFUACBmydCr-gGl705o68aB7vGYl7cHk,65405
19
19
  htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -21,8 +21,8 @@ htpolynet/cure/chain.py,sha256=-d5BFE5xUKjFdNkxLfSnCnZIRSJCtr7xuxYzNHBeSgU,5344
21
21
  htpolynet/cure/curecontroller.py,sha256=eTJc1JqrD7w6XLg4pL5ACHXo5N1oJ6P5pVdzMONxiBU,59756
22
22
  htpolynet/cure/expandreactions.py,sha256=eN35-SQrzjoo8ftZVLJkiAKxpA_FigERTwZ8jtoxDng,20682
23
23
  htpolynet/cure/reaction.py,sha256=_kRJ1JzT_fjLIAF6j9lH_Sft41KD1kVQuWPmXdHia-M,13446
24
- htpolynet/cure/ringcontroller.py,sha256=T104pX6qUwjzRgOmROuQnxiV6Eu3xSSZim2XBsFwNaY,19962
25
- htpolynet/cure/triplesearch.py,sha256=54Dl0RU_LHcwCDa4-0AiRH08eIEA8bTacrA1TDhs5I8,10605
24
+ htpolynet/cure/ringcontroller.py,sha256=-EmBsXEFZKRjeVroFR_9X2iCA8COZYIbVUVsZvcfiSs,31264
25
+ htpolynet/cure/triplesearch.py,sha256=3i0MBDa1ExFt0zhjvDUQk9GNxrjGwWAiWQAmFDYBWmE,16046
26
26
  htpolynet/external/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
27
  htpolynet/external/ambertools.py,sha256=NkZ0fP6iqwMnMk2jMD3-EaiGCmutHb1MVFOTFJiQ7WI,6286
28
28
  htpolynet/external/command.py,sha256=KYmWV8P4nuw_ciE16WazviorxjGj5un_z7dL62n0TG0,2480
@@ -92,7 +92,7 @@ htpolynet/resources/molecules/sample-inputs/STY.mol2,sha256=r1NqpovL6L7E96Kkyc6U
92
92
  htpolynet/resources/tcl/readbonds.tcl,sha256=l_bh7eMjbxVi44UMPMi32bFntZltij92KmKfXC1qDz4,972
93
93
  htpolynet/resources/tcl/readgrx.tcl,sha256=A1KvyIpFC_lwfze3XOqTCPqLIkq7HwmqJ96lZH42W0U,1731
94
94
  htpolynet/resources/tcl/render.tcl,sha256=KUszYxzWtfuL7OXdtdk8n6eAQbz8DJfKJrGbb0pOdrI,2379
95
- htpolynet/schema/base.yaml,sha256=rIAWZDJuiZLIpnVU5DZCv40Z7KmQ5cx8o5RJyOY2i20,40385
95
+ htpolynet/schema/base.yaml,sha256=Gl3cNHL-ifWa2-nVBPo1aY5OOhDKDADXTUJDcYqOGhI,45576
96
96
  htpolynet/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
97
97
  htpolynet/utils/banner.py,sha256=hdw6xoHNAo9p6X33LmhW5qyb67qAaQ3hmLnct3ZuDy0,906
98
98
  htpolynet/utils/checkpoint.py,sha256=QTZIJ8K777T6o-mNpjPdelTqrpT0amLlQcgpHBiq5V0,2924
@@ -103,8 +103,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
103
103
  htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
104
104
  htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
105
105
  htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
106
- htpolynet-2.11.2.dist-info/METADATA,sha256=OC5RW8dmoa0N3Ud9ZbTkPDqJnNPvX0PpA1fESIu-wes,6589
107
- htpolynet-2.11.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
108
- htpolynet-2.11.2.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
109
- htpolynet-2.11.2.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
110
- htpolynet-2.11.2.dist-info/RECORD,,
106
+ htpolynet-2.11.4.dist-info/METADATA,sha256=f665u_6EhWQkqK_HSwb5yyhaQnFSmOJig3Bo1vROtwU,6589
107
+ htpolynet-2.11.4.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
108
+ htpolynet-2.11.4.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
109
+ htpolynet-2.11.4.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
110
+ htpolynet-2.11.4.dist-info/RECORD,,