HTPolyNet 1.0.7.2__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.
- HTPolyNet/__init__.py +1 -0
- HTPolyNet/ambertools.py +94 -0
- HTPolyNet/analyze.py +258 -0
- HTPolyNet/banner.py +26 -0
- HTPolyNet/bondlist.py +206 -0
- HTPolyNet/bondtemplate.py +111 -0
- HTPolyNet/checkpoint.py +88 -0
- HTPolyNet/command.py +42 -0
- HTPolyNet/configuration.py +240 -0
- HTPolyNet/coordinates.py +1071 -0
- HTPolyNet/countTime.py +26 -0
- HTPolyNet/curecontroller.py +767 -0
- HTPolyNet/dataframetools.py +130 -0
- HTPolyNet/driver.py +250 -0
- HTPolyNet/expandreactions.py +154 -0
- HTPolyNet/gromacs.py +333 -0
- HTPolyNet/inputcheck.py +51 -0
- HTPolyNet/linkcell.py +322 -0
- HTPolyNet/molecule.py +1279 -0
- HTPolyNet/plot.py +607 -0
- HTPolyNet/postsim.py +444 -0
- HTPolyNet/projectfilesystem.py +483 -0
- HTPolyNet/reaction.py +282 -0
- HTPolyNet/resources/README.md +20 -0
- HTPolyNet/resources/__init__.py +0 -0
- HTPolyNet/resources/cfg/DGE-PAC-hi.yaml +115 -0
- HTPolyNet/resources/cfg/DGE-PAC-lo.yaml +115 -0
- HTPolyNet/resources/cfg/FDE-DFDA-hi.yaml +116 -0
- HTPolyNet/resources/cfg/FDE-DFDA-lo.yaml +116 -0
- HTPolyNet/resources/cfg/GMASTY-hi.yaml +158 -0
- HTPolyNet/resources/cfg/GMASTY-lo.yaml +158 -0
- HTPolyNet/resources/cfg/README.md +1 -0
- HTPolyNet/resources/cfg/STY.yaml +23 -0
- HTPolyNet/resources/cfg/pMSTY-hi.yaml +101 -0
- HTPolyNet/resources/cfg/pMSTY-lo.yaml +101 -0
- HTPolyNet/resources/cfg/pSTY-hi.yaml +101 -0
- HTPolyNet/resources/cfg/pSTY-lo.yaml +101 -0
- HTPolyNet/resources/example_depot/0-liquid-styrene.tgz +0 -0
- HTPolyNet/resources/example_depot/1-polystyrene.tgz +0 -0
- HTPolyNet/resources/example_depot/2-polymethylstyrene.tgz +0 -0
- HTPolyNet/resources/example_depot/3-bisgma-styrene-thermoset.tgz +0 -0
- HTPolyNet/resources/example_depot/4-pacm-dgeba-epoxy-thermoset.tgz +0 -0
- HTPolyNet/resources/example_depot/5-dfda-fde-epoxy-thermoset.tgz +0 -0
- HTPolyNet/resources/mdp/README.md +1 -0
- HTPolyNet/resources/mdp/drag-min.mdp +13 -0
- HTPolyNet/resources/mdp/drag-npt.mdp +36 -0
- HTPolyNet/resources/mdp/drag-nvt.mdp +31 -0
- HTPolyNet/resources/mdp/min.mdp +14 -0
- HTPolyNet/resources/mdp/npt.mdp +37 -0
- HTPolyNet/resources/mdp/nvt.mdp +29 -0
- HTPolyNet/resources/mdp/relax-min.mdp +13 -0
- HTPolyNet/resources/mdp/relax-npt.mdp +37 -0
- HTPolyNet/resources/mdp/relax-nvt.mdp +31 -0
- HTPolyNet/resources/mdp/single-molecule-min.mdp +12 -0
- HTPolyNet/resources/mdp/single-molecule-nvt.mdp +25 -0
- HTPolyNet/resources/molecules/inputs/DFA.pdb +62 -0
- HTPolyNet/resources/molecules/inputs/DGE.mol2 +115 -0
- HTPolyNet/resources/molecules/inputs/EMB.mol2 +50 -0
- HTPolyNet/resources/molecules/inputs/FDE.pdb +72 -0
- HTPolyNet/resources/molecules/inputs/GMA.mol2 +163 -0
- HTPolyNet/resources/molecules/inputs/PAC.mol2 +91 -0
- HTPolyNet/resources/molecules/inputs/STY.mol2 +44 -0
- HTPolyNet/resources/molecules/make-monomers.sh +64 -0
- HTPolyNet/resources/molecules/pics/DFA.png +0 -0
- HTPolyNet/resources/molecules/pics/DGE.png +0 -0
- HTPolyNet/resources/molecules/pics/EMB.png +0 -0
- HTPolyNet/resources/molecules/pics/FDE.png +0 -0
- HTPolyNet/resources/molecules/pics/GMA.png +0 -0
- HTPolyNet/resources/molecules/pics/PAC.png +0 -0
- HTPolyNet/resources/molecules/pics/STY.png +0 -0
- HTPolyNet/resources/molecules/sample-inputs/DFA.pdb +62 -0
- HTPolyNet/resources/molecules/sample-inputs/DGE.mol2 +115 -0
- HTPolyNet/resources/molecules/sample-inputs/EMB.mol2 +50 -0
- HTPolyNet/resources/molecules/sample-inputs/FDE.pdb +72 -0
- HTPolyNet/resources/molecules/sample-inputs/GMA.mol2 +163 -0
- HTPolyNet/resources/molecules/sample-inputs/PAC.mol2 +91 -0
- HTPolyNet/resources/molecules/sample-inputs/STY.mol2 +44 -0
- HTPolyNet/resources/tcl/readbonds.tcl +32 -0
- HTPolyNet/resources/tcl/readgrx.tcl +46 -0
- HTPolyNet/resources/tcl/render.tcl +74 -0
- HTPolyNet/ring.py +155 -0
- HTPolyNet/runtime.py +709 -0
- HTPolyNet/software.py +106 -0
- HTPolyNet/stringthings.py +39 -0
- HTPolyNet/topocoord.py +1877 -0
- HTPolyNet/topology.py +1288 -0
- HTPolyNet/unused_symmetry_stuff.py +291 -0
- HTPolyNet/utils.py +405 -0
- htpolynet-1.0.7.2.dist-info/METADATA +84 -0
- htpolynet-1.0.7.2.dist-info/RECORD +93 -0
- htpolynet-1.0.7.2.dist-info/WHEEL +4 -0
- htpolynet-1.0.7.2.dist-info/entry_points.txt +2 -0
- htpolynet-1.0.7.2.dist-info/licenses/LICENSE +21 -0
HTPolyNet/plot.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""
|
|
2
|
+
|
|
3
|
+
.. module:: plot
|
|
4
|
+
:synopsis: provides plotting functionality
|
|
5
|
+
|
|
6
|
+
.. moduleauthor: Cameron F. Abrams, <cfa22@drexel.edu>
|
|
7
|
+
|
|
8
|
+
"""
|
|
9
|
+
from HTPolyNet.gromacs import *
|
|
10
|
+
from HTPolyNet.utils import *
|
|
11
|
+
from HTPolyNet.banner import banner
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
import matplotlib.cm as cm
|
|
14
|
+
import pandas as pd
|
|
15
|
+
import logging
|
|
16
|
+
import networkx as nx
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
import yaml
|
|
19
|
+
|
|
20
|
+
logger=logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
# prevents "RuntimeError: main thread is not in main loop" tk bug
|
|
23
|
+
plt.switch_backend('agg')
|
|
24
|
+
|
|
25
|
+
def scatter(df,xcolumn,columns=[],outfile='plot.png',**kwargs):
|
|
26
|
+
"""scatter generic scatter plot generator
|
|
27
|
+
|
|
28
|
+
:param df: dataframe containing data
|
|
29
|
+
:type df: pd.DataFrame
|
|
30
|
+
:param xcolumn: name of column holding x-data
|
|
31
|
+
:type xcolumn: str
|
|
32
|
+
:param columns: list of y-value columns to be plotted vs. x, defaults to []
|
|
33
|
+
:type columns: list, optional
|
|
34
|
+
:param outfile: name of output image file, defaults to 'plot.png'
|
|
35
|
+
:type outfile: str, optional
|
|
36
|
+
"""
|
|
37
|
+
logging.disable(logging.DEBUG)
|
|
38
|
+
cmapname=kwargs.get('colormap','plasma')
|
|
39
|
+
size=kwargs.get('size',(8,6))
|
|
40
|
+
yunits=kwargs.get('yunits',None)
|
|
41
|
+
cmap=cm.get_cmap(cmapname)
|
|
42
|
+
fig,ax=plt.subplots(1,1,figsize=size)
|
|
43
|
+
ax.set_xlabel(xcolumn)
|
|
44
|
+
for n in columns:
|
|
45
|
+
ax.scatter(df[xcolumn],df[n],label=n)
|
|
46
|
+
plt.legend()
|
|
47
|
+
plt.savefig(outfile)
|
|
48
|
+
plt.close(fig)
|
|
49
|
+
logging.disable(logging.NOTSET)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def trace(qty,edrs,outfile='plot.png',**kwargs):
|
|
53
|
+
"""trace 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'
|
|
54
|
+
|
|
55
|
+
:param qty: name of energy-like quantity; must conform to menu generated by 'gmx energy'
|
|
56
|
+
:type qty: str
|
|
57
|
+
:param edrs: list of names of edr files to scan, in order
|
|
58
|
+
:type edrs: list
|
|
59
|
+
:param outfile: name of output image file, defaults to 'plot.png'
|
|
60
|
+
:type outfile: str, optional
|
|
61
|
+
:return: the list of average values
|
|
62
|
+
:rtype: list
|
|
63
|
+
"""
|
|
64
|
+
# disable debug-level logging and above since matplotlib has a lot of debug statements
|
|
65
|
+
logging.disable(logging.DEBUG)
|
|
66
|
+
df=pd.DataFrame()
|
|
67
|
+
cmapname=kwargs.get('colormap','plasma')
|
|
68
|
+
size=kwargs.get('size',(8,6))
|
|
69
|
+
yunits=kwargs.get('yunits',None)
|
|
70
|
+
avgafter=kwargs.get('avgafter',0)
|
|
71
|
+
cmap=cm.get_cmap(cmapname)
|
|
72
|
+
xshift=0.0
|
|
73
|
+
chkpt=[]
|
|
74
|
+
for edr in edrs:
|
|
75
|
+
if not df.empty:
|
|
76
|
+
xshift=df.tail(1).iloc[0,0]
|
|
77
|
+
data=gmx_energy_trace(edr,[qty],xshift=xshift)
|
|
78
|
+
lastchkpt=0
|
|
79
|
+
if len(chkpt)>0:
|
|
80
|
+
lastchkpt=chkpt[-1]
|
|
81
|
+
chkpt.append(data.shape[0]+lastchkpt)
|
|
82
|
+
df=pd.concat((df,data),ignore_index=True)
|
|
83
|
+
fig,ax=plt.subplots(1,1,figsize=size)
|
|
84
|
+
nseg=len(chkpt)
|
|
85
|
+
beg=0
|
|
86
|
+
avg=[]
|
|
87
|
+
for c in df.columns[1:]:
|
|
88
|
+
for seg in range(nseg):
|
|
89
|
+
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))
|
|
90
|
+
beg=chkpt[seg]
|
|
91
|
+
if 'avgafter' in kwargs:
|
|
92
|
+
if avgafter>0:
|
|
93
|
+
pass
|
|
94
|
+
else:
|
|
95
|
+
avgafter=df['time(ps)'].iloc[-1]/2
|
|
96
|
+
sdf=df[df['time(ps)']>avgafter]
|
|
97
|
+
avg.append(sdf[c].mean())
|
|
98
|
+
ax.plot(df.iloc[:,0],[avg]*df.shape[0],'k-',alpha=0.3,label=f'{avg:0.2f}')
|
|
99
|
+
else:
|
|
100
|
+
avg.append(df[c].mean())
|
|
101
|
+
if not yunits:
|
|
102
|
+
plt.ylabel(qty)
|
|
103
|
+
else:
|
|
104
|
+
plt.ylabel(f'{qty} ({yunits})')
|
|
105
|
+
plt.xlabel('time(ps)')
|
|
106
|
+
plt.legend()
|
|
107
|
+
plt.savefig(outfile)
|
|
108
|
+
plt.close(fig)
|
|
109
|
+
# re-establish previous logging level
|
|
110
|
+
logging.disable(logging.NOTSET)
|
|
111
|
+
return avg
|
|
112
|
+
|
|
113
|
+
def multi_trace(dfL,xnames,ynames,labels=[],xlabel='time [ps]',ylabel='',outfile='plot.png',**kwargs):
|
|
114
|
+
"""multi_trace generates a plot of each y vs x in df
|
|
115
|
+
|
|
116
|
+
:param df: a pandas dataframe
|
|
117
|
+
:type df: pandas.DataFrame
|
|
118
|
+
:param xnames: list of x-column names
|
|
119
|
+
:type xnames: list
|
|
120
|
+
:param ynames: list of y-column names, parallel to xnames
|
|
121
|
+
:type ynames: list
|
|
122
|
+
:param outfile: name of output image file, defaults to 'plot.png'
|
|
123
|
+
:type outfile: str, optional
|
|
124
|
+
"""
|
|
125
|
+
# disable debug-level logging and above since matplotlib has a lot of debug statements
|
|
126
|
+
default_units={'Temperature':'K','Pressure':'bar','Density':'kg/m^3','Potential':'kJ/mol'}
|
|
127
|
+
units=kwargs.get('units',default_units)
|
|
128
|
+
logging.disable(logging.DEBUG)
|
|
129
|
+
size=kwargs.get('size',(16,4))
|
|
130
|
+
legend=kwargs.get('legend',True)
|
|
131
|
+
fig,ax=plt.subplots(1,1,figsize=size)
|
|
132
|
+
plt.xlabel(xlabel)
|
|
133
|
+
plt.ylabel(ylabel)
|
|
134
|
+
cmapname=kwargs.get('colormap','plasma')
|
|
135
|
+
cmap=cm.get_cmap(cmapname)
|
|
136
|
+
|
|
137
|
+
ndatasets=len(xnames)
|
|
138
|
+
assert ndatasets==len(ynames)
|
|
139
|
+
|
|
140
|
+
for i,(df,x,y,l) in enumerate(zip(dfL,xnames,ynames,labels)):
|
|
141
|
+
ax.plot(df[x],df[y],label=l,color=cmap(i/ndatasets))
|
|
142
|
+
|
|
143
|
+
if legend:
|
|
144
|
+
plt.legend()
|
|
145
|
+
plt.savefig(outfile)
|
|
146
|
+
plt.close(fig)
|
|
147
|
+
# re-establish previous logging level
|
|
148
|
+
logging.disable(logging.NOTSET)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def global_trace(df,names,outfile='plot.png',transition_times=[],markers=[],interval_labels=[],y2names=[],**kwargs):
|
|
152
|
+
"""global_trace generates custom-formatted multiplots of energy-like quantities named in 'names' in the input dataframe df
|
|
153
|
+
|
|
154
|
+
:param df: pandas dataframe containing all data
|
|
155
|
+
:type df: pd.DataFrame
|
|
156
|
+
:param names: list of quantity names (Density, Temperature, etc)
|
|
157
|
+
:type names: list
|
|
158
|
+
:param outfile: name of output image file, defaults to 'plot.png'
|
|
159
|
+
:type outfile: str, optional
|
|
160
|
+
:param transition_times: time values at which vertical lines are drawn, defaults to []
|
|
161
|
+
:type transition_times: list, optional
|
|
162
|
+
:param markers: time values at which transitions are marked somehow, I forget, defaults to []
|
|
163
|
+
:type markers: list, optional
|
|
164
|
+
:param interval_labels: list of labels of intervals defined by markers, defaults to []
|
|
165
|
+
:type interval_labels: list, optional
|
|
166
|
+
:param y2names: names of quantities to be plotted on a secondary y axis, defaults to []
|
|
167
|
+
:type y2names: list, optional
|
|
168
|
+
"""
|
|
169
|
+
# disable debug-level logging and above since matplotlib has a lot of debug statements
|
|
170
|
+
default_units={'Temperature':'K','Pressure':'bar','Density':'kg/m^3','Potential':'kJ/mol'}
|
|
171
|
+
units=kwargs.get('units',default_units)
|
|
172
|
+
logging.disable(logging.DEBUG)
|
|
173
|
+
size=kwargs.get('size',(16,4*len(names)))
|
|
174
|
+
legend=kwargs.get('legend',False)
|
|
175
|
+
fig,ax=plt.subplots(len(names),1,figsize=size)
|
|
176
|
+
plt.xlabel('time(ps)')
|
|
177
|
+
cmapname=kwargs.get('colormap','plasma')
|
|
178
|
+
# yunits=kwargs.get('yunits',None)
|
|
179
|
+
cmap=cm.get_cmap(cmapname)
|
|
180
|
+
# print(f'in global_trace:\n{df.head().to_string()}')
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
interval_times=[]
|
|
184
|
+
if interval_labels:
|
|
185
|
+
for i in range(1,len(transition_times)):
|
|
186
|
+
interval_times.append((transition_times[i]+transition_times[i-1])/2)
|
|
187
|
+
for l,t in zip(interval_labels,interval_times):
|
|
188
|
+
logger.info(f'{t} {l}')
|
|
189
|
+
assert len(interval_labels)==len(interval_times)
|
|
190
|
+
L,R=-1,-1
|
|
191
|
+
if len(markers)>1:
|
|
192
|
+
L,R=markers[0],markers[-1]
|
|
193
|
+
in_tt=[x for x in transition_times if L<x<R]
|
|
194
|
+
marked_df=df[(df['time(ps)']>L)&(df['time(ps)']<R)]
|
|
195
|
+
fig,ax=plt.subplots(len(names)*2,1,figsize=size)
|
|
196
|
+
for i,colname in enumerate(names):
|
|
197
|
+
out_ax=ax[0] if len(names)==1 else ax[i*2]
|
|
198
|
+
in_ax=ax[1] if len(names)==1 else ax[i*2+1]
|
|
199
|
+
out_ax.plot(df['time(ps)'],df[colname],label=colname)
|
|
200
|
+
ylabel=colname
|
|
201
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
202
|
+
out_ax.set_ylabel(ylabel)
|
|
203
|
+
out_ax.set_xlabel('time(ps)')
|
|
204
|
+
if len(y2names)>i:
|
|
205
|
+
out_ax2=out_ax.twinx()
|
|
206
|
+
out_ax2.plot(df['time(ps)'],df[y2names[i]],label=y2names[i],color='black')
|
|
207
|
+
ylabel=y2names[i]
|
|
208
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
209
|
+
out_ax2.set_ylabel(ylabel)
|
|
210
|
+
out_ax2.set_xlabel('time(ps)')
|
|
211
|
+
if len(transition_times)>0:
|
|
212
|
+
colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
|
|
213
|
+
ylim=out_ax.get_ylim()
|
|
214
|
+
out_ax.vlines(transition_times,ylim[0],ylim[1],color=colors,linewidth=0.75,alpha=0.5)
|
|
215
|
+
# for x,l in zip(interval_times,interval_labels):
|
|
216
|
+
# out_ax.text(x,0.9*ylim[1],l,fontsize=8)
|
|
217
|
+
in_ax.plot(marked_df['time(ps)'],marked_df[colname],label=colname)
|
|
218
|
+
ylabel=colname
|
|
219
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
220
|
+
in_ax.set_xlabel('time(ps)')
|
|
221
|
+
in_ax.set_yabel(ylabel)
|
|
222
|
+
if len(y2names)>i:
|
|
223
|
+
in_ax2=in_ax.twinx()
|
|
224
|
+
in_ax2.plot(marked_df['time(ps)'],marked_df[y2names[i]],label=y2names[i],color='black')
|
|
225
|
+
ylabel=y2names[i]
|
|
226
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
227
|
+
in_ax2.set_ylabel(ylabel)
|
|
228
|
+
in_ax2.set_xlabel('time(ps)')
|
|
229
|
+
if len(transition_times)>0:
|
|
230
|
+
colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
|
|
231
|
+
ylim=in_ax.get_ylim()
|
|
232
|
+
in_ax.vlines(in_tt,ylim[0],ylim[1],color=colors,linewidth=0.75,alpha=0.5)
|
|
233
|
+
# for x,l in zip(interval_times,interval_labels):
|
|
234
|
+
# if L<x<R:
|
|
235
|
+
# out_ax.text(x,0.9*ylim[1],l,fontsize=8)
|
|
236
|
+
else:
|
|
237
|
+
fig,ax=plt.subplots(len(names),1,figsize=size)
|
|
238
|
+
for i,colname in enumerate(names):
|
|
239
|
+
the_ax=ax if len(names)==1 else ax[i]
|
|
240
|
+
the_ax.plot(df['time(ps)'],df[colname],label=colname)
|
|
241
|
+
ylabel=colname
|
|
242
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
243
|
+
the_ax.set_ylabel(ylabel)
|
|
244
|
+
the_ax.set_xlabel('time(ps)')
|
|
245
|
+
if len(y2names)>i:
|
|
246
|
+
the_ax2=the_ax.twinx()
|
|
247
|
+
the_ax2.plot(df['time(ps)'],df[y2names[i]],label=y2names[i],color='black')
|
|
248
|
+
ylabel=y2names[i]
|
|
249
|
+
if ylabel in units: ylabel+=f' ({units[ylabel]})'
|
|
250
|
+
the_ax2.set_ylabel(ylabel)
|
|
251
|
+
if len(transition_times)>0:
|
|
252
|
+
colors=[cmap(i/len(transition_times)) for i in range(len(transition_times))]
|
|
253
|
+
ylim=the_ax.get_ylim()
|
|
254
|
+
the_ax.vlines(transition_times,ylim[0],ylim[1],color=colors,linewidth=0.5,alpha=0.5)
|
|
255
|
+
|
|
256
|
+
# plt.xlabel('time(ps)')
|
|
257
|
+
if legend:
|
|
258
|
+
plt.legend()
|
|
259
|
+
plt.savefig(outfile)
|
|
260
|
+
plt.close(fig)
|
|
261
|
+
# re-establish previous logging level
|
|
262
|
+
logging.disable(logging.NOTSET)
|
|
263
|
+
|
|
264
|
+
def network_graph(G,filename,**kwargs):
|
|
265
|
+
"""network_graph draws a custom formatted network plot from graph G
|
|
266
|
+
|
|
267
|
+
:param G: a graph from networkx
|
|
268
|
+
:type G: nx.Graph or nx.DiGraph
|
|
269
|
+
:param filename: name of output image filename
|
|
270
|
+
:type filename: str
|
|
271
|
+
"""
|
|
272
|
+
logging.disable(logging.DEBUG)
|
|
273
|
+
arrows=kwargs.get('arrows',False)
|
|
274
|
+
figsize=kwargs.get('figsize',(32,32))
|
|
275
|
+
node_size=kwargs.get('node_size',200)
|
|
276
|
+
with_labels=kwargs.get('with_labels',False)
|
|
277
|
+
cmap=cm.get_cmap('seismic')
|
|
278
|
+
fig,ax=plt.subplots(1,1,figsize=figsize)
|
|
279
|
+
ax.axis('off')
|
|
280
|
+
molnames=list(set([n.get('molecule_name','anonymous') for k,n in G.nodes.items()]))
|
|
281
|
+
nmolname=len(molnames)
|
|
282
|
+
cx=[]
|
|
283
|
+
for n in G.nodes.values():
|
|
284
|
+
idx=molnames.index(n.get('molecule_name','anonymous'))
|
|
285
|
+
cx.append((float(idx)+0.25)/(nmolname+1))
|
|
286
|
+
nx.draw_networkx(G,ax=ax,arrows=arrows,node_size=node_size,node_color=cx,cmap=cmap,with_labels=with_labels)
|
|
287
|
+
plt.savefig(filename)
|
|
288
|
+
plt.close(fig)
|
|
289
|
+
logging.disable(logging.NOTSET)
|
|
290
|
+
|
|
291
|
+
# below are representive diagnostic output lines to establish extraction patterns
|
|
292
|
+
_template_1='2022-08-11 17:40:36,969 HTPolyNet.runtime.my_logger INFO> ********* Connect-Update-Relax-Equilibrate (CURE) begins **********'
|
|
293
|
+
_template_1_token_idx=[2,3,5,7]
|
|
294
|
+
_template_2='2022-09-03 19:32:46,830 HTPolyNet.curecontroller.do_iter INFO> Iteration 1 current conversion 0.283 or 1082 bonds'
|
|
295
|
+
_template_2_token_idx=[2,3,6,7]
|
|
296
|
+
_template_2_data_idx={'iter':(int,5),'conv':(float,8),'nbonds':(int,10)}
|
|
297
|
+
|
|
298
|
+
def _token_match(l,template,pat_idx):
|
|
299
|
+
"""_token_match returns True if tokens indexed by pat_idx in the space-split l and template match
|
|
300
|
+
|
|
301
|
+
:param l: probe string
|
|
302
|
+
:type l: str
|
|
303
|
+
:param template: template string
|
|
304
|
+
:type template: str
|
|
305
|
+
:param pat_idx: list of token indices
|
|
306
|
+
:type pat_idx: list
|
|
307
|
+
:return: True if tokens in l match those in template
|
|
308
|
+
:rtype: bool
|
|
309
|
+
"""
|
|
310
|
+
if len(l.split())!=len(template.split()): return
|
|
311
|
+
return all([l.split()[t]==template.split()[t] for t in pat_idx])
|
|
312
|
+
|
|
313
|
+
def _parse_data(dat,l,idx_dict):
|
|
314
|
+
"""_parse_data parses data in a matching line
|
|
315
|
+
|
|
316
|
+
:param dat: pandas dataframe
|
|
317
|
+
:type dat: pd.DataFame
|
|
318
|
+
:param l: line
|
|
319
|
+
:type l: str
|
|
320
|
+
:param idx_dict: dictionary of column-name:(type-converter,token-index)
|
|
321
|
+
:type idx_dict: dict
|
|
322
|
+
"""
|
|
323
|
+
tok=l.split()
|
|
324
|
+
for k,v in idx_dict.items():
|
|
325
|
+
conv,s=v
|
|
326
|
+
dat[k].append(conv(tok[s]))
|
|
327
|
+
|
|
328
|
+
def diagnostics_graphs(logfiles,filename,**kwargs):
|
|
329
|
+
"""diagnostics_graphs extracts selected data from the diagnostic output and generates plots
|
|
330
|
+
|
|
331
|
+
:param logfiles: list of names of diagnostic log files to treat in parallel
|
|
332
|
+
:type logfiles: list
|
|
333
|
+
:param filename: name of output image file
|
|
334
|
+
:type filename: str
|
|
335
|
+
"""
|
|
336
|
+
xmax=kwargs.get('xmax',-1)
|
|
337
|
+
figsize=kwargs.get('figsize',(12,6))
|
|
338
|
+
logging.disable(logging.DEBUG)
|
|
339
|
+
df:dict[pd.DataFrame]={}
|
|
340
|
+
for logfile in logfiles:
|
|
341
|
+
bn,ex=os.path.splitext(logfile)
|
|
342
|
+
with open(logfile,'r') as f:
|
|
343
|
+
lines=f.read().split('\n')
|
|
344
|
+
logger.info(f'read {len(lines)} lines from {logfile}')
|
|
345
|
+
data={}
|
|
346
|
+
data['time']=[]
|
|
347
|
+
data['iter']=[]
|
|
348
|
+
data['conv']=[]
|
|
349
|
+
data['nbonds']=[]
|
|
350
|
+
counter=0
|
|
351
|
+
for l in lines:
|
|
352
|
+
if _token_match(l,_template_1,_template_1_token_idx):
|
|
353
|
+
# print('you should only see this once')
|
|
354
|
+
counter+=1
|
|
355
|
+
assert not counter>1
|
|
356
|
+
data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
|
|
357
|
+
data['iter'].append(0)
|
|
358
|
+
data['conv'].append(0.0)
|
|
359
|
+
data['nbonds'].append(0)
|
|
360
|
+
elif _token_match(l,_template_2,_template_2_token_idx):
|
|
361
|
+
data['time'].append(datetime.strptime(' '.join(l.split()[0:2]),'%Y-%m-%d %H:%M:%S,%f'))
|
|
362
|
+
# print('data tok',f'{l.split()}')
|
|
363
|
+
_parse_data(data,l,_template_2_data_idx)
|
|
364
|
+
# print('data',f'{data}')
|
|
365
|
+
df[logfile]=pd.DataFrame(data)
|
|
366
|
+
time_idx=list(df[logfile].columns).index('time')
|
|
367
|
+
df[logfile]['elapsed']=(df[logfile]['time']-df[logfile].iloc[0,time_idx]).astype(int)/1.e9/3600.0
|
|
368
|
+
df[logfile].to_csv(f'{bn}.csv',index=False,sep=' ',header=True)
|
|
369
|
+
fig,ax=plt.subplots(1,2,sharex=True,figsize=figsize)
|
|
370
|
+
ax[0].set_ylim([0,1])
|
|
371
|
+
ax[0].set_xlabel('runtime (h)')
|
|
372
|
+
ax[0].set_ylabel('conversion')
|
|
373
|
+
ax[1].set_xlabel('runtime (h)')
|
|
374
|
+
ax[1].set_ylabel('iteration')
|
|
375
|
+
if xmax>-1:
|
|
376
|
+
ax[0].set_xlim([0,xmax])
|
|
377
|
+
for logfile in logfiles:
|
|
378
|
+
ax[0].plot(df[logfile]['elapsed'],df[logfile]['conv'],label=logfile)
|
|
379
|
+
ax[1].plot(df[logfile]['elapsed'],df[logfile].index+1,label=logfile)
|
|
380
|
+
plt.legend()
|
|
381
|
+
plt.savefig(filename)
|
|
382
|
+
plt.close(fig)
|
|
383
|
+
logging.disable(logging.NOTSET)
|
|
384
|
+
|
|
385
|
+
def init_molecule_graph(proj_dir):
|
|
386
|
+
"""init_molecule_graph creates and initializes a inter-molecular graph to show network connectivity
|
|
387
|
+
|
|
388
|
+
:param proj_dir: name of project directory
|
|
389
|
+
:type proj_dir: str
|
|
390
|
+
:return: a nodes-only Graph enumerating all molecules; this will be further processed elsewhere to add connectivity information
|
|
391
|
+
:rtype: networkx.Graph
|
|
392
|
+
"""
|
|
393
|
+
gro=os.path.join(proj_dir,'systems/init/init.gro')
|
|
394
|
+
top=os.path.join(proj_dir,'systems/init/init.top')
|
|
395
|
+
grx=os.path.join(proj_dir,'systems/init/init.grx')
|
|
396
|
+
TC=TopoCoord(grofilename=gro,topfilename=top,grxfilename=grx)
|
|
397
|
+
G=nx.Graph()
|
|
398
|
+
adf=TC.Coordinates.A
|
|
399
|
+
mm=set(zip(adf['molecule'],adf['molecule_name']))
|
|
400
|
+
for mx,mn in mm:
|
|
401
|
+
G.add_node(mx,molecule_name=mn)
|
|
402
|
+
return G
|
|
403
|
+
|
|
404
|
+
def plots(args):
|
|
405
|
+
"""plots handles the plots subcommand
|
|
406
|
+
|
|
407
|
+
:param args: command-line arguments
|
|
408
|
+
:type args: argparse.Namespace
|
|
409
|
+
"""
|
|
410
|
+
loglevel_numeric=getattr(logging, args.loglevel.upper())
|
|
411
|
+
logging.basicConfig(format='%(levelname)s> %(message)s',level=loglevel_numeric)
|
|
412
|
+
if not args.no_banner: banner(logger.info)
|
|
413
|
+
|
|
414
|
+
if args.source=='build':
|
|
415
|
+
build_plots(args)
|
|
416
|
+
elif args.source=='diag':
|
|
417
|
+
diag_plots(args)
|
|
418
|
+
elif args.source=='post':
|
|
419
|
+
post_plots(args)
|
|
420
|
+
else:
|
|
421
|
+
logger.error(f'Source {args.source} is not recognized.')
|
|
422
|
+
|
|
423
|
+
def diag_plots(args):
|
|
424
|
+
diags=args.diags
|
|
425
|
+
plotfile=args.plotfile
|
|
426
|
+
if not plotfile:
|
|
427
|
+
plotfile='cure_info.png'
|
|
428
|
+
if len(diags)>0:
|
|
429
|
+
diagnostics_graphs(diags,plotfile)
|
|
430
|
+
|
|
431
|
+
def build_plots(args):
|
|
432
|
+
GmxNames={'t':'Temperature','d':'Density','p':'Potential'}
|
|
433
|
+
plot_types=args.buildplot
|
|
434
|
+
trace_types=[]
|
|
435
|
+
if 't' in plot_types:
|
|
436
|
+
trace_types=[GmxNames[i] for i in args.traces]
|
|
437
|
+
for p in args.proj:
|
|
438
|
+
if trace_types:
|
|
439
|
+
df,transition_times,cure_markers,interval_labels=density_evolution(p)
|
|
440
|
+
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)
|
|
441
|
+
df.to_csv(os.path.join(p,'buildtraces.csv'),index=False,header=True,float_format='{:.3f}'.format)
|
|
442
|
+
if any([x in plot_types for x in 'gnc']):
|
|
443
|
+
G=init_molecule_graph(p)
|
|
444
|
+
n=1
|
|
445
|
+
while os.path.exists(os.path.join(p,f'systems/iter-{n}/2-cure_update-bonds.csv')):
|
|
446
|
+
logger.info(f'iter-{n}/2-cure_update-bonds.csv')
|
|
447
|
+
g=graph_from_bondsfile(os.path.join(p,f'systems/iter-{n}/2-cure_update-bonds.csv'))
|
|
448
|
+
G=nx.compose(G,g)
|
|
449
|
+
if 'g' in plot_types:
|
|
450
|
+
network_graph(G,os.path.join(p,f'plots/iter-{n}-graph.png'))
|
|
451
|
+
n+=1
|
|
452
|
+
if 'g' in plot_types: network_graph(G,os.path.join(p,'graph.png'))
|
|
453
|
+
if 'c' in plot_types:
|
|
454
|
+
clu=clusters(G)
|
|
455
|
+
clu.to_csv(os.path.join(p,'clusters.csv'),sep=' ',header=True,index=False)
|
|
456
|
+
logger.info(f'{os.path.join(p,"clusters.csv")} created.')
|
|
457
|
+
# cluster_plot(clu,os.path.join(p,"clusters.png"))
|
|
458
|
+
if 'n' in plot_types:
|
|
459
|
+
am=mwbxl(G)
|
|
460
|
+
logger.info(f'Avg homo-N between xlinks: {np.average(am["n"],weights=am["counts"]):.2f}')
|
|
461
|
+
am.to_csv(os.path.join(p,'dist_bw_xlinks.csv'),sep=' ',index=False,header=True)
|
|
462
|
+
logger.info(f'{os.path.join(p,"dist_bw_xlinks.csv")} created.')
|
|
463
|
+
# dist_bw_xlinks_plot(am,os.path.join(p,"dist_bw_xlinks.png"))
|
|
464
|
+
|
|
465
|
+
def do_tg_plots(phases,projdirs,outfile='tg.png',save_data='data.csv',n_points=[10,20]):
|
|
466
|
+
res={}
|
|
467
|
+
means={}
|
|
468
|
+
stds={}
|
|
469
|
+
rate=[]
|
|
470
|
+
Tgs=[]
|
|
471
|
+
nproj=len(projdirs)
|
|
472
|
+
for i,phase in enumerate(phases):
|
|
473
|
+
p=phase['ladder']
|
|
474
|
+
rate.append(p['deltaT']/(p['ps_per_rise']+p['ps_per_run']))
|
|
475
|
+
res[i]=[]
|
|
476
|
+
for d in projdirs:
|
|
477
|
+
df=pd.read_csv(os.path.join(d,p['subdir'],'ladder.csv'),index_col=None,header=0)
|
|
478
|
+
t0=p['warmup_ps']
|
|
479
|
+
ps_per_step=p['ps_per_rise']+p['ps_per_run']
|
|
480
|
+
final_ps=df['time(ps)'].iloc[-1]
|
|
481
|
+
curr_ps=t0
|
|
482
|
+
T=[]
|
|
483
|
+
rho=[]
|
|
484
|
+
V=[]
|
|
485
|
+
Tstd=[]
|
|
486
|
+
rhostd=[]
|
|
487
|
+
Vstd=[]
|
|
488
|
+
while curr_ps<final_ps:
|
|
489
|
+
ll=curr_ps+p['ps_per_rise']+0.5*p['ps_per_run']
|
|
490
|
+
ul=ll+0.5*p['ps_per_run']
|
|
491
|
+
tdf=df[(df['time(ps)']>=ll)&(df['time(ps)']<=ul)]
|
|
492
|
+
T.append(tdf['Temperature'].mean())
|
|
493
|
+
rho.append(tdf['Density'].mean())
|
|
494
|
+
V.append(tdf['Volume'].mean())
|
|
495
|
+
Tstd.append(tdf['Temperature'].std())
|
|
496
|
+
rhostd.append(tdf['Density'].std())
|
|
497
|
+
Vstd.append(tdf['Volume'].std())
|
|
498
|
+
curr_ps+=ps_per_step
|
|
499
|
+
|
|
500
|
+
res[i].append(pd.DataFrame({'Temperature':T,'Volume':V,'Density':rho,'Temperature-std':Tstd,'Volume-std':Vstd,'Density-std':rhostd}))
|
|
501
|
+
|
|
502
|
+
df_concat0 = pd.concat(res[i], axis=1)
|
|
503
|
+
means[i]=df_concat0.stack().groupby(level=[0,1]).mean().unstack()
|
|
504
|
+
stds[i]=df_concat0.stack().groupby(level=[0,1]).std().unstack()
|
|
505
|
+
means[i]['Volume-std']=stds[i]['Volume']
|
|
506
|
+
means[i]['Density-std']=stds[i]['Density']
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
fig,ax=plt.subplots(1,2,figsize=(10,6),sharex=True,sharey=True)
|
|
510
|
+
for i,v in enumerate(means.keys()):
|
|
511
|
+
m=means[v]
|
|
512
|
+
std=stds[v]
|
|
513
|
+
if np.isnan(np.sum(std['Density'])):
|
|
514
|
+
std['Density']=np.zeros(len(std['Density']))
|
|
515
|
+
m.sort_values('Temperature',axis=0,inplace=True)
|
|
516
|
+
ax[i].set_xlabel('Temperature [K]')
|
|
517
|
+
ax[i].set_ylabel('Density [kg/m$^3$]')
|
|
518
|
+
if nproj<2:
|
|
519
|
+
ax[i].scatter(m['Temperature'],m['Density'])
|
|
520
|
+
else:
|
|
521
|
+
ax[i].errorbar(m['Temperature'],m['Density'],std['Density'])
|
|
522
|
+
Tg,c,h=compute_tg(m['Temperature'],m['Density'],n_points=n_points)
|
|
523
|
+
Tgs.append(Tg)
|
|
524
|
+
if Tg!=-1:
|
|
525
|
+
ax[i].plot(m['Temperature'],c[0]*m['Temperature']+c[1],color='blue',alpha=0.5)
|
|
526
|
+
ax[i].plot(m['Temperature'],h[0]*m['Temperature']+h[1],color='red',alpha=0.5)
|
|
527
|
+
ax[i].scatter([Tg],[c[0]*Tg+c[1]],marker='o',color='black')
|
|
528
|
+
ax[i].text(Tg,c[0]*Tg+c[1],f' {Tg:.2f} K',verticalalignment='top')
|
|
529
|
+
means[v]['glassy-line-Density']=c[0]*m['Temperature']+c[1]
|
|
530
|
+
means[v]['rubbery-line-Density']=h[0]*m['Temperature']+h[1]
|
|
531
|
+
means[v].to_csv(f'ladder{v}-{save_data}',index=False,header=True,sep=' ')
|
|
532
|
+
logger.info(f'ladder{v}-{save_data} created.')
|
|
533
|
+
plt.savefig(outfile,bbox_inches='tight')
|
|
534
|
+
plt.close(fig)
|
|
535
|
+
hTg=Tgs[0]
|
|
536
|
+
cTg=Tgs[1]
|
|
537
|
+
logger.info(f'{outfile} created.')
|
|
538
|
+
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)')
|
|
539
|
+
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)')
|
|
540
|
+
|
|
541
|
+
def do_E_plots(phases,projdirs,outfile='e.png',fit_domain=[10,200],save_data='E.csv'):
|
|
542
|
+
MPa_per_bar=1.e-1
|
|
543
|
+
# average over replicas and directions (here, phases)
|
|
544
|
+
all_stress_strains=[]
|
|
545
|
+
for p in phases:
|
|
546
|
+
params=p['deform']
|
|
547
|
+
dir=params['direction']
|
|
548
|
+
# Box-X-strain,Pres-XX-stress
|
|
549
|
+
strain_name=f'Box-{dir.upper()}-strain'
|
|
550
|
+
stress_name=f'Pres-{dir.upper()}{dir.upper()}-stress'
|
|
551
|
+
for d in projdirs:
|
|
552
|
+
df=pd.read_csv(os.path.join(d,params['subdir'],f'deform-{dir}.csv'),index_col=None,header=0)
|
|
553
|
+
all_stress_strains.append(pd.DataFrame({'strain':df[strain_name],'stress':(df[stress_name]*MPa_per_bar)}))
|
|
554
|
+
df_concat=pd.concat(all_stress_strains,axis=1)
|
|
555
|
+
mean_stress_strains=df_concat.stack().groupby(level=[0,1]).mean().unstack()
|
|
556
|
+
stds_stress_strains=df_concat.stack().groupby(level=[0,1]).std().unstack()
|
|
557
|
+
mean_stress_strains['stress-std']=stds_stress_strains['stress']
|
|
558
|
+
mean_stress_strains.to_csv(save_data,header=True,index=False,sep=' ')
|
|
559
|
+
fig,ax=plt.subplots(1,1,figsize=(8,6))
|
|
560
|
+
|
|
561
|
+
ax.set_ylabel('Stress, [MPa]')
|
|
562
|
+
ax.set_xlabel('Strain [*]')
|
|
563
|
+
ax.errorbar(mean_stress_strains['strain'],mean_stress_strains['stress'],stds_stress_strains['stress'],alpha=0.2)
|
|
564
|
+
ax.plot(mean_stress_strains['strain'],mean_stress_strains['stress'])
|
|
565
|
+
E,R2=compute_E(mean_stress_strains['strain'],mean_stress_strains['stress'],fit_domain=fit_domain)
|
|
566
|
+
fitline=E*mean_stress_strains['strain']
|
|
567
|
+
half_domain=int(mean_stress_strains['strain'].shape[0]/2)
|
|
568
|
+
line_domain=[0,fit_domain[1] if fit_domain[1]>half_domain else half_domain]
|
|
569
|
+
X=np.array(mean_stress_strains['strain'])[line_domain[0]:line_domain[1]]
|
|
570
|
+
Y=np.array(fitline)[line_domain[0]:line_domain[1]]
|
|
571
|
+
ax.plot(X,Y,'k--',alpha=0.7)
|
|
572
|
+
plt.savefig(outfile,bbox_inches='tight')
|
|
573
|
+
plt.close(fig)
|
|
574
|
+
logger.info(f'{outfile} and {save_data} created. E = {E/1000.0:.3f} GPa (R^2 {R2:.3f})')
|
|
575
|
+
|
|
576
|
+
def post_plots(args):
|
|
577
|
+
n_points=args.n_points
|
|
578
|
+
phases=[]
|
|
579
|
+
# print(args.cfg)
|
|
580
|
+
for c in args.cfg:
|
|
581
|
+
with open(c,'r') as f:
|
|
582
|
+
phases+=yaml.safe_load(f)
|
|
583
|
+
phasenames=[list(x.keys())[0] for x in phases]
|
|
584
|
+
# print(phasenames)
|
|
585
|
+
mdf=[]
|
|
586
|
+
for p in args.proj:
|
|
587
|
+
if 'anneal' in phasenames and 'equilibrate' in phasenames:
|
|
588
|
+
mdf.append(postsim_density_evolution(p))
|
|
589
|
+
if mdf:
|
|
590
|
+
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')
|
|
591
|
+
logger.info('-'.join(phasenames)+'-density.png created.')
|
|
592
|
+
m=[]
|
|
593
|
+
for d in mdf:
|
|
594
|
+
seg=d.iloc[int(0.9*d.shape[0]):]
|
|
595
|
+
logger.debug(f'averaging {seg.shape[0]} final density values out of {d.shape[0]}')
|
|
596
|
+
m.append(seg['Density'].mean())
|
|
597
|
+
m=np.array(m)
|
|
598
|
+
logger.info(f'mean density {m.mean():.0f} kg/m^3 ({m.mean()/1000.0:.3f} g/cc)')
|
|
599
|
+
|
|
600
|
+
ladder_phases=[idx for idx, value in enumerate(phasenames) if value == 'ladder']
|
|
601
|
+
# print(ladder_phases)
|
|
602
|
+
if len(ladder_phases)>0: # perform Tg calculations on each phase
|
|
603
|
+
do_tg_plots([phases[i] for i in ladder_phases],args.proj,n_points=n_points)
|
|
604
|
+
|
|
605
|
+
deform_phases=[idx for idx,value in enumerate(phasenames) if value == 'deform']
|
|
606
|
+
if len(deform_phases)>0:
|
|
607
|
+
do_E_plots([phases[i] for i in deform_phases],args.proj)
|