-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathACTE.py
3985 lines (3415 loc) · 175 KB
/
ACTE.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Nicholas Pike
Email : [email protected]
Purpose: Calculation of the thermal expansion coefficients
Notes: - Oct 4th start of program
- Apr 5th two dimensional fit for free energy
- Nov 21th three dimensional fit for free energy
- Jan 29th minor bug fixes and simplification of build_cell routine
"""
#import needed functions
import os
import sys
import subprocess
import linecache
import numpy as np
import scipy.optimize as so
import scipy.constants as sc
from mendeleev import element
#define unit relationships
ang_to_m = sc.physical_constants['Angstrom star'][0] #angstrom to meter
amu_kg = sc.atomic_mass
J_to_cal = 1.0/sc.calorie
h = sc.physical_constants['Planck constant'][0]
kb = sc.physical_constants['Boltzmann constant'][0]
Na = sc.physical_constants['Avogadro constant'][0]
kbar_to_GPa = 0.1
m_to_cm = 100.0
kgm3_to_cm3 = 1000.0 #density conversion
g_to_kg = 1000.0
cal_to_J = 4.184
difftol = 1E-5
"""
###############################################################################
The following information should be modified by the user to suit their own
supercomputer.
###############################################################################
"""
supercomputer_software = 'slurm' #'pbs'
use_scratch = 'yes' # yes is recommended
account_number = 'nnxxxx'
account_email = '[email protected]'
__root__ = os.getcwd()
"""
##############################################################################
VASP parameters. Make sure you change convergence parameters before doing your
calculation
##############################################################################
"""
ecut = '500' #value in eV
ediff = '1E-7' #value in eV
kdensity = 5
"""
##############################################################################
TDEP parameters. These parameters may need to be converged.
##############################################################################
"""
natom_ss = '200' #number of atoms in the supercell (metals ~100, semiconductor ~200])
rc_cut = '100' #second order cut-off radius (100 defaults to the maximum radius)
tmin = '0' #minimum temperature
tmax = '3000' #maximum temperature
tsteps = '1500' #number of temperature steps
qgrid = '30 30 30' #q point grid density for DOS
iter_type = '3' #method for numerical integration
n_configs = '12' #number of configurations
t_configs = '0.8' #temperature of configurations as a fraction of Debye temperature
# this should be less than one
"""
##############################################################################
Paths to executables and main file name
##############################################################################
"""
VASPSR = 'path to vasp source' #source path to VASP executable
TDEPSR = 'path to tdep source' #source path to TDEP bin of executables
PYTHMOD = 'path to python' #module for python
"""
Begin modules used in this program
"""
def main_thermal(DFT_INPUT,tags):
"""
Author: Nicholas Pike
Email: [email protected]
Purpose: Calculate the thermal expansion coefficients of the material.
Return: None
"""
if sys.version_info<=(2,7,0):
print('ERROR: This program requires Python version 2.7.0 or greater.' )
sys.exit()
# get data from TDEP and DFT calculations
cell_data = READ_INPUT_DFT(DFT_INPUT)
#calculation of lattice expansion coefficients.
print('Launching calculation of the coefficients of thermal expansion.')
#launch calculation of linear expansion coefficients
cell_data = linear_exp(cell_data,tags)
print('Calculation of the coefficients of thermal expansion are complete\n')
return None
def READ_INPUT_DFT(DFT_INPUT):
"""
Author: Nicholas Pike
Email : [email protected]
Purpose: To read an input file which is formatted and contains the results of
our DFT, DFPT, and TDEP calculations
Input: DFT_INPUT - name of formatted input file
OUTPUT: cell_data - array of data about the unit cell
"""
#store data in arrays
cell_data = [0] *30
#open file and look for data
print('Reading input data from DFT and DFPT calculations in %s\n' %DFT_INPUT)
with open(DFT_INPUT,'r') as f:
for num,line in enumerate(f,1):
if line.startswith( 'volume'):
l = line.strip('\n').split(' ')
cell_data[0] = float(l[1])*ang_to_m**3.0 #cell volume converted to m^3
elif line.startswith('alat'):
l = line.strip('\n').split(' ')
cell_data[1] = float(l[1])*ang_to_m
elif line.startswith('blat'):
l = line.strip('\n').split(' ')
cell_data[2] = float(l[1])*ang_to_m
elif line.startswith('clat'):
l = line.strip('\n').split(' ')
cell_data[3] = float(l[1])*ang_to_m
elif line.startswith('natom'):
l = line.strip('\n').split(' ')
cell_data[4] = int(l[1])
elif line.startswith('atpos'):
l = line.strip('\n').split(' ')
cell_data[5] = []
for i in range(1,len(l)):
elname = element(l[i])
cell_data[5] = np.append(cell_data[5],[l[i],float(elname.mass*amu_kg)])
elif line.startswith('Free energy on grid filenames'):
#need to read in the next 25 filenames
files = []
diff_volumes,speccell = determine_volumes()
for y in range(int(diff_volumes)):
with open(DFT_INPUT,'r') as h:
for j,line2 in enumerate(h):
l = line2.strip('\n').split(' ')
if j == num+y:
files = np.append(files,l[0])
cell_data[19] = files
elif line.startswith('TMIN'):
l = line.strip('\n').split(' ')
cell_data[23] = l[1]
elif line.startswith('TMAX'):
l = line.strip('\n').split(' ')
cell_data[24] = l[1]
elif line.startswith('TSTEP'):
l = line.strip('\n').split(' ')
cell_data[25] = l[1]
elif line.startswith('Bulk Mod'):
l = line.strip('\n').split(' ')
cell_data[27] = float(l[2])
#print data that is read in so far to the terminal
print(' Printing data from DFT and DFPT calculations...\n')
print(' Input data for the unit cell:')
print(' alat: \t\t %s meters' %cell_data[1])
print(' blat: \t\t %s meters' %cell_data[2])
print(' clat: \t\t %s meters' %cell_data[3])
print(' volume: \t\t %s meters^3' %cell_data[0])
print(' natom: \t\t %s'%cell_data[4])
print(' Tmin: \t\t %s' %cell_data[23])
print(' Tmax: \t\t %s' %cell_data[24])
print(' Tstep: \t\t %s\n' %cell_data[25])
attype = ''
for i in range(len(cell_data[5])):
if i %2 == 0:
attype += cell_data[5][i]+' '
print(' atom type: \t %s\n'%attype)
print('Data read in from DFT, DFPT, and TDEP calculations.\n')
return cell_data
def linear_exp(cell_data,tags):
"""
Author: Nicholas Pike
Email: [email protected]
Purpose: Calculates the linear expansion coefficient using a spline interpolation at
each temperature step
Output: modified cell_data with linear expansion coefficients
"""
#split tags
withbounds = tags[0]
#withsolver = tags[1]
#withBEC = tags[2]
withpoly = tags[3]
#initialize variables
a0 = cell_data[1]/ang_to_m
b0 = cell_data[2]/ang_to_m
c0 = cell_data[3]/ang_to_m
mass = cell_data[5]
#quick calculations of variables
total_mass = 0.0
for i in range(1,len(mass),2):
total_mass += float(mass[i])
#optimize calculations based on the number of unique lattice parameters
"""
Calculations of isotropic systems!
"""
if np.abs(a0-b0) <= difftol and np.abs(a0-c0) <= difftol:
volnum = 6
num_unique = 1
print(' Number of volumes: %s'%volnum)
print(' Number of unique axes: %i' %num_unique)
#step 1: read in free energy files
latt_array,vol_array,engy_array,free_array,cell_data = read_free_energies(volnum,num_unique,cell_data)
#step 2: determine the lattice parameters that minimize the temperature
latt_data,cell_data = minimize_free(volnum,num_unique,cell_data,latt_array,engy_array,free_array,withbounds)
#step 3: Fit the equation of state
bulkT,cell_data = fit_EOS(volnum,num_unique,cell_data,engy_array,free_array,vol_array,withbounds)
#step 4: Calculate coefficients of thermal expansion
lattder,cell_data = find_CTE(volnum,num_unique,cell_data,latt_data,withpoly)
#step 5: Calculate specific heat at constant pressure
sheat,cell_data = find_CP(volnum,num_unique,cell_data,lattder,bulkT,total_mass)
#step 6: print all calculations to a file
print_all(volnum,num_unique,cell_data,free_array,latt_data,lattder,bulkT,sheat)
"""
Anisotropic system with two similiar axis (hexgonal first with c as the free axis)
"""
elif np.abs(a0-b0)<= difftol and np.abs(a0-c0) >difftol :
volnum = 36
num_unique = 2
print(' Number of volumes: %s'%volnum)
print(' Number of unique axes: %i' %num_unique)
#step 1: read in free energy files
latt_array,vol_array,engy_array,free_array,cell_data = read_free_energies(volnum,num_unique,cell_data)
#step 2: determine the lattice parameters that minimize the temperature
latt_data,cell_data = minimize_free(volnum,num_unique,cell_data,latt_array,engy_array,free_array,withbounds)
#step 3: Fit the equation of state
bulkT,cell_data = fit_EOS(volnum,num_unique,cell_data,engy_array,free_array,vol_array,withbounds)
#step 4: Calculate coefficients of thermal expansion
lattder, cell_data = find_CTE(volnum,num_unique,cell_data,latt_data,withpoly)
#step 5: Calculate specific heat at constant pressure
sheat,cell_data = find_CP(volnum,num_unique,cell_data,lattder,bulkT,total_mass)
#step 6: print all calculations to a file
print_all(volnum,num_unique,cell_data,free_array,latt_data,lattder,bulkT,sheat)
"""
Fully anisotropic system
"""
elif np.abs(a0-b0)> difftol and np.abs(a0-c0) >difftol :
volnum = 216
num_unique = 3
print(' Number of volumes: %s'%volnum)
print(' Number of unique axes: %i' %num_unique)
#step 1: read in free energy files
latt_array,vol_array,engy_array,free_array,cell_data = read_free_energies(volnum,num_unique,cell_data)
#step 2: determine the lattice parameters that minimize the temperature
latt_data,cell_data = minimize_free(volnum,num_unique,cell_data,latt_array,engy_array,free_array,withbounds)
#step 3: Fit the equation of state
bulkT,cell_data = fit_EOS(volnum,num_unique,cell_data,engy_array,free_array,vol_array,withbounds)
#step 4: Calculate coefficients of thermal expansion
lattder, cell_data = find_CTE(volnum,num_unique,cell_data,latt_data,withpoly)
#step 5: Calculate specific heat at constant pressure
sheat,cell_data = find_CP(volnum,num_unique,cell_data,lattder,bulkT,total_mass)
#step 6: print all calculations to a file
print_all(volnum,num_unique,cell_data,free_array,latt_data,lattder,bulkT,sheat)
return cell_data
def read_free_energies(volnum,num_unique,cell_data):
"""
Author: Nicholas Pike
Email : [email protected]
Purpose: Read in the free energy files and process them
Return: Arrays of the lattice parameters, volume, electronic energy, free energy, and cell data
"""
#build arrays
free_array = np.empty(shape=(int(volnum),int(cell_data[25])))
latt_array = np.empty(shape=(int(volnum),3))
engy_array = np.empty(shape=(int(volnum),1))
vol_array = []
#gather necessary data
files = cell_data[19]
print(' 1 - Reading in the free energy files for each lattice grid')
found_unstable = False
unstable_files = []
unstable_numbs = []
if num_unique == 1:
i = 0
for file in files:
#use the file name to determine the lattice constants
l = file.split('_')
latt_array[i][0] = float(l[3]) # a lattice
engy_array[i][0] = float(l[6]) # U_0 (a)
vol_array = np.append(vol_array,float(l[7])) #volume
try:
os.path.isfile('free_energies/'+file)
except:
print('ERROR: The file %s was not found in the directory or contains errors.' %file)
sys.exit()
with open('free_energies/'+file,'r') as f:
for num,line in enumerate(f,0):
l = line.strip('\n').split()
if l[1] != 'NaN':
free_array[i][num] = float(l[1])
if float(l[1]) > 3.0E8:
found_unstable = True
if found_unstable == True:
print(' ERROR: Free energy calculation for %i may have an instability. Will relaunch at end.'%i)
print(' Suggestion: Plot the dispersion relation to view the instability.')
unstable_files = np.append(unstable_files,file)
unstable_numbs = np.append(unstable_numbs,i)
found_unstable = False
i+=1
elif num_unique == 2:
i = 0
for file in files:
#use the file name to determine the lattice constants
l = file.split('_')
latt_array[i][0] = float(l[3]) # a lattice
latt_array[i][2] = float(l[5]) # c lattice
engy_array[i][0] = float(l[6]) # U_0 (a)
vol_array = np.append(vol_array,float(l[7])) #volume
try:
os.path.isfile('free_energies/'+file)
except:
print('ERROR: The file %s was not found in the directory or contains errors.' %file)
sys.exit()
with open('free_energies/'+file,'r') as f:
for num,line in enumerate(f,0):
l = line.strip('\n').split()
if l[1] != 'NaN':
free_array[i][num] = float(l[1])
if float(l[1]) > 3.0E8:
found_unstable = True
if found_unstable == True:
print(' ERROR: Free energy calculation for %i may have an instability. Will relaunch at end.'%i)
print(' Suggestion: Plot the dispersion relation to view the instability.')
unstable_files = np.append(unstable_files,file)
unstable_numbs = np.append(unstable_numbs,i)
found_unstable = False
i+=1
elif num_unique == 3:
i = 0
for file in files:
#use the file name to determine the lattice constants
l = file.split('_')
latt_array[i][0] = float(l[3]) # a lattice
latt_array[i][1] = float(l[4]) # b lattice
latt_array[i][2] = float(l[5]) # c lattice
engy_array[i][0] = float(l[6]) # U_0 (a)
vol_array = np.append(vol_array,float(l[7])) #volume
try:
os.path.isfile('free_energies/'+file)
except:
print('ERROR: The file %s was not found in the directory or contains errors.' %file)
sys.exit()
with open('free_energies/'+file,'r') as f:
for num,line in enumerate(f,0):
l = line.strip('\n').split()
if l[1] != 'NaN':
free_array[i][num] = float(l[1])
if float(l[1]) > 3.0E8:
found_unstable = True
if found_unstable == True:
print(' ERROR: Free energy calculation for %i may have an instability. Will relaunch at end.'%i)
print(' Suggestion: Plot the dispersion relation to view the instability.')
unstable_files = np.append(unstable_files,file)
unstable_numbs = np.append(unstable_numbs,i)
found_unstable = False
i+=1
if unstable_numbs !=[]:
relaunch_configs(unstable_numbs,unstable_files)
sys.exit()
return latt_array,vol_array,engy_array,free_array,cell_data
def minimize_free(volnum,num_unique,cell_data,latt_array,engy_array,free_array,withbounds):
"""
Author: Nicholas Pike
Email: [email protected]
Purpose: Find lattice parameters that minimize the free energy
Return: Arrays of lattice parameters and cell data
"""
#gather necessary information
a0 = cell_data[1]/ang_to_m
b0 = cell_data[2]/ang_to_m
c0 = cell_data[3]/ang_to_m
numatoms = float(cell_data[4])
Tmin = int(cell_data[23])
Tmax = int(cell_data[24])
tempsteps = int(cell_data[25])
desired_acc = 1.0E-3
#build arrays
x = []
y = []
t = []
latt_data = np.empty(shape=(4,tempsteps))
print(' 2 - Generating the fits for each temperature and \n'\
' finding the minimum set of coordinates.')
print(' ---Brief pauses are normal---')
with open('out.coefficients','w') as f:
f.write('# Output coefficients of fit to free energy polynomial.\n')
f.write('# tstep cof[0] cof[1] ... etc\n')
if withbounds == True:
print(' Bounds are being used.')
if num_unique == 1:
for i in range(int(volnum)):
x = np.append(x,latt_array[i][0])
#find max and min of the lattice x
xmin = min(x)
xmax = max(x)
#generate list of coordinates for each temperature
for i in range(tempsteps):
z = []
for j in range(int(volnum)):
z = np.append(z,(engy_array[j][0]+numatoms*free_array[j][i])) #Add internal energy to each point.
#internal test that they are all the same length
try:
x.shape[0] == z.shape[0]
except:
print('ERROR: The dimensions of either x or z are unequal.')
print('The dimensions of the arrays are %s %s.'%(x.shape[0],z.shape[0]))
sys.exit()
#find best fit 6th order fit
#this is written in the same order as the coefficients of the fit. I.e. c00 , c10, c20 etc.
A = np.c_[x*0.0+1.0,x, x**2,x**3,x**4]
#C contains the coefficients to the polynomial we are trying to fit.
# if statement added to handle bad behavior in older versions of numpy
try:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
except FutureWarning:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
#print the coefficients, C, to a file as a function of temperature
with open('out.coefficients','a') as f:
f.write('%s %s %s %s %s %s\n' %(i,C[0],C[1],C[2],C[3],C[4]))
#use the BFGS method to determine the point that minimizes the function
if i == 0:
initial_guess = [a0]
else:
initial_guess = [latt_data[1][i-1]]
tol = 1E-10
if withbounds == True:
bounds = [(xmin,xmax),] #bounds of free energy grid
result = so.minimize(fourthorder_ploy,initial_guess,
method='L-BFGS-B',args=(C,),bounds=bounds,tol=tol)
else:
result = so.minimize(fourthorder_ploy,initial_guess,
method='BFGS',args=(C,),tol=tol)
#gather results from optimization routine
latt_data[0][i] = Tmin+(Tmax-Tmin)/tempsteps*i
latt_data[1][i] = result.x[0]
elif num_unique == 2:
for i in range(int(volnum)):
x = np.append(x,latt_array[i][0])
y = np.append(y,latt_array[i][2]) #here y is the c direction
#find max and min of the lattice parameters
xmin = min(x)
xmax = max(x)
ymin = min(y)
ymax = max(y)
#generate list of coordinates for each temperature
for i in range(tempsteps):
z = []
for j in range(int(volnum)):
z = np.append(z,(engy_array[j][0]+numatoms*free_array[j][i])) #Add internal energy to each point.
#internal test that they are all the same length
try:
x.shape[0] == y.shape[0] == z.shape[0]
except:
print('ERROR: The dimensions of either x,y, or z are unequal.')
print('The dimensions of the arrays are %s %s %s.'%(x.shape[0],y.shape[0],z.shape[0]))
sys.exit()
#find best fit 6th order fit
A = np.c_[x**0*y**0+1, x**1*y**0, x**2*y**0, x**3*y**0, x**4*y**0,
x**0*y**1, x**1*y**1, x**2*y**1, x**3*y**1, x**4*y**1,
x**0*y**2, x**1*y**2, x**2*y**2, x**3*y**2, x**4*y**2,
x**0*y**3, x**1*y**3, x**2*y**3, x**3*y**3, x**4*y**3,
x**0*y**4, x**1*y**4, x**2*y**4, x**3*y**4, x**4*y**4]
#C contains the coefficients to the polynomial we are trying to fit.
# if statement added to handle bad behavior in older versions of numpy
try:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
except FutureWarning:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
#print the coefficients, C, to a file as a function of temperature
with open('out.coefficients','a') as f:
f.write('%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s '\
'%s %s %s %s %s\n'
%(i,C[0],C[1],C[2],C[3],C[4],C[5],C[6],C[7],C[8],C[9],C[10],C[11],
C[12],C[13],C[14],C[15],C[16],C[17],C[18],C[19],C[20],C[21],C[22],C[23],
C[24]))
#use the BFGS method to determine the point that minimizes the function
tol = 1E-10
if i == 0:
initial_guess = [a0,c0]
else:
initial_guess = [latt_data[1][i-1],latt_data[3][i-1]]
if withbounds == True:
bounds = [(xmin,xmax),(ymin,ymax)] #bounds of free energy grid
result = so.minimize(eighthorder_ploy,initial_guess,args=(C),
method='L-BFGS-B',bounds = bounds,tol = tol)
else:
result = so.minimize(eighthorder_ploy,initial_guess,args=(C),
method='BFGS',tol = tol)
#gather results from optimization routine
latt_data[0][i] = Tmin+(Tmax-Tmin)/tempsteps*i
latt_data[1][i] = result.x[0]
latt_data[3][i] = result.x[1]
elif num_unique == 3:
for i in range(int(volnum)):
x = np.append(x,latt_array[i][0]) # a
y = np.append(y,latt_array[i][1]) # b
t = np.append(t,latt_array[i][2]) # c
#find max and min of the lattice parameters
xmin = min(x)
xmax = max(x)
ymin = min(y)
ymax = max(y)
tmin = min(t)
tmax = max(t)
#determine the density by looking at the required accuracy in the lattice parameters
density_array = [(xmax-xmin)/desired_acc,(ymax-ymin)/desired_acc,(tmax-tmin)/desired_acc]
density = int(max(density_array))
print(' number of new lattice points: %s'%density)
print(' total number of extrapulation points: %s' %(density*density*density))
#generate list of coordinates for each temperature
for i in range(tempsteps):
z = []
for j in range(int(volnum)):
z = np.append(z,(engy_array[j][0]+numatoms*free_array[j][i])) #Add internal energy to each point.
#internal test that they are all the same length
try:
x.shape[0] == y.shape[0] == z.shape[0] == t.shape[0]
except:
print('ERROR: The dimensions of either x,y, or z are unequal.')
print('The dimensions of the arrays are %s %s %s.'%(x.shape[0],y.shape[0],z.shape[0]))
sys.exit()
#find best fit 6th order fit
A = np.c_[x**0*y**0*t**0+1, x**1*y**0*t**0, x**2*y**0*t**0, x**3*y**0*t**0, x**4*y**0*t**0,
x**0*y**1*t**0, x**1*y**1*t**0, x**2*y**1*t**0, x**3*y**1*t**0, x**4*y**1*t**0,
x**0*y**2*t**0, x**1*y**2*t**0, x**2*y**2*t**0, x**3*y**2*t**0, x**4*y**2*t**0,
x**0*y**3*t**0, x**1*y**3*t**0, x**2*y**3*t**0, x**3*y**3*t**0, x**4*y**3*t**0,
x**0*y**4*t**0, x**1*y**4*t**0, x**2*y**4*t**0, x**3*y**4*t**0, x**4*y**4*t**0,
x**0*y**0*t**1, x**1*y**0*t**1, x**2*y**0*t**1, x**3*y**0*t**1, x**4*y**0*t**1,
x**0*y**1*t**1, x**1*y**1*t**1, x**2*y**1*t**1, x**3*y**1*t**1, x**4*y**1*t**1,
x**0*y**2*t**1, x**1*y**2*t**1, x**2*y**2*t**1, x**3*y**2*t**1, x**4*y**2*t**1,
x**0*y**3*t**1, x**1*y**3*t**1, x**2*y**3*t**1, x**3*y**3*t**1, x**4*y**3*t**1,
x**0*y**4*t**1, x**1*y**4*t**1, x**2*y**4*t**1, x**3*y**4*t**1, x**4*y**4*t**1,
x**0*y**0*t**2, x**1*y**0*t**2, x**2*y**0*t**2, x**3*y**0*t**2, x**4*y**0*t**2,
x**0*y**1*t**2, x**1*y**1*t**2, x**2*y**1*t**2, x**3*y**1*t**2, x**4*y**1*t**2,
x**0*y**2*t**2, x**1*y**2*t**2, x**2*y**2*t**2, x**3*y**2*t**2, x**4*y**2*t**2,
x**0*y**3*t**2, x**1*y**3*t**2, x**2*y**3*t**2, x**3*y**3*t**2, x**4*y**3*t**2,
x**0*y**4*t**2, x**1*y**4*t**2, x**2*y**4*t**2, x**3*y**4*t**2, x**4*y**4*t**2,
x**0*y**0*t**3, x**1*y**0*t**3, x**2*y**0*t**3, x**3*y**0*t**3, x**4*y**0*t**3,
x**0*y**1*t**3, x**1*y**1*t**3, x**2*y**1*t**3, x**3*y**1*t**3, x**4*y**1*t**3,
x**0*y**2*t**3, x**1*y**2*t**3, x**2*y**2*t**3, x**3*y**2*t**3, x**4*y**2*t**3,
x**0*y**3*t**3, x**1*y**3*t**3, x**2*y**3*t**3, x**3*y**3*t**3, x**4*y**3*t**3,
x**0*y**4*t**3, x**1*y**4*t**3, x**2*y**4*t**3, x**3*y**4*t**3, x**4*y**4*t**3,
x**0*y**0*t**4, x**1*y**0*t**4, x**2*y**0*t**4, x**3*y**0*t**4, x**4*y**0*t**4,
x**0*y**1*t**4, x**1*y**1*t**4, x**2*y**1*t**4, x**3*y**1*t**4, x**4*y**1*t**4,
x**0*y**2*t**4, x**1*y**2*t**4, x**2*y**2*t**4, x**3*y**2*t**4, x**4*y**2*t**4,
x**0*y**3*t**4, x**1*y**3*t**4, x**2*y**3*t**4, x**3*y**3*t**4, x**4*y**3*t**4,
x**0*y**4*t**4, x**1*y**4*t**4, x**2*y**4*t**4, x**3*y**4*t**4, x**4*y**4*t**4]
#C contains the coefficients to the polynomial we are trying to fit.
# if statement added to handle bad behavior in older versions of numpy
try:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
except FutureWarning:
C,_,_,_ = np.linalg.lstsq(A, z,rcond=-1)
#print the coefficients, C, to a file as a function of temperature
with open('out.coefficients','a') as f:
f.write('%i %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s '\
'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s '\
'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s '\
'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s '\
'%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n'
%(i,C[0],C[1],C[2],C[3],C[4],C[5],C[6],C[7],C[8],C[10],C[11],C[12],C[13],C[14],
C[15],C[16],C[17],C[18],C[19],C[20],C[21],C[22],C[23],C[24],C[25],C[26],C[27],C[28],C[29],
C[30],C[31],C[32],C[33],C[34],C[35],C[36],C[37],C[38],C[39],C[40],C[41],C[42],C[43],C[44],
C[45],C[46],C[47],C[48],C[49],C[50],C[51],C[51],C[52],C[53],C[54],C[55],C[56],C[57],C[58],
C[59],C[60],C[61],C[62],C[63],C[64],C[65],C[66],C[67],C[68],C[69],C[70],C[71],C[72],C[73],
C[74],C[75],C[76],C[77],C[78],C[79],C[80],C[81],C[82],C[83],C[84],C[85],C[86],C[87],C[88],
C[89],C[90],C[91],C[92],C[93],C[94],C[95],C[96],C[97],C[98],C[99],C[100],C[101],C[102],C[103],
C[104],C[105],C[106],C[107],C[108],C[109],C[110],C[111],C[112],C[113],C[114],C[115],C[116],C[117],C[118],
C[119],C[120],C[121],C[122],C[123],C[124]))
#use the BFGS method to determine the point that minimizes the function
tol = 1E-10
if i == 0:
initial_guess = [a0,b0,c0]
else:
initial_guess = [latt_data[1][i-1],latt_data[2][i-1],latt_data[3][i-1]]
if withbounds == True:
bounds = [(xmin,xmax),(ymin,ymax),(tmin,tmax)] #bounds of free energy grid
result = so.minimize(sixthfourhorder_ploy,initial_guess,args=(C),
method='L-BFGS-B',bounds = bounds,tol = tol)
else:
result = so.minimize(sixthfourhorder_ploy,initial_guess,args=(C),
method='BFGS',tol = tol)
#gather results from optimization routine
latt_data[0][i] = Tmin+(Tmax-Tmin)/tempsteps*i
latt_data[1][i] = result.x[0]
latt_data[2][i] = result.x[1]
latt_data[3][i] = result.x[2]
return latt_data,cell_data
def fit_EOS(volnum,num_unique,cell_data,engy_array,free_array,vol_array,withbounds):
"""
Author: Nicholas Pike
Email : [email protected]
Purpose: Fit equation of state using volume data
Return: Arrays of bulk modulus data and cell data
"""
#declare useful information
a0 = cell_data[1]/ang_to_m
b0 = cell_data[2]/ang_to_m
c0 = cell_data[3]/ang_to_m
numatoms = float(cell_data[4])
Tmin = int(cell_data[23])
Tmax = int(cell_data[24])
tempsteps = int(cell_data[25])
#declare arrays
bulkT = np.empty(shape=(8,tempsteps))
print(' 3 - Fitting the equations of state.' )
print(' ---Brief pauses are normal---')
if withbounds == True:
print(' Bounds are being used.')
plsq2 = []
for i in range(tempsteps):
z = []
for j in range(int(volnum)):
z = np.append(z,(engy_array[j][0]+numatoms*free_array[j][i])) #Add internal energy to each point.
#internal test that they are all the same length
try:
vol_array.shape[0] == z.shape[0]
except:
print('ERROR: The dimensions of either volume or z are unequal.')
print('The dimensions of the arrays are %s %s.'%(vol_array.shape[0],z.shape[0]))
sys.exit()
#define an initial guess for the parameters of the Birch_Murnaghan equation
if z[0] > 0:
print('ERROR: Check calculation of free energy or internal energy. Bad value encountered: %s' %z[0])
sys.exit()
E0 = 0 #reference energy (should be negative and in eV)
else:
E0 = z[0] #reference energy (should be negative and in eV)
if i == 0:
B0 = float(cell_data[27]/(10*160.21765)) #guess at bulk modulus
BP = 5.0 #guess at pressure dependence of bulk modulus
V0 = a0*b0*c0 #guess for initial volume (in Å^3)
x0 = np.array([E0,B0,BP,V0],dtype=float)
else:
x0 = plsq2
if withbounds == True:
bounds = ((-1000,0.0,-15,V0*0.6),(0,B0*1.2,15,V0*1.2))
else:
bounds = ((-np.inf,-np.inf,-np.inf,-np.inf),( np.inf,np.inf,np.inf,np.inf))
#determine the least squared fit parameters
try:
plsq,covariance = so.curve_fit(Birch_Murnaghan, vol_array, z, p0=x0, bounds = bounds, sigma=0.5*np.ones(shape=z.shape[0]))
plsq2,covariance = so.curve_fit(Murnaghan, vol_array, z, p0=x0, bounds = bounds, sigma=0.5*np.ones(shape=z.shape[0]))
except RuntimeError:
print('The E vs. V data is rather spread out. Consider a better k-point grid')
plsq,covariance = so.curve_fit(Birch_Murnaghan, vol_array, z, p0=x0, bounds = bounds, sigma=3.0*np.ones(shape=z.shape[0]))
plsq2,covariance = so.curve_fit(Murnaghan, vol_array, z, p0=x0, bounds = bounds, sigma=3.0*np.ones(shape=z.shape[0]))
#store the bulk modulus as a function of temperature
bulkT[0][i] = Tmin+(Tmax-Tmin)/tempsteps*i
bulkT[1][i] = plsq[0] #cohesive energy
bulkT[2][i] = plsq[1]*160.21765 #changes the unit to GPa (bulk modulus)
bulkT[3][i] = plsq[2] #unitless (pressure derivative)
bulkT[4][i] = plsq2[0] #cohesive energy
bulkT[5][i] = plsq2[1]*160.21765 #changes the unit to GPa
bulkT[6][i] = plsq2[2] #unitless (pressure derivative)
return bulkT,cell_data
def find_CTE(volnum,num_unique,cell_data,latt_data,withpoly):
"""
Author: Nicholas Pike
Email : [email protected]
Purpose: Calculate the coefficients of thermal expansion
Return:
"""
#declare useful information
tempsteps = int(cell_data[25])
tmin = int(cell_data[23])
tmax = int(cell_data[24])
tempsteps = int(cell_data[25])
tspacing = (tmax-tmin)/tempsteps
#declare arrays
xdata = latt_data[0][:] #temperature
adata = latt_data[1][:] #a lattice
bdata = latt_data[2][:] #b lattice
cdata = latt_data[3][:] #c lattice
latt_der = np.zeros(shape=(4,tempsteps))
lattdata = np.zeros(shape=(tempsteps,9))
#poly fit ranges
if withpoly[0] == True:
fitlower = float(withpoly[1])
fitupper = float(withpoly[2])
print_poly = withpoly[3]
else:
fitlower = 0.1
fitupper = 2
#note that window must be an odd number!
if int(tempsteps*0.01)%2 == 0: #number is odd
window = int(tempsteps*0.01)+1
else:
window = int(tempsteps*0.01)
with open('data_extraction','r') as datafile:
for line in datafile:
if 'Debye' in line:
l = line.split()
debye = l[1]
#set lower and upper limit to fit
fitrangelow = int(fitlower*float(debye)/tspacing)
fitrangeup = int(fitupper*float(debye)/tspacing)
print(' 4 - Calculate the coefficients of thermal expansion.')
if num_unique == 1:
if withpoly[0] == True:
#fit the extracted data to a polynomial of order 8
pa = np.polyfit(xdata[fitrangelow:fitrangeup],adata[fitrangelow:fitrangeup],8)#produces an array of coefficients, highest to lowest
#produces an equation using the previously calculated coefficients
apoly = np.poly1d(pa)
#get array of values
ahat = apoly(xdata)
if print_poly:
f1= open('out.poly_lattice','w')
for i in range(len(ahat)):
f1.write('%s %s\n' %(xdata[i],ahat[i]))
f1.close()
#take the log of the lattice parameter
logahat = np.zeros(shape=(len(ahat)))
for i in range(len(adata)):
logahat[i] = np.log(ahat[i])
# calculate the derivative of the polynomial
ahatder = np.gradient(logahat,tspacing)
for i in range(int(tempsteps)):
latt_der[0][i] = xdata[i]
latt_der[1][i] = ahatder[i]
lattdata[i][0] = latt_der[1][i]
lattdata[i][4] = latt_der[1][i]
lattdata[i][8] = latt_der[1][i]
elif withpoly[0] == False:
#smooth data with running mean
ahat = running_mean(adata,window)
#take the log of the lattice parameter
for i in range(len(adata)):
ahat[i] = np.log(ahat[i])
# take derivative of ahat using a gradient
dera = np.gradient(ahat,tspacing)
#filter to smooth
for i in range(10):
dera = running_mean(dera,window)
for i in range(int(tempsteps)):
latt_der[0][i] = xdata[i]
latt_der[1][i] = dera[i]
lattdata[i][0] = latt_der[1][i]
lattdata[i][4] = latt_der[1][i]
lattdata[i][8] = latt_der[1][i]
else:
print('Something bad happened in find_CTE. Contact developer.')
sys.exit()
elif num_unique == 2:
if withpoly[0] == True:
#fit the extracted data to a polynomial of order 6
pa = np.polyfit(xdata[fitrangelow:fitrangeup],adata[fitrangelow:fitrangeup],8) #produces an array of coefficients, highest to lowest
pc = np.polyfit(xdata[fitrangelow:fitrangeup],cdata[fitrangelow:fitrangeup],8)
#produces an equation using the previously calculated coefficients
apoly = np.poly1d(pa)
cpoly = np.poly1d(pc)
#get array of values
ahat = apoly(xdata)
chat = cpoly(xdata)
if print_poly:
f1= open('out.poly_lattice','w')
for i in range(len(ahat)):
f1.write('%s %s %s\n' %(xdata[i],ahat[i],chat[i]))
f1.close()
#take the log of the lattice parameter
logahat = np.zeros(shape=(len(ahat)))
logchat = np.zeros(shape=(len(chat)))
for i in range(len(adata)):
logahat[i] = np.log(ahat[i])
logchat[i] = np.log(chat[i])
# calculate the derivative of the polynomial
ahatder = np.gradient(logahat,tspacing)
chatder = np.gradient(logchat,tspacing)
for i in range(int(tempsteps)):
latt_der[0][i] = xdata[i]
latt_der[1][i] = ahatder[i]
latt_der[2][i] = chatder[i]
lattdata[i][0] = latt_der[1][i]
lattdata[i][4] = latt_der[1][i]
lattdata[i][8] = latt_der[2][i]
elif withpoly[0] == False:
#smooth data with running mean
ahat = running_mean(adata,window)
chat = running_mean(cdata,window)
#take the log of the lattice parameter
for i in range(len(adata)):
ahat[i] = np.log(ahat[i])
chat[i] = np.log(chat[i])
# take derivative of ahat using a gradient
dera = np.gradient(ahat,tspacing)
derc = np.gradient(chat,tspacing)
#filter to smooth
for i in range(10):
dera = running_mean(dera,window)
derc = running_mean(derc,window)
for i in range(int(tempsteps)):
latt_der[0][i] = xdata[i]
latt_der[1][i] = dera[i]
latt_der[2][i] = derc[i]
lattdata[i][0] = latt_der[1][i]
lattdata[i][4] = latt_der[1][i]
lattdata[i][8] = latt_der[2][i]
else:
print('Something bad happened in find_CTE. Contact developer.')
sys.exit()
elif num_unique == 3:
if withpoly[0] == True:
#fit the extracted data to a polynomial of order 6
pa = np.polyfit(xdata[fitrangelow:fitrangeup],adata[fitrangelow:fitrangeup],8) #produces an array of coefficients, highest to lowest
pb = np.polyfit(xdata[fitrangelow:fitrangeup],bdata[fitrangelow:fitrangeup],8)
pc = np.polyfit(xdata[fitrangelow:fitrangeup],cdata[fitrangelow:fitrangeup],8)
#produces an equation using the previously calculated coefficients
apoly = np.poly1d(pa)
bpoly = np.poly1d(pb)
cpoly = np.poly1d(pc)
#get array of values
ahat = apoly(xdata)
bhat = bpoly(xdata)
chat = cpoly(xdata)
if print_poly:
f1= open('out.poly_lattice','w')
for i in range(len(ahat)):
f1.write('%s %s %s %s\n' %(xdata[i],ahat[i],bhat[i],chat[i]))
f1.close()
#take the log of the lattice parameter
logahat = np.zeros(shape=(len(ahat)))
logbhat = np.zeros(shape=(len(bhat)))
logchat = np.zeros(shape=(len(chat)))
for i in range(len(adata)):
logahat[i] = np.log(ahat[i])
logbhat[i] = np.log(bhat[i])