HTPolyNet 2.11.6__py3-none-any.whl → 2.13.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)
@@ -92,7 +92,13 @@ class PostSimMD:
92
92
  L0=box[0][0] if sznm=='Box-X' else box[1][1] if sznm=='Box-Y' else box[2][2]
93
93
  temp_x=f'{sznm}-strain'
94
94
  df[temp_x]=df[sznm]/L0-1.0
95
- for sznm in ['Pres-XX','Pres-YY','Pres-ZZ']:
95
+ # shear: the off-diagonal box element starts at zero, so the engineering shear
96
+ # strain is the element itself over the length of the sheared face -- no -1
97
+ for sznm,ref in [('Box-YX',1),('Box-ZX',2),('Box-ZY',2)]:
98
+ if sznm in p['traces']:
99
+ temp_x=f'{sznm}-strain'
100
+ df[temp_x]=df[sznm]/box[ref][ref]
101
+ for sznm in ['Pres-XX','Pres-YY','Pres-ZZ','Pres-XY','Pres-XZ','Pres-ZY']:
96
102
  if sznm in p['traces']:
97
103
  df[f'{sznm}-stress']=df[sznm]*(-1)
98
104
  temp_y=[f'{sznm}-stress']
@@ -241,6 +247,47 @@ class PostSimLadder(PostSimMD):
241
247
  }
242
248
  mdp_modify(mdpname,mod_dict)
243
249
 
250
+ def _strain_advice(edot,ps,logger=logger,what='strain'):
251
+ """Says what strain a deformation will reach, and what a modulus from it is worth.
252
+
253
+ The measured warning is not about the rate, it is about replicates. Eight
254
+ independent ramps of one protocol on one network gave shear moduli from 1.29 to
255
+ 1.74 GPa --- 10% scatter --- while each run's own fit reported a standard error far
256
+ smaller than that. So a single ramp gives a modulus to roughly 10%, which is often
257
+ good enough, but it cannot give the uncertainty on it, and a fit's own error bar is
258
+ not that uncertainty. Averaging replicates also does something a single run cannot:
259
+ it separates a real trend in the modulus with strain from one draw wandering.
260
+
261
+ Rate does matter past yield --- 1.22 +/- 0.06 GPa at ``edot = 1e-3`` against
262
+ 0.96 +/- 0.02 at ``1e-4`` over the same window --- and a fast ramp spends little of
263
+ its time at the low strains a tangent modulus would come from. Whether that biases
264
+ the modulus is not established: the one experiment that appeared to show it was a
265
+ single trajectory and a replicate refuted it.
266
+
267
+ A known disagreement that is *not* about rate: :class:`PostSimShear` has to switch
268
+ the barostat off for the Cartesian component it shears, because Gromacs refuses the
269
+ run otherwise, and *G* from that configuration comes out about 29% above a less
270
+ constrained variant --- 1.51 against 1.17 GPa on one network, where only the latter
271
+ agrees with that network's own *E* and Poisson ratio. Why is open; the obvious
272
+ answer, that constraint inflates it, fails because a fully constant-volume variant is
273
+ more constrained still and sits lower. See ROADMAP.md.
274
+ """
275
+ total=edot*ps
276
+ logger.info(f'This run reaches {what} {total:.3f} at {edot:g} ps^-1 over {ps} ps')
277
+ logger.info('One ramp gives a modulus to about 10% but not its uncertainty: eight '
278
+ 'replicates of one protocol spanned 1.29 to 1.74 GPa while each fit '
279
+ 'reported a much smaller error. Run several seeds and take the scatter '
280
+ 'between them as the error bar.')
281
+ if edot>=1e-3:
282
+ logger.warning(
283
+ f'{what} passes 0.02 after only {0.02/edot:.0f} ps at edot={edot:g}, so '
284
+ f'little of this run samples the low strains a modulus would come from; what '
285
+ f'is fitted is a secant over a large window. edot=1e-4 reaches 0.03 in the '
286
+ f'same wall time if that is what you want. Rate dependence past yield is '
287
+ f'real and measured; whether the rate biases the modulus itself is not '
288
+ f'established.')
289
+
290
+
244
291
  class PostSimDeform(PostSimMD):
245
292
  """ a class to handle a uniaxial deformation MD simulation
246
293
  """
@@ -291,7 +338,17 @@ class PostSimDeform(PostSimMD):
291
338
  'tau_t':0.5,
292
339
  'tau_p':1.0,
293
340
  'refcoord_scaling': 'com',
