HTPolyNet 2.4.0__py3-none-any.whl → 2.6.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.
htpolynet/core/runtime.py CHANGED
@@ -7,6 +7,8 @@ import os
7
7
  import random
8
8
  import shutil
9
9
 
10
+ import yaml
11
+
10
12
  from collections import namedtuple
11
13
  from copy import deepcopy
12
14
 
@@ -470,8 +472,9 @@ class Runtime:
470
472
  from ..repair import run_repair
471
473
  TC = self.TopoCoord
472
474
  my_logger(f'Postcure repair in {pfs.cwd()}', logger.info)
473
- n_repaired = run_repair(TC, self.molecules, specs, self.reactions)
475
+ n_repaired, repair_stats = run_repair(TC, self.molecules, specs, self.reactions)
474
476
  my_logger(f'Postcure repair performed {n_repaired} dismantle operations', logger.info)
477
+ self._report_repair_conversion(repair_stats)
475
478
  # Write out the repaired system so the relaxation can pick it up
476
479
  TC.write_grx_attributes('repaired.grx')
477
480
  TC.write_gro('repaired.gro')
@@ -487,6 +490,54 @@ class Runtime:
487
490
  deffnm='repair-nvt')
488
491
  return {c: os.path.basename(x) for c, x in TC.files.items() if c != 'mol2'}
489
492
 
493
+ def _report_repair_conversion(self, repair_stats):
494
+ """Reports the conversion a repaired system actually carries, next to the one the cure reported.
495
+
496
+ The cure iterates on bond conversion: bonds formed over bonds
497
+ possible. Repair then dismantles every crosslinker that did not fill
498
+ all of its sites, so the structure that leaves this stage contains
499
+ only complete crosslinkers, and the fraction of those is what an
500
+ experiment measures. The two numbers differ -- for a trifunctional
501
+ crosslinker under random placement the second is roughly the cube of
502
+ the first -- and reporting only the cure's number invites a run at a
503
+ bond conversion of 0.90 to be written up as a 0.90 when it is closer
504
+ to 0.76. Both numbers, and the counts behind them, are also written
505
+ to ``repair-summary.yaml`` in this stage's directory.
506
+
507
+ Args:
508
+ repair_stats (list): statistics dicts returned by :func:`htpolynet.repair.run_repair`
509
+ """
510
+ if not any(st['n_crosslinkers'] for st in repair_stats):
511
+ return
512
+ bond_conversion = None
513
+ cc = getattr(self, 'cc', None)
514
+ if cc is not None:
515
+ bond_conversion = cc.conversion()
516
+ record = {'bond_conversion': bond_conversion, 'repairs': repair_stats}
517
+ for st in repair_stats:
518
+ if not st['n_crosslinkers']:
519
+ continue
520
+ msg = (f'Crosslinker conversion after repair: '
521
+ f'{st["crosslinker_conversion"]:.3f} '
522
+ f'({st["n_complete"]}/{st["n_crosslinkers"]} {st["residue"]} complete)')
523
+ if bond_conversion is not None:
524
+ msg += f'; the cure reported a bond conversion of {bond_conversion:.3f}'
525
+ my_logger(msg, logger.info)
526
+ # the transfer count is what predicts whether this stage survives,
527
+ # so it belongs next to the conversion rather than mid-log
528
+ if st.get('n_transferred'):
529
+ tmsg = f'Repair transferred {st["n_transferred"]} cap fragments'
530
+ if st.get('min_clearance_nm') is not None:
531
+ tmsg += f'; tightest placement {st["min_clearance_nm"]:.3f} nm'
532
+ if st.get('n_below_target'):
533
+ tmsg += f'; {st["n_below_target"]} below the clearance target'
534
+ my_logger(tmsg, logger.info)
535
+ try:
536
+ with open('repair-summary.yaml', 'w') as f:
537
+ yaml.dump(record, f, default_flow_style=False)
538
+ except Exception as e:
539
+ logger.warning(f'Could not write repair-summary.yaml: {e}')
540
+
490
541
  @cp.enableCheckpoint
491
542
  def do_postcure(self):
