HTPolyNet 2.5.0__py3-none-any.whl → 2.6.1__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
@@ -443,6 +443,7 @@ class Runtime:
443
443
  cure_finished=cc.is_cured()
444
444
  if not cure_finished:
445
445
  cure_finished=cc.next_iter()
446
+ cc.check_iterations_vs_functionality(TC)
446
447
  ''' perform capping if necessary '''
447
448
  my_logger(f'Capping begins',logger.info)
448
449
  pfs.go_to(pfs.Dirs.systems_capping)
@@ -523,6 +524,15 @@ class Runtime:
523
524
  if bond_conversion is not None:
524
525
  msg += f'; the cure reported a bond conversion of {bond_conversion:.3f}'
525
526
  my_logger(msg, logger.info)
527
+ # the transfer count is what predicts whether this stage survives,
528
+ # so it belongs next to the conversion rather than mid-log
529
+ if st.get('n_transferred'):
530
+ tmsg = f'Repair transferred {st["n_transferred"]} cap fragments'
531
+ if st.get('min_clearance_nm') is not None:
532
+ tmsg += f'; tightest placement {st["min_clearance_nm"]:.3f} nm'
533
+ if st.get('n_below_target'):
534
+ tmsg += f'; {st["n_below_target"]} below the clearance target'
535
+ my_logger(tmsg, logger.info)
526
536
  try:
527
537
  with open('repair-summary.yaml', 'w') as f:
528
538
  yaml.dump(record, f, default_flow_style=False)
@@ -38,6 +38,22 @@ def residue_reaction_counts(adf):
38
38
  """
39
39
  return adf.groupby('resNum')['nreactions'].sum()
40
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
+
41
57
  def rank_bond_candidates(bdf,reaction_counts=None):
42
58
  """Orders bond candidates ahead of the greedy one-bond-per-residue downselection.
43
59
 
@@ -212,6 +228,9 @@ class CureController:
212
228
  self.dicts[k][kk]=vv
213
229
 
214
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
215
234
  self.dragging_enabled=False
216
235
  d=self.dicts['drag']
217
236
  if (d['nstages']>0 or d['increment']>0.0) and d['limit']>0.0:
@@ -620,6 +639,40 @@ class CureController:
620
639
  self.state.current_stage[mode]=0
621
640
  self.state._to_yaml()
622
641
 
642
+ def check_iterations_vs_functionality(self,TC:TopoCoord):
643
+ """Warns if the cure ran too few iterations for its crosslinkers to have completed.
644
+
645
+ The bond downselection admits at most one bond per residue per
646
+ iteration, so a residue with ``f`` reactive sites cannot be fully
647
+ reacted in fewer than ``f`` iterations — whatever the bond conversion
648
+ says. A cure that reaches its target conversion in two iterations
649
+ therefore leaves *every* trifunctional crosslinker incomplete, and a
650
+ system with no complete crosslinker has no junctions: it is a monomer
651
+ melt that equilibrates, reports a sensible density, and looks in every
652
+ other respect like a cured network.
653
+
654
+ Nothing else surfaces this. The conversion the cure reports is a bond
655
+ conversion and is perfectly happy; only a postcure repair stage would
656
+ notice, and only if one is configured. ``completion_bias`` does not
657
+ help — it changes which residues react, not the one-per-residue-per-
658
+ iteration rule — which matters because it is the first thing a user
659
+ would reach for on seeing a low crosslinker conversion.
660
+
661
+ Args:
662
+ TC (TopoCoord): global system topology and coordinates
663
+ """
664
+ adf=TC.gro_DataFrame('atoms')
665
+ if adf is None or not all(c in adf.columns for c in ('resNum','z','nreactions')): return
666
+ func=residue_functionality(adf)
667
+ if func.empty: return
668
+ fmax=int(func.max())
669
+ iterations=self.state.iter
670
+ if fmax<2 or iterations>=fmax: return
671
+ top=func.idxmax()
672
+ names=adf.loc[adf['resNum']==top,'resName']
673
+ resname=names.iloc[0] if len(names) else f'residue {top}'
674
+ logger.warning(f'The cure ran {iterations} iteration(s), but {resname} carries {fmax} reactive sites and the bond search admits at most one bond per residue per iteration. No {resname} can have reacted at all {fmax} of its sites, whatever bond conversion was reached, so this system contains no fully-reacted {resname} and therefore no crosslink junctions. completion_bias does not change this. To spend more iterations reaching the same conversion, lower CURE.controls.max_conversion_per_iteration or min_bonds_per_iteration.')
675
+
623
676
  def _completion_bias_counts(self,adf):
