HTPolyNet 2.15.0__py3-none-any.whl → 2.17.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,9 @@ 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=[]
677
+ whole=[]
675
678
  nproj=len(projdirs)
676
679
  for i,phase in enumerate(phases):
677
680
  p=phase['ladder']
@@ -710,7 +713,7 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
710
713
  means[i]['Density-std']=stds[i]['Density']
711
714
 
712
715
 
713
- fig,ax=plt.subplots(1,2,figsize=(10,6),sharex=True,sharey=True)
716
+ fig,ax=plt.subplots(1,max(2,len(means)),figsize=(10,6),sharex=True,sharey=True)
714
717
  for i,v in enumerate(means.keys()):
715
718
  m=means[v]
716
719
  std=stds[v]
@@ -718,6 +721,7 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
718
721
  std['Density']=np.zeros(len(std['Density']))
719
722
  m.sort_values('Temperature',axis=0,inplace=True)
720
723
  ax[i].set_xlabel('Temperature [K]')
724
+ ax[i].set_title('heating' if rate[i]>0 else 'cooling')
721
725
  ax[i].set_ylabel('Density [kg/m$^3$]')
722
726
  if nproj<2:
723
727
  ax[i].scatter(m['Temperature'],m['Density'])
@@ -725,6 +729,13 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
725
729
  ax[i].errorbar(m['Temperature'],m['Density'],std['Density'])
726
730
  Tg,c,h=compute_tg(m['Temperature'],m['Density'],n_points=n_points)
727
731
  Tgs.append(Tg)
732
+ spread.append(tg_window_range(m['Temperature'].values,m['Density'].values))
733
+ curves=[(r['Temperature'].values,r['Density'].values) for r in res[v]]
734
+ w=pooled_tg(curves)
735
+ if len(curves)==1 and w['fit'] is not None and not w['fit']['held_out']:
736
+ w['fit']=fit_tg_hyperbola(*curves[0],n_synth=200)
737
+ whole.append(w)
738
+ span.append((m['Temperature'].min(),m['Temperature'].max()))
728
739
  if Tg!=-1:
729
740
  ax[i].plot(m['Temperature'],c[0]*m['Temperature']+c[1],color='blue',alpha=0.5)
730
741
  ax[i].plot(m['Temperature'],h[0]*m['Temperature']+h[1],color='red',alpha=0.5)
@@ -736,11 +747,53 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
736
747
  logger.info(f'ladder{v}-{save_data} created.')
737
748
  plt.savefig(outfile,bbox_inches='tight')
738
749
  plt.close(fig)
739
- hTg=Tgs[0]
740
- cTg=Tgs[1]
750
+ # direction from the sign of the ladder's own deltaT, not its position in the
751
+ # config: a config listing cooling first was labeled "heating" (htpolynet-sweep,
752
+ # plan B on example 5, 2026-10-23)
753
+ labels=['heating' if r>0 else 'cooling' for r in rate]
741
754
  logger.info(f'{outfile} created.')