294
- 'pcoupltype': 'anisotropic'
341
+ 'pcoupltype': 'anisotropic',
342
+ # stress is what this stage exists to measure, so sample it far more often
343
+ # than the packaged npt.mdp does. At 1 ps the frames are already
344
+ # near-independent, so ten times as many cut the standard error on a fitted
345
+ # modulus by sqrt(10) for nothing but a larger edr.
346
+ 'nstcalcenergy': 50,
347
+ 'nstenergy': 50,
348
+ # required from Gromacs 2025 whenever deform is combined with generated
349
+ # velocities: the initial velocities must carry the flow profile the
350
+ # deformation implies, and grompp refuses the run outright without it
351
+ 'deform-init-flow': 'yes'
295
352
  }
296
353
  if direction=='x':
297
354
  strain_vel=box[0][0]*edot
@@ -319,7 +376,126 @@ class PostSimDeform(PostSimMD):
319
376
  params['scatter']=('Box-Z',['Pres-ZZ'],'tension_v_zlength.png')
320
377
  else:
321
378
  logger.error(f'Bad direction for uniaxial strain {direction}')
379
+ return
380
+ _strain_advice(edot,duration)
381
+
382
+ mdp_modify(mdpname,mod_dict)
383
+
384
+ class PostSimShear(PostSimMD):
385
+ """ a class to handle a constant-rate simple shear MD simulation
386
+
387
+ The shear counterpart of :class:`PostSimDeform`. Gromacs' ``deform`` moves one
388
+ off-diagonal element of the box matrix at a constant rate; the shear modulus is then
389
+ the slope of shear stress against engineering shear strain, exactly as Young's
390
+ modulus is the slope of tensile stress against tensile strain.
322
391
 
392
+ ``direction`` names the plane: ``xy`` shears the x face along y (box element YX),
393
+ ``xz`` and ``yz`` likewise. The normal pressures stay coupled at ``P`` while the
394
+ off-diagonal is driven, because the anisotropic barostat is given zero
395
+ compressibility off the diagonal and so does not fight the deformation.
396
+ """
397
+ # box element driven, the box length the strain is measured against, and the two
398
+ # energy terms to trace, per shear plane. The deform slot order is Gromacs'
399
+ # own: XX YY ZZ YX ZX ZY.
400
+ # 'zero' is the diagonal compressibility that must be switched off: driving an
401
+ # off-diagonal element moves one Cartesian component of a box vector, and Gromacs
402
+ # refuses to have the barostat acting on that same component of another vector
403
+ # ("spurious periodicity effects"). Shearing YX or ZX moves x; ZY moves y.
404
+ _planes={
405
+ 'xy': {'slot': 3, 'ref': 1, 'zero': 0, 'box': 'Box-YX', 'pres': 'Pres-XY'},
406
+ 'xz': {'slot': 4, 'ref': 2, 'zero': 0, 'box': 'Box-ZX', 'pres': 'Pres-XZ'},
407
+ 'yz': {'slot': 5, 'ref': 2, 'zero': 1, 'box': 'Box-ZY', 'pres': 'Pres-ZY'},
408
+ }
409
+ default_params={
410
+ 'subdir': f'{pfs.Dirs.postsim}/shear-xy',
411
+ 'input_top': f'{pfs.Dirs.systems_final}/final.top',
412
+ 'input_gro': f'{pfs.Dirs.postsim}/equilibrate/equilibrate.gro',
413
+ 'input_grx': f'{pfs.Dirs.systems_final}/final.grx',
414
+ 'gromacs' : {
415
+ 'gmx': 'gmx',
416
+ 'mdrun': 'gmx mdrun',
417
+ 'options': '-quiet -nobackup',
418
+ 'mdrun_single_molecule': 'gmx mdrun mdrun'
419
+ },
420
+ 'output_deffnm':'shear-xy',
421
+ 'traces': ['Box-YX','Pres-XY'],
422
+ 'scatter': ('Box-YX',['Pres-XY'],'shearstress_v_yxbox.png'),
423
+ 'direction':'xy',
424
+ 'coupling':'clamped',
425
+ 'T':300.0,
426
+ 'P':1.0,
427
+ 'ps':1000,
428
+ 'edot': 0.001 # shear rate in ps^-1
429
+ }
430
+
431
+ def build_mdp(self,mdpname,**kwargs):
432
+ """Builds the Gromacs mdp file required for a constant-rate simple shear.
433
+
434
+ Args:
435
+ mdpname (str): name of mdp file
436
+ """
437
+ params=self.params
438
+ timestep=float(mdp_get(mdpname,'dt'))
439
+ nsteps=int(params['ps']/timestep)
440
+ box=kwargs.get('box',np.array([[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]]))
441
+ direction=params.get('direction','xy')
442
+ plane=self._planes.get(direction)
443
+ if plane is None:
444
+ logger.error(f'Bad plane for simple shear {direction}; expected one of '
445
+ + ', '.join(sorted(self._planes)))
446
+ return
447
+ # the box element is driven at L*edot, so edot is a true strain rate in ps^-1
448
+ rate=box[plane['ref']][plane['ref']]*params.get('edot',0.0)
449
+ deform=['0']*6
450
+ deform[plane['slot']]=f'{rate:.3e}'
451
+ compress=['4.5e-5','4.5e-5','4.5e-5','0','0','0']
452
+ compress[plane['zero']]='0'
453
+ coupling=params.get('coupling','clamped')
454
+ if coupling not in ('clamped','isochoric'):
455
+ logger.error(f'Bad coupling for simple shear {coupling}; expected clamped or isochoric')
456
+ return
457
+ mod_dict={
458
+ 'ref_t':params['T'],
459
+ 'gen-temp':params['T'],
460
+ 'gen-vel':'yes',
461
+ 'tcoupl':'v-rescale',
462
+ 'nsteps': nsteps,
463
+ 'rlist': 1.2,
464
+ 'rcoulomb': 1.2,
465
+ 'rvdw': 1.2,
466
+ 'tau_t':0.5,
467
+ 'tau_p':1.0,
468
+ 'refcoord_scaling': 'com',
469
+ 'pcoupltype': 'anisotropic',
470
+ # the Cartesian component the shear moves is uncoupled; the other two
471
+ # normal directions stay at P. Gromacs rejects the run otherwise.
472
+ 'ref_p':f'{params["P"]} {params["P"]} {params["P"]} 0 0 0',
473
+ 'compressibility':' '.join(compress),
474
+ 'deform':' '.join(deform),
475
+ # as in PostSimDeform: the fitted modulus is only as good as the stress
476
+ # sampling, and denser output is the cheapest way to improve it
477
+ 'nstcalcenergy': 50,
478
+ 'nstenergy': 50,
479
+ # required from Gromacs 2025 whenever deform is combined with generated
480
+ # velocities: without it the initial velocities carry no flow profile and
481
+ # grompp refuses the run outright
482
+ 'deform-init-flow':'yes',
483
+ }
484
+ if coupling=='isochoric':
485
+ # no barostat, so nothing conflicts with the driven box element and nothing
486
+ # needs uncoupling; Gromacs ignores the leftover coupling keys
487
+ mod_dict['pcoupl']='no'
488
+ for _k in ('pcoupltype','ref_p','compressibility'):
489
+ mod_dict.pop(_k,None)
490
+ params['output_deffnm']=f'shear-{direction}'
491
+ params['traces']=[plane['box'],plane['pres']]
492
+ params['scatter']=(plane['box'],[plane['pres']],
493
+ f'shearstress_v_{direction}.png')
494
+ logger.info(f'Shearing {direction} with {coupling} box coupling. G spans about '
495
+ f'29% across three defensible couplings on one measured network, '
496
+ f'wider than the scatter between trajectories, so quote the coupling '
497
+ f'alongside the modulus.')
498
+ _strain_advice(params.get('edot',0.0),params['ps'],what='shear strain')
323
499
  mdp_modify(mdpname,mod_dict)