624
677
  """Returns per-residue reaction counts when the completion bias is enabled, else None.
625
678
 
@@ -636,6 +689,33 @@ class CureController:
636
689
  return None
637
690
  return residue_reaction_counts(adf)
638
691
 
692
+ def _check_bias_side(self,adf,bdf):
693
+ """Warns, once per run, if the completion bias is ranking the less functional side.
694
+
695
+ The bias ranks on the ``B`` reactant because htpolynet's A2+B3 idiom
696
+ puts the crosslinker there. Declare the crosslinker as ``A`` instead
697
+ and the bias silently starts completing the *bridges*, which is a
698
+ different claim about which species is a reactive intermediate and
699
+ almost certainly not the one that was wanted. It cannot be caught by
700
+ looking for an all-zero bias key -- a difunctional bridge accumulates
701
+ reactions perfectly well, so the key is non-zero and the ranking looks
702
+ healthy. What distinguishes the two cases is which side is the more
703
+ functional one, and that is fixed at setup.
704
+
705
+ Args:
706
+ adf (pandas.DataFrame): the global atom dataframe
707
+ bdf (pandas.DataFrame): the bond candidates for this iteration
708
+ """
709
+ if self.bias_side_checked: return
710
+ if not all(c in adf.columns for c in ('z','nreactions')): return
711
+ self.bias_side_checked=True
712
+ func=residue_functionality(adf)
713
+ a=bdf['ri'].map(func).dropna()
714
+ b=bdf['rj'].map(func).dropna()
715
+ if a.empty or b.empty: return
716
+ if a.max()>b.max():
717
+ 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.')
718
+
639
719
  # TODO: move to searchbonds.by; split into make_candidates() and apply_filters()
640
720
  def _searchbonds(self,TC:TopoCoord,RL:ReactionList,MD:MoleculeDict,stage=reaction_stage.cure,abs_max=0,apply_probabilities=False,reentry=False):
641
721
  """Manages the search for bonds.
@@ -749,6 +829,7 @@ class CureController:
749
829
  reaction_counts=self._completion_bias_counts(adf)
750
830
  bdf=rank_bond_candidates(bdf,reaction_counts)
751
831
  if reaction_counts is not None:
832
+ self._check_bias_side(adf,bdf)
752
833
  nrx=bdf['rj'].map(reaction_counts).fillna(0).astype(int)
753
834
  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())})')
754
835
  bdf['allowed']=[True for x in range(bdf.shape[0])]