492
543
  """Manages execution of mdrun to perform any post-cure MD simulation(s).
@@ -27,6 +27,59 @@ from ..utils.stringthings import my_logger
27
27
 
28
28
  logger = logging.getLogger(__name__)
29
29
 
30
+ def residue_reaction_counts(adf):
31
+ """Counts, per residue, how many bonds that residue's atoms have already formed.
32
+
33
+ Args:
34
+ adf (pandas.DataFrame): the global atom dataframe; must carry the 'resNum' and 'nreactions' attributes
35
+
36
+ Returns:
37
+ pandas.Series: number of bonds already formed, indexed by residue number
38
+ """
39
+ return adf.groupby('resNum')['nreactions'].sum()
40
+
41
+ def residue_functionality(adf):
42
+ """Counts, per residue, how many reactive sites it started with.
43
+
44
+ Forming a bond decrements an atom's 'z' and increments its 'nreactions' in
45
+ the same operation, so their sum is conserved per atom for the whole cure.
46
+ Summed over a residue it is that residue's initial functionality, and it
47
+ reads the same at iteration 0 as at the end.
48
+
49
+ Args:
50
+ adf (pandas.DataFrame): the global atom dataframe; must carry the 'resNum', 'z' and 'nreactions' attributes
51
+
52
+ Returns:
53
+ pandas.Series: initial reactive sites, indexed by residue number
54
+ """
55
+ return adf.groupby('resNum')[['z','nreactions']].sum().sum(axis=1)
56
+
57
+ def rank_bond_candidates(bdf,reaction_counts=None):
58
+ """Orders bond candidates ahead of the greedy one-bond-per-residue downselection.
59
+
60
+ The default ordering is by pair separation alone. Separation is
61
+ uncorrelated with how many bonds a crosslinker already carries, so bonds
62
+ spread evenly over all crosslinkers rather than completing the
63
+ partly-reacted ones. Supplying ``reaction_counts`` promotes candidates
64
+ whose B-side residue already carries the most bonds, with each such group
65
+ still ordered by separation; because the downselection that follows is
66
+ greedy and admits at most one bond per residue per iteration, this ordering
67
+ is what decides which residues react.
68
+
69
+ Args:
70
+ bdf (pandas.DataFrame): bond candidates, with column 'r' and, when biasing, column 'rj'
71
+ reaction_counts (pandas.Series): bonds already formed per residue, as returned by :func:`residue_reaction_counts`; None (the default) selects the distance-only ordering
72
+
73
+ Returns:
74
+ pandas.DataFrame: bdf reordered; its columns are unchanged
75
+ """
76
+ if reaction_counts is None:
77
+ return bdf.sort_values('r',axis=0,ignore_index=True).reset_index(drop=True)
78
+ ranked=bdf.copy()
79
+ ranked['_nrx']=ranked['rj'].map(reaction_counts).fillna(0).astype(int)
80
+ ranked=ranked.sort_values(['_nrx','r'],ascending=[False,True],ignore_index=True)
81
+ return ranked.drop(columns=['_nrx']).reset_index(drop=True)
82
+
30
83
  class cure_step(Enum):
31
84
  """Enumerated CURE step
32
85
  """
@@ -127,6 +180,7 @@ class CureController:
127
180
  'desired_conversion': 0.5,
128
181
  'min_allowable_bondcycle_length':-1, # not set
129
182
  'min_bonds_per_iteration': 10, # grow radius until >= this many bonds (or max radius)
183
+ 'completion_bias': False, # rank bond candidates by B-side completion before distance
130
184
  'ncpu' : os.cpu_count()
131
185
  },
132
186
  'drag': {
@@ -174,6 +228,9 @@ class CureController:
174
228
  self.dicts[k][kk]=vv
175
229
 
176
230
  self.chain_manager=None
231
+ # once-per-run: has the completion bias been checked against which side
232
+ # of the reaction actually carries the more functional residue?
233
+ self.bias_side_checked=False
177
234
  self.dragging_enabled=False
178
235
  d=self.dicts['drag']
179
236
  if (d['nstages']>0 or d['increment']>0.0) and d['limit']>0.0:
@@ -261,6 +318,19 @@ class CureController:
261
318
  if not self.state.max_nxlinkbonds: return 0
262
319
  return float(self.state.cum_nxlinkbonds)/self.state.max_nxlinkbonds
263
320
 
321
+ def conversion(self):
322
+ """Returns the current bond conversion: the fraction of all possible crosslink bonds that have been formed.
323
+
324
+ This is the number the cure iterates against and reports. For a
325
+ chemistry whose crosslinkers only count as reacted once every one of
326
+ their sites is filled, it is an upper bound on the conversion an
327
+ experiment would measure; see :mod:`htpolynet.repair.cyanate_cap`.
328
+
329
+ Returns:
330
+ float: bond conversion
331
+ """
332
+ return self._curr_conversion()
333
+
264
334
  def reset(self):
265
335
  """Resets this CureController object by resetting its CureState, its bonds dataframe, and its search_failed member.