742
- 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
- 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)')
755
+ for label,Tg,r in zip(labels,Tgs,rate):
756
+ logger.info(f'{label} Tg = {Tg:.2f} K ({(Tg-273.15):.2f} C) at {r:.5f} K/ps ({r*1.e12:.3e} K/s)')
757
+ unquotable=[]
758
+ for label,r,(lo,hi) in zip(labels,spread,span):
759
+ if r is None:
760
+ continue
761
+ logger.info(f'{label} Tg over fit windows of 10-25 points per side: {r[0]:.0f} to {r[1]:.0f} K')
762
+ if r[0]<lo or r[1]>hi:
763
+ unquotable.append(label)
764
+ logger.warning(f'the {label} Tg leaves the ladder\'s {lo:.0f}-{hi:.0f} K range for some fit '
765
+ f'windows, so the glassy and rubbery lines are nearly parallel and no '
766
+ f'{label} Tg can be read off this ladder; equilibrate longer before it')
767
+ for label,w in zip(labels,whole):
768
+ f=w['fit']
769
+ if f is None:
770
+ logger.info(f'{label} Tg, whole-curve fit: did not converge')
771
+ elif f['held_out']:
772
+ logger.info(f'{label} Tg, whole-curve fit: none ({f["reason"]})')
773
+ else:
774
+ if w['Tg_boot_sd'] is not None:
775
+ err=(f'+/- {w["Tg_boot_sd"]:.0f} K (uncertainty of the mean, bootstrap over '
776
+ f'{w["n_builds"]} builds); {w["n_kept"]} of {w["n_builds"]} builds give a Tg alone'
777
+ + (f', s.d. {w["per_build_sd"]:.0f} K over those {w["n_kept"]} '
778
+ f'({w["n_kept"]}/{w["n_builds"]} kept)'
779
+ if w['per_build_sd'] is not None else ''))
780
+ elif f.get('Tg_synth_sd') is not None:
781
+ err=f'+/- {f["Tg_synth_sd"]:.0f} K within this build'
782
+ else:
783
+ err='no error bar'
784
+ logger.info(f'{label} Tg, whole-curve fit: {f["Tg"]:.1f} K {err}; tangents at the '
785
+ f'ladder ends cross at {f["Tg_tangents"]:.1f} K'
786
+ + ('; a sharp break' if f['sharp'] else ''))
787
+ first={}
788
+ for i,label in enumerate(labels):
789
+ first.setdefault(label,i)
790
+ hTg=Tgs[first['heating']] if 'heating' in first else None
791
+ cTg=Tgs[first['cooling']] if 'cooling' in first else None
792
+ if hTg is not None and cTg is not None and abs(hTg-cTg)>50.0:
793
+ logger.warning(f'heating and cooling Tg differ by {abs(hTg-cTg):.0f} K; more than rate '
794
+ f'hysteresis explains, so treat at least one as a failed fit')
795
+ return {'heating':hTg,'cooling':cTg,'directions':labels,'window_range':spread,
796
+ 'unquotable':unquotable,'whole_curve':whole}
744
797
 
745
798
  def do_E_plots(phases,projdirs,outfile='e.png',save_data='E.csv',fit_strain=None):
