HTPolyNet 2.11.5__py3-none-any.whl → 2.12.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.
@@ -0,0 +1,226 @@
1
+ """Finds bonds threaded through rings in a finished network.
2
+
3
+ htpolynet can refuse to *create* a threading during a ring cure, and until now it could
4
+ not *tell you whether one is there*. That asymmetry is the reason this exists: a
5
+ preventive check whose effect cannot be measured with the same tool is hard to trust,
6
+ and the numbers that justified those filters all came from scripts outside the package.
7
+
8
+ Nothing here is specific to cyanate esters. Any network built by dragging monomers
9
+ together can thread a bond through a ring, and htpolynet builds those by construction.
10
+
11
+ The geometry lives in :mod:`htpolynet.geometry.piercing`, shared with the ring cure's own
12
+ filters so a measurement and the thing it measures cannot drift apart.
13
+
14
+ Author: Cameron F. Abrams <cfa22@drexel.edu>
15
+ """
16
+ import logging
17
+
18
+ import networkx as nx
19
+ import numpy as np
20
+
21
+ from scipy.spatial import cKDTree
22
+
23
+ from ..core.topology import _element_of
24
+ from ..geometry.piercing import pierces_ring, ring_frame
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def _bounded_path(G, u, v, max_depth):
30
+ """Shortest path from u to v of at most `max_depth` edges, or None."""
31
+ if u not in G or v not in G:
32
+ return None
33
+ prev, frontier = {u: None}, [u]
34
+ for _ in range(max_depth):
35
+ nxt = []
36
+ for a in frontier:
37
+ for b in G[a]:
38
+ if b in prev:
39
+ continue
40
+ prev[b] = a
41
+ if b == v:
42
+ path, cur = [], v
43
+ while cur is not None:
44
+ path.append(cur)
45
+ cur = prev[cur]
46
+ return path[::-1]
47
+ nxt.append(b)
48
+ if not nxt:
49
+ return None
50
+ frontier = nxt
51
+ return None
52
+
53
+
54
+ def detect_rings(bonds, max_size=8):
55
+ """Smallest ring through each bond, for a topology with no ring list of its own.
56
+
57
+ A build made by htpolynet carries its rings already; this is the fallback for a bare
58
+ top/gro pair. Enumerating all chordless cycles is not an option --- on a percolated
59
+ network it does not finish in reasonable time --- so this takes the shortest
60
+ alternative path between each bonded pair, which gives the smallest ring through
61
+ that bond and nothing larger.
62
+
63
+ Args:
64
+ bonds (pandas.DataFrame): with ai and aj columns
65
+ max_size (int): largest ring to look for
66
+
67
+ Returns:
68
+ list: rings, each a list of atom indices in cyclic order
69
+ """
70
+ G = nx.Graph()
71
+ G.add_edges_from((int(r.ai), int(r.aj)) for r in bonds.itertuples())
72
+ seen, out = set(), []
73
+ for u, v in list(G.edges()):
74
+ G.remove_edge(u, v)
75
+ # depth-limited on purpose: an unbounded search on a percolated network walks
76
+ # the whole component for every bond that is not in a small ring, which is most
77
+ # of them
78
+ path = _bounded_path(G, u, v, max_size - 1)
79
+ G.add_edge(u, v)
80
+ if path is None:
81
+ continue
82
+ key = frozenset(path)
83
+ if key in seen:
84
+ continue
85
+ seen.add(key)
86
+ out.append([int(x) for x in path])
87
+ return out
88
+
89
+
90
+ def ring_composition(ring, element_of):
91
+ """A ring's composition as a formula string, heaviest-count first.
92
+
93
+ Deliberately general: a triazine reads ``C3N3`` and a benzene ``C6`` without this
94
+ module knowing either name. Classify on the whole ring --- keying on residue count
95
+ or on a truncated printout are both ways this has been got wrong.
96
+ """
97
+ counts = {}
98
+ for i in ring:
99
+ e = element_of.get(int(i), '?')
100
+ counts[e] = counts.get(e, 0) + 1
101
+ return ''.join(f'{e}{counts[e]}' for e in sorted(counts, key=lambda x: (-counts[x], x)))
102
+
103
+
104
+ def find_piercings(TC, max_ring=8, margin=0.3):
105
+ """Every bond that passes through a ring.
106
+
107
+ Args:
108
+ TC (TopoCoord): the system, with coordinates loaded
109
+ max_ring (int): largest ring to consider when detecting rings
110
+ margin (float): how far beyond a ring's radius to look for bonds, in nm
111
+
112
+ Returns:
113
+ list: one dict per piercing, with the ring, its composition, the bond, whether
114
+ the bond belongs to a residue of the ring, and the geometry of the crossing
115
+ """
116
+ A = TC.Coordinates.A
117
+ positions = {int(r.globalIdx): np.array([r.posX, r.posY, r.posZ]) for r in A.itertuples()}
118
+ box = np.asarray(TC.Coordinates.box.diagonal(), dtype=float)
119
+ at = TC.Topology.D['atoms']
120
+ element_of = {int(r.nr): _element_of(r.atom, r.type) for r in at.itertuples()}
121
+ resnr_of = {int(r.nr): int(r.resnr) for r in at.itertuples()}
122
+ bonds = TC.Topology.D['bonds']
123
+
124
+ rings = [[int(x) for x in r.idx] for r in (getattr(TC.Topology, 'rings', None) or [])]
125
+ rings = [r for r in rings if 3 <= len(r) <= max_ring]
126
+ if not rings:
127
+ logger.info('No ring list on this topology; detecting rings from the bond graph')
128
+ rings = detect_rings(bonds, max_size=max_ring)
129
+ logger.info(f'Scanning {len(rings)} ring(s) against {bonds.shape[0]} bond(s)')
130
+
131
+ ids = np.fromiter(positions.keys(), dtype=int, count=len(positions))
132
+ pts = np.array([positions[i] for i in ids], dtype=float)
133
+ tree = cKDTree(np.mod(pts, box), boxsize=box)
134
+ bonds_of = {}
135
+ for r in bonds.itertuples():
136
+ ai, aj = int(r.ai), int(r.aj)
137
+ bonds_of.setdefault(ai, []).append((ai, aj))
138
+ bonds_of.setdefault(aj, []).append((ai, aj))
139
+
140
+ out = []
141
+ for ring in rings:
142
+ frame = ring_frame(ring, positions, box)
143
+ if frame is None:
144
+ continue
145
+ _, O, _, radius = frame
146
+ near = tree.query_ball_point(np.mod(O, box), radius + margin)
147
+ ring_set, seen = set(ring), set()
148
+ for j in near:
149
+ a = int(ids[j])
150
+ if a in ring_set:
151
+ continue
152
+ for bond in bonds_of.get(a, ()):
153
+ key = (min(bond), max(bond))
154
+ if key in seen:
155
+ continue
156
+ seen.add(key)
157
+ hit = pierces_ring(ring, bond, positions, box)
158
+ if hit is None:
159
+ continue
160
+ ring_res = {resnr_of.get(i) for i in ring}
161
+ out.append({'ring': ring, 'composition': ring_composition(ring, element_of),
162
+ 'bond': key, 'self': resnr_of.get(key[0]) in ring_res
163
+ or resnr_of.get(key[1]) in ring_res,
164
+ **{k: v for k, v in hit.items() if k != 'point'}})
165
+ return out
166
+
167
+
168
+ def format_report(piercings, overlong=0.2):
169
+ """A human-readable summary, correlating piercings with over-long bonds."""
170
+ if not piercings:
171
+ return 'No bond passes through a ring in this system.'
172
+ lines = [f'{len(piercings)} bond(s) pass through a ring:', '']
173
+ by_comp = {}
174
+ for p in piercings:
175
+ by_comp[p['composition']] = by_comp.get(p['composition'], 0) + 1
176
+ lines.append(' by ring composition: '
177
+ + ', '.join(f'{k} {v}' for k, v in sorted(by_comp.items())))
178
+ n_self = sum(1 for p in piercings if p['self'])
179
+ lines.append(f' {n_self} by a bond of a residue in the ring, '
180
+ f'{len(piercings) - n_self} by a foreign residue')
181
+ n_long = sum(1 for p in piercings if p['length'] > overlong)
182
+ lines.append(f' {n_long} of {len(piercings)} piercing bond(s) are longer than '
183
+ f'{overlong} nm, which is longer than any real bond')
184
+ lines.append('')
185
+ lines.append(' (from-normal 0 deg means the bond runs straight through the ring)')
186
+ lines.append('')
187
+ lines.append(' ring composition bond offset frac from-norm length')
188
+ for p in sorted(piercings, key=lambda x: -x['length']):
189
+ r = ','.join(str(x) for x in p['ring'][:3]) + '...'
190
+ lines.append(f' {r:<13} {p["composition"]:<12} '
191
+ f'{p["bond"][0]}-{p["bond"][1]:<10} '
192
+ f'{p["offset"] * 10:6.2f} {p["offset_frac"]:5.2f} '
193
+ f'{p["angle_from_normal"]:9.1f} {p["length"] * 10:6.2f} (A, deg)')
194
+ return '\n'.join(lines)
195
+
196
+
197
+ def piercings(args):
198
+ """CLI handler for ``htpolynet piercings``.
199
+
200
+ Args:
201
+ args (argparse.Namespace): parsed arguments with ``.top``, ``.gro``,
202
+ ``.max_ring``, and optional ``.json``
203
+ """
204
+ import json
205
+ import os
206
+
207
+ from ..core.topocoord import TopoCoord
208
+
209
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
210
+ for f in (args.top, args.gro):
211
+ if not os.path.exists(f):
212
+ logger.error(f'{f} not found')
213
+ raise SystemExit(1)
214
+ try:
215
+ TC = TopoCoord(topfilename=args.top, grofilename=args.gro)
216
+ found = find_piercings(TC, max_ring=args.max_ring)
217
+ except Exception as e:
218
+ logger.error(f'Piercing analysis failed: {e}')
219
+ raise SystemExit(1)
220
+ print(format_report(found))
221
+ if getattr(args, 'json', None):
222
+ with open(args.json, 'w') as f:
223
+ json.dump([{k: (list(v) if isinstance(v, tuple) else v)
224
+ for k, v in p.items()} for p in found], f, indent=2)
225
+ logger.info(f'Wrote {args.json}')
226
+ raise SystemExit(1 if found else 0)
htpolynet/cli.py CHANGED
@@ -25,6 +25,7 @@ from .utils.banner import banner_message
25
25
  from .utils.inputcheck import input_check
