HTPolyNet 2.14.0__py3-none-any.whl → 2.16.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@
3
3
  Author: Cameron F. Abrams <cfa22@drexel.edu>
4
4
  """
5
5
  import logging
6
+ import re
6
7
 
7
8
  from datetime import datetime
8
9
 
@@ -462,6 +463,12 @@ _template_2='2026-05-29 04:29:10,323 htpolynet.cure.curecontroller.do_iter INFO>
462
463
  _template_2_token_idx=[3,6,7]
463
464
  _template_2_data_idx={'iter':(int,5),'conv':(float,8),'nbonds':(int,10)}
464
465
 
466
+ # The ring cure logs its own pair, and its lines vary in token count (the group
467
+ # tuple), so they are matched by pattern. A ring forms three bonds and consumes
468
+ # three groups, so groups consumed is the bond count.
469
+ _ring_begin_re=re.compile(r' INFO>\s+Ring cure begins: ')
470
+ _ring_iter_re=re.compile(r' INFO> Iteration (\d+): \d+ ring\(s\), (\d+) of \d+ groups consumed \(conversion ([0-9.]+)\)')
471
+
465
472
  def _token_match(l,template,pat_idx):
466
473
  """Returns True if tokens indexed by pat_idx in the space-split l and template match.
467
474
 
@@ -524,7 +531,21 @@ def diagnostics_graphs(logfiles, filename, **kwargs):
524
531
  data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
525
532
  # print('data tok',f'{l.split()}')
526
533
  _parse_data(data,l,_template_2_data_idx)
527
- # print('data',f'{data}')
534
+ elif _ring_begin_re.search(l):
535
+ counter+=1
536
+ assert not counter>1
537
+ data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
538
+ data['iter'].append(0)
539
+ data['conv'].append(0.0)
540
+ data['nbonds'].append(0)
541
+ elif (m:=_ring_iter_re.search(l)):
542
+ data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
543
+ data['iter'].append(int(m.group(1)))
544
+ data['nbonds'].append(int(m.group(2)))
545
+ data['conv'].append(float(m.group(3)))
546
+ if not data['time']:
547
+ raise ValueError(f'{logfile}: no CURE or ring-cure progress lines found; '
548
+ f'is it a diagnostics log from htpolynet run -diag?')
528
549
  df[logfile]=pd.DataFrame(data)
529
550
  time_idx=list(df[logfile].columns).index('time')
530
551
  # Use dt.total_seconds() instead of .astype(int) — the latter
@@ -541,23 +562,26 @@ def diagnostics_graphs(logfiles, filename, **kwargs):
541
562
  ax[0].set_xlabel('runtime (h)')
542
563
  ax[0].set_ylabel('conversion')
543
564
  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')
565
+ ax[1].set_xlabel('cure iteration')
566
+ # plot against the logged iteration, not the row: row 0 is the cure's start
567
+ # (iteration 0), so row+1 put every iteration one place to the right
568
+ niter = int(max(df[lf]['iter'].max() for lf in logfiles))
569
+ ax[1].set_xlim([0, niter])
570
+ ax[1].set_xticks(range(0, niter + 1))
571
+ ax[2].set_xlabel('cure iteration')
548
572
  ax[2].set_ylabel('conversion')
549
573
  ax[2].set_ylim([0,1])
550
574
  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]])
575
+ ax[2].set_xticks(range(0, niter + 1))
576
+ ax[2].set_xlim([0, niter])
553
577
  if xmax == -1: # use autodetected xmax
554
578
  xmax = np.max([df[logfile]['elapsed'].max() for logfile in logfiles])
555
579
  ax[0].set_xlim([0,xmax])
556
580
  ax[1].set_ylim([0,xmax])
557
581
  for logfile in logfiles:
558
582
  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)
583
+ ax[1].scatter(df[logfile]['iter'], df[logfile]['elapsed'], label=logfile)
584
+ ax[2].scatter(df[logfile]['iter'], df[logfile]['conv'], label=logfile)
561
585
  # plt.legend()
