HTPolyNet 2.15.0__py3-none-any.whl → 2.16.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.
@@ -672,6 +672,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
672
672
  stds={}
673
673
  rate=[]
674
674
  Tgs=[]
675
+ spread=[]
676
+ span=[]
675
677
  nproj=len(projdirs)
676
678
  for i,phase in enumerate(phases):
677
679
  p=phase['ladder']
@@ -725,6 +727,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
725
727
  ax[i].errorbar(m['Temperature'],m['Density'],std['Density'])
726
728
  Tg,c,h=compute_tg(m['Temperature'],m['Density'],n_points=n_points)
727
729
  Tgs.append(Tg)
730
+ spread.append(tg_window_range(m['Temperature'].values,m['Density'].values))
731
+ span.append((m['Temperature'].min(),m['Temperature'].max()))
728
732
  if Tg!=-1:
729
733
  ax[i].plot(m['Temperature'],c[0]*m['Temperature']+c[1],color='blue',alpha=0.5)
730
734
  ax[i].plot(m['Temperature'],h[0]*m['Temperature']+h[1],color='red',alpha=0.5)
@@ -741,6 +745,20 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
741
745
  logger.info(f'{outfile} created.')
742
746
  logger.info(f'heating Tg = {hTg:.2f} K ({(hTg-273.15):.2f} C) at {rate[0]:.5f} K/ps ({rate[0]*1.e12:.3e} K/s)')
743
747
  logger.info(f'cooling Tg = {cTg:.2f} K ({(cTg-273.15):.2f} C) at {rate[1]:.5f} K/ps ({rate[1]*1.e12:.3e} K/s)')
748
+ unquotable=[]
749
+ for label,r,(lo,hi) in zip(('heating','cooling'),spread,span):
750
+ if r is None:
751
+ continue
752
+ logger.info(f'{label} Tg over fit windows of 10-25 points per side: {r[0]:.0f} to {r[1]:.0f} K')
753
+ if r[0]<lo or r[1]>hi:
754
+ unquotable.append(label)
755
+ logger.warning(f'the {label} Tg leaves the ladder\'s {lo:.0f}-{hi:.0f} K range for some fit '
756
+ f'windows, so the glassy and rubbery lines are nearly parallel and no '
757
+ f'{label} Tg can be read off this ladder; equilibrate longer before it')
758
+ if abs(hTg-cTg)>50.0:
759
+ logger.warning(f'heating and cooling Tg differ by {abs(hTg-cTg):.0f} K; more than rate '
760
+ f'hysteresis explains, so treat at least one as a failed fit')
761
+ return {'heating':hTg,'cooling':cTg,'window_range':spread,'unquotable':unquotable}
744
762
 
745
763
  def do_E_plots(phases,projdirs,outfile='e.png',save_data='E.csv',fit_strain=None):