26
26
  from .utils.logsetup import setup_logging
27
27
  from .utils.stringthings import my_logger
28
+ from .analysis.piercings import piercings
28
29
  from .utils.vmd_viz import make_viz
29
30
 
30
31
  logger = logging.getLogger(__name__)
@@ -292,6 +293,7 @@ def cli():
292
293
  ('analyze', analyze, "perform 'gmx <command>' style analyses specified in the config file"),
293
294
  ('gen-slurm-script', gen_slurm_script, 'generate a SLURM submission script for running htpolynet on a cluster'),
294
295
  ('make-viz', make_viz, 'regenerate VMD viz files (.viz.psf + .viz.tcl) from an existing gromacs top + gro pair'),
296
+ ('piercings', piercings, 'report any bond threaded through a ring in a gromacs top + gro pair; exits 1 if any are found'),
295
297
  ('setup-claude', setup_claude, "install htpolynet's Claude Code skill so an agent can drive htpolynet"),
296
298
  ]
297
299
 
@@ -327,6 +329,11 @@ def cli():
327
329
  cp['make-viz'].add_argument('-grx', type=str, default=None, help='input htpolynet .grx (default: auto-detect <gro-stem>.grx; needed for the constituent-selection macros)')
328
330
  cp['make-viz'].add_argument('-prefix', type=str, default=None, help='output basename; the .viz.psf, .viz.tcl, and .viz.macros.tcl are written next to the input gro (default: stem of -gro)')