746
799
  """Fits Young's modulus to the deform stages and plots the mean stress-strain curve.
@@ -838,6 +891,10 @@ def do_E_plots(phases,projdirs,outfile='e.png',save_data='E.csv',fit_strain=None
838
891
 
839
892
  def post_plots(args):
840
893
  n_points=args.n_points
894
+ if not args.cfg:
895
+ # without it there are no stanzas, so every branch below is skipped and the
896
+ # command used to exit 0 having written nothing (htpolynet-sweep, 2026-10-15)
897
+ raise ValueError('plots post needs the postsim config that ran the stages: --cfg postsim.yaml')
841
898
  phases=[]
842
899
  # print(args.cfg)
843
900
  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}')
@@ -11,6 +11,7 @@ import pandas as pd
11
11
 
12
12
  from scipy.constants import physical_constants
13
13
  from scipy.optimize import curve_fit
14
+ from scipy.stats import f as f_dist
14
15
 
15
16
  from ..core.coordinates import Coordinates
16
17
  from ..core.topocoord import TopoCoord
@@ -375,6 +376,246 @@ def compute_tg(T,v,n_points=[10,20]):
375
376
  Tg=-(hot_par[1]-cold_par[1])/(hot_par[0]-cold_par[0])
376
377
  return Tg,cold_par,hot_par
377
378
 
379
+ def tg_window_range(T,v,glassy=(10,15,20,25),rubbery=(10,15,20,25)):
380
+ """Lowest and highest Tg over a grid of fit windows.
381
+
382
+ A Tg is the crossing of two fitted lines, so when the lines are nearly parallel a
383
+ small change in either window moves it a long way --- or off the temperature scale.
384
+ Seen 2026-10-15 on a rebuild of example 6: the heating ladder's glassy slope was a
385
+ third of the usual, the default windows gave 332.5 K against the reference build's
386
+ 529.2 K, and other windows gave anything from -1128 to 1640 K. The spread over
387
+ windows is what says whether a Tg can be quoted.
388
+
389
+ Args:
390
+ T (array-like): temperatures, sorted ascending
391
+ v (array-like): density or volume
392
+ glassy (tuple): glassy-side point counts to try
393
+ rubbery (tuple): rubbery-side point counts to try
394
+
395
+ Returns:
396
+ tuple: (lowest, highest) Tg over the windows that fit in the data, or None if none do
397
+ """
398
+ n=len(T)
399
+ tgs=[compute_tg(T,v,n_points=[c,h])[0] for c in glassy for h in rubbery if c+h<=n]
400
+ return (min(tgs),max(tgs)) if tgs else None
401
+
402
+ def _tg_hyperbola(T,rho0,T0,a,b,c):
403
+ """rho0 + a (T-T0) + b H(T-T0), H(t) = t/2 + sqrt(t^2/4 + exp(c)).
404
+
405
+ Asymptotes: slope a well below T0 (glassy) and a+b well above (rubbery), crossing
406
+ at T0, which is Tg; exp(c/2) sets the width of the transition between them."""
407
+ t=np.asarray(T,dtype=float)-T0
408
+ return rho0+a*t+b*(0.5*t+np.sqrt(0.25*t*t+np.exp(c)))
409
+
410
+ def fit_tg_hyperbola(T,v,width_bounds=(1.0,200.0),P_hat=0.9,n_synth=0,seed=0):
411
+ """Tg from one hyperbola fitted to the whole density (or volume) curve.
412
+
413
+ The two-line intersection of :func:`compute_tg` fits each side separately and
414
+ intersects them, so how many points each side gets moves Tg -- by 100 K or more on
415
+ some shipped examples. Following Patrone et al., Polymer 87, 246 (2016), a
416
+ hyperbola whose asymptotes are the glassy and rubbery lines is fitted to every point
417
+ at once, weighted by sigma_j proportional to T_j, and Tg is read off it two ways:
418
+ ``Tg`` is T0, the hyperbola's center, and ``Tg_tangents`` is where its tangents at
419
+ the two ends of the ladder cross. When the data reach both asymptotes the two
420
+ agree; their gap is the paper's own check that they do.
421
+
422
+ The screening criterion (their Eqs. 4-5): the slope reaches a fraction P_hat of the
423
+ way between its asymptotes at T0 +/- DeltaT, DeltaT = e^(c/2) (2P-1)/sqrt(P(1-P)).
424
+ A ladder that does not extend past that interval on both sides does not contain the
425
+ asymptotic regimes, and its Tg is held out. Also held out: a width on its upper
426
+ bound, and a bend that does not beat a straight line (F-test, p > 0.01) -- a
427
+ straight line otherwise fits as a sharp break at a noise feature. A width on its lower
428
+ bound is kept and flagged ``sharp``: the fit is then a two-line fit with its break
429
+ where the misfit is least.
430
+
431
+ Args:
432
+ T (array-like): temperatures, K
433
+ v (array-like): density or volume
434
+ width_bounds (tuple): allowed e^(c/2), K
435
+ P_hat (float): slope convergence that defines the transition interval
436
+ n_synth (int): synthetic datasets for the within-build uncertainty (their
437
+ section 5.1): residuals give a noise level, rising as T, from which data
438
+ are redrawn about the fit and refitted; 0 skips it
439
+ seed (int): random seed for the synthetic data
440
+
441
+ Returns:
442
+ dict: Tg, Tg_tangents, Tg_se (from the covariance), Tg_synth_sd, glassy and
443
+ rubbery slopes, width, transition (T0-DeltaT, T0+DeltaT), sharp, held_out,
444
+ reason, params; None if the fit does not converge
445
+ """
446
+ T=np.asarray(T,dtype=float); v=np.asarray(v,dtype=float)
447
+ o=np.argsort(T); T,v=T[o],v[o]
448
+ p,cov=_fit_hyperbola(T,v,width_bounds)
449
+ if p is None:
450
+ return None
451
+ rho0,T0,a,b,c=p
452
+ w_lo,w_hi=width_bounds
453
+ width=float(np.exp(c/2))
454
+ dT=width*(2*P_hat-1)/np.sqrt(P_hat*(1-P_hat))
455
+ sharp=bool(width<=w_lo*1.001)
456
+ # does the bend beat a straight line? An F-test on the weighted residuals, not the
457
+ # covariance of b: at the sharp-width bound that covariance is ill-conditioned and
458
+ # would hold out a real break
459
+ n=len(T)
460
+ ss_h=float(np.sum(((v-_tg_hyperbola(T,*p))/T)**2))
461
+ lin=np.polyfit(T,v,1,w=1.0/T)
462
+ ss_l=float(np.sum(((v-np.polyval(lin,T))/T)**2))
463
+ F=((ss_l-ss_h)/3.0)/(ss_h/(n-5)) if ss_h>0 and n>5 else float('inf')
464
+ p_line=float(f_dist.sf(F,3,n-5)) if np.isfinite(F) else 0.0
465
+ reason=None
466
+ if T0<=T[0]+1.0 or T0>=T[-1]-1.0:
467
+ reason='Tg at the edge of the data'
468
+ elif width>=w_hi*0.999:
469
+ reason=f'transition width at its {w_hi:g} K bound'
470
+ elif p_line>0.01:
471
+ reason=f'no significant change of slope (a straight line fits as well, p = {p_line:.2f})'
472
+ elif T[0]>T0-dT or T[-1]<T0+dT:
473
+ reason=(f'the ladder ({T[0]:.0f}-{T[-1]:.0f} K) does not reach past the transition, '
474
+ f'{T0-dT:.0f}-{T0+dT:.0f} K at {P_hat:.0%} slope convergence')
475
+ Tt=_tangent_crossing(p,T[0],T[-1])
476
+ se=float(np.sqrt(cov[1,1])) if np.isfinite(cov[1,1]) and not sharp else float('nan')
477
+ synth=None
478
+ if n_synth>0:
479
+ resid=v-_tg_hyperbola(T,*p)
480
+ scale=np.sqrt(np.mean((resid/T)**2))
481
+ rng=np.random.default_rng(seed)
482
+ tgs=[]
483
+ for _ in range(n_synth):
484
+ q,_=_fit_hyperbola(T,_tg_hyperbola(T,*p)+rng.normal(0.0,scale*T),width_bounds,p0=p)
485
+ if q is not None:
486
+ tgs.append(q[1])
487
+ synth=float(np.std(tgs,ddof=1)) if len(tgs)>1 else None
488
+ return {'Tg':float(T0),'Tg_tangents':Tt,'Tg_se':se,'Tg_synth_sd':synth,
489
+ 'glassy':float(a),'rubbery':float(a+b),'width':width,
490
+ 'transition':(float(T0-dT),float(T0+dT)),'sharp':sharp,
491
+ 'held_out':reason is not None,'reason':reason,'params':p}
492
+
493
+ def _fit_hyperbola(T,v,width_bounds,p0=None):
494
+ """Weighted least-squares fit of :func:`_tg_hyperbola`; (params, cov) or (None, None)."""
495
+ w_lo,w_hi=width_bounds
496
+ if p0 is None:
497
+ k=max(3,len(T)//4)
498
+ a0=np.polyfit(T[:k],v[:k],1)[0]
499
+ a1=np.polyfit(T[-k:],v[-k:],1)[0]
500
+ T0=0.5*(T[0]+T[-1])
501
+ p0=[np.interp(T0,T,v),T0,a0,a1-a0,2*np.log(20.0)]
502
+ lo=[-np.inf,T[0],-np.inf,-np.inf,2*np.log(w_lo)]
503
+ hi=[np.inf,T[-1],np.inf,np.inf,2*np.log(w_hi)]
504
+ p0=np.clip(np.asarray(p0,dtype=float),np.array(lo)+1e-9,np.array(hi)-1e-9)
505
+ try:
506
+ # sigma_j ~ T_j: Patrone et al. take sigma_j ~ T_j^p, 1/2 <= p <= 2, and find p
507
+ # barely matters
508
+ return curve_fit(_tg_hyperbola,T,v,p0=p0,sigma=T,bounds=(lo,hi),maxfev=40000)
509
+ except (RuntimeError,ValueError):
510
+ return None,None
511
+
512
+ def _tangent_crossing(p,T_lo,T_hi):
513
+ """Where the fitted hyperbola's tangents at T_lo and T_hi cross."""
514
+ def tangent(Tx,h=1e-3):
515
+ y=_tg_hyperbola(Tx,*p)
516
+ m=(_tg_hyperbola(Tx+h,*p)-_tg_hyperbola(Tx-h,*p))/(2*h)
517
+ return m,y-m*Tx
518
+ m1,b1=tangent(T_lo)
519
+ m2,b2=tangent(T_hi)
520
+ return float((b2-b1)/(m1-m2)) if abs(m1-m2)>1e-12 else float('nan')
521
+
522
+ def _align_builds(curves,width_bounds=(1.0,200.0)):
523
+ """Each build's curve shifted onto a common density, by a joint fit.
524
+
525
+ Replica builds of one system differ in density by a few kg/m^3 (3-11 across the
526
+ v2.16.0 replicates), which is as large as the change of slope a Tg fit looks for,
527
+ so pooling raw points turns the offsets into noise and hides the transition. This
528
+ fits one hyperbola -- shared T0, slopes and width -- with a separate rho0 for each
529
+ build, and returns the curves with those offsets removed.
530
+ """
531
+ Ts=[np.asarray(c[0],dtype=float) for c in curves]
532
+ Vs=[np.asarray(c[1],dtype=float) for c in curves]
533
+ n=len(curves)
534
+ T=np.concatenate(Ts); idx=np.concatenate([np.full(len(t),k) for k,t in enumerate(Ts)])
535
+ V=np.concatenate(Vs)
536
+ means=np.array([v.mean() for v in Vs])
537
+ first=fit_tg_hyperbola(T,V-means[idx]+means.mean(),width_bounds)
538
+ if first is None:
539
+ return None
540
+ _,T0,a0,b0,c0=first['params']
541
+ def model(X,T0,a,b,c,*rho0):
542
+ return np.asarray(rho0)[X[1].astype(int)]+_tg_hyperbola(X[0],0.0,T0,a,b,c)
543
+ w_lo,w_hi=width_bounds
544
+ lo=[T.min(),-np.inf,-np.inf,2*np.log(w_lo)]+[-np.inf]*n
545
+ hi=[T.max(),np.inf,np.inf,2*np.log(w_hi)]+[np.inf]*n
546
+ p0=[T0,a0,b0,c0]+[float(np.mean(v-_tg_hyperbola(t,0.0,T0,a0,b0,c0))) for t,v in zip(Ts,Vs)]
547
+ p0=np.clip(np.asarray(p0,dtype=float),np.array(lo)+1e-9,np.array(hi)-1e-9)
548
+ try:
549
+ p,_=curve_fit(model,np.vstack([T,idx]),V,p0=p0,sigma=T,bounds=(lo,hi),maxfev=40000)
550
+ except (RuntimeError,ValueError):
551
+ return None
552
+ rho0=np.asarray(p[4:])
553
+ return [(t,v-(rho0[k]-rho0.mean())) for k,(t,v) in enumerate(zip(Ts,Vs))]
554
+
555
+ def pooled_tg(curves,n_boot=500,seed=0):
556
+ """Tg from replica builds' curves fitted together, with a between-build error bar.
557
+
558
+ Each build's curve is noisy on its own; fitting all builds at once uses them as data
559
+ rather than averaging separately fitted answers. Builds are first aligned on
560
+ density (:func:`_align_builds`), since replicas differ by about as much as the
561
+ signal. The points within one build are correlated -- one structure, one
562
+ trajectory -- so the pooled fit's own standard error understates the uncertainty,
563
+ which is taken instead from a bootstrap over builds: resample whole builds with
564
+ replacement, realign, refit. That bootstrap is the uncertainty of the pooled Tg.
565
+ Beside it, ``per_build_sd`` is the s.d. of the Tg of the builds that pass on their
566
+ own, with ``n_kept`` saying how many. It is conditioned on that filter, so it is
567
+ not the scatter of an arbitrary build: on example 3 heating it is 7.7 K over the
568
+ 3 of 5 kept, and 73.6 K over all five, one of which the fit puts on the ladder's
569
+ edge. Quote it with k/n. A pooled fit that is sharp when most builds are refused
570
+ on their own is held out.
571
+ Patrone et al. (2016) found exactly this: two
572
+ simulations of one chemistry gave Tg distributions that did not overlap, because
573
+ the structures crosslinking produces differ.
574
+
575
+ Args:
576
+ curves (list): one (T, v) pair of arrays per build
577
+ n_boot (int): bootstrap resamples
578
+ seed (int): random seed for the resampling
579
+
580
+ Returns:
581
+ dict: Tg and fit (the pooled :func:`fit_tg_hyperbola` result), Tg_boot_sd (None
582
+ with one build or too few usable resamples), per_build (each build's own
583
+ fit), n_builds, n_kept, per_build_sd (s.d. over the n_kept kept builds'
584
+ Tg, None with fewer than two)
585
+ """
586
+ per=[fit_tg_hyperbola(t,y) for t,y in curves]
587
+ def fit_pool(cs):
588
+ aligned=_align_builds(cs) if len(cs)>1 else cs
589
+ if aligned is None:
590
+ return None
591
+ return fit_tg_hyperbola(np.concatenate([c[0] for c in aligned]),
592
+ np.concatenate([c[1] for c in aligned]))
593
+ pool=fit_pool(curves)
594
+ kept=[f['Tg'] for f in per if f is not None and not f['held_out']]
595
+ if (pool is not None and not pool['held_out'] and pool['sharp']
596
+ and len(curves)>1 and 2*len(kept)<len(curves)):
597
+ # pooling n builds buys significance with n: five straight lines can pool into
598
+ # a "sharp" break that none of them shows (example 2 cooling, 2026-10-23: 4 of 5
599
+ # builds refused, pooled kept at width 1 K, local slope showing no step)
600
+ pool['held_out']=True
601
+ pool['reason']=(f'a sharp break in the pool that {len(curves)-len(kept)} of '
602
+ f'{len(curves)} builds do not show on their own')
603
+ sd=None
604
+ if len(curves)>1 and pool is not None and not pool['held_out']:
605
+ rng=np.random.default_rng(seed)
606
+ tgs=[]
607
+ for _ in range(n_boot):
608
+ pick=rng.integers(0,len(curves),len(curves))
609
+ if len(set(pick.tolist()))<2:
610
+ continue
611
+ r=fit_pool([curves[i] for i in pick])
612
+ if r is not None and not r['held_out']:
613
+ tgs.append(r['Tg'])
614
+ sd=float(np.std(tgs,ddof=1)) if len(tgs)>1 else None
615
+ return {'Tg':pool['Tg'] if pool and not pool['held_out'] else None,'fit':pool,
616
+ 'Tg_boot_sd':sd,'per_build':per,'n_builds':len(curves),'n_kept':len(kept),
617
+ 'per_build_sd':float(np.std(kept,ddof=1)) if len(kept)>1 else None}
618
+
378
619
  def compute_G(shear_strain,shear_stress,fit_domain=[10,100],fit_strain=None):