266
336
  """
@@ -569,6 +639,49 @@ class CureController:
569
639
  self.state.current_stage[mode]=0
570
640
  self.state._to_yaml()
571
641
 
642
+ def _completion_bias_counts(self,adf):
643
+ """Returns per-residue reaction counts when the completion bias is enabled, else None.
644
+
645
+ Args:
646
+ adf (pandas.DataFrame): the global atom dataframe
647
+
648
+ Returns:
649
+ pandas.Series: per-residue bond counts, or None to rank by distance alone
650
+ """
651
+ if not self.dicts['controls'].get('completion_bias',False):
652
+ return None
653
+ if 'nreactions' not in adf.columns:
654
+ logger.warning('completion_bias is enabled but the atom dataframe carries no "nreactions" attribute; ranking bond candidates by distance alone')
655
+ return None
656
+ return residue_reaction_counts(adf)
657
+
658
+ def _check_bias_side(self,adf,bdf):
659
+ """Warns, once per run, if the completion bias is ranking the less functional side.
660
+
661
+ The bias ranks on the ``B`` reactant because htpolynet's A2+B3 idiom
662
+ puts the crosslinker there. Declare the crosslinker as ``A`` instead
663
+ and the bias silently starts completing the *bridges*, which is a
664
+ different claim about which species is a reactive intermediate and
665
+ almost certainly not the one that was wanted. It cannot be caught by
666
+ looking for an all-zero bias key -- a difunctional bridge accumulates
667
+ reactions perfectly well, so the key is non-zero and the ranking looks
668
+ healthy. What distinguishes the two cases is which side is the more
669
+ functional one, and that is fixed at setup.
670
+
671
+ Args:
672
+ adf (pandas.DataFrame): the global atom dataframe
673
+ bdf (pandas.DataFrame): the bond candidates for this iteration
674
+ """
675
+ if self.bias_side_checked: return
676
+ if not all(c in adf.columns for c in ('z','nreactions')): return
677
+ self.bias_side_checked=True
678
+ func=residue_functionality(adf)
679
+ a=bdf['ri'].map(func).dropna()
680
+ b=bdf['rj'].map(func).dropna()
681
+ if a.empty or b.empty: return
682
+ if a.max()>b.max():
683
+ logger.warning(f'completion_bias ranks candidates on the B-side residue, but the A side is the more functional one here ({int(a.max())} reactive sites vs {int(b.max())}). The bias will complete B-side residues, which is probably not what was intended; declare the crosslinker as the second reactant to bias toward it.')
684
+
572
685
  # TODO: move to searchbonds.by; split into make_candidates() and apply_filters()
573
686
  def _searchbonds(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,stage=reaction_stage.cure,abs_max=0,apply_probabilities=False,reentry=False):
574
687
  """Manages the search for bonds.
@@ -679,7 +792,12 @@ class CureController:
679
792
  # logger.debug(ln)
680
793
 
681
794
  if stage==reaction_stage.cure and bdf.shape[0]>0:
682
- bdf=bdf.sort_values('r',axis=0,ignore_index=True).reset_index(drop=True)
795
+ reaction_counts=self._completion_bias_counts(adf)
796
+ bdf=rank_bond_candidates(bdf,reaction_counts)
797
+ if reaction_counts is not None:
798
+ self._check_bias_side(adf,bdf)
799
+ nrx=bdf['rj'].map(reaction_counts).fillna(0).astype(int)
800
+ logger.debug(f'Completion bias: {int((nrx>0).sum())} of {bdf.shape[0]} candidates extend an already-reacted B-side residue (most bonds already carried: {int(nrx.max())})')
683
801
  bdf['allowed']=[True for x in range(bdf.shape[0])]
684
802
  unique_atomidx=set(bdf.ai.to_list()).union(set(bdf.aj.to_list()))
685
803
  unique_resids=set(bdf.ri.to_list()).union(set(bdf.rj.to_list()))
@@ -24,16 +24,21 @@ def run_repair(TC, moldict, repair_specs, reactions):
24
24
  parameter templates by the drivers.
25
25
 
26
26
  Returns:
27
- int: number of repairs performed across all drivers.
27
+ tuple: (int, list) -- the number of repairs performed across all
28
+ drivers, and one statistics dict per driver that reported any
29
+ (see :func:`htpolynet.repair.cyanate_cap._completion_stats`).
28
30
  """
29
31
  if not repair_specs:
30
- return 0
32
+ return 0, []
31
33
  total = 0
34
+ stats = []
32
35
  for spec in repair_specs:
33
36
  rtype = spec.get('type')
34
37
  if rtype == 'triazine_to_cyanate_cap':
35
38
  from .cyanate_cap import triazine_to_cyanate_cap
36
- total += triazine_to_cyanate_cap(TC, moldict, spec, reactions)
39
+ result = triazine_to_cyanate_cap(TC, moldict, spec, reactions)
40
+ total += result['n_dismantled']
41
+ stats.append(result)
37
42
  else:
38
43
  logger.warning(f'Unknown postcure_repair type "{rtype}"; skipping')
39
- return total
44
+ return total, stats
@@ -106,6 +106,10 @@ def _place_cyn_along(bpa_o_xyz, bpa_o_h_xyz, oc_len=0.136, cn_len=0.116):
106
106
  direction from BPA-O toward the (about-to-be-deleted) H, so the new
107
107
  cap sticks out along the original O-H bond.
108
108
 
109
+ This is the unconditioned placement: it is where the cap goes if that
110
+ direction happens to be empty, and it is blind to whether it is. See
111
+ :func:`_choose_cap_placement`, which uses it as its first candidate.
112
+
109
113
  Lengths in nm: standard -O-C ester ~1.36 A, -C#N ~1.16 A.
110
114
  Returns (C_xyz, N_xyz).
111
115
  """
@@ -122,11 +126,179 @@ def _place_cyn_along(bpa_o_xyz, bpa_o_h_xyz, oc_len=0.136, cn_len=0.116):
122
126
  return c_xyz, n_xyz
123
127
 
124
128
 
