HTPolyNet 2.19.0__py3-none-any.whl → 2.20.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.
Files changed (68) hide show
  1. htpolynet/analysis/analyze.py +31 -28
  2. htpolynet/analysis/plot.py +46 -20
  3. htpolynet/analysis/postsim.py +17 -13
  4. htpolynet/analysis/utils.py +29 -35
  5. htpolynet/cli.py +38 -7
  6. htpolynet/core/bondtemplate.py +14 -14
  7. htpolynet/core/coordinates.py +12 -60
  8. htpolynet/core/molecule.py +45 -191
  9. htpolynet/core/projectfilesystem.py +13 -16
  10. htpolynet/core/runtime.py +215 -59
  11. htpolynet/core/seeding.py +1 -1
  12. htpolynet/core/topocoord.py +60 -487
  13. htpolynet/core/topology.py +124 -197
  14. htpolynet/cure/chain.py +58 -10
  15. htpolynet/cure/curecontroller.py +91 -53
  16. htpolynet/cure/expandreactions.py +4 -5
  17. htpolynet/cure/reaction.py +11 -25
  18. htpolynet/cure/ringcontroller.py +29 -10
  19. htpolynet/cure/triplesearch.py +9 -7
  20. htpolynet/external/ambertools.py +2 -2
  21. htpolynet/external/gromacs.py +52 -52
  22. htpolynet/external/slurm.py +6 -2
  23. htpolynet/external/smiles_input.py +8 -6
  24. htpolynet/external/software.py +9 -4
  25. htpolynet/geometry/bondlist.py +7 -48
  26. htpolynet/geometry/linkcell.py +8 -40
  27. htpolynet/geometry/matrix4.py +5 -2
  28. htpolynet/geometry/piercing.py +4 -4
  29. htpolynet/geometry/ring.py +10 -64
  30. htpolynet/io/__init__.py +1 -0
  31. htpolynet/io/mol2.py +2 -2
  32. htpolynet/io/pdb.py +1 -2
  33. htpolynet/repair/cyanate_cap.py +7 -9
  34. htpolynet/repair/topology_surgery.py +1 -29
  35. htpolynet/resources/README.md +11 -15
  36. htpolynet/resources/claude/SKILL.md +12 -4
  37. htpolynet/resources/example_depot/0-liquid-styrene.yaml +1 -1
  38. htpolynet/resources/example_depot/2-bisgma-styrene-thermoset.yaml +1 -6
  39. htpolynet/schema/base.yaml +65 -48
  40. htpolynet/utils/checkpoint.py +6 -6
  41. htpolynet/utils/convergence.py +3 -3
  42. htpolynet/utils/dataframetools.py +17 -36
  43. htpolynet/utils/inputcheck.py +61 -13
  44. htpolynet/utils/logsetup.py +92 -7
  45. {htpolynet-2.19.0.dist-info → htpolynet-2.20.0.dist-info}/METADATA +1 -1
  46. htpolynet-2.20.0.dist-info/RECORD +96 -0
  47. htpolynet/resources/molecules/make-monomers.sh +0 -64
  48. htpolynet/resources/molecules/pics/DFA.png +0 -0
  49. htpolynet/resources/molecules/pics/DGE.png +0 -0
  50. htpolynet/resources/molecules/pics/EMB.png +0 -0
  51. htpolynet/resources/molecules/pics/FDE.png +0 -0
  52. htpolynet/resources/molecules/pics/GMA.png +0 -0
  53. htpolynet/resources/molecules/pics/PAC.png +0 -0
  54. htpolynet/resources/molecules/pics/STY.png +0 -0
  55. htpolynet/resources/molecules/sample-inputs/DFA.pdb +0 -62
  56. htpolynet/resources/molecules/sample-inputs/DGE.mol2 +0 -115
  57. htpolynet/resources/molecules/sample-inputs/EMB.mol2 +0 -50
  58. htpolynet/resources/molecules/sample-inputs/FDE.pdb +0 -72
  59. htpolynet/resources/molecules/sample-inputs/GMA.mol2 +0 -163
  60. htpolynet/resources/molecules/sample-inputs/PAC.mol2 +0 -91
  61. htpolynet/resources/molecules/sample-inputs/STY.mol2 +0 -44
  62. htpolynet/resources/tcl/readbonds.tcl +0 -32
  63. htpolynet/resources/tcl/readgrx.tcl +0 -46
  64. htpolynet/resources/tcl/render.tcl +0 -74
  65. htpolynet-2.19.0.dist-info/RECORD +0 -114
  66. {htpolynet-2.19.0.dist-info → htpolynet-2.20.0.dist-info}/WHEEL +0 -0
  67. {htpolynet-2.19.0.dist-info → htpolynet-2.20.0.dist-info}/entry_points.txt +0 -0
  68. {htpolynet-2.19.0.dist-info → htpolynet-2.20.0.dist-info}/licenses/LICENSE +0 -0
@@ -31,21 +31,22 @@ class Analyze:
31
31
  for p,v in self.default_params.items():
32
32
  self.params[p]=indict.get(p,v)
33
33
  for p,v in indict.items():
34
- if not p in self.allowed_keys:
35
- if strict:
36
- logger.info(f'Ignoring directive \'{p}\' in yaml input file')
34
+ if not p in self.allowed_keys and strict:
35
+ # this used to say "Ignoring" at INFO and then keep the key anyway
36
+ logger.warning(f'Ignoring unknown directive \'{p}\' in the analyze config '
37
+ f'(known: {", ".join(self.allowed_keys)})')
38
+ continue
37
39
  if p in self.default_params:
38
- logger.info(f'Overwriting default {p} value')
40
+ logger.debug(f'Overwriting default {p} value')
39
41
  self.params[p]=v
40
42
  self.console_output=None
41
43
 
42
44
  def do(self,**gromacs_dict):
43
45
  """Handles executing the analysis."""
44
46
  p=self.params
45
- print(p)
47
+ logger.debug(f'analyze stage {p}')
46
48
  for rk in self.required_keys:
47
49
  assert rk in p, f'Error: no {rk} value found'
48
- # logger.info(f'do {p}')
49
50
  # if a gromacs dict is passed in, assume this overrides the one read in from the file
50
51
  if gromacs_dict:
51
52
  software.set_gmx_preferences(gromacs_dict)
@@ -141,19 +142,21 @@ class AnalyzeFFV(Analyze):
141
142
 
142
143
 
143
144
  class AnalyzeConfiguration:
144
- """ handles reading and parsing an analysis input config file.
145
- Config file format
146
-
147
- - { key1: {<paramdict>}}
148
- - { key2: {<paramdict>}}
149
-
150
- ...
145
+ """Handles reading and parsing an analysis input config file.
151
146
 
152
- The config file is a list of single-element dictionaries, whose single keyword
153
- indicates the type of analysis to be run; analyses are run in the order
154
- they appear in the config file.
155
-
156
- """
147
+ The config file is a list of dictionaries, one per analysis, run in the
148
+ order they appear::
149
+
150
+ - command: freevolume
151
+ subdir: analyze/freevolume
152
+ options: {s: equilibrate.tpr, f: equilibrate.trr}
153
+ - command: density
154
+ ...
155
+
156
+ Each record's ``command`` names the ``gmx`` subcommand; ``density`` and
157
+ ``freevolume`` have predefined defaults, and any other command runs with
158
+ only what the record gives.
159
+ """
157
160
  default_class=Analyze
158
161
  predefined_classes={'density':AnalyzeDensity,'freevolume':AnalyzeFFV}
159
162
  def __init__(self):
@@ -163,17 +166,17 @@ class AnalyzeConfiguration:
163
166
 
164
167
  @classmethod
165
168
  def read(cls,filename,parse=True,**kwargs):
166
- """Generates a new PostsimConfiguration object by reading in the JSON or YAML file indicated by filename.
169
+ """Generates a new AnalyzeConfiguration object by reading in the JSON or YAML file indicated by filename.
167
170
 
168
171
  Args:
169
- filename (str): name of file from which to read new PostsimConfiguration object
172
+ filename (str): name of file from which to read new AnalyzeConfiguration object
170
173
  parse (bool): if True, parse the input configuration file, defaults to True
171
174
 
172
175
  Raises:
173
176
  Exception: if extension of filename is not '.json' or '.yaml' or '.yml'
174
177
 
175
178
  Returns:
176
- PostsimConfiguration: a new PostsimConfiguration object
179
+ AnalyzeConfiguration: a new AnalyzeConfiguration object
177
180
  """
178
181
  basename,extension=os.path.splitext(filename)
179
182
  if extension=='.json':
@@ -185,14 +188,14 @@ class AnalyzeConfiguration:
185
188
 
186
189
  @classmethod
187
190
  def _read_json(cls,filename,parse=True,**kwargs):
188
- """Creates a new PostsimConfiguration object by reading from JSON input.
191
+ """Creates a new AnalyzeConfiguration object by reading from JSON input.
189
192
 
190
193
  Args:
191
194
  filename (str): name of JSON file
192
195
  parse (bool): if True, parse the JSON data, defaults to True
193
196
 
194
197
  Returns:
195
- PostsimConfiguration: a new PostsimConfiguration object
198
+ AnalyzeConfiguration: a new AnalyzeConfiguration object
196
199
  """
197
200
  inst=cls()
198
201
  inst.cfgFile=filename
@@ -204,14 +207,14 @@ class AnalyzeConfiguration:
204
207
 
205
208
  @classmethod
206
209
  def _read_yaml(cls,filename,parse=True,**kwargs):
207
- """Creates a new PostsimConfiguration object by reading from YAML input.
210
+ """Creates a new AnalyzeConfiguration object by reading from YAML input.
208
211
 
209
212
  Args:
210
213
  filename (str): name of YAML file
211
214
  parse (bool): if True, parse the YAML data, defaults to True
212
215
 
213
216
  Returns:
214
- PostsimConfiguration: a new PostsimConfiguration object
217
+ AnalyzeConfiguration: a new AnalyzeConfiguration object
215
218
  """
216
219
  inst=cls()
217
220
  inst.cfgFile=filename
@@ -222,7 +225,7 @@ class AnalyzeConfiguration:
222
225
  return inst
223
226
 
224
227
  def parse(self,**kwargs):
225
- """Parses a PostsimConfiguration file to build the list of stages to run."""
228
+ """Parses a AnalyzeConfiguration file to build the list of stages to run."""
226
229
  for content in self.baselist:
227
230
  analysistype=content['command']
228
231
  if analysistype in self.predefined_classes:
@@ -236,8 +239,8 @@ def analyze(args):
236
239
  Args:
237
240
  args (argparse.Namespace): command-line arguments
238
241
  """