329
331
 
332
+ cp['piercings'].add_argument('-top', type=str, default='final.top', help='input gromacs topology file (default: final.top)')
333
+ cp['piercings'].add_argument('-gro', type=str, default='final.gro', help='input gromacs coordinate file (default: final.gro)')
334
+ cp['piercings'].add_argument('-max-ring', dest='max_ring', type=int, default=8, help='largest ring to consider when the topology carries no ring list (default: 8)')
335
+ cp['piercings'].add_argument('-json', type=str, default=None, help='also write the findings to this JSON file')
336
+
330
337
  cp['setup-claude'].add_argument('--skills-dir', type=str, default='~/.claude/skills',
331
338
  help='skills directory to install into (default: %(default)s); use ./.claude/skills to scope the skill to one project')
332
339
  cp['setup-claude'].add_argument('--force', default=False, action='store_true', help='overwrite an existing installed skill')
htpolynet/core/runtime.py CHANGED
@@ -706,11 +706,15 @@ class Runtime:
706
706
  rc.state.iter += 1
707
707
  continue
708
708
  bdf = triple_bonds_dataframe(chosen, sites, R.product, order=R.bonds[0].get('order', 1))
709
+ # what these monomers already thread, so only what the ladder creates counts
710
+ before_threading = rc.threading_census(TC, bdf, chosen)
709
711
  work = rc.close_rings(TC, bdf, gromacs_dict=gromacs_dict)
710
712
  # a ring the ladder could not pull shut would be bonded long and stay that way
711
713
  bdf, chosen = rc.accept(bdf, work, chosen)
712
714
  # now that the loop is nearly ring-sized, ask what it actually encloses
713
715
  bdf, chosen = rc.reject_threaded(TC, bdf, chosen)
716
+ # and the converse: did the drag push one of their own bonds through a ring
717
+ bdf, chosen = rc.reject_new_threading(TC, bdf, chosen, before_threading)
714
718
  if not chosen:
715
719
  rc.state.iter += 1
716
720
  continue
@@ -27,9 +27,10 @@ import yaml
27
27
  from ..analysis.plot import trace
28
28
  from ..core import projectfilesystem as pfs
29
29
  from ..core.productsplice import map_product_from_template
30
- from ..cure.triplesearch import (bonds_by_atom, candidate_triples, drop_threaded,
30
+ from ..cure.triplesearch import (_mic, bonds_by_atom, candidate_triples, drop_threaded,
31
31
  reactive_sites, residue_map, ring_threading_bonds,
32
- select_disjoint, site_name_maps)
32
+ rings_threaded_by, select_disjoint, site_name_maps)
33
+ from ..geometry.ring import Ring
33
34
  from ..external.gromacs import mdp_modify
34
35
  from ..repair.topology_surgery import neutralize_touched_fragments
35
36
 
@@ -112,6 +113,7 @@ class RingController:
112
113
  'min_rings_per_iteration': 4,
113
114
  'reject_threaded_rings': True,
114
115
  'prefilter_threaded_candidates': False,
116
+ 'reject_new_threading': True,
115
117
  'same_molecule': False,
116
118
  'same_residue': False,