129
+ _PLACEMENT_LOCALITY = 0.8
130
+ """nm: an atom farther than this from the target oxygen cannot constrain a cap
131
+ that reaches only ~0.25 nm from it, so it is not scored against."""
132
+
133
+
134
+ def _report_placements(placements, target):
135
+ """Say how well the transferred caps landed, and complain about the tight ones.
136
+
137
+ The transfer count is the quantity that predicts whether this stage will
138
+ survive, so it is stated plainly rather than left to be inferred, and a
139
+ placement that could not reach the target clearance is named while it is
140
+ still cheap to act on -- the alternative is reading it back out of a
141
+ Lennard-Jones term at step 0.
142
+
143
+ Args:
144
+ placements (list): one dict per transferred cap, with 'o' and 'clearance'
145
+ target (float): the clearance in nm that was being aimed for
146
+
147
+ Returns:
148
+ dict: n_transferred, n_direction_searched, n_below_target, min_clearance_nm
149
+ """
150
+ if not placements:
151
+ return {'n_transferred': 0, 'n_direction_searched': 0,
152
+ 'n_below_target': 0, 'min_clearance_nm': None}
153
+ gaps = np.array([p['clearance'] for p in placements], dtype=float)
154
+ searched = sum(1 for p in placements if not p['kept_o_h_direction'])
155
+ below = [p for p in placements if p['clearance'] < target]
156
+ logger.info(
157
+ f'triazine_to_cyanate_cap: placed {len(placements)} transferred caps '
158
+ f'({searched} needed a direction search); clearance min/median '
159
+ f'{gaps.min():.3f}/{float(np.median(gaps)):.3f} nm against a target of {target:.3f}'
160
+ )
161
+ if below:
162
+ worst = sorted(below, key=lambda p: p['clearance'])[:5]
163
+ detail = ', '.join(f'O {int(p["o"])} at {p["clearance"]:.3f} nm' for p in worst)
164
+ logger.warning(
165
+ f'triazine_to_cyanate_cap: {len(below)} of {len(placements)} transferred '
166
+ f'caps could not reach {target:.3f} nm of clearance in any direction '
167
+ f'(worst: {detail}). The box is too crowded here for this many caps; '
168
+ f'if the following minimization fails with a huge Lennard-Jones term, '
169
+ f'this is why.'
170
+ )
171
+ return {
172
+ 'n_transferred': len(placements),
173
+ 'n_direction_searched': searched,
174
+ 'n_below_target': len(below),
175
+ 'min_clearance_nm': float(gaps.min()),
176
+ }
177
+
178
+
179
+ def _sphere_directions(n=48):
180
+ """``n`` roughly uniform unit vectors on the sphere, deterministically.
181
+
182
+ A Fibonacci spiral: no randomness, so a rebuild of the same system places
183
+ its caps identically.
184
+
185
+ Args:
186
+ n (int): how many directions to generate
187
+
188
+ Returns:
189
+ numpy.ndarray: (n, 3) array of unit vectors
190
+ """
191
+ k = np.arange(n) + 0.5
192
+ phi = np.arccos(1.0 - 2.0 * k / n)
193
+ theta = np.pi * (1.0 + 5.0 ** 0.5) * k
194
+ return np.stack([np.cos(theta) * np.sin(phi),
195
+ np.sin(theta) * np.sin(phi),
196
+ np.cos(phi)], axis=1)
197
+
198
+
199
+ def _clearance(c_xyz, n_xyz, neighbors, box):
200
+ """Smallest distance from either cap atom to any neighbouring atom.
201
+
202
+ Args:
203
+ c_xyz (numpy.ndarray): position of the cap carbon
204
+ n_xyz (numpy.ndarray): position of the cap nitrogen
205
+ neighbors (numpy.ndarray): (m, 3) positions to stay clear of
206
+ box (numpy.ndarray): orthorhombic box lengths, for minimum image
207
+
208
+ Returns:
209
+ float: the smallest such distance in nm, or inf if there are no neighbours
210
+ """
211
+ if neighbors is None or len(neighbors) == 0:
212
+ return float('inf')
213
+ return float(min(_min_image_dist(c_xyz, neighbors, box).min(),
214
+ _min_image_dist(n_xyz, neighbors, box).min()))
215
+
216
+
217
+ def _choose_cap_placement(o_xyz, ref_xyz, neighbors, box, oc_len=0.136,
218
+ cn_len=0.116, target=0.15, n_directions=48):
219
+ """Place a transferred -C#N group in the clearest direction available.
220
+
221
+ The old O-H vector is tried first and kept if it is clear enough, so a
222
+ cap in open space lands exactly where it always did. Only when that
223
+ direction is occupied does this search the sphere -- which is the case
224
+ that used to produce a step-0 Lennard-Jones term around 1e15 and a
225
+ minimization that could not recover. Bond lengths are held fixed; only
226
+ the direction moves, so the chemistry is unchanged.
227
+
228
+ Args:
229
+ o_xyz (numpy.ndarray): position of the bridge oxygen the cap attaches to
230
+ ref_xyz (numpy.ndarray): position defining the preferred direction, normally the O's about-to-be-deleted H
231
+ neighbors (numpy.ndarray): (m, 3) positions the cap must avoid
232
+ box (numpy.ndarray): orthorhombic box lengths, for minimum image
233
+ oc_len (float): O-C bond length in nm
234
+ cn_len (float): C#N bond length in nm
235
+ target (float): clearance in nm that counts as good enough to stop searching; the default 0.15 is about what a steepest-descent minimization absorbs without trouble, and is achievable in a box at polymer density -- 0.22 is not, and asking for it would flag every cap
236
+ n_directions (int): how many directions to try when the preferred one is occupied
237
+
238
+ Returns:
239
+ tuple: (C position, N position, achieved clearance in nm, whether the preferred direction was kept)
240
+ """
241
+ o = np.asarray(o_xyz, dtype=float)
242
+ c_xyz, n_xyz = _place_cyn_along(o, ref_xyz, oc_len=oc_len, cn_len=cn_len)
243
+ best = _clearance(c_xyz, n_xyz, neighbors, box)
244
+ if best >= target:
245
+ return c_xyz, n_xyz, best, True
246
+ for u in _sphere_directions(n_directions):
247
+ cc = o + u * oc_len
248
+ nn = cc + u * cn_len
249
+ gap = _clearance(cc, nn, neighbors, box)
250
+ if gap > best:
251
+ best, c_xyz, n_xyz = gap, cc, nn
252
+ if best >= target:
253
+ break
254
+ return c_xyz, n_xyz, best, False
255
+
256
+
125
257
  # ---------------------------------------------------------------------------