746
764
  """Fits Young's modulus to the deform stages and plots the mean stress-strain curve.
@@ -838,6 +856,10 @@ def do_E_plots(phases,projdirs,outfile='e.png',save_data='E.csv',fit_strain=None
838
856
 
839
857
  def post_plots(args):
840
858
  n_points=args.n_points
859
+ if not args.cfg:
860
+ # without it there are no stanzas, so every branch below is skipped and the
861
+ # command used to exit 0 having written nothing (htpolynet-sweep, 2026-10-15)
862
+ raise ValueError('plots post needs the postsim config that ran the stages: --cfg postsim.yaml')
841
863
  phases=[]
842
864
  # print(args.cfg)
843
865
  for c in args.cfg:
@@ -0,0 +1,379 @@
1
+ """Non-covalent structure around rings in a finished network.
2
+
3
+ Three measurements on one top/gro pair, each normalized so that "more than chance" means
4
+ something:
5
+
6
+ - :func:`face_on_contacts` --- how often a chosen atom sits over the *face* of a ring,
7
+ close and on the ring's normal, relative to a uniform random placement. This is the
8
+ geometry of a lone-pair/pi contact.
9
+ - :func:`centroid_rdf` --- orientation-averaged radial distribution from chosen atoms (or
10
+ bridge groups) to ring centroids, excluding rings the selection is covalently part of.
11
+ - :func:`ring_flip_clearance` --- for each ring, the cylinder it must sweep to flip about
12
+ its para axis and how many foreign heavy atoms sit inside it: the static steric part of
13
+ a ring-flip barrier.
14
+
15
+ Rings are selected by composition (``C3N3`` for a triazine, ``C6`` for a phenylene) and
16
+ atoms by force-field type, so nothing here knows any chemistry by name. Ported from
17
+ htpolynet-study's bisphenol-bridge analysis (2026-10-06), where sulfone oxygens were
18
+ found over triazine faces about twice as often as chance.
19
+
20
+ Single structure only: averaging over a trajectory means running this per frame.
21
+
22
+ Author: Cameron F. Abrams <cfa22@drexel.edu>
23
+ """
24
+ import logging
25
+ import math
26
+ from collections import defaultdict
27
+
28
+ import numpy as np
29
+
30
+ from ..core.topology import _element_of
31
+ from ..geometry.piercing import ring_frame
32
+ from .piercings import detect_rings, ring_composition
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ class RingSystem:
38
+ """Positions, box, per-atom data, bond graph and rings of one structure.
39
+
40
+ Args:
41
+ TC (TopoCoord): the system, with coordinates loaded
42
+ max_ring (int): largest ring to detect when the topology carries no ring list
43
+ """
44
+ def __init__(self, TC, max_ring=6):
45
+ A = TC.Coordinates.A
46
+ self.box = np.asarray(TC.Coordinates.box.diagonal(), dtype=float)
47
+ self.pos = {int(r.globalIdx): np.array([r.posX, r.posY, r.posZ], dtype=float)
48
+ for r in A.itertuples()}
49
+ at = TC.Topology.D['atoms']
50
+ self.type = {int(r.nr): str(r.type) for r in at.itertuples()}
51
+ self.resnr = {int(r.nr): int(r.resnr) for r in at.itertuples()}
52
+ self.mass = {int(r.nr): float(r.mass) for r in at.itertuples()}
53
+ self.element = {int(r.nr): _element_of(r.atom, r.type) for r in at.itertuples()}
54
+ self.adj = defaultdict(set)
55
+ bonds = TC.Topology.D['bonds']
56
+ for r in bonds.itertuples():
57
+ ai, aj = int(r.ai), int(r.aj)
58
+ self.adj[ai].add(aj)
59
+ self.adj[aj].add(ai)
60
+ self.rings = detect_rings(bonds, max_size=max_ring)
61
+ self.composition = [ring_composition(r, self.element) for r in self.rings]
62
+ self.volume = float(np.prod(self.box))
63
+
64
+ def rings_of(self, composition):
65
+ """Rings (atom lists in cyclic order) of the given composition, e.g. ``C3N3``."""
66
+ return [r for r, c in zip(self.rings, self.composition) if c == composition]
67
+
68
+ def atoms_of_types(self, types):
69
+ """Atom indices whose force-field type is in `types`."""
70
+ types = set(types)
71
+ return sorted(i for i, t in self.type.items() if t in types)
72
+
73
+ def heavy(self, i):
74
+ return self.element.get(i, '?') != 'H'
75
+
76
+ def mic(self, d):
77
+ """Minimum-image of displacement(s) `d`."""
78
+ return d - self.box * np.round(d / self.box)
79
+
80
+ def unwrap(self, idx, anchor=None):
81
+ """Positions of `idx` imaged next to `anchor` (default: the first of them)."""
82
+ p = np.array([self.pos[i] for i in idx])
83
+ a = p[0] if anchor is None else anchor
84
+ return a + self.mic(p - a)
85
+
86
+ def com(self, idx):
87
+ p = self.unwrap(idx)
88
+ m = np.array([self.mass[i] for i in idx])
89
+ return (p * m[:, None]).sum(0) / m.sum()
90
+
91
+ def within_bonds(self, seeds, maxd):
92
+ """Atoms within `maxd` bonds of any seed, seeds included."""
93
+ seen = set(seeds)
94
+ frontier = list(seeds)
95
+ for _ in range(maxd):
96
+ nxt = []
97
+ for a in frontier:
98
+ for b in self.adj[a]:
99
+ if b not in seen:
100
+ seen.add(b)
101
+ nxt.append(b)
102
+ frontier = nxt
103
+ return seen
104
+
105
+
106
+ def face_on_contacts(S, donors, rings, rmax=0.37, max_angle=35.0, exclude_bonds=4,
107
+ rmin=0.0, exclude='bonds'):
108
+ """Face-on donor-over-ring contacts, against a uniform random expectation.
109
+
110
+ A contact is a donor between `rmin` and `rmax` of a ring centroid with the
111
+ centroid-to-donor vector within `max_angle` of the ring normal (either face). The
112
+ expectation is the number of eligible donor-ring pairs times the fraction of the box
113
+ the two acceptance cones occupy, ``(1 - cos max_angle) * (4/3) pi (rmax^3 - rmin^3) / V``.
114
+
115
+ Rings covalently close to the donor are not eligible: with ``exclude='bonds'``, rings
116
+ within `exclude_bonds` bonds; with ``exclude='residue'``, rings containing an atom of
117
+ the donor's own residue. Without an exclusion the result is meaningless: a donor
118
+ scores contacts with its own substituents, which are two or three bonds away.
119
+
120
+ Args:
121
+ S (RingSystem): the structure
122
+ donors (list): donor atom indices
123
+ rings (list): rings, as atom lists in cyclic order
124
+ rmax (float): contact distance, nm
125
+ max_angle (float): largest angle from the ring normal, degrees
126
+ exclude_bonds (int): covalent exclusion depth for ``exclude='bonds'``
127
+ rmin (float): inner contact distance, nm; nonzero makes the region a shell
128
+ exclude (str): ``'bonds'`` or ``'residue'``
129
+
130
+ Returns:
131
+ dict: observed, expected, enhancement (observed/expected), pairs (eligible
132
+ donor-ring pairs) and contacts, an (n,2) array of (distance nm, angle deg)
133
+ for every eligible pair inside 0.6 nm, for histogramming
134
+ """
135
+ frames = [ring_frame(r, S.pos, S.box) for r in rings]
136
+ keep = [k for k, f in enumerate(frames) if f is not None]
137
+ if not donors or not keep:
138
+ return {'observed': 0, 'expected': 0.0, 'enhancement': float('nan'), 'pairs': 0,
139
+ 'contacts': np.empty((0, 2))}
140
+ cen = np.array([frames[k][1] for k in keep])
141
+ nor = np.array([frames[k][2] for k in keep])
142
+ if exclude not in ('bonds', 'residue'):
143
+ raise ValueError(f"exclude must be 'bonds' or 'residue', not {exclude!r}")
144
+ ringsets = [set(rings[k]) for k in keep]
145
+ ringres = [{S.resnr[i] for i in rings[k]} for k in keep]
146
+ near_r = max(rmax, 0.6)
147
+ out, npairs, obs = [], 0, 0
148
+ for o in donors:
149
+ if exclude == 'bonds':
150
+ near = S.within_bonds([o], exclude_bonds)
151
+ ok = np.array([not (near & rs) for rs in ringsets])
152
+ else:
153
+ ok = np.array([S.resnr[o] not in rr for rr in ringres])
154
+ npairs += int(ok.sum())
155
+ d = S.mic(cen[ok] - S.pos[o])
156
+ r = np.linalg.norm(d, axis=1)
157
+ m = r < near_r
158
+ if not m.any():
159
+ continue
160
+ cosang = np.abs(np.einsum('ij,ij->i', d[m] / r[m][:, None], nor[ok][m]))
161
+ ang = np.degrees(np.arccos(np.clip(cosang, 0.0, 1.0)))
162
+ obs += int(((r[m] >= rmin) & (r[m] < rmax) & (ang < max_angle)).sum())
163
+ out.extend(zip(r[m], ang))
164
+ vcone = (1 - math.cos(math.radians(max_angle))) * (4.0 / 3.0) * math.pi * (rmax ** 3 - rmin ** 3)
165
+ exp = npairs * vcone / S.volume
166
+ return {'observed': obs, 'expected': exp,
167
+ 'enhancement': obs / exp if exp > 0 else float('nan'), 'pairs': npairs,
168
+ 'contacts': np.array(out) if out else np.empty((0, 2))}
169
+
170
+
171
+ def bridge_groups(S, composition):
172
+ """Bridge groups between rings of one composition.
173
+
174
+ A bridge center is a heavy atom outside the rings bonded to atoms of two *different*
175
+ rings of `composition`; its group is the center plus its neighbors outside those
176
+ rings (a sulfone's two oxygens, an isopropylidene's methyls). For ``C6`` this picks
177
+ -O-, -S-, -CH2-, -C(CH3)2-, -C(CF3)2- and -SO2- alike, and rejects an aryl ether
178
+ oxygen that links one phenylene to a triazine.
179
+
180
+ Returns:
181
+ list: groups, each a list of atom indices with the center first
182
+ """
183
+ ring_of = {}
184
+ for k, r in enumerate(S.rings_of(composition)):
185
+ for i in r:
186
+ ring_of[i] = k
187
+ groups = []
188
+ for i in sorted(S.type):
189
+ if i in ring_of or not S.heavy(i):
190
+ continue
191
+ if len({ring_of[j] for j in S.adj[i] if j in ring_of}) >= 2:
192
+ groups.append([i] + sorted(j for j in S.adj[i] if j not in ring_of))
193
+ return groups
194
+
195
+
196
+ def centroid_rdf(S, groups, rings, rmax=1.5, dr=0.02):
197
+ """Radial distribution from group centers of mass to ring centers of mass.
198
+
199
+ A ring containing any atom of the group's own residue is excluded: a monomer's
200
+ bridge is covalently a fixed distance from rings it is part of, and counting those
201
+ measures molecular geometry, not packing.
202
+
203
+ Args:
204
+ S (RingSystem): the structure
205
+ groups (list): atom groups (a single atom is a group of one)
206
+ rings (list): rings, as atom lists
207
+ rmax (float): largest distance, nm
208
+ dr (float): bin width, nm
209
+
210
+ Returns:
211
+ tuple: (bin centers in nm, g(r)); g is normalized by the eligible pair count
212
+ """
213
+ nbin = int(round(rmax / dr))
214
+ edges = np.linspace(0.0, rmax, nbin + 1)
215
+ if not groups or not rings:
216
+ return 0.5 * (edges[1:] + edges[:-1]), np.zeros(nbin)
217
+ gcom = np.array([S.com(g) for g in groups])
218
+ gres = [{S.resnr[i] for i in g} for g in groups]
219
+ rcom = np.array([S.com(r) for r in rings])
220
+ rres = [{S.resnr[i] for i in r} for r in rings]
221
+ hist = np.zeros(nbin)
222
+ npair = 0
223
+ for k in range(len(groups)):
224
+ ok = np.array([not (gres[k] & s) for s in rres])
225
+ npair += int(ok.sum())
226
+ r = np.linalg.norm(S.mic(rcom[ok] - gcom[k]), axis=1)
227
+ hist += np.histogram(r, bins=nbin, range=(0.0, rmax))[0]
228
+ shell = 4.0 / 3.0 * np.pi * (edges[1:] ** 3 - edges[:-1] ** 3)
229
+ g = hist / (npair * shell / S.volume) if npair else hist
230
+ return 0.5 * (edges[1:] + edges[:-1]), g
231
+
232
+
233
+ def flip_axis(S, ring):
234
+ """The two ring atoms a ring flips about: the para pair carrying exocyclic heavy atoms.
235
+
236
+ Falls back to the farthest-apart pair when a ring does not have exactly one para pair
237
+ of substituted atoms. The farthest pair alone is not a flip axis --- a hexagon has
238
+ three para pairs at nearly equal separation --- so the fallback is logged.
239
+ """
240
+ n = len(ring)
241
+ rs = set(ring)
242
+ subst = [any(S.heavy(j) and j not in rs for j in S.adj[i]) for i in ring]
243
+ if n % 2 == 0:
244
+ pairs = [(k, k + n // 2) for k in range(n // 2) if subst[k] and subst[k + n // 2]]
245
+ if len(pairs) == 1:
246
+ return ring[pairs[0][0]], ring[pairs[0][1]], True
247
+ p = S.unwrap(ring)
248
+ dmat = np.linalg.norm(p[:, None] - p[None, :], axis=-1)
249
+ i, j = np.unravel_index(np.argmax(dmat), dmat.shape)
250
+ return ring[i], ring[j], False
251
+
252
+
253
+ def ring_flip_clearance(S, rings):
254
+ """Room each ring needs to flip about its para axis, and what is in the way.
255
+
256
+ The ring's own group is its atoms, their exocyclic neighbors that are not in another
257
+ ring, and the hydrogens on those neighbors --- an ortho methyl's hydrogens are what
258
+ actually sweep. ``R_sweep`` is the largest distance of that group from the axis;
259
+ ``blocking`` counts foreign heavy atoms inside the cylinder of that radius over the
260
+ group's own axial extent. This is the static steric part of a flip barrier, not the
261
+ barrier: no electrostatics and no relaxation of the neighbors as the ring turns.
262
+
263
+ Returns:
264
+ dict: arrays R_sweep (nm) and blocking, one entry per ring, and the number of
265
+ rings whose axis fell back to the farthest-apart pair
266
+ """
267
+ all_rings = set().union(*(set(r) for r in S.rings)) if S.rings else set()
268
+ heavy = np.array(sorted(i for i in S.pos if S.heavy(i)))
269
+ hx = np.array([S.pos[i] for i in heavy])
270
+ R, N, fallback = [], [], 0
271
+ for ring in rings:
272
+ ia, ib, para = flip_axis(S, ring)
273
+ if not para:
274
+ fallback += 1
275
+ a0 = S.pos[ia]
276
+ a1 = a0 + S.mic(S.pos[ib] - a0)
277
+ ax = (a1 - a0) / np.linalg.norm(a1 - a0)
278
+ rs = set(ring)
279
+ own = rs | {k for i in ring for k in S.adj[i] if k not in all_rings}
280
+ own |= {k for i in own - rs for k in S.adj[i] if S.element.get(k) == 'H'}
281
+ q = S.unwrap(sorted(own), anchor=a0)
282
+ rad = np.linalg.norm(np.cross(q - a0, ax), axis=1)
283
+ rsweep = rad.max()
284
+ t_own = (q - a0) @ ax
285
+ v = S.mic(hx - a0)
286
+ t = v @ ax
287
+ perp = np.linalg.norm(v - t[:, None] * ax, axis=1)
288
+ inside = (perp < rsweep) & (t > t_own.min()) & (t < t_own.max())
289
+ R.append(rsweep)
290
+ N.append(int(sum(1 for k in heavy[inside] if k not in own)))
291
+ return {'R_sweep': np.array(R), 'blocking': np.array(N), 'axis_fallback': fallback}
292
+
293
+
294
+ def _donor_groups(S, args):
295
+ """(label, atom list) per donor selection: each ``-donors`` entry is a type or a
296
+ comma-joined set of types, and ``-bridge`` adds the bridges' heavy atoms."""
297
+ out = [(d, S.atoms_of_types(d.split(','))) for d in (args.donors or [])]
298
+ if args.bridge:
299
+ heavy = [i for g in bridge_groups(S, args.bridge) for i in g if S.heavy(i)]
300
+ out.append((f'bridge({args.bridge}) heavy atoms', heavy))
301
+ return out
302
+
303
+
304
+ def ring_contacts(args):
305
+ """CLI handler for ``htpolynet ring-contacts``.
306
+
307
+ Args:
308
+ args (argparse.Namespace): parsed arguments; see ``htpolynet ring-contacts -h``
309
+ """
310
+ import os
311
+
312
+ from ..core.topocoord import TopoCoord
313
+
314
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
315
+ for f in (args.top, args.gro):
316
+ if not os.path.exists(f):
317
+ logger.error(f'{f} not found')
318
+ raise SystemExit(1)
319
+ S = RingSystem(TopoCoord(topfilename=args.top, grofilename=args.gro), max_ring=args.max_ring)
320
+ found = {}
321
+ for c in S.composition:
322
+ found[c] = found.get(c, 0) + 1
323
+ print('rings: ' + (', '.join(f'{n} {c}' for c, n in sorted(found.items())) or 'none'))
324
+ comps = args.rings or (['C6'] if args.analysis == 'flip' else ['C3N3'])
325
+ missing = [c for c in comps if c not in found]
326
+ if missing:
327
+ logger.error(f'no ring of composition {", ".join(missing)} in this system')
328
+ raise SystemExit(1)
329
+
330
+ if args.analysis == 'flip':
331
+ print(f'{"rings":>8}{"n":>7}{"R_sweep (nm)":>18}{"blocking heavy atoms":>24}')
332
+ for c in comps:
333
+ res = ring_flip_clearance(S, S.rings_of(c))
334
+ R, N = res['R_sweep'], res['blocking']
335
+ print(f'{c:>8}{len(R):7d}{R.mean():11.3f} +/- {R.std():.3f}'
336
+ f'{N.mean():15.2f} +/- {N.std() / np.sqrt(len(N)):.2f}')
337
+ if res['axis_fallback']:
338
+ logger.warning(f'{res["axis_fallback"]} {c} ring(s) had no unique substituted '
339
+ 'para pair; their axis is the farthest-apart pair')
340
+ return
341
+
342
+ groups = _donor_groups(S, args)
343
+ if not groups:
344
+ logger.error('select atoms with -donors <type> [...] and/or -bridge <composition>')
345
+ raise SystemExit(1)
346
+ if args.analysis == 'contacts':
347
+ region = (f'{args.rmin * 10:.1f}-{args.rmax * 10:.1f}' if args.rmin
348
+ else f'< {args.rmax * 10:.1f}')
349
+ print(f'face-on: {region} A from the centroid, < {args.angle:g} deg from the normal; '
350
+ + (f'rings within {args.exclude_bonds} bonds excluded' if args.exclude == 'bonds'
351
+ else "rings of the donor's own residue excluded"))
352
+ print(f'{"donors":>28}{"n":>7}{"rings":>8}{"observed":>10}{"expected":>10}{"enhancement":>13}')
353
+ for lab, don in groups:
354
+ for c in comps:
355
+ r = face_on_contacts(S, don, S.rings_of(c), rmax=args.rmax, max_angle=args.angle,
356
+ exclude_bonds=args.exclude_bonds, rmin=args.rmin,
357
+ exclude=args.exclude)
358
+ print(f'{lab:>28}{len(don):7d}{c:>8}{r["observed"]:10d}{r["expected"]:10.1f}'
359
+ f'{r["enhancement"]:12.2f}x')
360
+ return
361
+
362
+ # rdf: one group per atom for -donors, the whole bridge group for -bridge
363
+ sel = [(lab, [[i] for i in don]) for lab, don in groups if not lab.startswith('bridge(')]
364
+ if args.bridge:
365
+ sel.append((f'bridge({args.bridge})', bridge_groups(S, args.bridge)))
366
+ cols, names = [], []
367
+ for lab, grp in sel:
368
+ for c in comps:
369
+ x, g = centroid_rdf(S, grp, S.rings_of(c), rmax=args.rdf_max, dr=args.dr)
370
+ w = (x > 0.3) & (x < 1.2)
371
+ pk = x[w][np.argmax(g[w])] if w.any() else float('nan')
372
+ print(f'{lab} -> {c}: {len(grp)} group(s); first peak in 3-12 A at '
373
+ f'{pk * 10:.2f} A, g = {g[w].max() if w.any() else float("nan"):.2f}')
374
+ cols.append(g)
375
+ names.append(f'{lab}->{c}'.replace(' ', '_'))
376
+ if args.o:
377
+ np.savetxt(args.o, np.column_stack([x] + cols), fmt='%.4f',
378
+ header='r_nm ' + ' '.join(names))
379
+ logger.info(f'Wrote {args.o}')
@@ -375,6 +375,29 @@ 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 tg_window_range(T,v,glassy=(10,15,20,25),rubbery=(10,15,20,25)):
379
+ """Lowest and highest Tg over a grid of fit windows.
380
+
381
+ A Tg is the crossing of two fitted lines, so when the lines are nearly parallel a
382
+ small change in either window moves it a long way --- or off the temperature scale.
383
+ Seen 2026-10-15 on a rebuild of example 6: the heating ladder's glassy slope was a
384
+ third of the usual, the default windows gave 332.5 K against the reference build's
385
+ 529.2 K, and other windows gave anything from -1128 to 1640 K. The spread over
386
+ windows is what says whether a Tg can be quoted.
387
+
388
+ Args:
389
+ T (array-like): temperatures, sorted ascending
390
+ v (array-like): density or volume
391
+ glassy (tuple): glassy-side point counts to try
392
+ rubbery (tuple): rubbery-side point counts to try
393
+
394
+ Returns:
395
+ tuple: (lowest, highest) Tg over the windows that fit in the data, or None if none do
396
+ """
397
+ n=len(T)
398
+ tgs=[compute_tg(T,v,n_points=[c,h])[0] for c in glassy for h in rubbery if c+h<=n]
399
+ return (min(tgs),max(tgs)) if tgs else None
400
+
378
401
  def compute_G(shear_strain,shear_stress,fit_domain=[10,100],fit_strain=None):