562
586
  plt.savefig(filename)
563
587
  plt.close(fig)
@@ -648,6 +672,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
648
672
  stds={}
649
673
  rate=[]
650
674
  Tgs=[]
675
+ spread=[]
676
+ span=[]
651
677
  nproj=len(projdirs)
652
678
  for i,phase in enumerate(phases):
653
679
  p=phase['ladder']
@@ -701,6 +727,8 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
701
727
  ax[i].errorbar(m['Temperature'],m['Density'],std['Density'])
702
728
  Tg,c,h=compute_tg(m['Temperature'],m['Density'],n_points=n_points)
703
729
  Tgs.append(Tg)
730
+ spread.append(tg_window_range(m['Temperature'].values,m['Density'].values))
731
+ span.append((m['Temperature'].min(),m['Temperature'].max()))
704
732
  if Tg!=-1:
705
733
  ax[i].plot(m['Temperature'],c[0]*m['Temperature']+c[1],color='blue',alpha=0.5)
706
734
  ax[i].plot(m['Temperature'],h[0]*m['Temperature']+h[1],color='red',alpha=0.5)
@@ -717,23 +745,84 @@ def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[
717
745
  logger.info(f'{outfile} created.')
718
746
  logger.info(f'heating Tg = {hTg:.2f} K ({(hTg-273.15):.2f} C) at {rate[0]:.5f} K/ps ({rate[0]*1.e12:.3e} K/s)')
719
747
  logger.info(f'cooling Tg = {cTg:.2f} K ({(cTg-273.15):.2f} C) at {rate[1]:.5f} K/ps ({rate[1]*1.e12:.3e} K/s)')
748
+ unquotable=[]
749
+ for label,r,(lo,hi) in zip(('heating','cooling'),spread,span):
750
+ if r is None:
751
+ continue
752
+ logger.info(f'{label} Tg over fit windows of 10-25 points per side: {r[0]:.0f} to {r[1]:.0f} K')
753
+ if r[0]<lo or r[1]>hi:
754
+ unquotable.append(label)
755
+ logger.warning(f'the {label} Tg leaves the ladder\'s {lo:.0f}-{hi:.0f} K range for some fit '
756
+ f'windows, so the glassy and rubbery lines are nearly parallel and no '
757
+ f'{label} Tg can be read off this ladder; equilibrate longer before it')
758
+ if abs(hTg-cTg)>50.0:
759
+ logger.warning(f'heating and cooling Tg differ by {abs(hTg-cTg):.0f} K; more than rate '
760
+ f'hysteresis explains, so treat at least one as a failed fit')
761
+ return {'heating':hTg,'cooling':cTg,'window_range':spread,'unquotable':unquotable}
762
+
763
+ def do_E_plots(phases,projdirs,outfile='e.png',save_data='E.csv',fit_strain=None):
764
+ """Fits Young's modulus to the deform stages and plots the mean stress-strain curve.
765
+
766
+ Every pull -- each direction, each replica, each project -- is fitted on its own over
767
+ the same strain window, and E is reported as the mean of those fits with the standard
768
+ error between them, which is the uncertainty a single fit's own statistics cannot
769
+ give. The mean curve is plotted, and fitted too for comparison.
720
770
 
721
- def do_E_plots(phases,projdirs,outfile='e.png',fit_domain=[10,200],save_data='E.csv'):
771
+ Args:
772
+ phases (list): the ``deform`` stanzas from the postsim config
773
+ projdirs (list): project directories
774
+ outfile (str): plot file, defaults to 'e.png'
775
+ save_data (str): mean-curve data file, defaults to 'E.csv'; the per-pull fits go
776
+ to the same name with ``-fits`` appended
777
+ fit_strain (list): [lo, hi] strain window; defaults to the stanzas' ``fit_strain``
778
+ """
779
+ from ..analysis.postsim import PostSimDeform, replica_subdirs
722
780
  MPa_per_bar=1.e-1
723
- # average over replicas and directions (here, phases)
724
- all_stress_strains=[]
781
+ if fit_strain is None:
782
+ windows={tuple(p['deform'].get('fit_strain',PostSimDeform.default_params['fit_strain'])) for p in phases}
783
+ if len(windows)>1:
784
+ logger.warning(f'deform stages give different fit_strain windows {sorted(windows)}; using the first')
785
+ fit_strain=list(sorted(windows)[0])
786
+ lo,hi=fit_strain
787
+ curves=[]
725
788
  for p in phases:
726
- params=p['deform']
789
+ params={**PostSimDeform.default_params,**p['deform']}
727
790
  dir=params['direction']
728
791
  # Box-X-strain,Pres-XX-stress
729
792
  strain_name=f'Box-{dir.upper()}-strain'
730
793
  stress_name=f'Pres-{dir.upper()}{dir.upper()}-stress'
731
794
  for d in projdirs:
732
- df=pd.read_csv(os.path.join(d,params['subdir'],f'deform-{dir}.csv'),index_col=None,header=0)
733
- all_stress_strains.append(pd.DataFrame({'strain':df[strain_name],'stress':(df[stress_name]*MPa_per_bar)}))
734
- df_concat=pd.concat(all_stress_strains,axis=1)
735
- mean_stress_strains=df_concat.stack().groupby(level=[0,1]).mean().unstack()
736
- stds_stress_strains=df_concat.stack().groupby(level=[0,1]).std().unstack()
795
+ subs=replica_subdirs(params)
796
+ found=[s for s in subs if os.path.isdir(os.path.join(d,s))]
797
+ if not found and os.path.isdir(os.path.join(d,params['subdir'])):
798
+ # a run from before replicas existed, or one with replicas: 1
799
+ found=[params['subdir']]
800
+ elif len(found)<len(subs):
801
+ logger.warning(f'{d}: found {len(found)} of {len(subs)} replica directories for '
802
+ f'{params["subdir"]}; fitting those')
803
+ for sub in found:
804
+ df=pd.read_csv(os.path.join(d,sub,f'deform-{dir}.csv'),index_col=None,header=0)
805
+ curves.append((os.path.join(d,sub),pd.DataFrame({'strain':df[strain_name],'stress':(df[stress_name]*MPa_per_bar)})))
806
+ reached=min(c['strain'].max() for _,c in curves)
807
+ if reached<hi:
808
+ logger.warning(f'the shortest pull reaches strain {reached:.4f}, short of the fit window\'s '
809
+ f'upper end {hi}; the fit covers [{lo}, {reached:.4f}] only. Lengthen the '
810
+ f'deform stage (ps) to reach it.')
811
+ fits=[]
812
+ for name,c in curves:
813
+ E_i,R2_i=compute_E(c['strain'],c['stress'],fit_strain=fit_strain)
814
+ fits.append({'pull':name,'E_MPa':E_i,'R2':R2_i})
815
+ fits=pd.DataFrame(fits)
816
+ base,ext=os.path.splitext(save_data)
817
+ fits.to_csv(f'{base}-fits{ext}',header=True,index=False,sep=' ')
818
+
819
+ # mean and spread over the curves at each row (strain point). This used to
820
+ # concat side by side and stack(), which pandas >= 3 refuses: every frame has
821
+ # the same two column names. Keying the curves on a new outer level does the
822
+ # same averaging without duplicate columns.
823
+ df_concat=pd.concat([c for _,c in curves],keys=range(len(curves)))
824
+ mean_stress_strains=df_concat.groupby(level=1).mean()
825
+ stds_stress_strains=df_concat.groupby(level=1).std()
737
826
  mean_stress_strains['stress-std']=stds_stress_strains['stress']
738
827
  mean_stress_strains.to_csv(save_data,header=True,index=False,sep=' ')
739
828
  fig,ax=plt.subplots(1,1,figsize=(8,6))
@@ -742,19 +831,35 @@ def do_E_plots(phases,projdirs,outfile='e.png',fit_domain=[10,200],save_data='E.
742
831
  ax.set_xlabel('Strain [*]')
743
832
  ax.errorbar(mean_stress_strains['strain'],mean_stress_strains['stress'],stds_stress_strains['stress'],alpha=0.2)
744
833
  ax.plot(mean_stress_strains['strain'],mean_stress_strains['stress'])
745
- E,R2=compute_E(mean_stress_strains['strain'],mean_stress_strains['stress'],fit_domain=fit_domain)
746
- fitline=E*mean_stress_strains['strain']
747
- half_domain=int(mean_stress_strains['strain'].shape[0]/2)
748
- line_domain=[0,fit_domain[1] if fit_domain[1]>half_domain else half_domain]
749
- X=np.array(mean_stress_strains['strain'])[line_domain[0]:line_domain[1]]
750
- Y=np.array(fitline)[line_domain[0]:line_domain[1]]
751
- ax.plot(X,Y,'k--',alpha=0.7)
834
+ E,R2=compute_E(mean_stress_strains['strain'],mean_stress_strains['stress'],fit_strain=fit_strain)
835
+ X=np.array([0.0,min(hi,reached)])
836
+ ax.plot(X,E*X,'k--',alpha=0.7)
837
+ ax.axvspan(lo,min(hi,reached),color='grey',alpha=0.1)
752
838
  plt.savefig(outfile,bbox_inches='tight')
753
839
  plt.close(fig)
754
- logger.info(f'{outfile} and {save_data} created. E = {E/1000.0:.3f} GPa (R^2 {R2:.3f})')
840
+ n=len(fits)
841
+ E_mean=fits['E_MPa'].mean()
842
+ E_sem=fits['E_MPa'].std(ddof=1)/np.sqrt(n) if n>1 else float('nan')
843
+ logger.info(f'{outfile}, {save_data} and {base}-fits{ext} created.')
844
+ logger.info(f'E = {E_mean/1000.0:.3f} +/- {E_sem/1000.0:.3f} GPa: mean and standard error of '
845
+ f'{n} pull(s) fitted over strain [{lo}, {min(hi,reached):.4f}]; the mean curve '
846
+ f'fits to {E/1000.0:.3f} GPa (R^2 {R2:.3f})')
847
+ if n<2:
848
+ logger.warning('one pull gives no error bar; add directions or set `replicas`')
849
+ elif E_sem>0.2*abs(E_mean):
850
+ logger.warning(f'the standard error is {abs(E_sem/E_mean):.0%} of E; pull further '
851
+ f'(a longer deform stage) or add replicas before reporting it')
852
+ # No R^2 gate: single-frame pressure scatters so much that a sound fit to a real
853
+ # trace sits near R^2 0.45 (test_postsim_real_traces). The scatter between pulls is
854
+ # what says whether E is known.
855
+ return {'E':E_mean,'E_sem':E_sem,'n':n,'E_mean_curve':E,'R2_mean_curve':R2,'fit_strain':[lo,min(hi,reached)]}
755
856
 
756
857
  def post_plots(args):
757
858
  n_points=args.n_points
859
+ if not args.cfg:
860
+ # without it there are no stanzas, so every branch below is skipped and the
861
+ # command used to exit 0 having written nothing (htpolynet-sweep, 2026-10-15)
862
+ raise ValueError('plots post needs the postsim config that ran the stages: --cfg postsim.yaml')
758
863
  phases=[]
759
864
  # print(args.cfg)
760
865
  for c in args.cfg:
@@ -247,7 +247,7 @@ class PostSimLadder(PostSimMD):
247
247
  }
248
248
  mdp_modify(mdpname,mod_dict)
249
249
 
250
- def _strain_advice(edot,ps,logger=logger,what='strain'):
250
+ def _strain_advice(edot,ps,logger=logger,what='strain',rate_warning=True):
251
251
  """Says what strain a deformation will reach, and what a modulus from it is worth.
252
252
 
253
253
  The measured warning is not about the rate, it is about replicates. Eight
@@ -276,10 +276,12 @@ def _strain_advice(edot,ps,logger=logger,what='strain'):
276
276
  logger.info(f'This run reaches {what} {total:.3f} at {edot:g} ps^-1 over {ps} ps')
277
277
  logger.info('One ramp gives a modulus to about 10% but not its uncertainty: eight '
278
278
  'replicates of one protocol spanned 1.29 to 1.74 GPa while each fit '
279
- 'reported a much smaller error. Run several seeds and take the scatter '
280
- 'between them as the error bar.')
279
+ 'reported a much smaller error. Set `replicas` and take the scatter '
280
+ 'between them as the error bar; `plots post` reports it.')
281
281
  if edot>=1e-3:
282
- logger.warning(
282
+ # uniaxial passes rate_warning=False: its defaults were measured at this rate
283
+ # and fit [0.001, 0.03], inside the window this warning is about
284
+ (logger.warning if rate_warning else logger.info)(
283
285
  f'{what} passes 0.02 after only {0.02/edot:.0f} ps at edot={edot:g}, so '
284
286
  f'little of this run samples the low strains a modulus would come from; what '
285
287
  f'is fitted is a secant over a large window. edot=1e-4 reaches 0.03 in the '
@@ -308,8 +310,20 @@ class PostSimDeform(PostSimMD):
308
310
  'direction':'x',
309
311
  'T':300.0,
310
312
  'P':1.0,
311
- 'ps':1000,
312
- 'edot': 0.001 # strain rate in ps^-1
313
+ # Defaults measured on example 6 (2026-10-03: 15 pulls to 10% plus 6 at a tenth
314
+ # the rate; see the CHANGELOG). E is flat to 3-4% strain and softens past it; a
315
+ # single pull scatters ~30% over [0.001, 0.03] but ~80% over [0, 0.02], so 2% is
316
+ # too short at any replica count. Nine pulls -- three directions, three
317
+ # replicas -- give E to about 10%.
318
+ 'ps': 40, # 4% at the default rate, clearing the fit window
319
+ 'edot': 0.001, # strain rate in ps^-1
320
+ # independent pulls of this stage, each in <subdir>-r<k> with its own velocities;
321
+ # `plots post` fits each and reports the scatter between them as the error bar
322
+ 'replicas': 3,
323
+ # velocity seed; replica k uses seed+k-1. None leaves Gromacs to pick one
324
+ 'seed': None,
325
+ # strain window `plots post` fits E over
326
+ 'fit_strain': [0.001, 0.03],
313
327
  }
314
328
 
315
329
  def build_mdp(self,mdpname,**kwargs):
@@ -353,6 +367,8 @@ class PostSimDeform(PostSimMD):
353
367
  # deformation implies, and grompp refuses the run outright without it
354
368
  'deform-init-flow': 'yes'
355
369
  }
370
+ if params.get('seed') is not None:
371
+ mod_dict['gen-seed']=int(params['seed'])
356
372
  if direction=='x':
357
373
  strain_vel=box[0][0]*edot
358
374
  mod_dict['ref_p']='0.0 1.0 1.0 0 0 0'
@@ -380,7 +396,7 @@ class PostSimDeform(PostSimMD):
380
396
  else:
381
397
  logger.error(f'Bad direction for uniaxial strain {direction}')
382
398
  return
383
- _strain_advice(edot,duration)
399
+ _strain_advice(edot,duration,rate_warning=False)
384
400
 
385
401
  mdp_modify(mdpname,mod_dict)
386
402
 
@@ -503,6 +519,29 @@ class PostSimShear(PostSimMD):
503
519
  _strain_advice(params.get('edot',0.0),params['ps'],what='shear strain')
504
520
  mdp_modify(mdpname,mod_dict)
505
521
 
522
+ def bad_subdirs(stagelist):
523
+ """The stage directories :func:`pfs.go_to` would refuse, in config order."""
524
+ return [s.params['subdir'] for s in stagelist if not pfs.can_go_to(s.params['subdir'])]
525
+
526
+
527
+ def replica_subdirs(params):
528
+ """The directories a stage's replicas run in: its ``subdir``, or ``<subdir>-r<k>``.
529
+
530
+ Args:
531
+ params (dict): the stage's parameters, defaults included
532
+
533
+ Returns:
534
+ list: one subdirectory per replica
535
+ """
536
+ n=params.get('replicas',1)
537
+ n=1 if n is None else int(n)
538
+ if n<1:
539
+ raise ValueError(f'replicas must be at least 1, not {n}')
540
+ if n==1:
541
+ return [params['subdir']]
542
+ return [f"{params['subdir']}-r{k}" for k in range(1,n+1)]
543
+
544
+
506
545
  class PostsimConfiguration:
507
546
  """ handles reading and parsing a postcure simulation input config file.
508
547
  Config file format
@@ -591,14 +630,40 @@ class PostsimConfiguration:
591
630
  if parse: inst.parse(**kwargs)
592
631
  return inst
593
632
 
633
+ def check_subdirs(self):
634
+ """Raises before anything runs if any stage's ``subdir`` cannot be reached.
635
+
636
+ Raises:
637
+ ValueError: naming every unreachable subdir
638
+ """
639
+ bad=bad_subdirs(self.stagelist)
640
+ if bad:
641
+ raise ValueError(f'{self.cfgFile}: {len(bad)} stage subdir(s) cannot be used: {bad}. '
642
+ f'A subdir must be one name inside a project directory, such as '
643
+ f'postsim/deform-x; nothing deeper.')
644
+
594
645
  def parse(self,**kwargs):
595
- """Parses a PostsimConfiguration file to build the list of stages to run."""
646
+ """Parses a PostsimConfiguration file to build the list of stages to run.
647
+
648
+ A ``deform`` stanza with ``replicas: N`` becomes N stages, in ``<subdir>-r1`` to
649
+ ``<subdir>-rN``, each generating its own velocities.
650
+ """
596
651
  for p in self.baselist:
597
652
  assert len(p)==1,f'Poorly formatted {self.cfgFile}; each stanza may have only one keyword'
598
653
  simtype=list(p.keys())[0]
599
654
  assert simtype in self.default_classes,f'Simulation type "{simtype}" in {self.cfgFile} not understood.'
600
655
  logger.info(f'passing in {p[simtype]}')
601
- self.stagelist.append(self.default_classes[simtype](p[simtype]))
656
+ cls=self.default_classes[simtype]
657
+ if 'replicas' not in cls.default_params:
658
+ self.stagelist.append(cls(p[simtype]))
659
+ continue
660
+ stanza=dict(p[simtype])
661
+ subdirs=replica_subdirs({**cls.default_params,**stanza})
662
+ for k,subdir in enumerate(subdirs):
663
+ rep=dict(stanza,subdir=subdir)
664
+ if stanza.get('seed') is not None:
665
+ rep['seed']=int(stanza['seed'])+k
666
+ self.stagelist.append(cls(rep))
602
667
 
603
668
  def postsim(args):
604
669
  """Handles the postsim subcommand for managing post-cure production MD simulations.
@@ -619,6 +684,10 @@ def postsim(args):
619
684
  logger.debug(f'ogromacs {ogromacs}')
620
685
  for d in args.proj:
621
686
  pfs.pfs_setup(root=os.getcwd(),topdirs=pfs.Dirs.postsim_topdirs,verbose=True,projdir=d,reProject=False,userlibrary=pfs.resolve_user_library(args.lib))
687
+ # every stage's directory is checked before any of them runs: a bad one used
688
+ # to surface only when its turn came, after the stages before it had spent
689
+ # their allocation
690
+ cfg.check_subdirs()
622
691
  pfs.go_to(pfs.Dirs.postsim)
623
692
  for stage in cfg.stagelist:
624
693
  stage.do(mdp_pfx='local',**ogromacs)