126
258
  # Main driver
127
259
  # ---------------------------------------------------------------------------
128
260
 
129
261
 
262
+ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, placement=None):
263
+ """Summarize crosslinker completion and log it.
264
+
265
+ A crosslinker survives this repair only if every one of its sites is
266
+ filled; the incomplete ones are dismantled back into caps. So the
267
+ fraction of crosslinkers that survive intact -- not the bond conversion
268
+ the cure iterates against -- is the quantity an experiment measures.
269
+ For a cyanate ester that is the FTIR -OCN conversion, because each
270
+ complete triazine consumes exactly three -OCN groups.
271
+
272
+ Args:
273
+ residue_name (str): crosslinker residue name, used only in the message
274
+ n_crosslinkers (int): number of crosslinker residues in the system
275
+ n_incomplete (int): how many of them are being dismantled
276
+ log (bool): emit the summary message; False when there is nothing to summarize
277
+ placement (dict): cap-placement summary from :func:`_report_placements`, merged into the result
278
+
279
+ Returns:
280
+ dict: n_crosslinkers, n_complete, n_dismantled, crosslinker_conversion
281
+ """
282
+ n_complete = n_crosslinkers - n_incomplete
283
+ chi = n_complete / n_crosslinkers if n_crosslinkers else 0.0
284
+ if log:
285
+ logger.info(
286
+ f'triazine_to_cyanate_cap: {n_complete} of {n_crosslinkers} '
287
+ f'{residue_name} residues are complete and survive repair; '
288
+ f'crosslinker conversion {chi:.3f}'
289
+ )
290
+ out = {
291
+ 'residue': residue_name,
292
+ 'n_crosslinkers': n_crosslinkers,
293
+ 'n_complete': n_complete,
294
+ 'n_dismantled': n_incomplete,
295
+ 'crosslinker_conversion': chi,
296
+ }
297
+ if placement:
298
+ out.update(placement)
299
+ return out
300
+
301
+
130
302
  def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
131
303
  """Execute the triazine-to-cyanate-cap repair.
132
304
 
@@ -139,7 +311,7 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
139
311
  reactions: ReactionList (currently unused; reserved for cross-checks).
140
312
 
141
313
  Returns:
142
- int: number of incomplete triazines dismantled.
314
+ dict: completion statistics as returned by :func:`_completion_stats`.
143
315
  """
144
316
  cl = spec['crosslinker']
145
317
  br = spec['bridge']
@@ -158,7 +330,7 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
158
330
  cl_residues = _find_crosslinker_residues(TC, cl['residue'])
159
331
  if not cl_residues:
160
332
  logger.info(f'triazine_to_cyanate_cap: no {cl["residue"]} residues found; nothing to do')
161
- return 0
333
+ return _completion_stats(cl['residue'], 0, 0, log=False)
162
334
 
163
335
  incomplete_plans = [] # list of dicts, one per incomplete triazine
164
336
  h_to_delete = set() # global H indices, batched for final deletion
@@ -197,7 +369,7 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
197
369
  f'triazine_to_cyanate_cap: all {len(cl_residues)} {cl["residue"]} '
198
370
  f'residues are fully bonded; nothing to do'
199
371
  )
200
- return 0
372
+ return _completion_stats(cl['residue'], len(cl_residues), 0)
201
373
 
202
374
  total_caps = sum(len(p['caps']) for p in incomplete_plans)
203
375
  free_caps_planned = sum(1 for p in incomplete_plans for c in p['caps'] if c['bonded_o'] is None)
@@ -251,34 +423,60 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
251
423
  ts.reassign_residue(TC, [cap['c'], cap['n']], cap_residue_name, new_resnum)
252
424
  ts.set_atom_attributes(TC, cap['c'], atomName='C1')
253
425
  ts.set_atom_attributes(TC, cap['n'], atomName='N1')
254
- cap_records.append({'c': cap['c'], 'n': cap['n'], 'o': target_o, 'resnum': new_resnum})
426
+ cap_records.append({'c': cap['c'], 'n': cap['n'], 'o': target_o,
427
+ 'resnum': new_resnum, 'free': cap['bonded_o'] is None})
255
428
  new_resnum += 1
256
429
 