379
402
  """Computes the shear modulus by a linear fit to the elastic regime of a simple shear.
380
403
 
htpolynet/cli.py CHANGED
@@ -26,6 +26,7 @@ from .utils.inputcheck import input_check
26
26
  from .utils.logsetup import setup_logging
27
27
  from .utils.stringthings import my_logger
28
28
  from .analysis.piercings import piercings
29
+ from .analysis.ringcontacts import ring_contacts
29
30
  from .utils.vmd_viz import make_viz
30
31
 
31
32
  logger = logging.getLogger(__name__)
@@ -294,6 +295,7 @@ def cli():
294
295
  ('gen-slurm-script', gen_slurm_script, 'generate a SLURM submission script for running htpolynet on a cluster'),
295
296
  ('make-viz', make_viz, 'regenerate VMD viz files (.viz.psf + .viz.tcl) from an existing gromacs top + gro pair'),
296
297
  ('piercings', piercings, 'report any bond threaded through a ring in a gromacs top + gro pair; exits 1 if any are found'),
298
+ ('ring-contacts', ring_contacts, 'non-covalent structure around rings in a gromacs top + gro pair: face-on contacts, ring-centroid RDFs, ring-flip clearance'),
297
299
  ('setup-claude', setup_claude, "install htpolynet's Claude Code skill so an agent can drive htpolynet"),
298
300
  ]
299
301
 
@@ -334,6 +336,23 @@ def cli():
334
336
  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
337
  cp['piercings'].add_argument('-json', type=str, default=None, help='also write the findings to this JSON file')
336
338
 
339
+ rc = cp['ring-contacts']
340
+ rc.add_argument('analysis', type=str, choices=['contacts', 'rdf', 'flip'], help='contacts: face-on atom-over-ring contacts vs. random; rdf: atom or bridge to ring-centroid g(r); flip: room each ring needs to flip and what blocks it')
341
+ rc.add_argument('-top', type=str, default='final.top', help='input gromacs topology file (default: final.top)')
342
+ rc.add_argument('-gro', type=str, default='final.gro', help='input gromacs coordinate file (default: final.gro)')
343
+ rc.add_argument('-rings', type=str, nargs='+', default=None, help='ring compositions, e.g. C3N3 C6 (default: C3N3; C6 for flip)')
344
+ rc.add_argument('-donors', type=str, nargs='+', default=None, help="atom types to measure from; a comma-joined entry (e.g. 'os,ss') is one group")
345
+ rc.add_argument('-bridge', type=str, default=None, help='also measure from the bridges between rings of this composition (e.g. C6)')
346
+ rc.add_argument('-rmax', type=float, default=0.37, help='contacts: outer distance from the ring centroid, nm (default: %(default)s)')
347
+ rc.add_argument('-rmin', type=float, default=0.0, help='contacts: inner distance, nm; nonzero makes a shell (default: %(default)s)')
348
+ rc.add_argument('-angle', type=float, default=35.0, help='contacts: largest angle from the ring normal, degrees (default: %(default)s)')
349
+ rc.add_argument('-exclude', type=str, choices=['bonds', 'residue'], default='bonds', help='contacts: exclude rings near the donor by bond count or by residue (default: %(default)s)')
350
+ rc.add_argument('-exclude-bonds', dest='exclude_bonds', type=int, default=4, help='contacts: bond-count exclusion depth (default: %(default)s)')
351
+ rc.add_argument('-rdf-max', dest='rdf_max', type=float, default=1.5, help='rdf: largest distance, nm (default: %(default)s)')
352
+ rc.add_argument('-dr', type=float, default=0.02, help='rdf: bin width, nm (default: %(default)s)')
353
+ rc.add_argument('-o', type=str, default=None, help='rdf: write r and every g(r) to this file')
354
+ rc.add_argument('-max-ring', dest='max_ring', type=int, default=6, help='largest ring to detect (default: %(default)s)')
355
+
337
356
  cp['setup-claude'].add_argument('--skills-dir', type=str, default='~/.claude/skills',
338
357
  help='skills directory to install into (default: %(default)s); use ./.claude/skills to scope the skill to one project')
339
358
  cp['setup-claude'].add_argument('--force', default=False, action='store_true', help='overwrite an existing installed skill')
@@ -472,6 +472,27 @@ def resolve_user_library(pathname, default='lib'):
472
472
  return default if os.path.isdir(default) else None
473
473
 
474
474
 
475
+ # library-relative paths of inputs htpolynet makes from a SMILES string in the config;
476
+ # see note_smiles_input
477
+ _SMILES_INPUTS_ = set()
478
+
479
+
480
+ def note_smiles_input(filename):
481
+ """Records that `filename` is generated from SMILES, so it shadows nothing.
482
+
483
+ The SMILES generator writes into the user library, so the later checkout is a
484
+ user-library hit on htpolynet's own output. For such a constituent a packaged file
485
+ of the same name is not what the run would otherwise use --- without the library
486
+ copy htpolynet regenerates from SMILES --- so the shadowing note does not apply.
487
+ Seen 2026-10-15 in the v2.15.0 sweep: example 0's STY.mol2 drew the note seven log
488
+ lines after htpolynet wrote it.
489
+
490
+ Args:
491
+ filename (str): path relative to the library root, e.g. ``molecules/inputs/STY.mol2``
492
+ """
493
+ _SMILES_INPUTS_.add(os.path.normpath(filename))
494
+
495
+
475
496
  def _note_if_shadowing(filename, source):
476
497
  """Says so when a file of your own replaces one htpolynet ships.