324
500
 
325
501
  class PostsimConfiguration:
@@ -340,10 +516,11 @@ class PostsimConfiguration:
340
516
  - 'equilibrate': simple NPT equilibration;
341
517
  - 'anneal': simple simulated annealing;
342
518
  - 'ladder': temperature ladder;
343
- - 'deform: constant strain-rate uniaxial deformation;
519
+ - 'deform': constant strain-rate uniaxial deformation;
520
+ - 'shear': constant-rate simple shear, for the shear modulus;
344
521
 
345
522
  """
346
- default_classes={'equilibrate':PostSimMD,'anneal':PostSimAnneal,'ladder':PostSimLadder,'deform':PostSimDeform}
523
+ default_classes={'equilibrate':PostSimMD,'anneal':PostSimAnneal,'ladder':PostSimLadder,'deform':PostSimDeform,'shear':PostSimShear}
347
524
  def __init__(self):
348
525
  self.cfgFile=''
349
526
  self.baselist=[]
@@ -375,6 +375,25 @@ def compute_tg(T,v,n_points=[10,20]):
375
375
  Tg=-(hot_par[1]-cold_par[1])/(hot_par[0]-cold_par[0])
376
376
  return Tg,cold_par,hot_par
377
377
 
378
+ def compute_G(shear_strain,shear_stress,fit_domain=[10,100]):
379
+ """Computes the shear modulus by a linear fit to the elastic regime of a simple shear.
380
+
381
+ The same fit as :func:`compute_E`, named separately because the inputs are not the
382
+ same quantities: the engineering shear strain is the driven off-diagonal box element
383
+ over the length of the sheared face (it starts at zero, so there is no -1), and the
384
+ shear stress is the negated off-diagonal of the pressure tensor.
385
+ ``htpolynet postsim`` writes both columns for a ``shear`` stage.
386
+
387
+ Args:
388
+ shear_strain (numpy.array): engineering shear strain, dimensionless
389
+ shear_stress (numpy.array): shear stress, in the units of the pressure trace
390
+ fit_domain (list): domain over which the fit is made, defaults to [10,100]
391
+
392
+ Returns:
393
+ tuple(float,float): G and R2 from the fit
394
+ """
395
+ return compute_E(shear_strain,shear_stress,fit_domain=fit_domain)
396
+
378
397
  def compute_E(strain,stress,fit_domain=[10,100]):
379
398
  """Computes the Young's modulus by performing a linear fit to an elastic regime in stress-vs-strain data.