257
430
  # 3d. for free-cap donations: relocate the CYN atoms next to their target O
258
- for rec in cap_records:
259
- cap_in_plans = next(
260
- (c for p in incomplete_plans for c in p['caps']
261
- if c['c'] == rec['c'] and c['n'] == rec['n']),
262
- None,
263
- )
264
- if cap_in_plans is None or cap_in_plans['bonded_o'] is not None:
265
- continue
266
- o_idx = rec['o']
267
- o_xyz = ts.positions(TC, [o_idx])[0]
268
- # use the (about-to-be-deleted) H on the O as the direction reference
269
- o_h_idx = _find_bonded_hydrogen(TC, o_idx)
270
- if o_h_idx is None:
271
- # no H to use as reference (shouldn't happen for a still-reactive O,
272
- # but if it does, just push the cap along +x by the rest length)
273
- ref_xyz = o_xyz + np.array([1.0, 0.0, 0.0])
274
- else:
275
- ref_xyz = ts.positions(TC, [o_h_idx])[0]
276
- h_to_delete.add(int(o_h_idx))
277
- c_xyz, n_xyz = _place_cyn_along(o_xyz, ref_xyz)
278
- ts.set_atom_attributes(TC, rec['c'],
279
- posX=float(c_xyz[0]), posY=float(c_xyz[1]), posZ=float(c_xyz[2]))
280
- ts.set_atom_attributes(TC, rec['n'],
281
- posX=float(n_xyz[0]), posY=float(n_xyz[1]), posZ=float(n_xyz[2]))
431
+ #
432
+ # This is the phase that fails catastrophically when it fails at all. A
433
+ # cap dropped blindly along the old O-H vector can land on top of a
434
+ # neighbour, and the resulting step-0 Lennard-Jones term -- of order 1e15
435
+ # kJ/mol -- is not something the following minimization recovers from.
436
+ # The count of caps to place here is an identity, (total reactive sites -
437
+ # bonds formed), so it rises as conversion falls: a low-conversion build
438
+ # places hundreds and is where this has been seen to kill runs.
439
+ #
440
+ # So each cap is placed against its local neighbourhood, and every cap
441
+ # already placed is part of the neighbourhood the next one sees.
442
+ free_records = [rec for rec in cap_records if rec['free']]
443
+ placements = []
444
+ placement_summary = None
445
+ if free_records:
446
+ box = TC.Coordinates.box.diagonal()
447
+ target_clearance = float(spec.get('cap_min_clearance', 0.15))
448
+ # the O's H is consumed in forming the cap; collect them all up front
449
+ # so that a cap placed early does not dodge an atom about to vanish
450
+ for rec in free_records:
451
+ h = _find_bonded_hydrogen(TC, rec['o'])
452
+ rec['o_h'] = h
453
+ if h is not None:
454
+ h_to_delete.add(int(h))
455
+ moving = {int(rec['c']) for rec in free_records} | {int(rec['n']) for rec in free_records}
456
+ A = TC.Coordinates.A
457
+ going = moving | {int(x) for x in h_to_delete}
458
+ background = A.loc[~A['globalIdx'].isin(going),
459
+ ['posX', 'posY', 'posZ']].to_numpy(dtype=float)
460
+ for rec in free_records:
461
+ o_xyz = ts.positions(TC, [rec['o']])[0]
462
+ if rec['o_h'] is None:
463
+ # no H to take a direction from (shouldn't happen for a
464
+ # still-reactive O); any direction will do as a starting guess
465
+ ref_xyz = o_xyz + np.array([1.0, 0.0, 0.0])
466
+ else:
467
+ ref_xyz = ts.positions(TC, [rec['o_h']])[0]
468
+ # only atoms near this O can constrain a group that reaches
469
+ # 0.25 nm from it; the rest are not worth scoring against
470
+ local = background[_min_image_dist(o_xyz, background, box) < _PLACEMENT_LOCALITY]
471
+ c_xyz, n_xyz, gap, kept = _choose_cap_placement(
472
+ o_xyz, ref_xyz, local, box, target=target_clearance)
473
+ ts.set_atom_attributes(TC, rec['c'],
474
+ posX=float(c_xyz[0]), posY=float(c_xyz[1]), posZ=float(c_xyz[2]))
475
+ ts.set_atom_attributes(TC, rec['n'],
476
+ posX=float(n_xyz[0]), posY=float(n_xyz[1]), posZ=float(n_xyz[2]))
477
+ background = np.vstack([background, c_xyz, n_xyz])
478
+ placements.append({'o': rec['o'], 'clearance': gap, 'kept_o_h_direction': kept})
479
+ placement_summary = _report_placements(placements, target_clearance)
282
480
 
283
481
  # ---- Phase 4: splice template params (forms BPA-O-C bond with full
284
482
  # angle/dihedral/pair entries from the cap_template molecule) ----
@@ -326,7 +524,8 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
326
524
  msg='triazine_to_cyanate_cap post-deletion rebalance',
327
525
  )
328
526
 
329
- return len(incomplete_plans)
527
+ return _completion_stats(cl['residue'], len(cl_residues), len(incomplete_plans),
528
+ placement=placement_summary)
330
529
 
331
530
 
332
531
  # ---------------------------------------------------------------------------