117
119
  'relax': [{'ensemble': 'min'},
@@ -420,6 +422,110 @@ class RingController:
420
422
  keep.append(n)
421
423
  return self._keep_rings(bdf, chosen, keep)
422
424
 
425
+ def _system_rings(self, TC, positions, box):
426
+ """The system's known rings, with a centroid each for cheap proximity filtering.
427
+
428
+ ``Topology.rings`` is built once per molecule template and replicated; nothing
429
+ updates it during a cure, which is why :meth:`form_rings` now registers each
430
+ triazine it makes. Before that it held only the rings monomers were built with
431
+ --- overwhelmingly phenyls.
432
+ """
433
+ out = []
434
+ for r in getattr(TC.Topology, 'rings', []) or []:
435
+ idx = [int(x) for x in r.idx]
436
+ if len(idx) < 3 or any(i not in positions for i in idx):
437
+ continue
438
+ anchor_pos = positions[idx[0]]
439
+ pts = np.array([anchor_pos + _mic(positions[i] - anchor_pos, box) for i in idx])
440
+ out.append((idx, pts.mean(axis=0)))
441
+ return out
442
+
443
+ def threading_census(self, TC, bdf, chosen):
444
+ """What the participating monomers' bonds already thread, per candidate ring.
445
+
446
+ Taken before the closure ladder and again after it, so only threadings the drag
447
+ *created* count against a candidate. Without the before-picture a monomer that
448
+ arrived from packing already threaded through a phenyl would be refused every
449
+ reaction forever, silently, and htpolynet-study found one of those.
450
+
451
+ Returns:
452
+ dict: triple number -> set of (ring key, bond) currently threaded
453
+ """
454
+ if not self.dicts['reject_new_threading'] or not chosen or bdf.empty:
455
+ return {}
456
+ A = TC.Coordinates.A
457
+ positions = {int(r.globalIdx): np.array([r.posX, r.posY, r.posZ])
458
+ for r in A.itertuples()}
459
+ box = np.asarray(TC.Coordinates.box.diagonal(), dtype=float)
460
+ rings = self._system_rings(TC, positions, box)
461
+ if not rings:
462
+ return {}
463
+ centroids = np.array([c for _, c in rings])
464
+ bonds_of = bonds_by_atom(TC.Topology.D['bonds'])
465
+ res_atoms = {}
466
+ for r in A.itertuples():
467
+ res_atoms.setdefault(int(r.resNum), []).append(int(r.globalIdx))
468
+
469
+ census = {}
470
+ for t in sorted(set(int(x) for x in bdf['triple'])):
471
+ rows = bdf[bdf['triple'] == t]
472
+ resids = {int(x) for x in rows['ri']} | {int(x) for x in rows['rj']}
473
+ atoms = [a for rn in resids for a in res_atoms.get(rn, []) if a in positions]
474
+ if not atoms:
475
+ continue
476
+ pts = np.array([positions[a] for a in atoms])
477
+ here = pts.mean(axis=0)
478
+ span = float(np.linalg.norm(_mic(pts - here, box), axis=1).max())
479
+ near = np.linalg.norm(_mic(centroids - here, box), axis=1) <= span + 1.0
480
+ bonds = set()
481
+ for a in atoms:
482
+ bonds.update(bonds_of.get(a, ()))
483
+ census[t] = rings_threaded_by(bonds,
484
+ [rings[i][0] for i in np.flatnonzero(near)],
485
+ positions, box)
486
+ return census
487
+
488
+ def reject_new_threading(self, TC, bdf, chosen, before):
489
+ """Drops a ring whose closure ladder pushed a monomer through an existing ring.
490
+
491
+ :meth:`reject_threaded` asks whether the new ring would close around a bond.
492
+ This asks the converse: whether dragging these three monomers together has run
493
+ one of *their* bonds through a ring that was already there. Both happen.
494
+ htpolynet-study scanned ten builds and found the second kind is mostly phenyls,
495
+ which outnumber triazines about six to one here, and that two of three were made
496
+ by the cure rather than by packing -- one appearing in the same iteration as a
497
+ triazine piercing, which is what identifies it as one event.
498
+
499
+ Declining does not itself pull the monomer back out. What it prevents is the
500
+ threading being made permanent: without the ring bonds the dragged monomers have
501
+ nothing holding them, and the relaxation that follows can undo what the
502
+ restraints did.
503
+
504
+ Args:
505
+ TC (TopoCoord): the system
506
+ bdf (pandas.DataFrame): this iteration's bonds, three rows per ring
507
+ chosen (list): the rings still standing
508
+ before (dict): the census taken before the ladder
509
+
510
+ Returns:
511
+ tuple: (bdf, chosen) without the rings that created a threading
512
+ """
513
+ if not self.dicts['reject_new_threading'] or not chosen:
514
+ return bdf, chosen
515
+ after = self.threading_census(TC, bdf, chosen)
516
+ keep = []
517
+ for n in range(len(chosen)):
518
+ created = after.get(n, set()) - before.get(n, set())
519
+ if created:
520
+ ring_key, bond = sorted(created)[0]
521
+ logger.info(f'Iteration {self.state.iter}: declining a ring whose closure '
522
+ f'pulled bond {bond[0]}-{bond[1]} through the existing '
523
+ f'{len(ring_key)}-ring at {ring_key[0]}; that monomer would be '
524
+ f'threaded for good once the ring formed')
525
+ continue
526
+ keep.append(n)
527
+ return self._keep_rings(bdf, chosen, keep)
528
+
423
529
  def relax(self, TC, gromacs_dict=None):
424
530
  """Eases a freshly closed ring's bonds in, and lets the box respond.
425
531
 
@@ -478,7 +584,11 @@ class RingController:
478
584
  only ever grows. Measured with `relax` alone and no equilibration, a ring cure's
479
585
  box expands thermally for six iterations to +28% in volume and then comes back
480
586
  down as the network forms, the two legs nearly cancelling: path 0.4104 nm for a
481
- net of -0.0038 nm. A cure is not just shrinkage -- the hot stages enlarge the
587
+ net of -0.0038 nm. Those figures are RETRACTED as of 2.11.5 --- they were
588
+ produced by this stage and :meth:`relax` running against the ladder topology,
589
+ restraints loaded and rings unbonded, so the box was responding to the wrong
590
+ system. They are left here only because the shape of the argument survives:
591
+ a cure is not just shrinkage. A cure is not just shrinkage -- the hot stages enlarge the
482
592
  box and the cold stage pulls it back -- which is why path length rather than net
483
593
  is the statistic to look at, and why the surrogate route travels three to nine
484
594
  times further in box length than it ends up moving.
@@ -605,6 +715,10 @@ class RingController:
605
715
  touched.update(stats['atoms'])
606
716
  # the splice replaces charges wholesale over three residues at a time, so the
607
717
  # molecules it touched have to be brought back to neutral
718
+ # Topology.rings is template-derived and nothing else updates it, so a triazine
719
+ # formed here is invisible to every ring-aware check until it is registered
720
+ for n in range(len(chosen)):
721
+ TC.Topology.rings.append(Ring(_ring_atoms(bdf, n)))
608
722
  neutralize_touched_fragments(TC, touched)
609
723
  for r in bdf.itertuples():
610
724
  for idx in (int(r.ai), int(r.aj)):
@@ -17,6 +17,8 @@ import pandas as pd
17
17
 
18
18
  from scipy.spatial import cKDTree
19
19
 
20
+ from ..geometry.piercing import segment_pierces_triangle
21
+
20
22
  logger = logging.getLogger(__name__)
21
23
 
22
24
 
@@ -155,26 +157,6 @@ def candidate_triples(sites, positions, radius, box, same_molecule=False, same_r
155
157
  return out
156
158
 
157
159
 
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
160
  def ring_threading_bonds(ring, positions, bonds_of, box, margin=0.3):
179
161
  """Existing bonds that pass through the loop a candidate ring would close.
180
162
 
@@ -232,12 +214,63 @@ def ring_threading_bonds(ring, positions, bonds_of, box, margin=0.3):
232
214
  p1 = p0 + _mic(np.asarray(positions[aj], dtype=float)
233
215
  - np.asarray(positions[ai], dtype=float), box)
234
216
  for k in range(len(P)):
235
- if _segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]):
217
+ if segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]) is not None:
236
218
  out.append((ai, aj))
