-
Notifications
You must be signed in to change notification settings - Fork 2
/
ywplot.py
1451 lines (1293 loc) · 43.1 KB
/
ywplot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/global/project/projectdirs/m891/yiwang62/anaconda3/bin/python
#!/usr/bin/python -x
import sys
from datetime import datetime
import os, fnmatch
import copy
import time
import datetime
import numpy as np
from scipy.optimize import linprog
from scipy.interpolate import interp1d
from scipy import interpolate
from numpy.linalg import solve
from fractions import Fraction
from difflib import SequenceMatcher
from docx import Document
#from PIL import Image
from scipy import misc
import cv2 as cv
from scipy import ndimage as ndi
import math
import glob
from scipy.optimize import curve_fit
from scipy.constants import physical_constants
from scipy.optimize import brentq
from scipy.integrate import cumtrapz, trapz, simps
import re
import json
import subprocess
from shutil import copyfile
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from difflib import SequenceMatcher
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from elements import ELEMENTS
MM_of_Elements = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B': 10.811, 'C': 12.0107, 'N': 14.0067,
'O': 15.9994, 'F': 18.9984032, 'Ne': 20.1797, 'Na': 22.98976928, 'Mg': 24.305, 'Al': 26.9815386,
'Si': 28.0855, 'P': 30.973762, 'S': 32.065, 'Cl': 35.453, 'Ar': 39.948, 'K': 39.0983, 'Ca': 40.078,
'Sc': 44.955912, 'Ti': 47.867, 'V': 50.9415, 'Cr': 51.9961, 'Mn': 54.938045,
'Fe': 55.845, 'Co': 58.933195, 'Ni': 58.6934, 'Cu': 63.546, 'Zn': 65.409, 'Ga': 69.723, 'Ge': 72.64,
'As': 74.9216, 'Se': 78.96, 'Br': 79.904, 'Kr': 83.798, 'Rb': 85.4678, 'Sr': 87.62, 'Y': 88.90585,
'Zr': 91.224, 'Nb': 92.90638, 'Mo': 95.94, 'Tc': 98.9063, 'Ru': 101.07, 'Rh': 102.9055, 'Pd': 106.42,
'Ag': 107.8682, 'Cd': 112.411, 'In': 114.818, 'Sn': 118.71, 'Sb': 121.760, 'Te': 127.6,
'I': 126.90447, 'Xe': 131.293, 'Cs': 132.9054519, 'Ba': 137.327, 'La': 138.90547, 'Ce': 140.116,
'Pr': 140.90465, 'Nd': 144.242, 'Pm': 146.9151, 'Sm': 150.36, 'Eu': 151.964, 'Gd': 157.25,
'Tb': 158.92535, 'Dy': 162.5, 'Ho': 164.93032, 'Er': 167.259, 'Tm': 168.93421, 'Yb': 173.04,
'Lu': 174.967, 'Hf': 178.49, 'Ta': 180.9479, 'W': 183.84, 'Re': 186.207, 'Os': 190.23, 'Ir': 192.217,
'Pt': 195.084, 'Au': 196.966569, 'Hg': 200.59, 'Tl': 204.3833, 'Pb': 207.2, 'Bi': 208.9804,
'Po': 208.9824, 'At': 209.9871, 'Rn': 222.0176, 'Fr': 223.0197, 'Ra': 226.0254, 'Ac': 227.0278,
'Th': 232.03806, 'Pa': 231.03588, 'U': 238.02891, 'Np': 237.0482, 'Pu': 244.0642, 'Am': 243.0614,
'Cm': 247.0703, 'Bk': 247.0703, 'Cf': 251.0796, 'Es': 252.0829, 'Fm': 257.0951, 'Md': 258.0951,
'No': 259.1009, 'Lr': 262, 'Rf': 267, 'Db': 268, 'Sg': 271, 'Bh': 270, 'Hs': 269, 'Mt': 278,
'Ds': 281, 'Rg': 281, 'Cn': 285, 'Nh': 284, 'Fl': 289, 'Mc': 289, 'Lv': 292, 'Ts': 294, 'Og': 294,
'ZERO': 0}
periodictable = MM_of_Elements.keys() #""" list of all elements from the periodic table"""
def SGTE(T,a):
fval = a[0]+a[1]*T
if len(a) > 2:
fval += a[2]*T*np.log(T)
if len(a) > 3:
fval += a[3]*T*T
if len(a) > 4:
fval += a[4]*T*T*T
if len(a) > 5:
fval += a[5]/T
return(fval)
def SGTE2(T, a, b):
return (SGTE(T, [a,b]))
def SGTE3(T, a, b, c):
return (SGTE(T, [a,b,c]))
def SGTE4(T, a, b, c, d):
return (SGTE(T, [a,b,c,d]))
def SGTE5(T, a, b, c, d, e):
return (SGTE(T, [a,b,c,d,e]))
def SGTE6(T, a, b, c, d, e, f):
return (SGTE(T, [a,b,c,d,e,f]))
def SGTEC1(T,a):
return C_SGTE(T,[a])
def SGTEC2(T,a,b):
return C_SGTE(T,[a,b])
def SGTEC3(T,a,b,c):
return C_SGTE(T,[a,b,c])
def SGTEC4(T,a,b,c,d):
return C_SGTE(T,[a,b,c,d])
def C_SGTE(T,a):
fval = 0
if len(a) > 0:
fval += a[0]
if len(a) > 1:
fval += a[1]*T
if len(a) > 2:
fval += a[2]*T*T
if len(a) > 3:
fval += a[3]/T/T
return(fval)
def SGTES(T,f):
s = 0.0
if len(f)>0:
s += f[0]
if len(f)>1:
s += f[1]*np.log(T)
if len(f)>2:
s += f[2]*T
if len(f)>3:
s += f[3]*T*T
if len(f)>4:
s += f[4]/T/T
return s
def SGTEH(T,f):
h = 0.0
if len(f)>0:
h += f[0]
if len(f)>1:
h += f[1]*T
if len(f)>2:
h += f[2]*T*T
if len(f)>3:
h += f[3]*T*T*T
if len(f)>4:
h += f[4]/T
return h
def SGTEC(T,f):
s = 0.0
if len(f)>0:
s += f[0]
if len(f)>1:
s += f[1]*T
if len(f)>2:
s += f[2]*T*T
if len(f)>3:
s += f[3]/T/T
return s
def CSGTEfit(f, x, y):
popt,pcov = curve_fit(f, x, y)
z = C_SGTE(x,popt)
ferror=math.sqrt(((z-y)**2).sum()/len(z))
return(popt,ferror)
def fitStoichiometricCp(x,y, thr=0.001):
f,ferror = CSGTEfit(SGTEC2, x, y)
#if ferror > thr:
# f,ferror = CSGTEfit(SGTEC2, x, y)
if ferror > thr:
f,ferror = CSGTEfit(SGTEC3, x, y)
if ferror > thr:
f,ferror = CSGTEfit(SGTEC4, x, y)
return f,ferror
def H_SGTE(T,c):
h = 0.
if len(c)>0:
h += c[0]*T
if len(c)>1:
h += c[1]/2*T*T
if len(c)>2:
h += c[2]/3*T*T*T
if len(c)>3:
h += -c[3]/T
return h
def fitStoichiometricH(x,y,c):
zz = H_SGTE(x,c)
h = (y - zz).sum()/len(y)
ferror=math.sqrt(((h+zz-y)**2).sum()/len(zz))
h = [h]
if len(c)>0:
h.append(c[0])
if len(c)>1:
h.append(c[1]/2)
if len(c)>2:
h.append(c[2]/3)
if len(c)>3:
h.append(-c[3])
return h,ferror
def S_SGTE(T,c):
s = 0.
if len(c)>0:
s += c[0]+c[0]*np.log(T)
if len(c)>1:
s += c[1]*T
if len(c)>2:
s += c[2]/2*T*T
if len(c)>3:
s += -c[3]/2/T/T
return s
def fitStoichiometricS(x,y,c):
zz = S_SGTE(x,c)
b = (y - zz).sum()/len(y)
ferror=math.sqrt(((b+zz-y)**2).sum()/len(zz))
s = []
if len(c)>0:
s.append(b+c[0])
s.append(c[0])
if len(c)>1:
s.append(c[1])
if len(c)>2:
s.append(c[2]/2)
if len(c)>3:
s.append(-c[3]/2)
return s,ferror
def fitStoichiometric(x,y, thr=1.0):
f,ferror = SGTEfit(SGTE2, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE3, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE4, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE5, x, y)
if ferror > thr:
f,ferror = SGTEfit(SGTE6, x, y)
return f,ferror
def SGTEfit(f, x, y):
popt,pcov = curve_fit(f, x, y)
z = SGTE(x,popt)
ferror=math.sqrt(((z-y)**2).sum()/len(z))
return(popt,ferror)
def outexpressionG(f0):
out = ""
for i,f in enumerate(f0):
if i==0:
out += ' {:+g}'.format(f)
elif i==1:
out += ' {:+g}*T'.format(f)
elif i==2:
out += ' {:+g}*T*log(T)'.format(f)
elif i==3:
out += ' {:+g}*T*T'.format(f)
elif i==4:
out += ' {:+g}*T*T*T'.format(f)
elif i==5:
out += ' {:+g}/T'.format(f)
return out
def outexpressionS(f0):
out = ""
for i,f in enumerate(f0):
if i==0:
out += ' {:+g}'.format(f)
elif i==1:
out += ' {:+g}*log(T)'.format(f)
elif i==2:
out += ' {:+g}*T'.format(f)
elif i==3:
out += ' {:+g}*T*T'.format(f)
elif i==4:
out += ' {:+g}/T/T'.format(f)
return out
def outexpressionH(f0):
out = ""
for i,f in enumerate(f0):
if i==0:
out += ' {:+g}'.format(f)
elif i==1:
out += ' {:+g}*T'.format(f)
elif i==2:
out += ' {:+g}*T*T'.format(f)
elif i==3:
out += ' {:+g}*T*T*T'.format(f)
elif i==4:
out += ' {:+g}/T'.format(f)
return out
def outexpressionCp(f0):
out = ""
for i,f in enumerate(f0):
if i==0:
out += ' {:+g}'.format(f)
elif i==1:
out += ' {:+g}*T'.format(f)
elif i==2:
out += ' {:+g}*T*T'.format(f)
elif i==3:
out += ' {:+g}/T/T'.format(f)
return out
def proStoichiometricG():
#try:
x = zthermo.get("temperature (K)")
y = zthermo.get("Gibbs energy (eV/atom)")
H298 = threcord.get("H298.15 (J/mol-atom)")
x = np.array(list(map(float, x)))
y = np.array(list(map(float, y)))*eVtoJ - H298
i0 = 0
for i,T in enumerate(x):
if T < T0:
i0 = i
ifit0 = i0-15
ifit0 = max(ifit0,0)
f,ferror = fitStoichiometric(x[ifit0:],y[ifit0:])
gout = 'G(T) =' + outexpressionG(f)
print("fitting uncertainty=", ferror)
#print(gout)
s = []
h = []
c = []
if len(f) >0:
h.append(f[0])
if len(f) >1:
s.append(-f[1])
if len(f) >2:
s = []
s.append(-f[1]-f[2])
s.append(-f[2])
h.append(-f[2])
c.append(-f[2])
if len(f) >3:
s.append(-2.0*f[3])
h.append(-f[3])
c.append(-2.0*f[3])
if len(f) >4:
s.append(-3.0*f[4])
h.append(-2.0*f[4])
c.append(-6.0*f[4])
if len(f) >5:
s.append(f[5])
h.append(2.0*f[5])
c.append(-2.0*f[5])
sout = 'S(T) =' + outexpressionS(s)
hout = 'H(T) =' + outexpressionH(h)
cout = 'Cp(T) =' + outexpressionCp(c)
"""
print (sout)
print (hout)
print (cout)
"""
uncertanty = {}
SGTErec.update({"G-H298.15 (J/mol-atom)":gout})
SGTErec.update({"H-H298.15 (J/mol-atom)":hout})
SGTErec.update({"S (J/mol-atom/K)":sout})
SGTErec.update({"Cp (J/mol-atom/K)":cout})
return(f,h,s,c,x[i0:])
#except:
pass
def proStoichiometricCp():
#try:
uncertanty = {}
x = zthermo.get("temperature (K)")
y = zthermo.get("Cp (J/mol-atom/K)")
H298 = threcord.get("H298.15 (J/mol-atom)")
x = np.array(list(map(float, x)))
y = np.array(list(map(float, y)))
i0 = 0
for i,T in enumerate(x):
if T < T0:
i0 = i
ifit0 = i0-3
ifit0 = max(ifit0,0)
c,cerror = fitStoichiometricCp(x[ifit0:],y[ifit0:])
y = zthermo.get("enthalpy (J/mol-atom)")
y = np.array(list(map(float, y))) - H298
h,herror = fitStoichiometricH(x[ifit0:],y[ifit0:],c)
y = zthermo.get("entropy (J/mol-atom/K)")
y = np.array(list(map(float, y)))
s,serror = fitStoichiometricS(x[ifit0:],y[ifit0:],c)
f = [h[0]]
if len(s) >0:
f.append(-s[0]+c[0])
f.append(-c[0])
if len(c) >1:
f.append(-c[1]/2)
if len(c) >2:
f.append(-c[2]/6)
if len(c) >3:
f.append(-c[3]/2)
gout = 'G(T) =' + outexpressionG(f)
#print (gout)
SGTErec.update({"Cp (J/mol-atom/K)":[outexpressionCp(c),{"error":round(cerror,2)}]})
SGTErec.update({"H-H298.15 (J/mol-atom)":[outexpressionH(h),{"error":round(herror,2)}]})
SGTErec.update({"S (J/mol-atom/K)":[outexpressionS(s),{"error":round(serror,2)}]})
SGTErec.update({"G-H298.15 (J/mol-atom)":[outexpressionG(f),{"error":round(herror,2)}]})
return(f,h,s,c,x[i0:])
#except:
pass
def thermoplot(folder,thermodynamicproperty,x,y,yzero=None,fitted=None,xT=None,xlabel="T (k)"):
cwd = os.getcwd()
os.chdir( folder )
plt.rc('font', size=24)
fig,ax=plt.subplots()
fig.set_size_inches(12,9)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.set_xlim([0,np.array(list(map(float,x))).max()])
if thermodynamicproperty!="heat capacities ((J/mol-atom/K)":
if yzero != None:
y0 = np.array(list(map(float,y))).min()
y1 = np.array(list(map(float,y))).max()
ylow = 0.0
yhigh = y1*1.05
if y0 < 0.0:
ylow = y0
ax.set_ylim([ylow,yhigh])
ax.plot(x,y,'-',linewidth=2,color='b', label=thermodynamicproperty)
if fitted!=None:
ax.plot(xT[::5],fitted[::5],'--',fillstyle='none', marker='o', markersize=12, linewidth=2,color='k', label="fitted")
else:
y0 = []
y1 = []
y2 = []
for x0,x1,x2 in y:
y0.append(x0)
y1.append(x1)
y2.append(x2)
ax.set_ylim([0.0,np.array(list(map(float,y0))).max()*1.05])
ax.plot(x,y0,'-',linewidth=2,color='b', label="$C_p$")
if fitted!=None:
ax.plot(xT[::5],fitted[::5],'--',fillstyle='none', marker='o', markersize=12, linewidth=2,color='k', label="fitted")
ax.plot(x,y1,'--',linewidth=2,color='black', label="$C_v$")
ax.plot(x,y2,':',linewidth=2,color='g', label="$C_{v,ion}$")
y2 = np.array(list(map(float,y1))) - np.array(list(map(float,y2)))
ax.plot(x,y2,'-.',linewidth=2,color='r', label="$C_{ele}$")
plt.xlabel(xlabel)
plt.ylabel(thermodynamicproperty)
ax.legend(loc=0, prop={'size': 24})
fname = thermodynamicproperty.split('(')[0].strip().replace(' ','_')+".png"
figures.update({thermodynamicproperty:folder.split('/')[-1]+'/'+fname})
fig.savefig(fname,bbox_inches='tight')
plt.close(fig)
os.chdir( cwd )
def myjsonout(data,fp,indent="",comma=""):
#print (data)
mj = ''
if (isinstance(data,dict)):
fp.write('{}\n'.format('{'))
#sys.stdout.write('\n{}{}\n'.format(indent, '{'))
nkey = 0
for key in sorted(set(data.keys())):
nkey += 1
if nkey!=len(data):
comma1 = ","
else:
comma1 = ""
val = data[key]
jval = json.dumps(val)
jkey = json.dumps(key)
#print (val)
if (isinstance(val,dict)):
fp.write('{}{}: '.format(indent+" ",jkey))
myjsonout(val,fp,indent+" ",comma1)
elif (isinstance(val,tuple)):
#print (val)
out = list(val)
#print(out)
fp.write('{}{}: {}{}\n'.format(indent + " ", jkey, out, comma1))
elif (isinstance(val,str)):
if (indent == ""):
fp.write('{}{}: {}{}\n'.format(indent + " ", jkey, jval, comma1))
else:
fp.write('{}{}: {}{}\n'.format(indent + " ", jkey, jval, comma1))
else:
if (indent==""):
fp.write('{}{}: {}{}\n'.format(indent + " ", jkey, jval, comma1))
else:
fp.write('{}{}: {}{}\n'.format(indent + " ", jkey, jval, comma1))
#print(val)
"""
if (nkey!=len(data)):
sys.stdout.write('{}{}: {},\n'.format(indent+" ", key, val))
else:
sys.stdout.write('{}{}: {}\n'.format(indent+" ", key, val))
"""
if comma==',':
fp.write('{}{}{}\n\n'.format(indent,'}', comma))
else:
fp.write('{}{}{}\n'.format(indent, '}', comma))
def similar(pp,pall):
known = ["L12", "delta", "D022", "Gamma"]
ii = -1
for o in known:
if pp.find(o)>-1:
pname = o
ii = 0
break
if ii == -1:
return "unknown"
s = 0.0
for i,p in enumerate(pall):
snew = SequenceMatcher ( None, pname, p ).ratio()
if snew > s:
ii = i
s = snew
print (pp, "= ", pall[ii], " by ", s)
if s > 0.5:
return pall[ii]
else:
return "unknown"
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def formula2composition(formula):
formula = formula.replace(" ",'').replace("-",'').replace(",",'')
newc = ""
"""Follow the convention, elemental symbol must start from capital letter"""
for c in formula:
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
newc = newc + '|'
newc = newc + c
els = newc.split('|')
els = [k for k in els if k != '']
"""now get the composition for each element"""
ele = []
com = []
for el in els:
newel = ""
newcc = ""
for c in el:
if c.isalpha():
newel = newel + c
else:
newcc = newcc + c
if (newel not in periodictable):
print('"',newel,'" is not an element! your formula is wrong!')
sys.exit(1)
ele.append(newel)
if (len(newcc)!=0):
if (isfloat(newcc)):
com.append(int(newcc))
else:
print('"',newcc,'" is not an int number! your formula is wrong!')
sys.exit(1)
else:
com.append(1.0)
com = np.array(list(map(int,com)))
#sorted the sequence and merge the duplicate
elist = sorted(set(ele))
clist = np.zeros(len(elist), dtype=int)
for j,el in enumerate(ele):
ix = elist.index(el)
clist[ix] += com[j]
return elist,clist
def formula2elist(formula):
formula = formula.replace(" ",'').replace("-",'').replace(",",'')
newc = ""
"""Follow the convention, elemental symbol must start from capital letter"""
for c in formula:
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
newc = newc + '|'
newc = newc + c
els = newc.split('|')
els = [k for k in els if k != '']
"""now get the composition for each element"""
ele = []
com = []
for el in els:
newel = ""
newcc = ""
for c in el:
if c.isalpha():
newel = newel + c
else:
newcc = newcc + c
if (newel not in periodictable):
print('"',newel,'" is not an element! your formula is wrong!')
sys.exit(1)
ele.append(newel)
if (len(newcc)!=0):
if (isfloat(newcc)):
com.append(float(newcc))
else:
print('"',newcc,'" is not a float number! your formula is wrong!')
sys.exit(1)
else:
com.append(1.0)
com = np.array(list(map(float,com)))
com = com/sum(com)
#sorted the sequence and merge the duplicate
elist = sorted(set(ele))
clist = np.zeros(len(elist), dtype=float)
for j,el in enumerate(ele):
ix = elist.index(el)
clist[ix] += com[j]
return elist
def prety_formulaO(longphasename):
puc = longphasename.split('|')[-1]
_els,_nat=formula2composition(puc)
def prety_formula(_els,_nat):
els = sorted(set(_els))
nat = np.zeros(len(els),dtype=int)
for i,el in enumerate(_els):
ix = els.index(el)
nat[ix] += _nat[i]
Nd = min(nat)
for i in range(Nd,0,-1):
out = True
for j in range(len(nat)):
if ((nat[j]//i)*i!=nat[j]):
out = False
break
if out:
break
form = ""
for j,el in enumerate(els):
ix = nat[j]//i
form = form+el
if ix!=1:
form = form+str(ix)
return form
def Genergy(thermofile,dir0):
tmelt = 9999.
ele = threcord.get("Elements")
if len(ele)==1:
tmelt = ELEMENTS[ele[0]].tmelt
folder = dir0+'/'+"figures"
if not os.path.exists(folder):
os.mkdir(folder)
thermo = np.loadtxt(thermofile, comments="#", dtype=np.float)
thermo[np.isnan(thermo)] = 0.0
for i,cp in enumerate(thermo[:,6]):
if cp > CpMax: break
elif thermo[i,0] > tmelt: break
thermo = thermo[0:i,:]
Vstack=interpolate.splrep(thermo[:,0], thermo[:,1])
V298 = float(interpolate.splev(T0, Vstack))
Hstack=interpolate.splrep(thermo[:,0], thermo[:,4])
H298 = float(interpolate.splev(T0, Hstack))
threcord.update({"H298.15 (J/mol-atom)":round(H298,4)})
Sstack=interpolate.splrep(thermo[:,0], thermo[:,3])
S298 = float(interpolate.splev(T0, Sstack))
threcord.update({"S298.15 (J/mol-atom/K)":round(S298,6)})
zthermo.update({"temperature (K)":list(thermo[:,0])})
zthermo.update({"atomic volume (Angstrom^3)":list(thermo[:,1])})
thermoplot(folder,"atomic volume (Angstrom^3)",list(thermo[:,0]),list(thermo[:,1]))
zthermo.update({"Gibbs energy (eV/atom)":list(thermo[:,2])})
zthermo.update({"enthalpy (J/mol-atom)":list(thermo[:,4])})
zthermo.update({"entropy (J/mol-atom/K)":list(thermo[:,3])})
zthermo.update({"Cp (J/mol-atom/K)":list(thermo[:,6])})
if fitCp:
g,h,s,c,x=proStoichiometricCp()
else:
g,h,s,c,x=proStoichiometricG()
threcord.update({"SGTE fitting":SGTErec})
thermoplot(folder,"Gibbs energy-H298 (J/mol-atom)",list(thermo[:,0]),list(thermo[:,2]*eVtoJ-H298),fitted=list(SGTE(x,g)), xT=list(x))
thermoplot(folder,"enthalpy-H298 (J/mol-atom)",list(thermo[:,0]),list(thermo[:,4]-H298), fitted=list(SGTEH(x,h)), xT=list(x))
#thermoplot(folder,"enthalpy-H298 (J/mol-atom)",list(thermo[:,0]),list(thermo[:,4]-H298), fitted=list(SGTE(x,g)+x*SGTES(x,s)), xT=list(x))
thermoplot(folder,"entropy (J/mol-atom/K)",list(thermo[:,0]),list(thermo[:,3]),yzero=0.0, fitted=list(SGTES(x,s)), xT=list(x))
zthermo.update({"LTC (1/K)":list(thermo[:,5])})
thermoplot(folder,"LTC (1/K)",list(thermo[:,0]),list(thermo[:,5]),yzero=0.0)
zthermo.update({"Cv (J/mol-atom/K)":list(thermo[:,14])})
zthermo.update({"Cv,ion (J/mol-atom/K)":list(thermo[:,7])})
Cele = [round(c,6) for c in thermo[:,14]-thermo[:,7]]
zthermo.update({"Cele (J/mol-atom/K)":Cele})
ncols = [6,14,7]
thermoplot(folder,"heat capacities ((J/mol-atom/K)",list(thermo[:,0]),list(thermo[:,ncols]),fitted=list(SGTEC(x,c)), xT=list(x))
zthermo.update({"Debye temperature (K)":list(thermo[:,13])})
thermoplot(folder,"Debye temperature (K)",list(thermo[:,0]),list(thermo[:,13]),yzero=0.0)
zthermo.update({"bulk modulus (GPa)":list(thermo[:,15])})
thermoplot(folder,"bulk modulus (GPa)",list(thermo[:,0]),list(thermo[:,15]),yzero=0.0)
threcord.update({"zthermodynamic properies":zthermo})
threcord.update({"Atomic volume at 298.15 K (Angstrom^3)":round(V298,6)})
with open(vdos_e.replace('thermo/vdos_e','tplate/POSCAR'), 'r') as f:
vvv = f.readlines()
natom = sum([int(vv) for vv in vvv[6].split(' ') if vv!=""])
structure.update({"number of atoms in POSCAR":natom})
#natom = threcord.get("number of atoms in the primitive unit cell")
with open(vdos_e.replace('thermo/vdos_e','thermo/data.in'), 'r') as f:
vvv = f.readlines()
Vfiles = []
Pfiles = []
volumes = []
energies = []
for vv in vvv[1:]:
v = vv.split(' ')
Pfiles.append("phonon/"+v[2].split('/')[-1].replace('\n', '').replace('"', ''))
Vfiles.append(v[2].split('/')[-1].replace('\n', '').replace('"', ''))
volumes.append(round(float(v[0])/natom,6))
energies.append(round(float(v[1])/natom,6))
structure.update({"Static vasp settings":Vfiles})
structure.update({"phonon vasp settings and force constants":Pfiles})
threcord.update({"volumes":volumes})
threcord.update({"energies":energies})
with open(dir0+'/E-V.dat','w') as f:
for i,v in enumerate(volumes):
f.write('{} {}\n'.format(v,energies[i]))
#cmd = "YWfit -BMvol <"+dir0+'/E-V.dat | grep "f_expr(x) = "'
ffun = "-Morse"
cmd = "YWfit "+ffun+" <"+dir0+'/E-V.dat | grep "f_expr(x) = "'
output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
cwd = os.getcwd()
os.chdir( dir0+"/figures")
fitF = output.stdout
with open('E-V.plt','w') as f:
f.write('set terminal postscript landscape enhanced color "Times_Roman" 20\n')
f.write('set encoding iso_8859_1\n')
f.write('set pointsize 1.2\n')
f.write('set size 0.95,0.95\n')
f.write('set output "E-V.eps"\n')
f.write('{}\n'.format(fitF))
f.write('set key right bottom\n')
f.write('set xlabel "atomic volume (Angstrom^3)\n')
f.write('set ylabel "static energy (eV/atom)\n')
f.write('plot "../E-V.dat" title "calculated" w p pt 7, \\\n')
f.write(' f_expr(x) title "'+ffun+'" w l lt -1\n')
#cmd = "gnuplot E-V.plt; convert -fuzz 100% -transparent white -rotate 90 -density 120x120 E-V.eps E-V.png"
cmd = "gnuplot E-V.plt; convert -background white -alpha remove -rotate 90 -density 120x120 E-V.eps E-V.png"
output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
figures.update({"static E-V curve": "figures/E-V.png"})
threcord.update({"figures":figures})
os.chdir(cwd)
return Vfiles,Pfiles,g
def BMfitP(x,z):
p = 0.0
N = len(z)
for n in range(N):
p = p + float(N-n-1)*z[n]*x**(N-n+0.5)*(-2.0/3.0)
return (-p)
def BMfit(v,p,g, T):
global tPmax
v = np.array(list(map(float,v)))
p = np.array(list(map(float,p)))
g = np.array(list(map(float,g)))
f = g - p*v
x = v**(-2.0/3.0)
z = np.polyfit(x,f,BMvol)
gf = np.poly1d(z)
if (Debug==1):
for i, vv in enumerate(v):
print(vv, p[i], BMfitP(x[i],z), f[i], gf(x[i]))
xx = x[0]
xd = (x[len(x)-1] - x[0])*0.02
pp = []
gg = []
vv = []
for i in range(999):
ppxx = BMfitP(xx,z)
if (ppxx > tPmax*1.1):
break
pp.append(ppxx)
vv.append(xx**(-1.5))
gg.append(gf(xx)+ppxx*xx**(-1.5))
xx = xx + xd
try:
s = interpolate.splrep(pp, gg)
sv = interpolate.splrep(pp, vv)
except ValueError:
print("*******fetal ERROR: BMvol of order: ", BMvol, " fetal fitting error at T= ", T)
print(pp)
print(gg)
sys.exit()
gx =interpolate.splev(txx, s)
vx =interpolate.splev(txx, sv)
if (Debug==1):
for i, pp in enumerate(txx):
print(pp*eVtoGPa, gx[i])
for i, pp in enumerate(p):
print(pp*eVtoGPa, g[i])
sys.exit()
class result:
G = gx
V = vx
return(result)
def mkDict(line):
rec = {}
skiprec = False
ss = str(line)[0:].replace("'","").split()
ss = [k for k in ss if k != '']
for nc,el in enumerate(ss):
if isfloat(el):
break
if len(within)!=0:
for el in ss[0:nc]:
if el not in within:
return True, None, None, None
_sideal = 0
_PN = ""
i = nc*2+2
while i < len(ss):
if ss[i] == "PQ":
try:
_PQ = float(ss[i+1])
#threcord.update({"amount of imaginary phonon mode":float('{:.6f}'.format(_PQ))})
Uncertainty.update({"amount of imaginary phonon mode":round(_PQ,6)})
skiprec = _PQ >= PQ
i += 1
if skiprec:
if not paper: print (ss[nc*2+1],"skipped, PQ=", ss[i])
break
except:
skiprec = True
print ("********Wrong record", ss)
break
elif ss[i] == "EQ":
try:
_EQ = float(ss[i+1])
#threcord.update({"0 K energy uncertainty (eV/atom)":float('{:.6f}'.format(_EQ))})
Uncertainty.update({"0 K energy uncertainty (eV/atom)":round(_EQ,6)})
skiprec = _EQ >= EQ
i += 1
if skiprec:
print (ss[nc*2+1],"skipped, EQ=", ss[i])
break
except:
skiprec = True
print ("********Wrong record", ss)
break
elif ss[i] == "PN":
_PN = ss[i+1].strip("/")
threcord.update({"Phase name":_PN})
i += 1
mpid = ""
try:
mp = _PN.index("mp-")
mpid = _PN[mp:].split('_')[0]
except:
pass
structure.update({"mpid":mpid})
elif ss[i] == "E0":
#threcord.update({"static energy (eV/atom)":float('{:.6f}'.format(float(ss[i+1].strip("/"))))})
threcord.update({"Static energy (eV/atom)":round(float(ss[i+1]),6)})
i += 1
elif ss[i] == "TT":
Tup = float(ss[i+1])
threcord.update({"Tmax":Tup})
i += 1
if Tup < Tupmax:
print (ss[nc*2+1],"skipped, Tmax=", ss[i])
skiprec = True
break
elif isfloat(ss[i]):
_sideal = float(ss[i])
i += 1
if skiprec:
return True, None, None, None
threcord.update({"Uncertainty":Uncertainty})
space = ss[nc*2].strip("/").split("|")
structure.update({"space group":int(space[0])})
structure.update({"point group symmetry":space[1]})
structure.update({"space group symmetry":space[2]})
structure.update({"primitive unit cell formula":space[3]})
elist, clist = formula2composition(space[3])
pnatom = sum(clist)
structure.update({"number of atoms in the primitive unit cell":int(pnatom)})
tComponents = ss[0:nc]
tnComponents = np.array(list(map(int,ss[nc:nc+nc])))
natom = sum(tnComponents)
tnComponents = tnComponents/natom
Components = sorted(set(tComponents))
nComponents = np.zeros(len(Components))
for i0,el in enumerate(tComponents):
ix = Components.index(el)
nComponents[ix] = nComponents[ix] + tnComponents[i0]
compositions = []
for i in range(len(Components)):
compositions.append(int(0.1+natom*nComponents[i]))
threcord.update({"Elements":Components})
threcord.update({"Occupancies":list(compositions)})
i = nc*2+2
while i < len(ss):
if ss[i] == "disordered":
if i+1>=len(ss):
_sideal = -sum(nComponents*np.log(nComponents))
elif isfloat(ss[i+1]):
i += 1
if float(ss[i])<0.0:
_sideal = -sum(nComponents*np.log(nComponents))
else:
_sideal = float(ss[i])
else:
_sideal = -sum(nComponents*np.log(nComponents))
i += 1
threcord.update({"Ideal mixing entropy (kB/atom)":_sideal})
keys = threcord.keys()
vdos_e = str(ss[nc+nc+1]).replace('//','/')
threcord.update({"Calculation date":str(datetime.datetime.fromtimestamp(os.path.getmtime(vdos_e)))})
#threcord.update({"Calculation date":str(date.fromtimestamp(os.path.getatime(vdos_e)))})
dir0 = _PN
idx = 1
while True:
if not os.path.exists(dir0): break
recordfile = dir0+"/record.json"
newdir = False
try:
if os.path.exists(recordfile):
with open(recordfile) as jsonfile:
orec = json.load (jsonfile)
okeys = orec.keys()
for k in keys:
v = threcord.get(k)
for ok in okeys:
if ok != k: continue
newdir = orec.get(ok) != v
if newdir: break
if k == "Static energy":
if k in okeys:
if abs(float(v-okeys.get(k))) < THR0: newdir = False
except:
pass
if not newdir: break
idx += 1
dir0 = _PN+"#"+str(idx)
oldPN = dir0
newPN = PhaseName.get(_PN)
if newPN != None: dir0 = newPN
#print (_PN,dir0,PhaseName)