@@ -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,12 +126,282 @@ 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,
149
+ n_preferred_out_of_angle, min_clearance_nm and the medians
150
+ """
151
+ if not placements:
152
+ return {'n_transferred': 0, 'n_direction_searched': 0,
153
+ 'n_below_target': 0, 'n_preferred_out_of_angle': 0,
154
+ 'min_clearance_nm': None}
155
+ gaps = np.array([p['clearance'] for p in placements], dtype=float)
156
+ searched = sum(1 for p in placements if not p['kept_o_h_direction'])
157
+ # why the preferred direction was abandoned matters as much as how often.
158
+ # A metric that rejects every preferred direction for a reason unrelated
159
+ # to crowding is what 2.6.0 shipped, and it read as a crowded box; this
160
+ # separates "the site was occupied" from "the O-H vector was not a
161
+ # placeable C-O-C angle", which would point at the angle window instead.
162
+ out_of_window = sum(1 for p in placements if not p.get('blind_in_window', True))
163
+ below = [p for p in placements if p['clearance'] < target]
164
+ logger.info(
165
+ f'triazine_to_cyanate_cap: placed {len(placements)} transferred caps '
166
+ f'({searched} needed a direction search); clearance min/median '
167
+ f'{gaps.min():.3f}/{float(np.median(gaps)):.3f} nm against a target of {target:.3f}'
168
+ )
169
+ blind = np.array([p['blind_clearance'] for p in placements
170
+ if p.get('blind_clearance') is not None], dtype=float)
171
+ if blind.size:
172
+ logger.info(
173
+ f'triazine_to_cyanate_cap: along the O-H vector alone these same caps '
174
+ f'would have had min/median {blind.min():.3f}/{float(np.median(blind)):.3f} nm, '
175
+ f'with {int((blind < 0.10).sum())} under 0.10 nm -- that is what placement '
176
+ f'did before the direction search existed, measured on this box'
177
+ )
178
+ if out_of_window:
179
+ logger.info(
180
+ f'triazine_to_cyanate_cap: {out_of_window} of {len(placements)} preferred '
181
+ f'O-H directions were outside the placeable C-O-C angle window and were '
182
+ f'searched away from for that reason rather than for crowding'
183
+ )
184
+ if below:
185
+ worst = sorted(below, key=lambda p: p['clearance'])[:5]
186
+ detail = ', '.join(f'O {int(p["o"])} at {p["clearance"]:.3f} nm' for p in worst)
187
+ logger.warning(
188
+ f'triazine_to_cyanate_cap: {len(below)} of {len(placements)} transferred '
189
+ f'caps could not reach {target:.3f} nm of clearance in any direction '
190
+ f'(worst: {detail}). The box is too crowded here for this many caps; '
191
+ f'if the following minimization fails with a huge Lennard-Jones term, '
192
+ f'this is why.'
193
+ )
194
+ # medians as well as minima: a single worst placement says whether this
195
+ # build is in danger, but correlating placement quality against outcomes
196
+ # across a series of runs needs a statistic that is not an extreme value
197
+ return {
198
+ 'n_transferred': len(placements),
199
+ 'n_direction_searched': searched,
200
+ 'n_below_target': len(below),
201
+ 'n_preferred_out_of_angle': out_of_window,
202
+ 'min_clearance_nm': float(gaps.min()),
203
+ 'median_clearance_nm': float(np.median(gaps)),
204
+ 'blind_min_clearance_nm': float(blind.min()) if blind.size else None,
205
+ 'blind_median_clearance_nm': float(np.median(blind)) if blind.size else None,
206
+ 'n_blind_would_overlap': int((blind < 0.10).sum()) if blind.size else None,
207
+ }
208
+
209
+
210
+ def _sphere_directions(n=48):
211
+ """``n`` roughly uniform unit vectors on the sphere, deterministically.
212
+
213
+ A Fibonacci spiral: no randomness, so a rebuild of the same system places
214
+ its caps identically.
215
+
216
+ Args:
217
+ n (int): how many directions to generate
218
+
219
+ Returns:
220
+ numpy.ndarray: (n, 3) array of unit vectors
221
+ """
222
+ k = np.arange(n) + 0.5
223
+ phi = np.arccos(1.0 - 2.0 * k / n)
224
+ theta = np.pi * (1.0 + 5.0 ** 0.5) * k
225
+ return np.stack([np.cos(theta) * np.sin(phi),
226
+ np.sin(theta) * np.sin(phi),
227
+ np.cos(phi)], axis=1)
228
+
229
+
230
+ def _placement_neighbors(o_xyz, background, background_idx, box,
231
+ bonded=(), locality=_PLACEMENT_LOCALITY):
232
+ """The atoms a cap hung on this oxygen actually has to stay clear of.
233
+
234
+ Two filters. Distance: an atom farther than ``locality`` from the oxygen
235
+ cannot constrain a group that reaches only ~0.25 nm from it, so it is not
236
+ worth scoring against. Identity: an atom the cap is *bonded* through is
237
+ not an obstacle, and leaving one in silently destroys the metric, because
238
+ its distance to the cap is fixed by the bond geometry rather than by how
239
+ crowded the site is.
240
+
241
+ Both members of ``bonded`` matter and for the same reason. The oxygen
242
+ itself sits at exactly ``oc_len`` from the cap carbon in *every* candidate
243
+ direction, so leaving it in pins :func:`_clearance` at 0.136 nm and the
244
+ search cannot tell directions apart at all. The oxygen's aryl carbon is
245
+ softer but has the same character: with it in, the reachable clearance is
246
+ bounded by the C-O-C geometry at 0.272 nm, so every comfortably-placed cap
247
+ reports that constant instead of a measurement and the median saturates.
248
+ A distance metric cannot do clash detection and bond-angle enforcement at
249
+ once; the angle is enforced separately, in :func:`_choose_cap_placement`.
250
+
251
+ Only *this* cap's bonded atoms are dropped. Every other cap's attachment
252
+ oxygen is a real atom in the way, as is every cap already placed -- those
253
+ carry an index of -1 and are never masked out here.
254
+
255
+ Args:
256
+ o_xyz (numpy.ndarray): position of the oxygen this cap attaches to
257
+ background (numpy.ndarray): (m, 3) candidate obstacle positions
258
+ background_idx (numpy.ndarray): (m,) global indices, -1 for already-placed cap atoms
259
+ bonded (iterable): global indices the cap is bonded through -- the oxygen and its aryl carbon
260
+ box (numpy.ndarray): orthorhombic box lengths, for minimum image
261
+ locality (float): nm; ignore anything farther than this from the oxygen
262
+
263
+ Returns:
264
+ numpy.ndarray: (k, 3) positions to pass to :func:`_choose_cap_placement`
265
+ """
266
+ if len(background) == 0:
267
+ return background
268
+ near = _min_image_dist(o_xyz, background, box) < locality
269
+ drop = {int(i) for i in bonded if i is not None}
270
+ if drop:
271
+ near &= ~np.isin(np.asarray(background_idx, dtype=int), list(drop))
272
+ return background[near]
273
+
274
+
275
+ def _clearance(c_xyz, n_xyz, neighbors, box):
276
+ """Smallest distance from either cap atom to any neighbouring atom.
277
+
278
+ Args:
279
+ c_xyz (numpy.ndarray): position of the cap carbon
280
+ n_xyz (numpy.ndarray): position of the cap nitrogen
281
+ neighbors (numpy.ndarray): (m, 3) positions to stay clear of
282
+ box (numpy.ndarray): orthorhombic box lengths, for minimum image
283
+
284
+ Returns:
285
+ float: the smallest such distance in nm, or inf if there are no neighbours
286
+ """
287
+ if neighbors is None or len(neighbors) == 0:
288
+ return float('inf')
289
+ return float(min(_min_image_dist(c_xyz, neighbors, box).min(),
290
+ _min_image_dist(n_xyz, neighbors, box).min()))
291
+
292
+
293
+ _MIN_COC_ANGLE = 90.0
294
+ _MAX_COC_ANGLE = 150.0
295
+ """degrees: the window of C-O-C angles a cap may be placed at. An aryl ether
296
+ sits near 120; this is deliberately generous, because placement is a starting
297
+ guess and the angle potential does the rest. What it excludes is the two ends
298
+ that are qualitatively wrong -- a cap folded back onto the ring it hangs off,
299
+ and a linear C-O-C, which is what a pure clearance search converges to since
300
+ antiparallel maximizes distance from the rest of the molecule."""
301
+
302
+
303
+ def _angle_window(directions, o_xyz, anchor_xyz,
304
+ min_angle=_MIN_COC_ANGLE, max_angle=_MAX_COC_ANGLE):
305
+ """Boolean mask of ``directions`` whose C-O-C angle is inside the window.
306
+
307
+ Args:
308
+ directions (numpy.ndarray): (n, 3) unit vectors from the oxygen
309
+ o_xyz (numpy.ndarray): the oxygen's position
310
+ anchor_xyz (numpy.ndarray): the aryl carbon's position, or None for no constraint
311
+ min_angle (float): degrees; below this the cap is folding onto the ring
312
+ max_angle (float): degrees; above this the ether is unphysically extended
313
+
314
+ Returns:
315
+ numpy.ndarray: (n,) boolean, all True when there is no anchor
316
+ """
317
+ d = np.atleast_2d(np.asarray(directions, dtype=float))
318
+ if anchor_xyz is None:
319
+ return np.ones(len(d), dtype=bool)
320
+ a = np.asarray(anchor_xyz, dtype=float) - np.asarray(o_xyz, dtype=float)
321
+ na = np.linalg.norm(a)
322
+ if na < 1e-8:
323
+ return np.ones(len(d), dtype=bool)
324
+ cosines = d @ (a / na)
325
+ return ((cosines <= np.cos(np.radians(min_angle))) &
326
+ (cosines >= np.cos(np.radians(max_angle))))
327
+
328
+
329
+ def _choose_cap_placement(o_xyz, ref_xyz, neighbors, box, oc_len=0.136,
330
+ cn_len=0.116, target=0.15, n_directions=48,
331
+ anchor_xyz=None):
332
+ """Place a transferred -C#N group in the clearest direction available.
333
+
334
+ The old O-H vector is tried first and kept if it is clear enough, so a
335
+ cap in open space lands exactly where it always did. Only when that
336
+ direction is occupied does this search the sphere -- which is the case
337
+ that used to produce a step-0 Lennard-Jones term around 1e15 and a
338
+ minimization that could not recover. Bond lengths are held fixed; only
339
+ the direction moves, so the chemistry is unchanged.
340
+
341
+ The search is over directions inside a C-O-C angle window rather than the
342
+ whole sphere. Clearance alone is maximized by a linear ether, since
343
+ antiparallel puts the cap as far as possible from the ring it hangs off,
344
+ so a pure clearance search drifts toward a geometry no aryl ether adopts.
345
+ The window says that explicitly instead of leaving it to a distance metric
346
+ that cannot express it; see :data:`_MIN_COC_ANGLE`.
347
+
348
+ Args:
349
+ o_xyz (numpy.ndarray): position of the bridge oxygen the cap attaches to
350
+ ref_xyz (numpy.ndarray): position defining the preferred direction, normally the O's about-to-be-deleted H
351
+ neighbors (numpy.ndarray): (m, 3) positions the cap must avoid
352
+ box (numpy.ndarray): orthorhombic box lengths, for minimum image
353
+ oc_len (float): O-C bond length in nm
354
+ cn_len (float): C#N bond length in nm
355
+ 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. ``neighbors`` must already have the cap's own bonded atoms removed (see :func:`_placement_neighbors`) or this number is meaningless -- with the attachment oxygen left in, every direction scores exactly ``oc_len``
356
+ n_directions (int): how many directions to try when the preferred one is occupied
357
+ anchor_xyz (numpy.ndarray): position of the oxygen's aryl carbon, defining the C-O-C angle; None disables the angular guard
358
+
359
+ Returns:
360
+ dict: 'c' and 'n' positions, 'clearance' achieved, 'kept_o_h_direction',
361
+ and 'blind_clearance' -- what the O-H direction alone would have given.
362
+ The last is free to compute, since that direction is tried first, and it
363
+ is the only way to measure on a real box what the old blind placement
364
+ was actually doing.
365
+ """
366
+ o = np.asarray(o_xyz, dtype=float)
367
+ c_xyz, n_xyz = _place_cyn_along(o, ref_xyz, oc_len=oc_len, cn_len=cn_len)
368
+ blind = _clearance(c_xyz, n_xyz, neighbors, box)
369
+ # the O-H direction is kept only if it is both clear enough and a sane
370
+ # C-O-C angle; for a real hydroxyl it always is the latter, but the
371
+ # fallback direction used when the O has no H need not be
372
+ blind_ok = bool(_angle_window((c_xyz - o) / oc_len, o, anchor_xyz)[0])
373
+ if blind_ok and blind >= target:
374
+ return {'c': c_xyz, 'n': n_xyz, 'clearance': blind,
375
+ 'kept_o_h_direction': True, 'blind_clearance': blind,
376
+ 'blind_in_window': True}
377
+ directions = _sphere_directions(n_directions)
378
+ allowed = directions[_angle_window(directions, o, anchor_xyz)]
379
+ # a window this wide always leaves a good fraction of the sphere, but a
380
+ # caller narrowing it should still get a placement rather than nothing
381
+ if len(allowed) == 0:
382
+ allowed = directions
383
+ best = blind if blind_ok else -1.0
384
+ if not blind_ok:
385
+ c_xyz, n_xyz = None, None
386
+ for u in allowed:
387
+ cc = o + u * oc_len
388
+ nn = cc + u * cn_len
389
+ gap = _clearance(cc, nn, neighbors, box)
390
+ if gap > best:
391
+ best, c_xyz, n_xyz = gap, cc, nn
392
+ if best >= target:
393
+ break
394
+ return {'c': c_xyz, 'n': n_xyz, 'clearance': best,
395
+ 'kept_o_h_direction': False, 'blind_clearance': blind,
396
+ 'blind_in_window': blind_ok}
397
+
398
+
125
399
  # ---------------------------------------------------------------------------
126
400
  # Main driver
127
401
  # ---------------------------------------------------------------------------
128
402
 
129
403
 
130
- def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True):
404
+ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True, placement=None):
131
405
  """Summarize crosslinker completion and log it.