@@ -128,8 +128,16 @@ CURE:
128
128
  radial_increment: 0.25 # nm
129
129
  min_bonds_per_iteration: 10
130
130
  max_iterations: 150
131
- desired_conversion: 0.90
131
+ desired_conversion: 0.90 # BOND conversion; the cyanate (FTIR) conversion
132
+ # this yields is lower -- roughly its cube, since
133
+ # a triazine survives repair only if all three of
134
+ # its sites filled. Both numbers are reported at
135
+ # the end of the repair stage.
132
136
  late_threshold: 0.80
137
+ # completion_bias: true # finish partly-reacted triazines before starting
138
+ # untouched ones, so desired_conversion means the
139
+ # cyanate conversion. Off here so this example
140
+ # keeps its published behavior.
133
141
  drag:
134
142
  trigger_distance: 0.6 # nm
135
143
  increment: 0.08 # nm
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.4.0
3
+ Version: 2.6.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/
@@ -67,21 +67,24 @@ pip install -e .
67
67
 
68
68
  Once installed, the user has access to the main ``htpolynet`` command.
69
69
 
70
+ If you drive htpolynet with [Claude Code](https://claude.com/claude-code), install the bundled skill so the agent knows how to use it:
71
+ ```bash
72
+ htpolynet setup-claude
73
+ ```
74
+ This writes `~/.claude/skills/htpolynet/SKILL.md`; nothing is installed there unless you run it.
75
+
70
76
  IMPORTANT NOTES: The programs ``antechamber``, ``parmchk2`` and ``tleap`` from AmberTools must be in your path. These can be installed using the ``ambertools`` package from ``conda-forge`` or compiled from source. You also need Gromacs installed so ``gmx`` is in your path. The examples show how to build input monomer structures using OpenBabel, so to use them you need ``obabel`` in your path as well.
71
77
 
72
78
  ## Docker
73
79
 
74
- As an alternative to a local installation, a prebuilt container image is published at ``ghcr.io/cameronabrams/htpolynet``. It bundles htpolynet together with Gromacs, AmberTools, and OpenBabel, so no additional dependencies are required on the host beyond Docker (and, optionally, the NVIDIA Container Toolkit for GPU runs).
80
+ As an alternative to a local installation, a prebuilt container image is published at ``ghcr.io/cameronabrams/htpolynet``. It bundles htpolynet together with Gromacs, AmberTools, and OpenBabel, so no additional dependencies are required on the host beyond Docker.
75
81
 
76
82
  Run htpolynet against a configuration file in the current directory:
77
83
  ```bash
78
84
  docker run --rm -v $(pwd):/work ghcr.io/cameronabrams/htpolynet run config.yaml
79
85
  ```
80
86
 
81
- With GPU support:
82
- ```bash
83
- docker run --rm --gpus all -v $(pwd):/work ghcr.io/cameronabrams/htpolynet run config.yaml
84
- ```
87
+ **The image cannot use a GPU.** Its Gromacs comes from conda-forge, built against OpenCL rather than CUDA, and Gromacs no longer drives NVIDIA devices through OpenCL. Passing `--gpus all` starts the container and changes nothing about how it computes; on a cluster, target CPU partitions and do not request `--gres=gpu` or pass `--nv`. If you need GPU-accelerated Gromacs, install htpolynet natively against a CUDA-enabled Gromacs.
85
88
 
86
89
  A Docker Compose file is also provided in [docker/compose.yml](docker/compose.yml) for a shorter invocation (``docker compose run --rm htpolynet run config.yaml``). See [docs/source/user-guide/container-usage.rst](docs/source/user-guide/container-usage.rst) for the full story, including Singularity/Apptainer use on HPC systems.
87
90
 
@@ -12,12 +12,12 @@ htpolynet/core/coordinates.py,sha256=CGTHkdfw2ikc2ANacA5akRhZ9tOyM2IbELwQ2FVcKRw
12
12
  htpolynet/core/molecule.py,sha256=xUA52zkRMyAFCE8LbXvXghweDCPkrgD4rx1mcimddn0,52751
13
13
  htpolynet/core/paramcache.py,sha256=3MTG96F4vtT5w-pn1RWNmXic0QKB7WVcwCrD-BSY3B0,4508
14
14
  htpolynet/core/projectfilesystem.py,sha256=2U_EToZxN7yUGWu9BIRABVsYdp1AKkOuManwuFBz89k,20983
15
- htpolynet/core/runtime.py,sha256=BmWDttIKtRJnqYiYgrv7bJcivLaBtsgXK8q1jdYVKGw,53299
15
+ htpolynet/core/runtime.py,sha256=5djnRdIkiVf6K5p1hIQSeY1wzAZFlJT6LjdEVn2AOqM,56017
16
16
  htpolynet/core/topocoord.py,sha256=jtQcwzvzPVNjU9VxBF9iXw8g3KiY55_jGDlwAZDOSjs,101564
17
17
  htpolynet/core/topology.py,sha256=XcFL96x2E4MsMrUr9upjE211-VcPVwLVoPL9vrV4DOw,56954
18
18
  htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
19
  htpolynet/cure/chain.py,sha256=-d5BFE5xUKjFdNkxLfSnCnZIRSJCtr7xuxYzNHBeSgU,5344
20
- htpolynet/cure/curecontroller.py,sha256=a97x1GaJ7Q2ayDEN48K4QHS9EOCPEljraUN_joR9ag8,36040
20
+ htpolynet/cure/curecontroller.py,sha256=XWFJUEGgFLM-298KGKTEh6H2OAQ8brXdOTgI35BWlMA,42103
21
21
  htpolynet/cure/expandreactions.py,sha256=_NNsAuOCdgHMBLyEwl6S7VAZyDT5ei-m4OBBXjDE3YQ,13774
22
22
  htpolynet/cure/reaction.py,sha256=S-w60HocYknKnGbq1_uwLpKTL5Fte_o7zxwk3FbyQ1I,10557
23
23
  htpolynet/external/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -37,8 +37,8 @@ htpolynet/io/__init__.py,sha256=nX1-mb5tNRK_FTH1NP55ESWBSmiY_yBBU-43NMgzeA4,160
37
37
  htpolynet/io/gro.py,sha256=QGsAIlTIJlMRxtv_Juo0wdpbICAzyfQvSzzaMWrlMmA,7141
38
38
  htpolynet/io/mol2.py,sha256=5aU3HmQ5DS0LBF7tBPCNYKzBScwj8V3xfEUcFIrsevk,7314
39
39
  htpolynet/io/pdb.py,sha256=Np44dTbM0IcEAzfz6OGuH0rdQ63BGps3kOmkzH6syls,5293
40
- htpolynet/repair/__init__.py,sha256=7YEjlCLojgVi-PybKnMQ2r4fl65bp4lIEF-G9Tyud0E,1477
41
- htpolynet/repair/cyanate_cap.py,sha256=EfyQJeuu22oMoEpAmY4khJNwCQbXZzLR03JdoBLmoXs,17596
40
+ htpolynet/repair/__init__.py,sha256=cP3i-P-Wc6s0MgoFDp63kbLomM-ti3mMGEgeQzUVKuY,1740
41
+ htpolynet/repair/cyanate_cap.py,sha256=rJye8V8OWYI0relu-pRAoSUONKAe9L2fQkS0DMs9Mr4,27246
42
42
  htpolynet/repair/topology_surgery.py,sha256=aJ1md2SE4UzVU1YTS-Tiox8QXrr1hZwU6cCuEimlSrU,10030
43
43
  htpolynet/resources/README.md,sha256=epKLyqtcxtQOSzTYvaGlwhz970UA4vAU7r-iSBbbpmA,1432
44
44
  htpolynet/resources/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -49,7 +49,7 @@ htpolynet/resources/example_depot/2-bisgma-styrene-thermoset.yaml,sha256=Xk2sVcu
49
49
  htpolynet/resources/example_depot/3-pacm-dgeba-epoxy-thermoset.yaml,sha256=zOuU-cxUm8YsUHKzRFNr8EvrpCqxbG4NA3v89yzAOi4,4296
50
50
  htpolynet/resources/example_depot/4-dfda-fde-epoxy-thermoset.yaml,sha256=ydKmJ6cZSL-HFsrvd_YnRyYyFXIHNP90CR6KMf7Wvdk,4271
51
51
  htpolynet/resources/example_depot/5-htpb-ipdi.yaml,sha256=ZEdLzM9k68d0ED5uhKDUlqgcp4pynehI5ri2ckTmt9U,10441
52
- htpolynet/resources/example_depot/6-cyanate-ester.yaml,sha256=dyXRg2QOYjpsKEFZTmrqsguCjQM7nxE1697RjyicFso,8770
52
+ htpolynet/resources/example_depot/6-cyanate-ester.yaml,sha256=lrTH7M4SJW870lylZS4o63mEHxmkRAf2hVDqlkUzML0,9439
53
53
  htpolynet/resources/mdp/README.md,sha256=48RjM7HLRF776FUJXUxQIw8RZxc7z1ti6za3YB7_U80,20
54
54
  htpolynet/resources/mdp/drag-min.mdp,sha256=CrMRQIzwtG4TlYRY-nB1P7HPgdwrpwSJJW6yoYdfahY,225
55
55
  htpolynet/resources/mdp/drag-npt.mdp,sha256=vbU-LuDH-CLmB8s3kRx0SYkKMxR7Qjh8PuXGgpC2EGs,911
@@ -96,8 +96,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
96
96
  htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
97
97
  htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
98
98
  htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
99
- htpolynet-2.4.0.dist-info/METADATA,sha256=QevvufdlQm4SnXlihXKRVpBbMCSaFZi8I_9CKn365zE,6036
100
- htpolynet-2.4.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
101
- htpolynet-2.4.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
102
- htpolynet-2.4.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
103
- htpolynet-2.4.0.dist-info/RECORD,,
99
+ htpolynet-2.6.0.dist-info/METADATA,sha256=jddVgu49fDmeOBqZLDB38ToTqdIzMBNMmaqFg0ZFot0,6557
100
+ htpolynet-2.6.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
101
+ htpolynet-2.6.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
102
+ htpolynet-2.6.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
103
+ htpolynet-2.6.0.dist-info/RECORD,,