379
620
  """Computes the shear modulus by a linear fit to the elastic regime of a simple shear.
380
621
 
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.17.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/
@@ -113,6 +113,8 @@ its published description to that earlier work. When using htpolynet in publish
113
113
  please cite Huang and Abrams, *SoftwareX* **21**, 101303 (2023),
114
114
  [doi:10.1016/j.softx.2022.101303](https://doi.org/10.1016/j.softx.2022.101303), along with
115
115
  the GAFF and Gromacs papers listed in the [documentation](https://htpolynet.readthedocs.io/).
116
+ Papers by other groups that have used htpolynet are listed on the
117
+ [Publications Using HTPolyNet](https://htpolynet.readthedocs.io/en/latest/publications.html) page.
116
118
 
117
119
  ## Meta
118
120
 
@@ -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=NfowXFXU5mGCvnvO5sW37p-kuLgtm621RPId4q188bY,41171
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=kvRuuBarg5ghGrcpOerlosDHaMJk_Dbuny6APmgDTz4,31629
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.17.0.dist-info/METADATA,sha256=RF6zs0l22wIDWM3CpqwqboxsOP8ATZOOFo5RI_Pw05E,6754
110
+ htpolynet-2.17.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
111
+ htpolynet-2.17.0.dist-info/entry_points.txt,sha256=G5tx55llJf-IV9dIe7J8myGdyrhCVggCAhKrVNGP_s0,48
112
+ htpolynet-2.17.0.dist-info/licenses/LICENSE,sha256=piPSGqJdmTGyzF9HOnjlO2KvgOKT8NHwhCuGYM778tY,1071
113
+ htpolynet-2.17.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any