132
406
 
133
407
  A crosslinker survives this repair only if every one of its sites is
@@ -142,6 +416,7 @@ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True):
142
416
  n_crosslinkers (int): number of crosslinker residues in the system
143
417
  n_incomplete (int): how many of them are being dismantled
144
418
  log (bool): emit the summary message; False when there is nothing to summarize
419
+ placement (dict): cap-placement summary from :func:`_report_placements`, merged into the result
145
420
 
146
421
  Returns:
147
422
  dict: n_crosslinkers, n_complete, n_dismantled, crosslinker_conversion
@@ -154,13 +429,16 @@ def _completion_stats(residue_name, n_crosslinkers, n_incomplete, log=True):
154
429
  f'{residue_name} residues are complete and survive repair; '
155
430
  f'crosslinker conversion {chi:.3f}'
156
431
  )
157
- return {
432
+ out = {
158
433
  'residue': residue_name,
159
434
  'n_crosslinkers': n_crosslinkers,
160
435
  'n_complete': n_complete,
161
436
  'n_dismantled': n_incomplete,
162
437
  'crosslinker_conversion': chi,
163
438
  }
439
+ if placement:
440
+ out.update(placement)
441
+ return out
164
442
 
165
443
 
166
444
  def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
@@ -287,34 +565,72 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
287
565
  ts.reassign_residue(TC, [cap['c'], cap['n']], cap_residue_name, new_resnum)
288
566
  ts.set_atom_attributes(TC, cap['c'], atomName='C1')
289
567
  ts.set_atom_attributes(TC, cap['n'], atomName='N1')
290
- cap_records.append({'c': cap['c'], 'n': cap['n'], 'o': target_o, 'resnum': new_resnum})
568
+ cap_records.append({'c': cap['c'], 'n': cap['n'], 'o': target_o,
569
+ 'resnum': new_resnum, 'free': cap['bonded_o'] is None})
291
570
  new_resnum += 1
292
571
 
293
572
  # 3d. for free-cap donations: relocate the CYN atoms next to their target O
294
- for rec in cap_records:
295
- cap_in_plans = next(
296
- (c for p in incomplete_plans for c in p['caps']
297
- if c['c'] == rec['c'] and c['n'] == rec['n']),
298
- None,
299
- )
300
- if cap_in_plans is None or cap_in_plans['bonded_o'] is not None:
301
- continue
302
- o_idx = rec['o']
303
- o_xyz = ts.positions(TC, [o_idx])[0]
304
- # use the (about-to-be-deleted) H on the O as the direction reference
305
- o_h_idx = _find_bonded_hydrogen(TC, o_idx)
306
- if o_h_idx is None:
307
- # no H to use as reference (shouldn't happen for a still-reactive O,
308
- # but if it does, just push the cap along +x by the rest length)
309
- ref_xyz = o_xyz + np.array([1.0, 0.0, 0.0])
310
- else:
311
- ref_xyz = ts.positions(TC, [o_h_idx])[0]
312
- h_to_delete.add(int(o_h_idx))
313
- c_xyz, n_xyz = _place_cyn_along(o_xyz, ref_xyz)
314
- ts.set_atom_attributes(TC, rec['c'],
315
- posX=float(c_xyz[0]), posY=float(c_xyz[1]), posZ=float(c_xyz[2]))
316
- ts.set_atom_attributes(TC, rec['n'],
317
- posX=float(n_xyz[0]), posY=float(n_xyz[1]), posZ=float(n_xyz[2]))
573
+ #
574
+ # This is the phase that fails catastrophically when it fails at all. A
575
+ # cap dropped blindly along the old O-H vector can land on top of a
576
+ # neighbour, and the resulting step-0 Lennard-Jones term -- of order 1e15
577
+ # kJ/mol -- is not something the following minimization recovers from.
578
+ # The count of caps to place here is an identity, (total reactive sites -
579
+ # bonds formed), so it rises as conversion falls: a low-conversion build
580
+ # places hundreds and is where this has been seen to kill runs.
581
+ #
582
+ # So each cap is placed against its local neighbourhood, and every cap
583
+ # already placed is part of the neighbourhood the next one sees.
584
+ free_records = [rec for rec in cap_records if rec['free']]
585
+ placements = []
586
+ placement_summary = None
587
+ if free_records:
588
+ box = TC.Coordinates.box.diagonal()
589
+ target_clearance = float(spec.get('cap_min_clearance', 0.15))
590
+ # the O's H is consumed in forming the cap; collect them all up front
591
+ # so that a cap placed early does not dodge an atom about to vanish
592
+ for rec in free_records:
593
+ h = _find_bonded_hydrogen(TC, rec['o'])
594
+ rec['o_h'] = h
595
+ # the aryl carbon on the far side of the O: excluded from the
596
+ # clearance metric, since its distance is set by bond geometry,
597
+ # and used instead as the anchor for the C-O-C angle
598
+ rec['o_anchor'] = _find_bonded_heavy(TC, rec['o'])
599
+ if h is not None:
600
+ h_to_delete.add(int(h))
601
+ moving = {int(rec['c']) for rec in free_records} | {int(rec['n']) for rec in free_records}
602
+ A = TC.Coordinates.A
603
+ going = moving | {int(x) for x in h_to_delete}
604
+ staying = A.loc[~A['globalIdx'].isin(going),
605
+ ['globalIdx', 'posX', 'posY', 'posZ']]
606
+ # indices travel alongside the positions so each cap can drop the
607
+ # atoms it is bonded through; placed caps get -1 and are never dropped
608
+ background_idx = staying['globalIdx'].to_numpy(dtype=int)
609
+ background = staying[['posX', 'posY', 'posZ']].to_numpy(dtype=float)
610
+ for rec in free_records:
611
+ o_xyz = ts.positions(TC, [rec['o']])[0]
612
+ if rec['o_h'] is None:
613
+ # no H to take a direction from (shouldn't happen for a
614
+ # still-reactive O); any direction will do as a starting guess
615
+ ref_xyz = o_xyz + np.array([1.0, 0.0, 0.0])
616
+ else:
617
+ ref_xyz = ts.positions(TC, [rec['o_h']])[0]
618
+ local = _placement_neighbors(o_xyz, background, background_idx, box,
619
+ bonded=(rec['o'], rec['o_anchor']))
620
+ anchor_xyz = (ts.positions(TC, [rec['o_anchor']])[0]
621
+ if rec['o_anchor'] is not None else None)
622
+ placed = _choose_cap_placement(o_xyz, ref_xyz, local, box,
623
+ target=target_clearance,
624
+ anchor_xyz=anchor_xyz)
625
+ c_xyz, n_xyz = placed['c'], placed['n']
626
+ ts.set_atom_attributes(TC, rec['c'],
627
+ posX=float(c_xyz[0]), posY=float(c_xyz[1]), posZ=float(c_xyz[2]))
628
+ ts.set_atom_attributes(TC, rec['n'],
629
+ posX=float(n_xyz[0]), posY=float(n_xyz[1]), posZ=float(n_xyz[2]))
630
+ background = np.vstack([background, c_xyz, n_xyz])
631
+ background_idx = np.concatenate([background_idx, [-1, -1]])
632
+ placements.append({'o': rec['o'], **{k: v for k, v in placed.items() if k not in ('c', 'n')}})
633
+ placement_summary = _report_placements(placements, target_clearance)
318
634
 
319
635
  # ---- Phase 4: splice template params (forms BPA-O-C bond with full
320
636
  # angle/dihedral/pair entries from the cap_template molecule) ----
@@ -362,7 +678,8 @@ def triazine_to_cyanate_cap(TC, moldict, spec, reactions):
362
678
  msg='triazine_to_cyanate_cap post-deletion rebalance',
363
679
  )
