HTPolyNet 2.1.0__py3-none-any.whl → 2.3.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.
@@ -8,6 +8,7 @@ from datetime import datetime
8
8
 
9
9
  import yaml
10
10
 
11
+ import matplotlib
11
12
  import matplotlib.cm as cm
12
13
  import matplotlib.pyplot as plt
13
14
  import networkx as nx
@@ -19,6 +20,27 @@ from ..utils.logsetup import setup_logging
19
20
 
20
21
  logger=logging.getLogger(__name__)
21
22
 
23
+
24
+ def _get_cmap(name):
25
+ """Returns a named colormap, across matplotlib versions.
26
+
27
+ ``matplotlib.cm.get_cmap`` was deprecated in 3.7 and removed in 3.11, so
28
+ calling it breaks every plot on any reasonably fresh install -- including
29
+ the container image, which tracks the latest conda-forge matplotlib. The
30
+ ``matplotlib.colormaps`` registry is the supported spelling from 3.5 on;
31
+ fall back to the old call only for matplotlib older than that.
32
+
33
+ Args:
34
+ name (str): colormap name, e.g. 'plasma'
35
+
36
+ Returns:
37
+ matplotlib.colors.Colormap: the named colormap
38
+ """
39
+ registry = getattr(matplotlib, 'colormaps', None)
40
+ if registry is not None:
41
+ return registry[name]
42
+ return cm.get_cmap(name)
43
+
22
44
  # prevents "RuntimeError: main thread is not in main loop" tk bug
23
45
  plt.switch_backend('agg')
24
46
 
@@ -35,7 +57,7 @@ def scatter(df,xcolumn,columns=[],outfile='plot.png',**kwargs):
35
57
  cmapname=kwargs.get('colormap','plasma')
36
58
  size=kwargs.get('size',(8,6))
37
59
  yunits=kwargs.get('yunits',None)
38
- cmap=cm.get_cmap(cmapname)
60
+ cmap=_get_cmap(cmapname)
39
61
  fig,ax=plt.subplots(1,1,figsize=size)
40
62
  ax.set_xlabel(xcolumn)
41
63
  for n in columns:
@@ -46,67 +68,68 @@ def scatter(df,xcolumn,columns=[],outfile='plot.png',**kwargs):
46
68
  logging.disable(logging.NOTSET)
47
69
 
48
70
 
49
- def trace(qty,edrs,outfile='plot.png',**kwargs):
71
+ def trace(qty, edrs, outfile='plot.png', yunits=None, **kwargs):
50
72
  """Generates a plot of the energy-like quantity named by 'qty' vs time by reading data from the list of edr files named in 'edrs'.
51
73
 
52
74
  Args:
53
75
  qty (str): name of energy-like quantity; must conform to menu generated by 'gmx energy'
54
76
  edrs (list): list of names of edr files to scan, in order
55
77
  outfile (str): name of output image file, defaults to 'plot.png'
78
+ yunits (str): unit string to append to the y-axis label as ``f'{qty} ({yunits})'``; ``None`` leaves the label as bare ``qty``.
56
79
 
57
80
  Returns:
58
81
  list: the list of average values
59
82
  """
60
83
  # disable debug-level logging and above since matplotlib has a lot of debug statements
61
84
  logging.disable(logging.DEBUG)
62
- df=pd.DataFrame()
63
- cmapname=kwargs.get('colormap','plasma')
64
- size=kwargs.get('size',(8,6))
65
- yunits=kwargs.get('yunits',None)
66
- avgafter=kwargs.get('avgafter',0)
67
- cmap=cm.get_cmap(cmapname)
68
- xshift=0.0
69
- chkpt=[]
85
+ df = pd.DataFrame()
86
+ cmapname = kwargs.get('colormap', 'plasma')
87
+ size = kwargs.get('size', (8,6))
88
+ avgafter = kwargs.get('avgafter', 0)
89
+ cmap = _get_cmap(cmapname)
90
+ xshift = 0.0
91
+ chkpt = []
70
92
  for edr in edrs:
71
93
  if not df.empty:
72
- xshift=df.tail(1).iloc[0,0]
73
- data=gmx_energy_trace(edr,[qty],xshift=xshift)
74
- lastchkpt=0
75
- if len(chkpt)>0:
76
- lastchkpt=chkpt[-1]
77
- chkpt.append(data.shape[0]+lastchkpt)
78
- df=pd.concat((df,data),ignore_index=True)
79
- fig,ax=plt.subplots(1,1,figsize=size)
80
- nseg=len(chkpt)
81
- beg=0
82
- avg=[]
94
+ xshift = df.tail(1).iloc[0, 0]
95
+ data = gmx_energy_trace(edr, [qty], xshift=xshift)
96
+ lastchkpt = 0
97
+ if len(chkpt) > 0:
98
+ lastchkpt = chkpt[-1]
99
+ chkpt.append(data.shape[0] + lastchkpt)
100
+ df = pd.concat((df, data), ignore_index=True)
101
+ fig, ax = plt.subplots(1, 1, figsize=size)
102
+ nseg = len(chkpt)
103
+ beg = 0
104
+ avg = []
83
105
  for c in df.columns[1:]:
84
106
  for seg in range(nseg):
85
- ax.plot(df.iloc[beg:chkpt[seg],0],df[c].iloc[beg:chkpt[seg]],label=(c if seg==0 else None),color=cmap(seg/nseg))
86
- beg=chkpt[seg]
107
+ ax.plot(df.iloc[beg:chkpt[seg], 0], df[c].iloc[beg:chkpt[seg]], label=(c if seg==0 else None), color=cmap(seg/nseg))
108
+ beg = chkpt[seg]
87
109
  if 'avgafter' in kwargs:
88
- if avgafter>0:
110
+ if avgafter > 0:
89
111
  pass
90
112
  else:
91
- avgafter=df['time(ps)'].iloc[-1]/2
92
- sdf=df[df['time(ps)']>avgafter]
113
+ avgafter = df['time(ps)'].iloc[-1] / 2
114
+ sdf=df[df['time(ps)'] > avgafter]
93
115
  avg.append(sdf[c].mean())
94
- ax.plot(df.iloc[:,0],[avg]*df.shape[0],'k-',alpha=0.3,label=f'{avg:0.2f}')
116
+ ax.plot(df.iloc[:, 0], [avg[-1]] * df.shape[0], 'k-', alpha=0.3, label=f'{avg[-1]:0.2f}')
95
117
  else:
96
118
  avg.append(df[c].mean())
97
119
  if not yunits:
98
120
  plt.ylabel(qty)
99
121
  else:
100
122
  plt.ylabel(f'{qty} ({yunits})')
101
- plt.xlabel('time(ps)')
102
- plt.legend()
123
+ plt.xlabel('time (ps)')
124
+ if len(df.columns) > 2 or 'avgafter' in kwargs:
125
+ plt.legend()
103
126
  plt.savefig(outfile)
104
127
  plt.close(fig)
105
128
  # re-establish previous logging level
106
129
  logging.disable(logging.NOTSET)
107
130
  return avg
108
131
 
109
- def multi_trace(dfL,xnames,ynames,labels=[],xlabel='time [ps]',ylabel='',outfile='plot.png',**kwargs):
132
+ def multi_trace(dfL, xnames, ynames, labels=[], xlabel='time [ps]',ylabel='', outfile='plot.png', **kwargs):
110
133
  """Generates a plot of each y vs x in df.
111
134
 
112
135
  Args:
@@ -116,22 +139,22 @@ def multi_trace(dfL,xnames,ynames,labels=[],xlabel='time [ps]',ylabel='',outfile
116
139
  outfile (str): name of output image file, defaults to 'plot.png'
117
140
  """
118
141
  # disable debug-level logging and above since matplotlib has a lot of debug statements
119
- default_units={'Temperature':'K','Pressure':'bar','Density':'kg/m^3','Potential':'kJ/mol'}
120
- units=kwargs.get('units',default_units)
142
+ default_units = {'Temperature': 'K', 'Pressure': 'bar', 'Density': r'kg/m$^3$', 'Potential': 'kJ/mol'}
143
+ units = kwargs.get('units', default_units)
121
144
  logging.disable(logging.DEBUG)
122
- size=kwargs.get('size',(16,4))
123
- legend=kwargs.get('legend',True)
124
- fig,ax=plt.subplots(1,1,figsize=size)
145
+ size = kwargs.get('size', (16,4))
146
+ legend = kwargs.get('legend', True)
147
+ fig, ax = plt.subplots(1, 1, figsize=size)
125
148
  plt.xlabel(xlabel)
126
149
  plt.ylabel(ylabel)
127
- cmapname=kwargs.get('colormap','plasma')
128
- cmap=cm.get_cmap(cmapname)
150
+ cmapname = kwargs.get('colormap', 'plasma')
151
+ cmap = _get_cmap(cmapname)
129
152
 
130
- ndatasets=len(xnames)
131
- assert ndatasets==len(ynames)
153
+ ndatasets = len(xnames)
154
+ assert ndatasets == len(ynames)
132
155
 
133
- for i,(df,x,y,l) in enumerate(zip(dfL,xnames,ynames,labels)):
134
- ax.plot(df[x],df[y],label=l,color=cmap(i/ndatasets))
156
+ for i, (df, x, y, l) in enumerate(zip(dfL, xnames, ynames, labels)):
157
+ ax.plot(df[x], df[y], label=l, color=cmap(i/ndatasets))
135
158
 