380
399
 
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')
@@ -496,10 +496,13 @@ class RingController:
496
496
  by the cure rather than by packing -- one appearing in the same iteration as a
497
497
  triazine piercing, which is what identifies it as one event.
498
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.
499
+ Declining does not itself pull the monomer back out, and the relaxation that
500
+ follows does not reliably do it either -- one build declined the same bond at two
501
+ consecutive iterations, so the candidate came back and was refused again rather
502
+ than the threading dissolving. What declining reliably prevents is the threading
503
+ being made **permanent**: no ring forms around it, so nothing locks it in, and the
504
+ groups go back into the pool. Measured over twelve builds, none of the declined
505
+ threadings survived into the final structure.
503
506
 
504
507
  Args:
505
508
  TC (TopoCoord): the system
@@ -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,7 +214,7 @@ 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
@@ -283,7 +265,7 @@ def rings_threaded_by(bond_pairs, ring_atom_lists, positions, box, margin=0.3):
283
265
  p1 = p0 + _mic(np.asarray(positions[aj], dtype=float)
284
266
  - np.asarray(positions[ai], dtype=float), box)
285
267
  for k in range(len(P)):
286
- if _segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]):
268
+ if segment_pierces_triangle(p0, p1, O, P[k], P[(k + 1) % len(P)]) is not None:
287
269
  out.add((key, (min(ai, aj), max(ai, aj))))
288
270
  break
289
271
  return out
@@ -154,6 +154,44 @@ def ensure_thread_mpi_ranks(mdrun_options, mdrun_cmd=''):
154
154
  return adjusted
155
155
 
156
156
 
157
+ def report_grompp_warnings(out, err, mdp=''):
158
+ """Logs the warnings grompp emitted, which are otherwise thrown away.
159
+
160
+ htpolynet runs grompp with ``-maxwarn 4``, so up to four warnings do not stop a run,
161
+ and :func:`~htpolynet.external.command.run` only echoes captured output when a
162
+ command *fails*. Between them, a Gromacs warning on a successful run reached
163
+ neither the user nor the diagnostic log.
164
+
165
+ That is how the Berendsen barostat deprecation --- emitted on every constant-pressure
166
+ stage htpolynet runs, on every Gromacs since 2025 --- went unnoticed, and how an
167
+ off-diagonal box element being deformed against a coupled compressibility would have
168
+ gone unnoticed too. Warnings are how Gromacs says the setup is questionable; they
169
+ are worth seeing even when the run proceeds.
170
+
171
+ Args:
172
+ out (str): grompp stdout
173
+ err (str): grompp stderr
174
+ mdp (str): mdp basename, for the message
175
+
176
+ Returns:
177
+ list: the warning headings found
178
+ """
179
+ text = (out or '') + '\n' + (err or '')
180
+ found, lines = [], text.split('\n')
181
+ for i, line in enumerate(lines):
182
+ if not line.startswith('WARNING'):
183
+ continue
184
+ body = []
185
+ for nxt in lines[i + 1:]:
186
+ if not nxt.strip() or nxt.startswith(('WARNING', 'NOTE', 'ERROR')):
187
+ break
188
+ body.append(nxt.strip())
189
+ found.append(' '.join(body) or line)
190
+ for w in found:
191
+ logger.warning(f'grompp on {mdp}.mdp: {w}')
192
+ return found
193
+
194
+
157
195
  def grompp_and_mdrun(gro='',top='',out='',mdp='',boxSize=[],single_molecule=False,**kwargs):