364
680
 
365
- return _completion_stats(cl['residue'], len(cl_residues), len(incomplete_plans))
681
+ return _completion_stats(cl['residue'], len(cl_residues), len(incomplete_plans),
682
+ placement=placement_summary)
366
683
 
367
684
 
368
685
  # ---------------------------------------------------------------------------
@@ -393,6 +710,19 @@ def _find_bonded_hydrogen(TC, idx):
393
710
  return None
394
711
 
395
712
 
713
+ def _find_bonded_heavy(TC, idx):
714
+ """Return globalIdx of the first non-hydrogen atom bonded to ``idx``, or None.
715
+
716
+ For a bridge oxygen about to take a cap this is its aryl carbon, which is
717
+ the anchor the C-O-C angle is measured against.
718
+ """
719
+ for nbr in TC.Topology.bondlist.partners_of(int(idx)):
720
+ name = ts.get_attr(TC, nbr, 'atomName')
721
+ if not str(name).upper().startswith('H'):
722
+ return int(nbr)
723
+ return None
724
+
725
+
396
726
  def _greedy_match(TC, free_caps, unreacted_o, search_radius):
397
727
  """Match each free cap to its nearest available unreacted bridge-O.
398
728
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.5.0
3
+ Version: 2.6.1
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,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=lOI5mbrdnez-llynuFg6wgd_ZhKwAo5Nd918FvLSexE,55430
15
+ htpolynet/core/runtime.py,sha256=uyUXLQFRw3Wi7GT_0KahsqYPeJvXbgS-vHXLq-h_HEI,56066
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=Mkx72GzcknanmEDeMkashm1C7MbWshu86BBwQo9EiWE,39554
20
+ htpolynet/cure/curecontroller.py,sha256=smuAJYQYysSyIw3QywpwUCzkMwYE1N_i4ZyGR7NvXoU,44383
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
@@ -38,7 +38,7 @@ 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
40
  htpolynet/repair/__init__.py,sha256=cP3i-P-Wc6s0MgoFDp63kbLomM-ti3mMGEgeQzUVKuY,1740
41
- htpolynet/repair/cyanate_cap.py,sha256=JaGLU2_ttzc9jGm7NSsboOs4SBnFDyNBc2v_G9aZxdg,19298
41
+ htpolynet/repair/cyanate_cap.py,sha256=VdKxBs3oXLBiTZ4eW6oCKCbgOoeowTOdSwj21cSll3g,36476
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
@@ -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.5.0.dist-info/METADATA,sha256=Juj2GYFIHR_dLQY_1xvSyB0Yu8WfYy_zULfaEtCj6qo,6557
100
- htpolynet-2.5.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
101
- htpolynet-2.5.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
102
- htpolynet-2.5.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
103
- htpolynet-2.5.0.dist-info/RECORD,,
99
+ htpolynet-2.6.1.dist-info/METADATA,sha256=6a8-ltjHSemovupK6L8OJhgOfMMeVDCYj3L-oogwRx4,6557
100
+ htpolynet-2.6.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
101
+ htpolynet-2.6.1.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
102
+ htpolynet-2.6.1.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
103
+ htpolynet-2.6.1.dist-info/RECORD,,