237
219
  break
238
220
  return out
239
221
 
240
222
 
223
+ def rings_threaded_by(bond_pairs, ring_atom_lists, positions, box, margin=0.3):
224
+ """Which of `ring_atom_lists` each of `bond_pairs` passes through.
225
+
226
+ The mirror of :func:`ring_threading_bonds`: there a prospective ring is tested
227
+ against the bonds around it, here existing rings are tested against bonds that have
228
+ just been moved. A ring cure needs both, because dragging three monomers together
229
+ can push one of their own backbones through a ring that was already there --- a
230
+ phenyl, usually, since those outnumber triazines about six to one in these systems.
231
+
232
+ Args:
233
+ bond_pairs (iterable): (ai, aj) bonds to test
234
+ ring_atom_lists (iterable): existing rings, each a list of atoms in cyclic order
235
+ positions (dict): global atom index -> position, in nm
236
+ box (array-like): box diagonal, in nm
237
+ margin (float): how far beyond a ring's own radius to consider a bond, in nm
238
+
239
+ Returns:
240
+ set: (ring key, bond) pairs found threaded, where the ring key is its sorted
241
+ atom tuple so the result can be compared between two moments in time
242
+ """
243
+ box = np.asarray(box, dtype=float)
244
+ out = set()
245
+ pairs = [(int(a), int(b)) for a, b in bond_pairs]
246
+ for ring in ring_atom_lists:
247
+ ring = [int(x) for x in ring]
248
+ if any(i not in positions for i in ring):
249
+ continue
250
+ anchor = np.asarray(positions[ring[0]], dtype=float)
251
+ P = np.array([anchor + _mic(np.asarray(positions[i], dtype=float) - anchor, box)
252
+ for i in ring])
253
+ O = P.mean(axis=0)
254
+ reach = float(np.linalg.norm(P - O, axis=1).max()) + margin
255
+ ring_set = set(ring)
256
+ key = tuple(sorted(ring))
257
+ for ai, aj in pairs:
258
+ if ai in ring_set or aj in ring_set:
259
+ continue
260
+ if ai not in positions or aj not in positions:
261
+ continue
262
+ p0 = anchor + _mic(np.asarray(positions[ai], dtype=float) - anchor, box)
263
+ if float(np.linalg.norm(p0 - O)) > reach + margin:
264
+ continue
265
+ p1 = p0 + _mic(np.asarray(positions[aj], dtype=float)
266
+ - np.asarray(positions[ai], dtype=float), box)
267
+ for k in range(len(P)):
268
+ if segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]) is not None:
269
+ out.add((key, (min(ai, aj), max(ai, aj))))
270
+ break
271
+ return out
272
+
273
+
241
274
  def bonds_by_atom(bonds):