477
498
 
@@ -487,6 +508,8 @@ def _note_if_shadowing(filename, source):
487
508
  order 4, and the resulting instability was written up for weeks as a property of the
488
509
  systems being built.
489
510
  """
511
+ if os.path.normpath(filename) in _SMILES_INPUTS_:
512
+ return
490
513
  try:
491
514
  if _SYSTEM_LIBRARY_ and _SYSTEM_LIBRARY_._root.joinpath(filename).exists():
492
515
  logger.warning(
htpolynet/core/runtime.py CHANGED
@@ -179,6 +179,9 @@ class Runtime:
179
179
  else:
180
180
  inputs_dir = os.path.join(pfs.root(), 'lib', pfs.Dirs.molecules_inputs)
181
181
  generated=materialize_smiles_inputs(self.cfg.constituents, inputs_dir=inputs_dir)
182
+ for name,spec in self.cfg.constituents.items():
183
+ if isinstance(spec,dict) and spec.get('smiles'):
184
+ pfs.note_smiles_input(f'{pfs.Dirs.molecules_inputs}/{name}.mol2')
182
185
  if generated:
183
186
  logger.info(f'Generated mol2 inputs from SMILES for: {", ".join(generated)}')
184
187
  self._build_molecules_and_reactions()
@@ -47,7 +47,10 @@ def materialize_smiles_inputs(constituents, inputs_dir='lib/molecules/inputs'):
47
47
  continue
48
48
  out = os.path.join(inputs_dir, f'{name}.mol2')
49
49
  if os.path.exists(out):
50
- logger.debug(f'{out} exists, skipping SMILES regeneration')
50
+ # info, not debug: a kept file is the one way a SMILES constituent can run
51
+ # on something other than its SMILES, e.g. one generated by an older version
52
+ logger.info(f'{name}: using existing {out} rather than its SMILES; '
53
+ f'delete it to regenerate')
51
54
  continue
52
55
  _generate(name, spec, out)
53
56
  generated.append(name)
@@ -1,16 +1,9 @@
1
1
  # htpolynet configuration schema, for ycleptic.
2
2
  #
3
- # STATUS: not yet wired into htpolynet. This file is inert data until
4
- # `ycleptic` can be declared as a runtime dependency, which is blocked on
5
- # ycleptic reaching conda-forge (htpolynet is on conda-forge and a conda
6
- # package's run-deps must exist in the channel). See ROADMAP.md.
7
- #
8
- # REQUIRES ycleptic >= 2.4.0, for `value_attributes`/`key_text` (free-key
9
- # mappings), `value_type` (scalar-valued free-key mappings) and `list_defaults`
10
- # (per-attribute replace semantics). 2.4.0 is released on PyPI, but the pin
11
- # must NOT be written into pyproject.toml until the anaconda API says 2.4.0 is
12
- # on the conda-forge CHANNEL -- as of this writing ycleptic is not on
13
- # conda-forge at all. See ROADMAP.md for why.
3
+ # Wired in since 2.8.0: core/configuration.py validates every config against this
4
+ # file and fills in its defaults. REQUIRES ycleptic >= 2.4.0 for `value_attributes`/
5
+ # `key_text` (free-key mappings), `value_type` (scalar-valued free-key mappings) and
6
+ # `list_defaults` (per-attribute replace semantics); pyproject.toml floors it at 2.4.4.
14
7
  #
15
8
  # `constituents` is a free-key mapping: its keys are molecule names the user
16
9
  # invents, and `value_attributes` gives the schema every record must satisfy.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: htpolynet
3
- Version: 2.15.0
3
+ Version: 2.16.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,11 +1,12 @@
1
1
  htpolynet/__init__.py,sha256=_ApfhZLLP4Hd3b5ZCHAw6FHEj2VpQhu3RrZrZPiTef4,80
2
- htpolynet/cli.py,sha256=MKDArGrCp86xomkvUWKse858vU_uTQlBzNY1zgaDa5g,17682
2
+ htpolynet/cli.py,sha256=qProWJ0hGgs4lBa1h4etiLCRp3paYPCN-g3XGi_IO-c,20038
3
3
  htpolynet/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  htpolynet/analysis/analyze.py,sha256=vM-FpM7rC6hiXw7VjrKFmpTjrfRzSbWHG9McsaZrhMs,9132
5
5
  htpolynet/analysis/piercings.py,sha256=2w8Z98qxyl0oN5UQ0hBUf1Js12xpTLitEQ4UDg6trCI,9132
6
- htpolynet/analysis/plot.py,sha256=qHnRzF65TMtHnkNNp6FcSJE2JxmvFzDvvaSfu4duMe8,37844
6
+ htpolynet/analysis/plot.py,sha256=dJEGsdTd6nnbzizHQX9QgrMIIas2zKuq-_1_ZOJ436M,39220
7
7
  htpolynet/analysis/postsim.py,sha256=EgRYZy7Xpmv05hzUEW3tjNKRzjpnynb1UVUZqgjfz3E,30056
8
- htpolynet/analysis/utils.py,sha256=b8jYPaIoSWbF07hvLyDqPGWNDpPFZk6r-qY0Ttk1trk,19262
8
+ htpolynet/analysis/ringcontacts.py,sha256=r4pVLIMwKp-KsSmhNAbp4FHoa1yRVfsTw-5dbwDVEDE,17118
9
+ htpolynet/analysis/utils.py,sha256=_aCYvWoH2n_0ss5dchA5cZ0NJhXST-DBHd1Y3xxders,20361
9
10
  htpolynet/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
11
  htpolynet/core/bondtemplate.py,sha256=_1vYMugonDuogysu15IsbpthvxYb6uJKC5ao7pQcWvg,9969
11
12
  htpolynet/core/configuration.py,sha256=j-74qPF_bqZrt9fBivGj-jX85kkVHNkSHM13ewE2ut0,5279
@@ -13,8 +14,8 @@ htpolynet/core/coordinates.py,sha256=CGTHkdfw2ikc2ANacA5akRhZ9tOyM2IbELwQ2FVcKRw
13
14
  htpolynet/core/molecule.py,sha256=j0I0qsk5mRTg8QMysxJz6U9HxgTRpRSzHEgJ_SRT-jQ,63012
14
15
  htpolynet/core/paramcache.py,sha256=37S88gRXZ5_xAdWyUE-Q3Etxc5HMv8L_RHrykkq9YAs,6966
15
16
  htpolynet/core/productsplice.py,sha256=asFVCW8G_rcMIizvO2Sh98MpOsFqzP1kIX1JySei_p8,12816
16
- htpolynet/core/projectfilesystem.py,sha256=40zRje0sBuWAzLPvaNvvzCAnWAwFGi-tbGUju7MWlnY,23159
17
- htpolynet/core/runtime.py,sha256=JQ2tM4_ThBF8cOtlr9uq5EFmgZ9b5lWqLFj9bbTU5k4,77264
17
+ htpolynet/core/projectfilesystem.py,sha256=WH8rkQ_CVg-uZF8NZy8e-2V3CfNzyW33hnEIrjkX3jI,24109
18
+ htpolynet/core/runtime.py,sha256=Z8JUkvAzdD3Cg-5_AeM9hn0TOJjquhFKrsukpogf1eo,77463
18
19
  htpolynet/core/topocoord.py,sha256=jUgFg9TuUdSm14wo_464xX6dC4okJMrj1FbIzmaoA0Q,110520
19
20
  htpolynet/core/topology.py,sha256=ttdDUuE6noBhC-3B-x-lAfNVsXPOlEe-z4aKefZUOiY,65578
20
21
  htpolynet/cure/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -29,7 +30,7 @@ htpolynet/external/ambertools.py,sha256=NkZ0fP6iqwMnMk2jMD3-EaiGCmutHb1MVFOTFJiQ
29
30
  htpolynet/external/command.py,sha256=KYmWV8P4nuw_ciE16WazviorxjGj5un_z7dL62n0TG0,2480
30
31
  htpolynet/external/gromacs.py,sha256=0gxm3zcxICyRHvn1ZNt1r3aE2SobpYsl2H_0M0-0P6E,18427
31
32
  htpolynet/external/slurm.py,sha256=FvnKyNqFXgDe5bdTDB4Kcn9KU4mxq9Gcw675SzU-4w0,4082
32
- htpolynet/external/smiles_input.py,sha256=vt-CdEHSqpJ5EA57NqQSCywjpHnTE5wCk2im2oxhM3U,9830
33
+ htpolynet/external/smiles_input.py,sha256=s9WbDXN-Ls_iaPK7uZNzqsBomJ630DbuOBF8l8xlOPs,10067
33
34
  htpolynet/external/software.py,sha256=Uzd1vkNnLm8C6By9ryFlbAnVPII30oFHLUOxzxdJJmw,10054
34
35
  htpolynet/geometry/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
35
36
  htpolynet/geometry/bondlist.py,sha256=ps6AreIHLz-55zZieJiBg9rbd9zZctw8gPrmQYK0MbI,6144
@@ -94,7 +95,7 @@ htpolynet/resources/molecules/sample-inputs/STY.mol2,sha256=r1NqpovL6L7E96Kkyc6U
94
95
  htpolynet/resources/tcl/readbonds.tcl,sha256=l_bh7eMjbxVi44UMPMi32bFntZltij92KmKfXC1qDz4,972
95
96
  htpolynet/resources/tcl/readgrx.tcl,sha256=A1KvyIpFC_lwfze3XOqTCPqLIkq7HwmqJ96lZH42W0U,1731
96
97
  htpolynet/resources/tcl/render.tcl,sha256=KUszYxzWtfuL7OXdtdk8n6eAQbz8DJfKJrGbb0pOdrI,2379
97
- htpolynet/schema/base.yaml,sha256=VguKO7H2HgE_iC90CxlxnPLYJoxkWi_RcIA877aT4Y0,46222
98
+ htpolynet/schema/base.yaml,sha256=ugPcc0pZOmXNJDEhtOJyIz1jRqb27QxdMUDlvMyFpY4,45850
98
99
  htpolynet/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
99
100
  htpolynet/utils/banner.py,sha256=hdw6xoHNAo9p6X33LmhW5qyb67qAaQ3hmLnct3ZuDy0,906
100
101
  htpolynet/utils/checkpoint.py,sha256=QTZIJ8K777T6o-mNpjPdelTqrpT0amLlQcgpHBiq5V0,2924
@@ -105,8 +106,8 @@ htpolynet/utils/logsetup.py,sha256=o0mlVXNzqcfua2SAlJPkGSh4lM_bmI10gWwpb9gqYu8,1
105
106
  htpolynet/utils/profiling.py,sha256=su7qpGEz6FXVU4KT2HQDWG82bc1sgsfpDQBbAfPpsHc,7331
106
107
  htpolynet/utils/stringthings.py,sha256=Mr6o55EM8o4YAaVYpjIJj2IxDToNdbPzb-lpQ3w3jFk,1176
107
108
  htpolynet/utils/vmd_viz.py,sha256=Crk3Ln88PKiJ9X7DMMkFEVh2Ru6a1y0RUgj3w6EIgFc,10867
108
- htpolynet-2.15.0.dist-info/METADATA,sha256=CQ407bPBVmIhIoF1vTsk6Bfiv7k2oEPn75FJjHGZQMk,6589
109
- htpolynet-2.15.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
110
- htpolynet-2.15.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
111
- htpolynet-2.15.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
112
- htpolynet-2.15.0.dist-info/RECORD,,
109
+ htpolynet-2.16.0.dist-info/METADATA,sha256=wwWGa4ijdLu8DPnesZFlP5EbnhjCxag63Zth1ZH5vwU,6589
110
+ htpolynet-2.16.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
111
+ htpolynet-2.16.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
112
+ htpolynet-2.16.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
113
+ htpolynet-2.16.0.dist-info/RECORD,,