158
196
  """Launcher for grompp and mdrun.
159
197
 
@@ -184,7 +222,8 @@ def grompp_and_mdrun(gro='',top='',out='',mdp='',boxSize=[],single_molecule=Fals
184
222
  box_str = ' '.join(f'{x:.8f}' for x in boxSize)
185
223
  run(f'{sw.gmx} {sw.gmx_options} editconf -f {gro}.gro -o {gro} -box {box_str}', quiet=quiet)
186
224
  # nsteps=kwargs.get('nsteps',-2)
187
- run(f'{sw.gmx} {sw.gmx_options} grompp -f {mdp}.mdp -c {gro}.gro -p {top}.top -o {out}.tpr -maxwarn {maxwarn}', quiet=quiet)
225
+ _gout, _gerr = run(f'{sw.gmx} {sw.gmx_options} grompp -f {mdp}.mdp -c {gro}.gro -p {top}.top -o {out}.tpr -maxwarn {maxwarn}', quiet=quiet)
226
+ report_grompp_warnings(_gout, _gerr, mdp)
188
227
  mdrun_options = mdrun_options_for(mdrun_options, mdp_integrator(f'{mdp}.mdp'))
189
228
  mdrun_options = ensure_thread_mpi_ranks(
190
229
  mdrun_options, sw.mdrun_single_molecule if single_molecule else sw.mdrun)
@@ -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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.11.6
3
+ Version: 2.13.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,10 +1,11 @@
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
- htpolynet/analysis/postsim.py,sha256=7HvW6yPHfSddl63QUp8PbyzToMSm13Pw16cqCY8OnWw,16873
7
- htpolynet/analysis/utils.py,sha256=jmQMfw8EDzRSEvqBHUQV2g15-MmZbreJYiJ7gan_z-c,17246
7
+ htpolynet/analysis/postsim.py,sha256=TygzJ6tb60S9xKr8Nh4ZkZT-HWyFlhYx-wK01yGkF7c,26462
8
+ htpolynet/analysis/utils.py,sha256=9UsvtJzsSoXxYLnciRodtWYyRZC8y96twUVdDf13_VU,18200
8
9
  htpolynet/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
10
  htpolynet/core/bondtemplate.py,sha256=_1vYMugonDuogysu15IsbpthvxYb6uJKC5ao7pQcWvg,9969
10
11
  htpolynet/core/configuration.py,sha256=j-74qPF_bqZrt9fBivGj-jX85kkVHNkSHM13ewE2ut0,5279
@@ -21,12 +22,12 @@ 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=K_6bba5drbaRifimXLie1mqEclk0nmFaIfoQW94HGIs,38163
25
- htpolynet/cure/triplesearch.py,sha256=qn5Aaa1yQkN-KJPVYb8LpZCyauUetyeYI6im8LS4PDw,18487
25
+ htpolynet/cure/ringcontroller.py,sha256=rDczzToLiwaJsig8AOZt0hvqsG7s_ASiMi5ON3PMzhE,38471
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
29
- htpolynet/external/gromacs.py,sha256=2gcNeQUYLbAdd4ElFg4WqSXpGSQNu_byg8czyih_Vnw,16844
30
+ htpolynet/external/gromacs.py,sha256=0gxm3zcxICyRHvn1ZNt1r3aE2SobpYsl2H_0M0-0P6E,18427
30
31
  htpolynet/external/slurm.py,sha256=FvnKyNqFXgDe5bdTDB4Kcn9KU4mxq9Gcw675SzU-4w0,4082
31
32
  htpolynet/external/smiles_input.py,sha256=vt-CdEHSqpJ5EA57NqQSCywjpHnTE5wCk2im2oxhM3U,9830
32
33
  htpolynet/external/software.py,sha256=Uzd1vkNnLm8C6By9ryFlbAnVPII30oFHLUOxzxdJJmw,10054
@@ -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
@@ -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.6.dist-info/METADATA,sha256=6zAqfLLdgEofWONCfu8HjlH25_uGcKrfSit9CSXrT6E,6589
107
- htpolynet-2.11.6.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
108
- htpolynet-2.11.6.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
109
- htpolynet-2.11.6.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
110
- htpolynet-2.11.6.dist-info/RECORD,,
108
+ htpolynet-2.13.0.dist-info/METADATA,sha256=gqmSkp0HmVqfHe066noStuKE0KA0-6hTt9hczGAUtzc,6589
109
+ htpolynet-2.13.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
110
+ htpolynet-2.13.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
111
+ htpolynet-2.13.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
112
+ htpolynet-2.13.0.dist-info/RECORD,,