242
275
  """Inverts a bond table into {atom: [(ai, aj), ...]}, for threading lookups."""
243
276
  out = {}
@@ -0,0 +1,120 @@
1
+ """Whether a bond passes through a ring.
2
+
3
+ One question asked in three places: the ring cure asks it forward (would this new ring
4
+ close around a bond?) and backward (did dragging these monomers push a bond through a
5
+ ring already there?), and the analysis asks it of a finished network. The geometry is
6
+ the same each time and lives here so those three cannot drift apart.
7
+
8
+ A ring is treated as a fan of triangles from its centroid rather than as a plane,
9
+ because the thing being tested is not always flat: at candidate time in a ring cure it
10
+ is three reactive groups a search radius apart, and even a real ring puckers.
11
+
12
+ **Image before you average.** Every ring atom is brought into the same periodic image as
13
+ an anchor atom before the centroid is taken. A centroid of raw wrapped coordinates puts
14
+ the centre of any boundary-straddling ring in the middle of the box and its triangle fan
15
+ across the whole cell, which reports a piercing for nearly everything nearby. About 15%
16
+ of rings straddle a boundary in a typical crosslinked system, so this is the normal case
17
+ rather than a corner one: one detector written without it reported 212 piercings in an
18
+ uncured melt, where the true answer is zero by construction.
19
+
20
+ Author: Cameron F. Abrams <cfa22@drexel.edu>
21
+ """
22
+ import numpy as np
23
+
24
+
25
+ def mic(r, box):
26
+ """Minimum-image displacement."""
27
+ box = np.asarray(box, dtype=float)
28
+ return r - np.round(r / box) * box
29
+
30
+
31
+ def segment_pierces_triangle(p0, p1, a, b, c, eps=1e-12):
32
+ """Moller-Trumbore, restricted to a segment rather than an infinite ray.
33
+
34
+ Returns:
35
+ float or None: the fraction along p0->p1 at which it crosses, or None
36
+ """
37
+ e1, e2, d = b - a, c - a, p1 - p0
38
+ h = np.cross(d, e2)
39
+ det = float(np.dot(e1, h))
40
+ if abs(det) < eps:
41
+ return None
42
+ inv = 1.0 / det
43
+ s = p0 - a
44
+ u = inv * float(np.dot(s, h))
45
+ if u < 0.0 or u > 1.0:
46
+ return None
47
+ q = np.cross(s, e1)
48
+ v = inv * float(np.dot(d, q))
49
+ if v < 0.0 or u + v > 1.0:
50
+ return None
51
+ t = inv * float(np.dot(e2, q))
52
+ return t if 0.0 < t < 1.0 else None
53
+
54
+
55
+ def ring_frame(ring, positions, box):
56
+ """The ring's own coordinate frame, imaged so it does not straddle a boundary.
57
+
58
+ Args:
59
+ ring (list): atom indices in cyclic order
60
+ positions (dict): atom index -> position, in nm
61
+ box (array-like): box diagonal, in nm
62
+
63
+ Returns:
64
+ tuple: (points, centroid, unit normal, radius) or None if any atom is missing
65
+ """
66
+ if any(i not in positions for i in ring):
67
+ return None
68
+ anchor = np.asarray(positions[ring[0]], dtype=float)
69
+ P = np.array([anchor + mic(np.asarray(positions[i], dtype=float) - anchor, box)
70
+ for i in ring])
71
+ O = P.mean(axis=0)
72
+ # normal from the averaged cross products of successive centre-to-vertex vectors;
73
+ # sign is arbitrary, which is fine because every use here takes an absolute angle
74
+ V = P - O
75
+ n = np.zeros(3)
76
+ for k in range(len(V)):
77
+ n = n + np.cross(V[k], V[(k + 1) % len(V)])
78
+ norm = np.linalg.norm(n)
79
+ n = n / norm if norm > 1e-12 else np.array([0.0, 0.0, 1.0])
80
+ return P, O, n, float(np.linalg.norm(V, axis=1).max())
81
+
82
+
83
+ def pierces_ring(ring, bond, positions, box):
84
+ """Whether `bond` passes through `ring`, and where.
85
+
86
+ Args:
87
+ ring (list): the ring's atom indices in cyclic order
88
+ bond (tuple): (ai, aj); a bond sharing an atom with the ring never counts
89
+ positions (dict): atom index -> position, in nm
90
+ box (array-like): box diagonal, in nm
91
+
92
+ Returns:
93
+ dict or None: ``point``, ``offset`` from the ring centre in nm, ``offset_frac``
94
+ of the ring radius, ``angle`` of the bond to the ring normal in degrees, and
95
+ ``length`` of the bond in nm
96
+ """
97
+ ai, aj = int(bond[0]), int(bond[1])
98
+ if ai in ring or aj in ring:
99
+ return None
100
+ frame = ring_frame([int(x) for x in ring], positions, box)
101
+ if frame is None or ai not in positions or aj not in positions:
102
+ return None
103
+ P, O, n, radius = frame
104
+ anchor = np.asarray(positions[int(ring[0])], dtype=float)
105
+ p0 = anchor + mic(np.asarray(positions[ai], dtype=float) - anchor, box)
106
+ # the far end is imaged against the near end, so the bond stays one segment
107
+ d = mic(np.asarray(positions[aj], dtype=float) - np.asarray(positions[ai], dtype=float), box)
108
+ p1 = p0 + d
109
+ for k in range(len(P)):
110
+ t = segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)])
111
+ if t is not None:
112
+ point = p0 + t * (p1 - p0)
113
+ offset = float(np.linalg.norm(point - O))
114
+ length = float(np.linalg.norm(d))
115
+ cos = abs(float(np.dot(d / length, n))) if length > 0 else 0.0
116
+ return {'point': point, 'offset': offset,
117
+ 'offset_frac': offset / radius if radius > 0 else float('nan'),
118
+ 'angle_from_normal': float(np.degrees(np.arccos(min(1.0, cos)))),
119
+ 'length': length}
120
+ return None
@@ -832,6 +832,17 @@ attributes:
832
832
  monomer that shows up stretched past 2 A in the final structure. Set false