239
- setup_logging(args.loglevel, no_banner=args.no_banner)
240
- ess='y' if len(args.proj)==0 else 'ies'
242
+ setup_logging(args.loglevel, diag=getattr(args,'diag',None) or 'htpolynet_analyze_diagnostics.log', no_banner=args.no_banner)
243
+ ess='y' if len(args.proj)==1 else 'ies'
241
244
  ogromacs={}
242
245
  if args.ocfg:
243
246
  ocfg=Configuration.read(args.ocfg)
@@ -186,9 +186,7 @@ def global_trace(df, names, outfile='plot.png', transition_times=[], markers=[],
186
186
  fig, ax = plt.subplots(len(names),1,figsize=size)
187
187
  plt.xlabel('time (ps)')
188
188
  cmapname = kwargs.get('colormap','plasma')
189
- # yunits=kwargs.get('yunits',None)
190
189
  cmap = _get_cmap(cmapname)
191
- # print(f'in global_trace:\n{df.head().to_string()}')
192
190
 
193
191
  interval_times = []
194
192
  if interval_labels:
@@ -222,8 +220,6 @@ def global_trace(df, names, outfile='plot.png', transition_times=[], markers=[],
222
220
  colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
223
221
  ylim=out_ax.get_ylim()
224
222
  out_ax.vlines(transition_times,ylim[0],ylim[1],color=colors,linewidth=0.75,alpha=0.5)
225
- # for x,l in zip(interval_times,interval_labels):
226
- # out_ax.text(x,0.9*ylim[1],l,fontsize=8)
227
223
  in_ax.plot(marked_df['time(ps)'], marked_df[colname], label=colname)
228
224
  ylabel=colname
229
225
  if ylabel in units: ylabel+=f' ({units[ylabel]})'
@@ -240,9 +236,6 @@ def global_trace(df, names, outfile='plot.png', transition_times=[], markers=[],
240
236
  colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
241
237
  ylim=in_ax.get_ylim()
242
238
  in_ax.vlines(in_tt,ylim[0],ylim[1],color=colors,linewidth=0.75,alpha=0.5)
243
- # for x,l in zip(interval_times,interval_labels):
244
- # if L<x<R:
245
- # out_ax.text(x,0.9*ylim[1],l,fontsize=8)
246
239
  else:
247
240
  fig,ax=plt.subplots(len(names),1,figsize=size)
248
241
  for i,colname in enumerate(names):
@@ -263,7 +256,6 @@ def global_trace(df, names, outfile='plot.png', transition_times=[], markers=[],
263
256
  ylim=the_ax.get_ylim()
264
257
  the_ax.vlines(transition_times,ylim[0],ylim[1],color=colors,linewidth=0.5,alpha=0.5)
265
258
 
266
- # plt.xlabel('time(ps)')
267
259
  if legend:
268
260
  plt.legend(loc='right')
269
261
  plt.savefig(outfile)
@@ -452,7 +444,7 @@ def network_graph(G,filename,**kwargs):
452
444
  plt.close(fig)
453
445
  logging.disable(logging.NOTSET)
454
446
 
455
- # below are representive diagnostic output lines to establish extraction patterns
447
+ # below are representative diagnostic output lines to establish extraction patterns
456
448
  _template_1='2026-05-29 04:26:48,821 htpolynet.core.runtime.my_logger INFO> ********* Connect-Update-Relax-Equilibrate (CURE) begins **********'
457
449
  # Match on log-level + distinctive message tokens, NOT the module path.
458
450
  # The module path token (index 2) was historically included here but kept
@@ -520,7 +512,6 @@ def diagnostics_graphs(logfiles, filename, **kwargs):
520
512
  counter=0
521
513
  for l in lines:
522
514
  if _token_match(l,_template_1,_template_1_token_idx):
523
- # print('you should only see this once')
524
515
  counter+=1
525
516
  assert not counter>1
526
517
  data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
@@ -529,7 +520,6 @@ def diagnostics_graphs(logfiles, filename, **kwargs):
529
520
  data['nbonds'].append(0)
530
521
  elif _token_match(l,_template_2,_template_2_token_idx):
531
522
  data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
532
- # print('data tok',f'{l.split()}')
533
523
  _parse_data(data,l,_template_2_data_idx)
534
524
  elif _ring_begin_re.search(l):
535
525
  counter+=1
@@ -582,7 +572,6 @@ def diagnostics_graphs(logfiles, filename, **kwargs):
582
572
  ax[0].scatter(df[logfile]['elapsed'], df[logfile]['conv'], label=logfile)
583
573
  ax[1].scatter(df[logfile]['iter'], df[logfile]['elapsed'], label=logfile)
584
574
  ax[2].scatter(df[logfile]['iter'], df[logfile]['conv'], label=logfile)
585
- # plt.legend()
586
575
  plt.savefig(filename)
587
576
  plt.close(fig)
588
577
  logging.disable(logging.NOTSET)
@@ -613,7 +602,7 @@ def plots(args):
613
602
  Args:
614
603
  args (argparse.Namespace): command-line arguments
615
604
  """
616
- setup_logging(args.loglevel, no_banner=args.no_banner)
605
+ setup_logging(args.loglevel, diag=getattr(args,'logfile',None) or 'htpolynet_plots_diagnostics.log', no_banner=args.no_banner)
617
606
 
618
607
  if args.source=='build':
619
608
  build_plots(args)
@@ -647,7 +636,7 @@ def build_plots(args):
647
636
  G = init_molecule_graph(p)
648
637
  n = 1
649
638
  while os.path.exists(os.path.join(p, f'systems/iter-{n}/2-cure_update-bonds.csv')):
650
- logger.info(f'iter-{n}/2-cure_update-bonds.csv')
639
+ logger.info(f'reading bonds from iter-{n}/2-cure_update-bonds.csv')
651
640
  g=graph_from_bondsfile(os.path.join(p, f'systems/iter-{n}/2-cure_update-bonds.csv'))
652
641
  G = nx.compose(G,g)
653
642
  if 'g' in plot_types:
@@ -658,13 +647,48 @@ def build_plots(args):
658
647
  clu = clusters(G)
659
648
  clu.to_csv(os.path.join(p, 'clusters.csv'), sep=' ', header=True, index=False)
660
649
  logger.info(f'{os.path.join(p,"clusters.csv")} created.')
661
- # cluster_plot(clu,os.path.join(p,"clusters.png"))
662
650
  if 'n' in plot_types:
663
651
  am = mwbxl(G)
664
652
  logger.info(f'Avg homo-N between xlinks: {np.average(am["n"], weights=am["counts"]):.2f}')
665
653
  am.to_csv(os.path.join(p, 'dist_bw_xlinks.csv'), sep=' ', index=False, header=True)
666
654
  logger.info(f'{os.path.join(p, "dist_bw_xlinks.csv")} created.')
667
- # dist_bw_xlinks_plot(am,os.path.join(p,"dist_bw_xlinks.png"))
655
+
656
+ def _write_tg_csv(filename,ladder_ids,labels,rate,Tgs,per_build,spread,span,lines,unquotable):
657
+ """Writes one row per ladder: its Tg, the between-build spread, and the two fitted lines.
658
+
659
+ A Tg of -1 from :func:`compute_tg` (no crossing) is written as empty, as is any
660
+ value that was not computed. ``quotable`` is False when some fit window puts the
661
+ crossing outside the ladder, the case the log warns about.
662
+
663
+ Args:
664
+ filename (str): the csv to write
665
+ ladder_ids (list): each ladder's position in the config, as in ladder{v}-data.csv
666
+ labels (list): 'heating' or 'cooling' per ladder
667
+ rate (list): heating or cooling rate per ladder, K/ps
668
+ Tgs (list): two-line crossing Tg of the mean curve per ladder, K (-1 if none)
669
+ per_build (list): dicts with 'mean', 'sd' and 'n' of the per-build crossings
670
+ spread (list): (lo, hi) Tg over fit windows, or None, per ladder
671
+ span (list): (lo, hi) temperature range of each ladder, K
672
+ lines (list): (glassy, rubbery) [slope, intercept] pairs of density vs T, or (None, None)
673
+ unquotable (list): labels of the ladders whose Tg cannot be quoted
674
+ """
675
+ def num(x):
676
+ return None if x is None or (isinstance(x,float) and np.isnan(x)) else x
677
+ rows=[]
678
+ for v,label,r,Tg,b,w,sp,(c,h) in zip(ladder_ids,labels,rate,Tgs,per_build,spread,span,lines):
679
+ rows.append({
680
+ 'ladder':v,'direction':label,'rate_K_per_ps':r,
681
+ 'Tg_K':None if Tg==-1 else Tg,
682
+ 'Tg_per_build_mean_K':num(b.get('mean')),'Tg_per_build_sd_K':num(b.get('sd')),
683
+ 'n_builds':b.get('n'),
684
+ 'Tg_window_lo_K':None if w is None else w[0],'Tg_window_hi_K':None if w is None else w[1],
685
+ 'quotable':label not in unquotable,
686
+ 'T_lo_K':sp[0],'T_hi_K':sp[1],
687
+ 'glassy_slope_kg_m3_K':None if c is None else c[0],
688
+ 'rubbery_slope_kg_m3_K':None if h is None else h[0],
689
+ })
690
+ pd.DataFrame(rows).to_csv(filename,index=False)
691
+ logger.info(f'{filename} created.')
668
692
 
669
693
  def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[10,20]):
670
694
  """Tg from each ladder's density curve, by the two-line crossing.
@@ -685,6 +709,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
685
709
  span=[]
686
710
  whole=[]
687
711
  per_build=[]
712
+ lines=[]
713
+ ladder_ids=[]
688
714
  for i,phase in enumerate(phases):
689
715
  p=phase['ladder']
690
716
  # a ladder that crashed leaves no ladder.csv; it must not take the finished
@@ -759,6 +785,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
759
785
  ax[i].errorbar(m['Temperature'],m['Density'],std['Density'])
760
786
  Tg,c,h=compute_tg(m['Temperature'],m['Density'],n_points=n_points)
761
787
  Tgs.append(Tg)
788
+ lines.append((c,h) if Tg!=-1 else (None,None))
789
+ ladder_ids.append(v)
762
790
  spread.append(tg_window_range(m['Temperature'].values,m['Density'].values))
763
791
  curves=[(r['Temperature'].values,r['Density'].values) for r in res[v]]
764
792
  per_build.append(_crossing_per_build(curves,n_points))
@@ -851,6 +879,7 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
851
879
  first={}
852
880
  for i,label in enumerate(labels):
853
881
  first.setdefault(label,i)
882
+ _write_tg_csv(os.path.splitext(outfile)[0]+'.csv',ladder_ids,labels,rate,Tgs,per_build,spread,span,lines,unquotable)
854
883
  hTg=Tgs[first['heating']] if 'heating' in first else None
855
884
  cTg=Tgs[first['cooling']] if 'cooling' in first else None
856
885
  if hTg is not None and cTg is not None and abs(hTg-cTg)>50.0:
@@ -994,12 +1023,10 @@ def post_plots(args):
994
1023
  # command used to exit 0 having written nothing (htpolynet-sweep, 2026-10-15)
995
1024
  raise ValueError('plots post needs the postsim config that ran the stages: --cfg postsim.yaml')
996
1025
  phases=[]
997
- # print(args.cfg)
998
1026
  for c in args.cfg:
999
1027
  with open(c,'r') as f:
1000
1028
  phases+=yaml.safe_load(f)
1001
1029
  phasenames=[list(x.keys())[0] for x in phases]
1002
- # print(phasenames)
1003
1030
  mdf=[]
1004
1031
  for p in args.proj:
1005
1032
  if 'anneal' in phasenames and 'equilibrate' in phasenames:
@@ -1014,7 +1041,7 @@ def post_plots(args):
1014
1041
  mdf.append(postsim_density_evolution(p))
1015
1042
  if mdf:
1016
1043
  multi_trace(mdf,xnames=['time(ps)']*len(mdf),ynames=['Density']*len(mdf),labels=args.proj,ylabel='Density [kg/m$^3$]',outfile='anneal-equil-density.png')
1017
- logger.info('-'.join(phasenames)+'-density.png created.')
1044
+ logger.info('anneal-equil-density.png created.')
1018
1045
  m=[]
1019
1046
  for d in mdf:
1020
1047
  seg=d.iloc[int(0.9*d.shape[0]):]
@@ -1024,7 +1051,6 @@ def post_plots(args):
1024
1051
  logger.info(f'mean density {m.mean():.0f} kg/m^3 ({m.mean()/1000.0:.3f} g/cc)')
1025
1052
 
1026
1053
  ladder_phases=[idx for idx, value in enumerate(phasenames) if value == 'ladder']
1027
- # print(ladder_phases)
1028
1054
  if len(ladder_phases)>0: # perform Tg calculations on each phase
1029
1055
  do_tg_plots([phases[i] for i in ladder_phases],args.proj,n_points=n_points)
1030
1056
 
@@ -23,7 +23,7 @@ logger=logging.getLogger(__name__)
23
23
 
24
24
  class PostSimMD:
25
25
  """ Generic class for handling post-cure md simulations; this one just does simple NPT MD equilibration;
26
- Classes that inherit from this class should define their own default_params and build_npt
26
+ Classes that inherit from this class should define their own default_params and build_mdp
27
27
  """
28
28
  default_params={
29
29
  'subdir': f'{pfs.Dirs.postsim}/equilibrate',
@@ -34,7 +34,7 @@ class PostSimMD:
34
34
  'gmx': 'gmx',
35
35
  'mdrun': 'gmx mdrun',
36
36
  'options': '-quiet -nobackup',
37
- 'mdrun_single_molecule': 'gmx mdrun mdrun'
37
+ 'mdrun_single_molecule': 'gmx mdrun'
38
38
  },
39
39
  'ps': 1000,
40
40
  'T': 300,
@@ -50,7 +50,9 @@ class PostSimMD:
50
50
  for p,v in indict.items():
51
51
  if not p in self.default_params:
52
52
  if strict:
53
- logger.info(f'Ignoring directive \'{p}\' in yaml input file')
53
+ # a typo'd key used to be noted at INFO while its default ran
54
+ logger.warning(f'Ignoring unknown directive \'{p}\' in the {type(self).__name__} stage; '
55
+ f'its default runs instead (known: {", ".join(self.default_params)})')
54
56
  else:
55
57
  self.params[p]=v
56
58
 
@@ -58,10 +60,10 @@ class PostSimMD:
58
60
  """Handles executing the postsim MD simulation.
59
61
 
60
62
  Args:
61
- mdp_pfx (str): filename prefix for output files, defaults to 'npt'
63
+ mdp_pfx (str): basename of the mdp file this stage writes and runs, defaults to 'npt'
62
64
  """
63
65
  p=self.params
64
- logger.info(f'do {p}')
66
+ logger.debug(f'do {p}')
65
67
  # if a gromacs dict is passed in, assume this overrides the one read in from the file
66
68
  if gromacs_dict:
67
69
  software.set_gmx_preferences(gromacs_dict)
@@ -196,7 +198,7 @@ class PostSimLadder(PostSimMD):
196
198
  'gmx': 'gmx',
197
199
  'mdrun': 'gmx mdrun',
198
200
  'options': '-quiet -nobackup',
199
- 'mdrun_single_molecule': 'gmx mdrun mdrun'
201
+ 'mdrun_single_molecule': 'gmx mdrun'
200
202
  },
201
203
  'output_deffnm':'ladder',
202
204
  'traces': ['Temperature','Density','Volume'],
@@ -302,7 +304,7 @@ class PostSimDeform(PostSimMD):
302
304
  'gmx': 'gmx',
303
305
  'mdrun': 'gmx mdrun',
304
306
  'options': '-quiet -nobackup',
305
- 'mdrun_single_molecule': 'gmx mdrun mdrun'
307
+ 'mdrun_single_molecule': 'gmx mdrun'
306
308
  },
307
309
  'output_deffnm':'deform-x',
308
310
  'traces': ['Box-X','Pres-XX'],
@@ -409,9 +411,11 @@ class PostSimShear(PostSimMD):
409
411
  modulus is the slope of tensile stress against tensile strain.
410
412
 
411
413
  ``direction`` names the plane: ``xy`` shears the x face along y (box element YX),
412
- ``xz`` and ``yz`` likewise. The normal pressures stay coupled at ``P`` while the
413
- off-diagonal is driven, because the anisotropic barostat is given zero
414
- compressibility off the diagonal and so does not fight the deformation.
414
+ ``xz`` and ``yz`` likewise. With the default ``coupling: clamped``, the anisotropic
415
+ barostat has zero compressibility off the diagonal and on the one Cartesian
416
+ component the shear moves, so it does not fight the deformation; the other two
417
+ normal directions stay coupled at ``P``. ``coupling: isochoric`` runs with no
418
+ barostat at all.
415
419
  """
416
420
  # box element driven, the box length the strain is measured against, and the two
417
421
  # energy terms to trace, per shear plane. The deform slot order is Gromacs'
@@ -434,7 +438,7 @@ class PostSimShear(PostSimMD):
434
438
  'gmx': 'gmx',
435
439
  'mdrun': 'gmx mdrun',
436
440
  'options': '-quiet -nobackup',
437
- 'mdrun_single_molecule': 'gmx mdrun mdrun'
441
+ 'mdrun_single_molecule': 'gmx mdrun'
438
442
  },
439
443
  'output_deffnm':'shear-xy',
440
444
  'traces': ['Box-YX','Pres-XY'],
@@ -671,8 +675,8 @@ def postsim(args):
671
675
  Args:
672
676
  args (argparse.Namespace): command-line arguments
673
677
  """
674
- setup_logging(args.loglevel, no_banner=args.no_banner)
675
- ess='y' if len(args.proj)==0 else 'ies'
678
+ setup_logging(args.loglevel, diag=getattr(args,'diag',None) or 'htpolynet_postsim_diagnostics.log', no_banner=args.no_banner)
679
+ ess='y' if len(args.proj)==1 else 'ies'
676
680
  ogromacs={}
677
681
  if args.ocfg:
678
682
  ocfg=Configuration.read(args.ocfg)
@@ -56,10 +56,8 @@ def density_from_gro(gro,mollib='./lib/molecules/parameterized',units='SI'):
56
56
  fac=mfac/vfac
57
57
  return fac*mass/volume
58
58
 
59
- """ These globals are used in traversing a project directory to extract data from edr files """
59
+ # These globals are used in traversing a project directory to extract data from edr files
60
60
  _system_dirs=['densification','precure',r'iter-{iter:d}','capping','postcure']
61
- _postsim_dirs=['anneal','equilibrate']
62
- _measurement_dirs=['Tg','E']
63
61
  _md_ensembles={'nvt':['Temperature','Potential'],'npt':['Temperature','Potential','Density'],'default':['Temperature','Potential']}
64
62
  _indir_pfx={}
65
63
  _indir_pfx['densification']=[r'densified-{ens:s}',r'densified-repeat-{repeat:d}-{ens:s}']
@@ -83,7 +81,6 @@ def _concat_from_edr(df,edr,names,add=[],add_if_missing=[('Density',0.0)]):
83
81
  xshift=0.0
84
82
  if not df.empty: xshift=df.iloc[-1]['time(ps)']
85
83
  if len(names)==0: return df,xshift
86
- # print(f'{add_if_missing}')
87
84
  this_df=gmx_energy_trace(edr,names,xshift=xshift)
88
85
  for m in add:
89
86
  nm,val=m
@@ -100,6 +97,7 @@ def postsim_density_evolution(proj_dir,append_dirname=False):
100
97
 
101
98
  Args:
102
99
  proj_dir (str): name of complete project directory
100
+ append_dirname (bool): append '-<proj_dir>' to every column name, defaults to False
103
101
 
104
102
  Returns:
105
103
  pandas.DataFrame: the dataframe
@@ -116,7 +114,7 @@ def postsim_density_evolution(proj_dir,append_dirname=False):
116
114
  lt=t['time(ps)'].to_list()[-1]
117
115
  df=pd.concat((df,t))
118
116
  if append_dirname:
119
- df.rename(columns={x:f'{x}-{proj_dir}' for x in df.columns})
117
+ df=df.rename(columns={x:f'{x}-{proj_dir}' for x in df.columns})
120
118
  return df
121
119
 
122
120
  def density_evolution(proj_dir):
@@ -126,7 +124,10 @@ def density_evolution(proj_dir):
126
124
  proj_dir (str): name of complete project directory
127
125
 
128
126
  Returns:
129
- pandas.DataFrame: the dataframe
127
+ tuple: (df, transition_times, markers, interval_labels) -- the traces, the
128
+ times at which each run segment begins, the times at which each cure
129
+ iteration begins, and the edr prefix of each segment; None if proj_dir
130
+ does not exist
130
131
  """
131
132
  if not os.path.exists(proj_dir): return
132
133
  sysd=os.path.join(proj_dir,'systems')
@@ -137,10 +138,8 @@ def density_evolution(proj_dir):
137
138
  markers=[]
138
139
  nbonds=0
139
140
  for subd in _system_dirs:
140
- # print(f'subd {subd}')
141
141
  if subd==r'iter-{iter:d}' or subd=='capping' or subd=='densification':
142
- # loooking for iterations
143
- # print(iter_mark0)
142
+ # looking for iterations
144
143
  iter=1
145
144
  iter_subd_rel=subd if subd in ['capping','densification'] else subd.format(iter=iter)
146
145
  iter_subd=os.path.join(sysd,iter_subd_rel)
@@ -157,38 +156,30 @@ def density_evolution(proj_dir):
157
156
  if os.path.exists(os.path.join(iter_subd,'6-cap_update-bonds.csv')):
158
157
  bdf=pd.read_csv(os.path.join(iter_subd,'6-cap_update-bonds.csv'),sep=r'\s+',header=0,index_col=None)
159
158
  nbonds+=bdf.shape[0]
160
- # print(f'iter_subd {iter_subd} dirkey {dirkey}')
161
159
  for pfx in _indir_pfx[dirkey]:
162
- # print(f'pfx {pfx}')
163
160
  if r'stage' in pfx or r'repeat' in pfx:
164
161
  stg=1
165
162
  stg_present=any([os.path.exists(os.path.join(iter_subd,pfx.format(stage=stg,repeat=stg,ens=x))+r'.edr') for x in _md_ensembles])
166
- # print(f'{iter_subd} {stg} {pfx} stg_present {stg_present}')
167
163
  while stg_present:
168
164
  for ens,qtys in _md_ensembles.items():
169
165
  edr_pfx=os.path.join(iter_subd,pfx.format(stage=stg,repeat=stg,ens=ens))
170
166
  gro=edr_pfx+r'.gro'
171
- # print(edr_pfx,os.path.exists(edr_pfx+r'.edr'))
172
167
  if os.path.exists(edr_pfx+r'.edr'):
173
168
  density=0.0
174
169
  if ens!='npt':
175
170
  if os.path.exists(gro):
176
171
  density=density_from_gro(gro,os.path.join(proj_dir,'molecules/parameterized'))
177
- # print(f'density from gro {density}')
178
172
  df,xshift=_concat_from_edr(df,edr_pfx,qtys,add=[('nbonds',nbonds)],add_if_missing=[('Density',density)])
179
173
  transition_times.append(xshift)
180
174
  interval_labels.append([edr_pfx])
181
175
  stg+=1
182
176
  stg_present=any([os.path.exists(os.path.join(iter_subd,pfx.format(stage=stg,repeat=stg,ens=x))+r'.edr') for x in _md_ensembles])
183
- # print(f'->{iter_subd} {stg} {pfx} stg_present {stg_present}')
184
177
  elif r'equil' in pfx or r'densif' in pfx:
185
178
  eq_present=any([os.path.exists(os.path.join(iter_subd,pfx.format(ens=x))+r'.edr') for x in _md_ensembles])
186
- # print(f'{iter_subd} eq_present? {eq_present}')
187
179
  if eq_present:
188
180
  for ens,qtys in _md_ensembles.items():
189
181
  edr_pfx=os.path.join(iter_subd,pfx.format(ens=ens))
190
182
  gro=edr_pfx+r'.gro'
191
- # print(edr_pfx,os.path.exists(edr_pfx+r'.edr'),ens,qtys)
192
183
  if os.path.exists(edr_pfx+r'.edr'):
193
184
  density=0.0
194
185
  if ens!='npt':
@@ -200,19 +191,15 @@ def density_evolution(proj_dir):
200
191
  iter+=1
201
192
  iter_subd_rel=subd.format(iter=iter)
202
193
  iter_subd=os.path.join(sysd,iter_subd_rel) if r'iter' in subd else 'I_BET_THIS_FILE_DNE'
203
- # if r'iter' in subd: markers.append(df.iloc[-1]['time (ps)'])
204
194
  else:
205
195
  this_subd=os.path.join(sysd,subd)
206
196
  logger.info(f'Reading edrs in {subd}...')
207
197
 
208
198
  for pfx in _indir_pfx[subd]:
209
- # print(f'this_subd {this_subd} pfx {pfx}')
210
199
  if 'ens' in pfx:
211
200
  for ens,qtys in _md_ensembles.items():
212
201
  edr_pfx=os.path.join(this_subd,pfx.format(ens=ens))
213
202
  gro=edr_pfx+r'.gro'
214
- # print(edr_pfx,os.path.exists(edr_pfx+r'.edr'))
215
- # print(gro,os.path.exists(gro))
216
203
  if os.path.exists(edr_pfx+r'.edr'):
217
204
  density=0.0
218
205
  if ens=='nvt' and os.path.exists(gro):
@@ -223,7 +210,6 @@ def density_evolution(proj_dir):
223
210
  else:
224
211
  edr_pfx=os.path.join(this_subd,pfx.format(ens=ens))
225
212
  gro=edr_pfx+r'.gro'
226
- # print(edr_pfx,os.path.exists(edr_pfx+r'.edr'))
227
213
  if os.path.exists(edr_pfx+r'.edr'):
228
214
  density=0.0
229
215
  if os.path.exists(gro):
@@ -257,22 +243,29 @@ def mwbxl(G:nx.Graph,crosslinker='GMA',monomer='STY'):
257
243
  monomer (str): name of monomer, defaults to 'STY'
258
244
 
259
245
  Returns:
260
- pd.DataFrame: a dataframe of 'n' and 'count'
246
+ pd.DataFrame: a dataframe of 'n' and 'counts', for n from 0 to the longest bridge
247
+
248
+ Raises:
249
+ ValueError: if the graph has no molecule named ``crosslinker``
261
250
  """
251
+ if not any(d.get('molecule_name')==crosslinker for _,d in G.nodes(data=True)):
252
+ names=sorted({d.get('molecule_name') for _,d in G.nodes(data=True)})
253
+ raise ValueError(f'mwbxl: no {crosslinker} in this graph (it holds {", ".join(map(str,names))}); '
254
+ f'the crosslinker name is hardcoded for example 2')
262
255
  xG=G.copy()
263
256
  # traverse edges and label hetero/homo participants
264
257
  for n in xG.nodes():
265
258
  xG.nodes[n]['neighbor_count']=0
259
+ xG.nodes[n]['monomer_type']='homo'
266
260
  for u,v in xG.edges():
267
261
  n,m=xG.nodes[u],xG.nodes[v]
268
262
  n['neighbor_count']+=1
269
263
  m['neighbor_count']+=1
264
+ # one hetero neighbor makes a monomer hetero; a homo edge must not undo it,
265
+ # as it did when the label was whichever edge came last
270
266
  if n['molecule_name']!=m['molecule_name']:
271
267
  n['monomer_type']='hetero'
272
268
  m['monomer_type']='hetero'
273
- else:
274
- n['monomer_type']='homo'
275
- m['monomer_type']='homo'
276
269
  wipe_us=[]
277
270
  for n in xG.nodes():
278
271
  if xG.nodes[n]['molecule_name']==crosslinker:
@@ -292,7 +285,8 @@ def mwbxl(G:nx.Graph,crosslinker='GMA',monomer='STY'):
292
285
  chaintype.append('isolated')
293
286
  elif nhetero==1:
294
287
  if len(c)==1:
295
- node=list(xG.nodes.values())[0]
288
+ # this component's one node; it used to read the whole graph's first
289
+ node=xG.nodes[next(iter(c))]
296
290
  if node['neighbor_count']==1:
297
291
  chaintype.append('dangling')
298
292
  elif node['neighbor_count']==2:
@@ -308,10 +302,12 @@ def mwbxl(G:nx.Graph,crosslinker='GMA',monomer='STY'):
308
302
  mwhist[len(c)]=0
309
303
  mwhist[len(c)]+=1
310
304
  nb+=1
311
- maxlen=max(list(mwhist.keys()))
305
+ if not mwhist:
306
+ return pd.DataFrame({'n':[],'counts':[]})
307
+ maxlen=max(mwhist)
312
308
  mw=[]
313
309
  counts=[]
314
- for n in range(maxlen):
310
+ for n in range(maxlen+1): # range(maxlen) dropped the longest bridges
315
311
  cnt=mwhist.get(n,0)
316
312
  mw.append(n)
317
313
  counts.append(cnt)
@@ -349,6 +345,10 @@ def compute_tg(T,v,n_points=[10,20]):
349
345
  T (numpy.array): temperature values
350
346
  v (numpy.array): volume or density data
351
347
  n_points (list): number of points on the low and high side to fit lines to, defaults to [10,20]
348
+
349
+ Returns:
350
+ tuple: (Tg, cold_par, hot_par) -- the crossing temperature, and the (slope,
351
+ intercept) of the low-T and high-T lines
352
352
  """
353
353
  def func(x,a,b):
354
354
  return x*a+b
@@ -356,21 +356,17 @@ def compute_tg(T,v,n_points=[10,20]):
356
356
  cold_par=[]
357
357
  x=np.array(T)[:n_points[0]]
358
358
  y=np.array(v)[:n_points[0]]
359
- # logger.info(f'Tg: {len(x)} data points on cold side; begins at {x[0]}')
360
359
  cold_par,pcov=curve_fit(func,x,y)
361
360
  sse=(y-func(x,*cold_par))**2
362
361
  sst=(y-x.mean())**2
363
362
  r2=1-sse.sum()/sst.sum()
364
- # logger.info(f'cold fit: {cold_par} {r2}')
365
363
 
366
364
  x=np.array(T)[-n_points[1]:]
367
365
  y=np.array(v)[-n_points[1]:]
368
- # logger.info(f'Tg: {len(x)} data points on hot side; ends at {x[-1]}')
369
366
  hot_par,pcov=curve_fit(func,x,y)
370
367
  sse=(y-func(x,*hot_par))**2
371
368
  sst=(y-x.mean())**2
372
369
  r2=1-sse.sum()/sst.sum()
373
- # logger.info(f'hot fit: {hot_par} {r2}')
374
370
  Tg=-1
375
371
  if len(hot_par)>0 and len(cold_par)>0:
376
372
  Tg=-(hot_par[1]-cold_par[1])/(hot_par[0]-cold_par[0])
@@ -692,8 +688,6 @@ def compute_E(strain,stress,fit_domain=[10,100],fit_strain=None):
692
688
  else:
693
689
  x=np.array(strain[fit_domain[0]:fit_domain[1]])
694
690
  y=np.array(stress[fit_domain[0]:fit_domain[1]])
695
- # logger.info(f'x: {x[0]} -> {x[-1]}')
696
- # logger.info(f'y: {y[0]} -> {y[-1]}')
697
691
  # The intercept is free. A modulus is the slope; forcing the line through the
698
692
  # origin assumes the structure starts unstressed, and a glass equilibrated for
699
693
  # tens of ps does not -- example 6's reference structure started at +150-200 bar,