136
159
  if legend:
137
160
  plt.legend()
@@ -141,7 +164,7 @@ def multi_trace(dfL,xnames,ynames,labels=[],xlabel='time [ps]',ylabel='',outfile
141
164
  logging.disable(logging.NOTSET)
142
165
 
143
166
 
144
- def global_trace(df,names,outfile='plot.png',transition_times=[],markers=[],interval_labels=[],y2names=[],**kwargs):
167
+ def global_trace(df, names, outfile='plot.png', transition_times=[], markers=[], interval_labels=[], y2names=[], **kwargs):
145
168
  """Generates custom-formatted multiplots of energy-like quantities named in 'names' in the input dataframe df.
146
169
 
147
170
  Args:
@@ -154,65 +177,64 @@ def global_trace(df,names,outfile='plot.png',transition_times=[],markers=[],inte
154
177
  y2names (list): names of quantities to be plotted on a secondary y axis, defaults to []
155
178
  """
156
179
  # disable debug-level logging and above since matplotlib has a lot of debug statements
157
- default_units={'Temperature':'K','Pressure':'bar','Density':'kg/m^3','Potential':'kJ/mol'}
158
- units=kwargs.get('units',default_units)
180
+ default_units = {'Temperature': 'K', 'Pressure': 'bar', 'Density': r'kg/m$^3$', 'Potential': 'kJ/mol'}
181
+ units = kwargs.get('units', default_units)
159
182
  logging.disable(logging.DEBUG)
160
- size=kwargs.get('size',(16,4*len(names)))
161
- legend=kwargs.get('legend',False)
162
- fig,ax=plt.subplots(len(names),1,figsize=size)
163
- plt.xlabel('time(ps)')
164
- cmapname=kwargs.get('colormap','plasma')
183
+ size = kwargs.get('size', (16, 4*len(names)))
184
+ legend = kwargs.get('legend',False)
185
+ fig, ax = plt.subplots(len(names),1,figsize=size)
186
+ plt.xlabel('time (ps)')
187
+ cmapname = kwargs.get('colormap','plasma')
165
188
  # yunits=kwargs.get('yunits',None)
166
- cmap=cm.get_cmap(cmapname)
189
+ cmap = _get_cmap(cmapname)
167
190
  # print(f'in global_trace:\n{df.head().to_string()}')
168
191
 
169
-
170
- interval_times=[]
192
+ interval_times = []
171
193
  if interval_labels:
172
- for i in range(1,len(transition_times)):
173
- interval_times.append((transition_times[i]+transition_times[i-1])/2)
174
- for l,t in zip(interval_labels,interval_times):
194
+ for i in range(1, len(transition_times)):
195
+ interval_times.append((transition_times[i] + transition_times[i-1]) / 2)
196
+ for l, t in zip(interval_labels, interval_times):
175
197
  logger.info(f'{t} {l}')
176
- assert len(interval_labels)==len(interval_times)
177
- L,R=-1,-1
178
- if len(markers)>1:
179
- L,R=markers[0],markers[-1]
180
- in_tt=[x for x in transition_times if L<x<R]
181
- marked_df=df[(df['time(ps)']>L)&(df['time(ps)']<R)]
182
- fig,ax=plt.subplots(len(names)*2,1,figsize=size)
183
- for i,colname in enumerate(names):
184
- out_ax=ax[0] if len(names)==1 else ax[i*2]
185
- in_ax=ax[1] if len(names)==1 else ax[i*2+1]
186
- out_ax.plot(df['time(ps)'],df[colname],label=colname)
187
- ylabel=colname
188
- if ylabel in units: ylabel+=f' ({units[ylabel]})'
198
+ assert len(interval_labels) == len(interval_times)
199
+ L, R = -1, -1
200
+ if len(markers) > 1:
201
+ L, R = markers[0], markers[-1]
202
+ in_tt = [x for x in transition_times if L < x < R]
203
+ marked_df = df[(df['time(ps)'] > L) & (df['time(ps)'] < R)]
204
+ fig, ax = plt.subplots(len(names)*2, 1, figsize=size)
205
+ for i, colname in enumerate(names):
206
+ out_ax = ax[0] if len(names) == 1 else ax[i * 2]
207
+ in_ax = ax[1] if len(names) == 1 else ax[i * 2 + 1]
208
+ out_ax.plot(df['time(ps)'], df[colname], label=colname)
209
+ ylabel = colname
210
+ if ylabel in units: ylabel += f' ({units[ylabel]})'
189
211
  out_ax.set_ylabel(ylabel)
190
- out_ax.set_xlabel('time(ps)')
212
+ out_ax.set_xlabel('time (ps)')
191
213
  if len(y2names)>i:
192
214
  out_ax2=out_ax.twinx()
193
- out_ax2.plot(df['time(ps)'],df[y2names[i]],label=y2names[i],color='black')
215
+ out_ax2.plot(df['time(ps)'], df[y2names[i]], label=y2names[i], color='black')
194
216
  ylabel=y2names[i]
195
217
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
196
218
  out_ax2.set_ylabel(ylabel)
197
- out_ax2.set_xlabel('time(ps)')
219
+ out_ax2.set_xlabel('time (ps)')
198
220
  if len(transition_times)>0:
199
221
  colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
200
222
  ylim=out_ax.get_ylim()
201
223
  out_ax.vlines(transition_times,ylim[0],ylim[1],color=colors,linewidth=0.75,alpha=0.5)
202
224
  # for x,l in zip(interval_times,interval_labels):
203
225
  # out_ax.text(x,0.9*ylim[1],l,fontsize=8)
204
- in_ax.plot(marked_df['time(ps)'],marked_df[colname],label=colname)
226
+ in_ax.plot(marked_df['time(ps)'], marked_df[colname], label=colname)
205
227
  ylabel=colname
206
228
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
207
- in_ax.set_xlabel('time(ps)')
208
- in_ax.set_yabel(ylabel)
229
+ in_ax.set_xlabel('time (ps)')
230
+ in_ax.set_ylabel(ylabel)
209
231
  if len(y2names)>i:
210
232
  in_ax2=in_ax.twinx()
211
- in_ax2.plot(marked_df['time(ps)'],marked_df[y2names[i]],label=y2names[i],color='black')
233
+ in_ax2.plot(marked_df['time(ps)'], marked_df[y2names[i]], label=y2names[i], color='black')
212
234
  ylabel=y2names[i]
213
235
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
214
236
  in_ax2.set_ylabel(ylabel)
215
- in_ax2.set_xlabel('time(ps)')
237
+ in_ax2.set_xlabel('time (ps)')
216
238
  if len(transition_times)>0:
217
239
  colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
218
240
  ylim=in_ax.get_ylim()
@@ -224,14 +246,14 @@ def global_trace(df,names,outfile='plot.png',transition_times=[],markers=[],inte
224
246
  fig,ax=plt.subplots(len(names),1,figsize=size)
225
247
  for i,colname in enumerate(names):
226
248
  the_ax=ax if len(names)==1 else ax[i]
227
- the_ax.plot(df['time(ps)'],df[colname],label=colname)
249
+ the_ax.plot(df['time(ps)'], df[colname], label=colname)
228
250
  ylabel=colname
229
251
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
230
252
  the_ax.set_ylabel(ylabel)
231
- the_ax.set_xlabel('time(ps)')
253
+ the_ax.set_xlabel('time (ps)')
232
254
  if len(y2names)>i:
233
255
  the_ax2=the_ax.twinx()
234
- the_ax2.plot(df['time(ps)'],df[y2names[i]],label=y2names[i],color='black')
256
+ the_ax2.plot(df['time(ps)'], df[y2names[i]], label=y2names[i], color='black')
235
257
  ylabel=y2names[i]
236
258
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
237
259
  the_ax2.set_ylabel(ylabel)
@@ -242,12 +264,167 @@ def global_trace(df,names,outfile='plot.png',transition_times=[],markers=[],inte
242
264
 
243
265
  # plt.xlabel('time(ps)')
244
266
  if legend:
245
- plt.legend()
267
+ plt.legend(loc='right')
246
268
  plt.savefig(outfile)
247
269
  plt.close(fig)
248
270
  # re-establish previous logging level
249
271
  logging.disable(logging.NOTSET)
250
272
 
273
+ def draw_reaction_dag(rlist, filename, format='png'):
274
+ """Render the user-declared reaction set as a bipartite DAG via graphviz.
275
+
276
+ Each molecule template is a rounded box; each reaction is a diamond
277
+ that takes incoming edges from its reactants and emits an outgoing
278
+ edge to its product. Colors encode role (constituent / intermediate
279
+ / final product) and reaction stage (param / build / cure / cap /
280
+ repair).
281
+
282
+ Procession-expanded reactions (where the YAML declared one reaction
283
+ with ``procession.count: N`` and `parse_reaction_list` exploded it
284
+ into N+1 sequential reactions producing intermediate ``<product>_I0``
285
+ .. ``<product>_I{N-1}`` molecules) are collapsed back into a single
286
+ reaction node labeled with the iteration count; the synthetic
287
+ intermediates are hidden so the graph stays close to what the user
288
+ wrote.
289
+
290
+ Args:
291
+ rlist (ReactionList): reactions as returned by
292
+ ``parse_reaction_list`` (i.e. already procession-expanded).
293
+ filename (str): output path with or without the format suffix;
294
+ the suffix is stripped before passing to graphviz so e.g.
295
+ ``filename='plots/reaction_network.png'`` works.
296
+ format (str): graphviz output format, defaults to 'png'.
297
+
298
+ Returns:
299
+ str: the actual output path written.
300
+ """
301
+ import os
302
+ import re
303
+ import graphviz
304
+
305
+ # Reaction-stage palette. Param / build are setup-time bookkeeping
306
+ # so they get muted blue/green; cure / cap / repair are the
307
+ # runtime-firing stages so they get higher-contrast warm hues.
308
+ stage_color = {
309
+ 'param': '#a8c5e8',
310
+ 'build': '#b8d8a8',
311
+ 'cure': '#e8a8a8',
312
+ 'cap': '#e8c8a8',
313
+ 'repair': '#c8a8e8',
314
+ 'unset': '#cccccc',
315
+ 'build_stage_intermediate': '#dddddd',
316
+ }
317
+
318
+ # --- collapse procession expansions ---
319
+ # parse_reaction_list renames the original reaction to '<name>-i0'
320
+ # and synthesizes -i1 .. -i{count} producing intermediates
321
+ # '<product>_I0' .. '<product>_I{count-1}'. Detect the group by
322
+ # the trailing '-iN' suffix and treat the whole group as one logical
323
+ # reaction. The first member (-i0) gives the true reactant set;
324
+ # the last member's product is the user-declared final product.
325
+ proc_pattern = re.compile(r'^(.+)-i(\d+)$')
326
+ procession_groups = {} # base_name -> list of (idx, Reaction) ordered by iteration
327
+ standalone = [] # list of (idx, Reaction)
328
+ for i, R in enumerate(rlist):
329
+ m = proc_pattern.match(R.name)
330
+ if m:
331
+ procession_groups.setdefault(m.group(1), []).append((int(m.group(2)), R))
332
+ else:
333
+ standalone.append((i, R))
334
+ for k in procession_groups:
335
+ procession_groups[k].sort(key=lambda x: x[0])
336
+
337
+ # Intermediates synthesized by procession that we'll hide. Any
338
+ # molecule name '<base>_I{k}' for k in [0, count-1] inside a
339
+ # procession group is a synthetic intermediate.
340
+ hidden_intermediates = set()
341
+ for base, group in procession_groups.items():
342
+ for _, R in group[:-1]:
343
+ hidden_intermediates.add(R.product)
344
+
345
+ # --- build the molecule census ---
346
+ # Inputs: appear as reactants but never as products.
347
+ # Intermediates: appear as both.
348
+ # Finals: appear only as products (terminal in the DAG).
349
+ all_reactants, all_products = set(), set()
350
+ for R in rlist:
351
+ all_products.add(R.product)
352
+ for r in R.reactants.values():
353
+ all_reactants.add(r)
354
+ inputs = all_reactants - all_products
355
+ finals = all_products - all_reactants
356
+ intermediates = all_products & all_reactants
357
+
358
+ def molecule_style(name):
359
+ if name in inputs:
360
+ return {'fillcolor': '#d8e8f8', 'style': 'filled,rounded'}
361
+ if name in finals:
362
+ return {'fillcolor': '#c8e8c8', 'style': 'filled,rounded'}
363
+ return {'fillcolor': '#f8f0c8', 'style': 'filled,rounded'} # intermediate
364
+
365
+ # --- emit the dot graph ---
366
+ g = graphviz.Digraph(
367
+ 'reaction_network',
368
+ graph_attr={
369
+ 'rankdir': 'LR',
370
+ 'fontname': 'Helvetica',
371
+ 'fontsize': '10',
372
+ 'nodesep': '0.25',
373
+ 'ranksep': '0.6',
374
+ },
375
+ node_attr={'fontname': 'Helvetica', 'fontsize': '10'},
376
+ edge_attr={'fontname': 'Helvetica', 'fontsize': '9', 'arrowsize': '0.6'},
377
+ )
378
+
379
+ # molecule nodes (skipping hidden procession intermediates)
380
+ for m in inputs | finals | intermediates:
381
+ if m in hidden_intermediates:
382
+ continue
383
+ g.node(m, label=m, shape='box', **molecule_style(m))
384
+
385
+ # reaction nodes + edges
386
+ def add_reaction_node(rxn_id, label, stage_name):
387
+ color = stage_color.get(stage_name, stage_color['unset'])
388
+ g.node(
389
+ rxn_id,
390
+ label=label,
391
+ shape='diamond',
392
+ style='filled',
393
+ fillcolor=color,
394
+ fontsize='9',
395
+ )
396
+
397
+ rxn_seq = 0
398
+ for i, R in standalone:
399
+ rxn_id = f'_rxn_{rxn_seq}'
400
+ rxn_seq += 1
401
+ label = f'{R.name}\\n[{R.stage}]'
402
+ add_reaction_node(rxn_id, label, str(R.stage))
403
+ for r in R.reactants.values():
404
+ g.edge(r, rxn_id)
405
+ g.edge(rxn_id, R.product)
406
+
407
+ for base, group in procession_groups.items():
408
+ rxn_id = f'_rxn_{rxn_seq}'
409
+ rxn_seq += 1
410
+ first_R = group[0][1]
411
+ last_R = group[-1][1]
412
+ count = len(group)
413
+ label = f'{base}\\n[{first_R.stage}]\\n(×{count})'
414
+ add_reaction_node(rxn_id, label, str(first_R.stage))
415
+ for r in first_R.reactants.values():
416
+ g.edge(r, rxn_id)
417
+ g.edge(rxn_id, last_R.product)
418
+
419
+ # graphviz appends the format suffix itself, so strip any we got
420
+ base, ext = os.path.splitext(filename)
421
+ if ext.lstrip('.').lower() == format.lower():
422
+ out_base = base
423
+ else:
424
+ out_base = filename
425
+ return g.render(out_base, format=format, cleanup=True)
426
+
427
+
251
428
  def network_graph(G,filename,**kwargs):
252
429
  """Draws a custom formatted network plot from graph G.
253
430
 
@@ -260,7 +437,7 @@ def network_graph(G,filename,**kwargs):
260
437
  figsize=kwargs.get('figsize',(32,32))
261
438
  node_size=kwargs.get('node_size',200)
262
439
  with_labels=kwargs.get('with_labels',False)
263
- cmap=cm.get_cmap('seismic')
440
+ cmap=_get_cmap('seismic')
264
441
  fig,ax=plt.subplots(1,1,figsize=figsize)
265
442
  ax.axis('off')
266
443
  molnames=list(set([n.get('molecule_name','anonymous') for k,n in G.nodes.items()]))
@@ -275,10 +452,14 @@ def network_graph(G,filename,**kwargs):
275
452
  logging.disable(logging.NOTSET)
276
453
 
277
454
  # below are representive diagnostic output lines to establish extraction patterns
278
- _template_1='2022-08-11 17:40:36,969 HTPolyNet.runtime.my_logger INFO> ********* Connect-Update-Relax-Equilibrate (CURE) begins **********'
279
- _template_1_token_idx=[2,3,5,7]
280
- _template_2='2022-09-03 19:32:46,830 HTPolyNet.curecontroller.do_iter INFO> Iteration 1 current conversion 0.283 or 1082 bonds'
281
- _template_2_token_idx=[2,3,6,7]
455
+ _template_1='2026-05-29 04:26:48,821 htpolynet.core.runtime.my_logger INFO> ********* Connect-Update-Relax-Equilibrate (CURE) begins **********'
456
+ # Match on log-level + distinctive message tokens, NOT the module path.
457
+ # The module path token (index 2) was historically included here but kept
458
+ # breaking the parser when we reorganized modules — the message body alone
459
+ # is distinctive enough.
460
+ _template_1_token_idx=[3,5,7]
461
+ _template_2='2026-05-29 04:29:10,323 htpolynet.cure.curecontroller.do_iter INFO> Iteration 1 current conversion 0.222 or 160 bonds'
462
+ _template_2_token_idx=[3,6,7]
282
463
  _template_2_data_idx={'iter':(int,5),'conv':(float,8),'nbonds':(int,10)}
283
464
 
284
465
  def _token_match(l,template,pat_idx):
@@ -308,15 +489,15 @@ def _parse_data(dat,l,idx_dict):
308
489
  conv,s=v
309
490
  dat[k].append(conv(tok[s]))
310
491
 
311
- def diagnostics_graphs(logfiles,filename,**kwargs):
492
+ def diagnostics_graphs(logfiles, filename, **kwargs):
312
493
  """Extracts selected data from the diagnostic output and generates plots.
313
494
 
314
495
  Args:
315
496
  logfiles (list): list of names of diagnostic log files to treat in parallel
316
497
  filename (str): name of output image file
317
498
  """
318
- xmax=kwargs.get('xmax',-1)
319
- figsize=kwargs.get('figsize',(12,6))
499
+ xmax = kwargs.get('xmax',-1)
500
+ figsize = kwargs.get('figsize',(18,6))
320
501
  logging.disable(logging.DEBUG)
321
502
  df:dict[pd.DataFrame]={}
322
503
  for logfile in logfiles:
@@ -346,20 +527,38 @@ def diagnostics_graphs(logfiles,filename,**kwargs):
346
527
  # print('data',f'{data}')
347
528
  df[logfile]=pd.DataFrame(data)
348
529
  time_idx=list(df[logfile].columns).index('time')
349
- df[logfile]['elapsed']=(df[logfile]['time']-df[logfile].iloc[0,time_idx]).astype(int)/1.e9/3600.0
530
+ # Use dt.total_seconds() instead of .astype(int) — the latter
531
+ # returns the underlying-dtype int (microseconds in modern
532
+ # pandas, not nanoseconds), so /1e9 was silently off by 1000.
533
+ df[logfile]['elapsed']=(df[logfile]['time']-df[logfile].iloc[0,time_idx]).dt.total_seconds()/3600.0
350
534
  df[logfile].to_csv(f'{bn}.csv',index=False,sep=' ',header=True)
351
- fig,ax=plt.subplots(1,2,sharex=True,figsize=figsize)
535
+ fig, ax = plt.subplots(1, 3, sharex=False, figsize=figsize)
536
+ ax[0].grid(True)
537
+ ax[1].grid(True)
538
+ ax[2].grid(True)
352
539
  ax[0].set_ylim([0,1])
540
+ ax[0].set_yticks(np.arange(0, 1.1, 0.1))
353
541
  ax[0].set_xlabel('runtime (h)')
354
542
  ax[0].set_ylabel('conversion')
355
- ax[1].set_xlabel('runtime (h)')
356
- ax[1].set_ylabel('iteration')
357
- if xmax>-1:
358
- ax[0].set_xlim([0,xmax])
543
+ ax[1].set_ylabel('runtime (h)')
544
+ ax[1].set_xlabel('CURE iteration')
545
+ ax[1].set_xlim([1, df[logfile].shape[0]])
546
+ ax[1].set_xticks(range(1, df[logfile].shape[0] + 1))
547
+ ax[2].set_xlabel('CURE iteration')
548
+ ax[2].set_ylabel('conversion')
549
+ ax[2].set_ylim([0,1])
550
+ ax[2].set_yticks(np.arange(0, 1.1, 0.1))
551
+ ax[2].set_xticks(range(1, df[logfile].shape[0] + 1))
552
+ ax[2].set_xlim([1, df[logfile].shape[0]])
553
+ if xmax == -1: # use autodetected xmax
554
+ xmax = np.max([df[logfile]['elapsed'].max() for logfile in logfiles])
555
+ ax[0].set_xlim([0,xmax])
556
+ ax[1].set_ylim([0,xmax])
359
557
  for logfile in logfiles:
360
- ax[0].plot(df[logfile]['elapsed'],df[logfile]['conv'],label=logfile)
361
- ax[1].plot(df[logfile]['elapsed'],df[logfile].index+1,label=logfile)
362
- plt.legend()
558
+ ax[0].scatter(df[logfile]['elapsed'], df[logfile]['conv'], label=logfile)
559
+ ax[1].scatter(df[logfile].index+1, df[logfile]['elapsed'], label=logfile)
560
+ ax[2].scatter(df[logfile].index+1, df[logfile]['conv'], label=logfile)
561
+ # plt.legend()
363
562
  plt.savefig(filename)
364
563
  plt.close(fig)
365
564
  logging.disable(logging.NOTSET)
@@ -407,40 +606,40 @@ def diag_plots(args):
407
606
  if not plotfile:
408
607
  plotfile='cure_info.png'
409
608
  if len(diags)>0:
410
- diagnostics_graphs(diags,plotfile)
609
+ diagnostics_graphs(diags, plotfile)
411
610
 
412
611
  def build_plots(args):
413
- GmxNames={'t':'Temperature','d':'Density','p':'Potential'}
414
- plot_types=args.buildplot
415
- trace_types=[]
612
+ GmxNames = {'t': 'Temperature', 'd': 'Density', 'p': 'Potential'}
613
+ plot_types = args.buildplot
614
+ trace_types = []
416
615
  if 't' in plot_types:
417
- trace_types=[GmxNames[i] for i in args.traces]
616
+ trace_types = [GmxNames[i] for i in args.traces]
418
617
  for p in args.proj:
419
618
  if trace_types:
420
- df,transition_times,cure_markers,interval_labels=density_evolution(p)
421
- global_trace(df,trace_types,os.path.join(p,'buildtraces.png'),transition_times=transition_times,markers=[],interval_labels=interval_labels,y2names=['nbonds','nbonds'],legend=True)
422
- df.to_csv(os.path.join(p,'buildtraces.csv'),index=False,header=True,float_format='{:.3f}'.format)
619
+ df, transition_times, cure_markers, interval_labels = density_evolution(p)
620
+ global_trace(df, trace_types, os.path.join(p, 'buildtraces.png'), transition_times=transition_times, markers=[], interval_labels=interval_labels, y2names=['nbonds', 'nbonds'], legend=True)
621
+ df.to_csv(os.path.join(p, 'buildtraces.csv'), index=False, header=True,float_format='{:.3f}'.format)
423
622
  if any([x in plot_types for x in 'gnc']):
424
- G=init_molecule_graph(p)
425
- n=1
426
- while os.path.exists(os.path.join(p,f'systems/iter-{n}/2-cure_update-bonds.csv')):
623
+ G = init_molecule_graph(p)
624
+ n = 1
625
+ while os.path.exists(os.path.join(p, f'systems/iter-{n}/2-cure_update-bonds.csv')):
427
626
  logger.info(f'iter-{n}/2-cure_update-bonds.csv')
428
- g=graph_from_bondsfile(os.path.join(p,f'systems/iter-{n}/2-cure_update-bonds.csv'))
429
- G=nx.compose(G,g)
627
+ g=graph_from_bondsfile(os.path.join(p, f'systems/iter-{n}/2-cure_update-bonds.csv'))
628
+ G = nx.compose(G,g)
430
629
  if 'g' in plot_types:
431
- network_graph(G,os.path.join(p,f'plots/iter-{n}-graph.png'))
432
- n+=1
433
- if 'g' in plot_types: network_graph(G,os.path.join(p,'graph.png'))
630
+ network_graph(G, os.path.join(p, f'plots/iter-{n}-graph.png'))
631
+ n += 1
632
+ if 'g' in plot_types: network_graph(G, os.path.join(p, 'graph.png'))
434
633
  if 'c' in plot_types:
435
- clu=clusters(G)
436
- clu.to_csv(os.path.join(p,'clusters.csv'),sep=' ',header=True,index=False)
634
+ clu = clusters(G)
635
+ clu.to_csv(os.path.join(p, 'clusters.csv'), sep=' ', header=True, index=False)
437
636
  logger.info(f'{os.path.join(p,"clusters.csv")} created.')
438
637
  # cluster_plot(clu,os.path.join(p,"clusters.png"))
439
638
  if 'n' in plot_types:
440
- am=mwbxl(G)
441
- logger.info(f'Avg homo-N between xlinks: {np.average(am["n"],weights=am["counts"]):.2f}')
442
- am.to_csv(os.path.join(p,'dist_bw_xlinks.csv'),sep=' ',index=False,header=True)
443
- logger.info(f'{os.path.join(p,"dist_bw_xlinks.csv")} created.')
639
+ am = mwbxl(G)
640
+ logger.info(f'Avg homo-N between xlinks: {np.average(am["n"], weights=am["counts"]):.2f}')
641
+ am.to_csv(os.path.join(p, 'dist_bw_xlinks.csv'), sep=' ', index=False, header=True)
642
+ logger.info(f'{os.path.join(p, "dist_bw_xlinks.csv")} created.')
444
643
  # dist_bw_xlinks_plot(am,os.path.join(p,"dist_bw_xlinks.png"))
445
644
 
446
645
  def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[10,20]):
htpolynet/cli.py CHANGED
@@ -127,7 +127,7 @@ def _add_run_options(p, loglevel='debug'):
127
127
  p.add_argument('-restart',default=False,action='store_true',help='restart in latest proj dir (EXPERIMENTAL: broken at the cure stage; see usage docs)')
128
128
  p.add_argument('--no-banner',default=False,action='store_true',help='suppress the startup banner')
129
129
  p.add_argument('--force-parameterization',default=False,action='store_true',help='force GAFF parameterization of any input mol2 structures')
130
- p.add_argument('--force-checkin',default=False,action='store_true',help='force check-in of generated parameter files to the system library')
130
+ p.add_argument('--force-checkin',default=False,action='store_true',help='overwrite entries already in the user library (~/.htpolynet, or $HTPOLYNET_CACHE) with newly generated parameter files; a name the library does not yet hold is checked in either way')
131
131
  p.add_argument('--param-only',default=False,action='store_true',help='stop after parameterizing molecules without building the full system')
132
132
  p.add_argument('--loglevel',type=str,default=loglevel,help='log level for the diagnostic file (debug|info)')
133
133
 
@@ -86,6 +86,7 @@ class BondTemplate:
86
86
  valid description of `other` (an as-found system bond instance).
87
87
 
88
88
  Strict equality on:
89
+
89
90
  - atom names (``names``)
90
91
  - residue names (``resnames``) and ``intraresidue`` flag
91
92
  - one-away context (``oneaway_resnames`` / ``oneaway_atomnames``) —
@@ -93,6 +94,7 @@ class BondTemplate:
93
94
  trimer- vs tetramer-context bonds, so the match has to be exact.
94
95
 
95
96
  Subset semantics on bystanders:
97
+
96
98
  - paired ``(bystander_resname, bystander_atomname)`` items are
97
99
  treated as a multiset on each side; every item the template
98
100
  declares must appear in the instance, but the instance may