833
833
  to reproduce pre-2.11.4 behavior.
834
834
  default: true
835
+ - name: reject_new_threading
836
+ type: bool
837
+ text: >
838
+ Refuse a ring whose closure ladder dragged one of its own monomers' bonds
839
+ through a ring that was already there. The converse of
840
+ `reject_threaded_rings`, and mostly a different population: phenyls
841
+ outnumber triazines about six to one in these systems. Only threadings the
842
+ ladder creates count -- the same monomers are surveyed before and after it,
843
+ so one that arrived from packing already threaded is not refused every
844
+ reaction forever. Set false to reproduce pre-2.11.6 behavior.
845
+ default: true
835
846
  - name: prefilter_threaded_candidates
836
847
  type: bool
837
848
  text: >
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.11.5
3
+ Version: 2.12.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/
@@ -1,7 +1,8 @@
1
1
  htpolynet/__init__.py,sha256=_ApfhZLLP4Hd3b5ZCHAw6FHEj2VpQhu3RrZrZPiTef4,80
2
- htpolynet/cli.py,sha256=hj-JHRPmfaiQrvmcytywGtcrIf4rCAJN2zOmMVW6ERU,16949
2
+ htpolynet/cli.py,sha256=MKDArGrCp86xomkvUWKse858vU_uTQlBzNY1zgaDa5g,17682
3
3
  htpolynet/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  htpolynet/analysis/analyze.py,sha256=vM-FpM7rC6hiXw7VjrKFmpTjrfRzSbWHG9McsaZrhMs,9132
5
+ htpolynet/analysis/piercings.py,sha256=2w8Z98qxyl0oN5UQ0hBUf1Js12xpTLitEQ4UDg6trCI,9132
5
6
  htpolynet/analysis/plot.py,sha256=ncLduM4cK7ncQjksE2qL0Z086gqQOCpMs66rlI7AbOk,33020
6
7
  htpolynet/analysis/postsim.py,sha256=7HvW6yPHfSddl63QUp8PbyzToMSm13Pw16cqCY8OnWw,16873
7
8
  htpolynet/analysis/utils.py,sha256=jmQMfw8EDzRSEvqBHUQV2g15-MmZbreJYiJ7gan_z-c,17246
@@ -13,7 +14,7 @@ htpolynet/core/molecule.py,sha256=j0I0qsk5mRTg8QMysxJz6U9HxgTRpRSzHEgJ_SRT-jQ,63
13
14
  htpolynet/core/paramcache.py,sha256=37S88gRXZ5_xAdWyUE-Q3Etxc5HMv8L_RHrykkq9YAs,6966
14
15
  htpolynet/core/productsplice.py,sha256=asFVCW8G_rcMIizvO2Sh98MpOsFqzP1kIX1JySei_p8,12816
15
16
  htpolynet/core/projectfilesystem.py,sha256=KLpKlAaAG02bl6jZEZkYYTyjnHSrO5yAFAwI0uTMmDE,22630
16
- htpolynet/core/runtime.py,sha256=yKSSmaiUmRfJYYSrhqYvpxsD0RWCrYU8cWGl9GKn3v0,76493
17
+ htpolynet/core/runtime.py,sha256=bgFxqvqTX6574jArXAciwpBpjAY4XkdANShadjtrD9w,76823
17
18
  htpolynet/core/topocoord.py,sha256=jUgFg9TuUdSm14wo_464xX6dC4okJMrj1FbIzmaoA0Q,110520
18
19
  htpolynet/core/topology.py,sha256=ASyNbyWxw4bvFUACBmydCr-gGl705o68aB7vGYl7cHk,65405
19
20
  htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -21,8 +22,8 @@ htpolynet/cure/chain.py,sha256=-d5BFE5xUKjFdNkxLfSnCnZIRSJCtr7xuxYzNHBeSgU,5344
21
22
  htpolynet/cure/curecontroller.py,sha256=eTJc1JqrD7w6XLg4pL5ACHXo5N1oJ6P5pVdzMONxiBU,59756
22
23
  htpolynet/cure/expandreactions.py,sha256=eN35-SQrzjoo8ftZVLJkiAKxpA_FigERTwZ8jtoxDng,20682
23
24
  htpolynet/cure/reaction.py,sha256=_kRJ1JzT_fjLIAF6j9lH_Sft41KD1kVQuWPmXdHia-M,13446
24
- htpolynet/cure/ringcontroller.py,sha256=1OASSSpRRjVCNK3hvVCm7GsZ0EODwiNK10eppUvROLM,32253
25
- htpolynet/cure/triplesearch.py,sha256=3i0MBDa1ExFt0zhjvDUQk9GNxrjGwWAiWQAmFDYBWmE,16046
25
+ htpolynet/cure/ringcontroller.py,sha256=K_6bba5drbaRifimXLie1mqEclk0nmFaIfoQW94HGIs,38163
26
+ htpolynet/cure/triplesearch.py,sha256=5XDjwJs4NZNenSwHBRCLE3s-bOlAM6Ba4RJhM74YFBs,18002
26
27
  htpolynet/external/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
28
  htpolynet/external/ambertools.py,sha256=NkZ0fP6iqwMnMk2jMD3-EaiGCmutHb1MVFOTFJiQ7WI,6286
28
29
  htpolynet/external/command.py,sha256=KYmWV8P4nuw_ciE16WazviorxjGj5un_z7dL62n0TG0,2480
@@ -35,6 +36,7 @@ htpolynet/geometry/bondlist.py,sha256=ps6AreIHLz-55zZieJiBg9rbd9zZctw8gPrmQYK0Mb
35
36
  htpolynet/geometry/lattice.py,sha256=YgrX52xHjiK9DP-T_xFiqiCYLHukU5tKCxutl-rC5c0,896
36
37
  htpolynet/geometry/linkcell.py,sha256=11AWNugo9QruaVldMBhK23CuU3F-imkbbUvBX2r1khw,8212
37
38
  htpolynet/geometry/matrix4.py,sha256=hXVz9VGXT_0nJ-hI7xk4YZmeq4mntYqPrlJYdD1KFl4,3780
39
+ htpolynet/geometry/piercing.py,sha256=kYwrFVRbgcVuCxheOAVfMnwtthD1hpy2sSpPkP87BT4,5012
38
40
  htpolynet/geometry/placement.py,sha256=oSg4uFC8oOIm3UpTdGbD3PhgjdPDIvI3QgsVIcazHuk,3968
39
41
  htpolynet/geometry/ring.py,sha256=dpMajpPRRYTywpMsnwoyXVMNGfWZUZxS1SAx3Qh8E2I,9638
40
42
  htpolynet/geometry/templategeom.py,sha256=NO6RXL9_iYnPL6QOFPA9UeSDAaGUgxlbJuN8wnNw9p0,11702
@@ -92,7 +94,7 @@ htpolynet/resources/molecules/sample-inputs/STY.mol2,sha256=r1NqpovL6L7E96Kkyc6U
92
94
  htpolynet/resources/tcl/readbonds.tcl,sha256=l_bh7eMjbxVi44UMPMi32bFntZltij92KmKfXC1qDz4,972
93
95
  htpolynet/resources/tcl/readgrx.tcl,sha256=A1KvyIpFC_lwfze3XOqTCPqLIkq7HwmqJ96lZH42W0U,1731
94
96
  htpolynet/resources/tcl/render.tcl,sha256=KUszYxzWtfuL7OXdtdk8n6eAQbz8DJfKJrGbb0pOdrI,2379
95
- htpolynet/schema/base.yaml,sha256=Gl3cNHL-ifWa2-nVBPo1aY5OOhDKDADXTUJDcYqOGhI,45576
97
+ htpolynet/schema/base.yaml,sha256=VguKO7H2HgE_iC90CxlxnPLYJoxkWi_RcIA877aT4Y0,46222
96
98
  htpolynet/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
97
99
  htpolynet/utils/banner.py,sha256=hdw6xoHNAo9p6X33LmhW5qyb67qAaQ3hmLnct3ZuDy0,906
98
100
  htpolynet/utils/checkpoint.py,sha256=QTZIJ8K777T6o-mNpjPdelTqrpT0amLlQcgpHBiq5V0,2924
@@ -103,8 +105,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
103
105
  htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
104
106
  htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
105
107
  htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
106
- htpolynet-2.11.5.dist-info/METADATA,sha256=eIgJRsV0MJnWZ8Mtwu923mPvlXJCQRiAUN7EmmA19g0,6589
107
- htpolynet-2.11.5.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
108
- htpolynet-2.11.5.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
109
- htpolynet-2.11.5.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
110
- htpolynet-2.11.5.dist-info/RECORD,,
108
+ htpolynet-2.12.0.dist-info/METADATA,sha256=SiQmJFbOHfSMxXp6DwAwcihnpEDT2HSSiuOn-2-qf0g,6589
109
+ htpolynet-2.12.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
110
+ htpolynet-2.12.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
111
+ htpolynet-2.12.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
112
+ htpolynet-2.12.0.dist-info/RECORD,,