/
analysis.py
1488 lines (1047 loc) · 42 KB
/
analysis.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
# -*- coding: utf-8 -*-
#Copyright Aksyonov D.A
from __future__ import division, unicode_literals, absolute_import
import os, copy, shutil, sys
import numpy as np
try:
import scipy
from scipy import interpolate
# from scipy.interpolate import spline
# print (scipy.__version__)
# print (dir(interpolate))
except:
print('analysis.py: scipy is not avail')
try:
# sys.path.append('/home/aksenov/Simulation_wrapper/ase') #path to ase library
from ase.eos import EquationOfState
ase_flag = True
except:
print('ase is not avail; run pip install ase')
ase_flag = False
try:
from pymatgen.analysis.wulff import WulffShape
from pymatgen.analysis.ewald import EwaldSummation
except:
print('pymatgen is not avail; run pip install pymatgen')
from siman import header
from siman.header import printlog, print_and_log, mpl, db
from siman.functions import element_name_inv, invert, get_from_server
from siman.picture_functions import plot_mep, fit_and_plot
from siman.geo import determine_symmetry_positions, local_surrounding, find_moving_atom, image_distance, rms_pos_diff, interpolate
from siman.database import push_figure_to_archive
from siman.small_functions import is_list_like, makedir
from siman.inout import write_xyz, read_xyz, write_occmatrix
from siman.calcul import site_repulsive_e
def set_oxidation_states_guess(st):
# set from guess
pm = st.convert2pymatgen()
pm.add_oxidation_state_by_guess()
st = st.update_from_pymatgen(pm)
# print(pm)
return st
def calc_oxidation_states(cl = None, st = None, silent = 1):
#only use if charges are full charges from bader
if cl:
st = cl.end
ch = cl.charges
# if st:
# ch = st.charges
# print(st.get_elements() )
# print(ch)
z_vals = []
for j, z_val, el in zip(range(st.natom), st.get_elements_zval(), st.get_elements()):
ox = z_val - ch[j]
z_vals.append(ox)
if not silent:
''
print(el, '{:3.1f}'.format(ox))
# print(list(zip(z_vals, self.end.get_elements())))
# print(z_vals)
return z_vals
def determine_barrier(positions = None, energies = None):
"""
The sign of barrier determined by the curvuture at saddle point. Minimum at saddle point corresponds to negative barrier
The saddle point is determined as maximum deviation from energy in initial position
"""
import scipy
if positions is None:
positions = range(len(energies))
if energies is None:
printlog('Error! Please provide at least energies')
spl = scipy.interpolate.PchipInterpolator(positions, energies)
spl_der = spl.derivative()
spl_der2 = spl_der.derivative()
mi = min(positions)
ma = max(positions)
r = spl_der.roots()
# print(r)
r = r[ np.logical_and(mi<r, r<ma) ] # only roots inside the interval are interesting
e_at_roots = spl(r)
if len(e_at_roots) > 0:
# diff_barrier = max( e_at_roots ) # the maximum value
printlog('roots are at ', r, e_at_roots)
#find r for saddle point. the energy at saddle point is most far away from the energy at initial position by definition
de_s = np.abs(e_at_roots-energies[0])
i_r_de_max = np.argmax(de_s)
# print(de_s)
# print(i_r_de_max)
r_de_max = r[i_r_de_max]
e = spl(r_de_max)
curvuture_at_saddle = spl_der2(r_de_max)
sign = - np.sign(curvuture_at_saddle)
if curvuture_at_saddle < 0:
critical_point_type = 'maximum'
elif curvuture_at_saddle > 0:
critical_point_type = 'minimum'
else:
critical_point_type = 'undefined'
# print(type(r_de_max), type(e), critical_point_type)
print('Saddle point at {:.2f} {:.2f} is a local {:}'.format(r_de_max, float(e), critical_point_type) )
else:
print_and_log('Warning! no roots')
# diff_barrier = 0
sign = 1
mine = min(energies)
maxe = max(energies)
de = abs(mine - maxe)
# if de > diff_barrier:
diff_barrier = de * sign
print('Migration barrier is {:.2f}'.format( diff_barrier))
# plt.plot(spl(np.linspace(0, ma, 1000)))
# plt.show()
return diff_barrier
def calc_redox(cl1, cl2, energy_ref = None, value = 0, temp = None, silent = 0, mode = None, scale = 1):
"""
Calculated average redox potential and change of volume
cl1 (Calculation) - structure with higher concentration
cl2 (Calculation) - structure with lower concentration
energy_ref (float) - energy in eV per one alkali ion in anode; default value is for Li; -1.31 eV for Na, -1.02 eV for K
temp(float) - potential at temperature, self.F is expected from phonopy calculations
mode (str) - special
electrostatic_only - use Ewald summation to obtain electrostatic energy
ewald_vasp
scale - experimental
return dic {'redox_pot', 'vol_red', ...}
"""
if cl1 is None or cl2 is None:
printlog('Warning! cl1 or cl2 is none; return')
return
if not hasattr(cl1.end, 'znucl') or not hasattr(cl2.end, 'znucl') :
printlog('Warning! cl1 or cl2 is bad')
return
energy_ref_dict = {3:-1.9, 11:-1.31, 19:-1.02, 37:-0.93}
z_alk_ions = [3, 11, 19, 37]
#normalize numbers of atoms by some element except Li, Na, K
alk1l = []
alk2l = []
# print cl1.end.znucl
for i, z in enumerate(cl1.end.znucl):
# print i, z
if z in z_alk_ions:
alk1l.append(i)
# print 'i_alk is found'
continue
# print i, z
for j, zb in enumerate(cl2.end.znucl):
if zb in z_alk_ions:
# j_alk = j
alk2l.append(j)
continue
if z == zb:
# print "I use ", z, " to normalize"
i_n1 = i
i_n2 = j
n1 = cl1.end.nznucl[i_n1]
n2 = cl2.end.nznucl[i_n2]
# print(n1,n2)
nz1_dict = {}
nz2_dict = {}
n_alk1 = 0
n_alk2 = 0
for z in z_alk_ions:
nz1_dict[z] = 0
nz2_dict[z] = 0
for i in alk1l:
nz1_dict[ cl1.end.znucl[i] ] = cl1.end.nznucl[i]
for i in alk2l:
nz2_dict[ cl2.end.znucl[i] ] = cl2.end.nznucl[i]
for z in z_alk_ions:
mul = (nz1_dict[z] / n1 - nz2_dict[z] / n2)
# print(mul)
if abs(mul) > 0: #only change of concentration of one ion type is allowed; the first found is used
printlog('Change of concentration detected for ', element_name_inv(z))
if not energy_ref: #take energy ref from dict
energy_ref = energy_ref_dict[ z ]
break
# print(energy_ref)
# print(cl1.energy_sigma0, cl2.energy_sigma0, mul)
if mode == 'electrostatic_only':
# st1 = cl1.end.copy()
# st2 = cl2.end.copy()
st1 = cl1.end
st2 = cl2.end
# st1 = set_oxidation_states(st1)
# st2 = set_oxidation_states(st2)
# st1 = st1.remove_atoms(['Ti'])
st1.charges = cl1.charges
st2.charges = cl2.charges
# sys.exit()
stpm1 = st1.convert2pymatgen(chg_type = 'ox')
stpm2 = st2.convert2pymatgen(chg_type = 'ox')
ew1 = EwaldSummation(stpm1)
ew2 = EwaldSummation(stpm2)
e1 = ew1.total_energy
e2 = ew2.total_energy
# print(ew1.get_site_energy(0), ew1.get_site_energy(4), ew2.get_site_energy(9) )
elif mode == 'ewald_vasp':
e1 = cl1.energy.ewald
e2 = cl2.energy.ewald
else:
e1 = cl1.e0
e2 = cl2.e0
# print(e1,e2)
if temp != None:
#temperature corrections
e1 += cl1.F(temp)
e2 += cl2.F(temp)
# print(cl1.F(temp), cl2.F(temp))
# print(e1, cl1.energy_sigma0)
# print(e2, cl2.energy_sigma0)
if abs(mul) > 0:
redox = -( ( e1 / n1 - e2 / n2 ) / mul - energy_ref ) / scale
else:
redox = 0
# print(n1, n2)
dV = cl1.end.vol / n1 - cl2.end.vol / n2
vol_red = dV / (cl1.end.vol/n1) * 100 # %
# final_outstring = ("{:} | {:.2f} eV \n1".format(cl1.id[0]+'.'+cl1.id[1], redox ))
final_outstring = ("{:45} | {:30} | {:10.2f} V | {:10.1f} % | {:6.2f}| {:6.2f}| {:6.0f}| {:6.0f} | {:3.0f}".format(cl1.name,cl2.name, redox, vol_red, cl1.energy_sigma0, cl2.energy_sigma0, cl1.maxforce, cl2.maxforce, value ))
if not silent:
printlog( final_outstring, end = '\n', imp = 'y' )
try:
cl1.set.update()
results_dic = {'is':cl1.id[0], 'redox_pot':redox, 'id_is':cl1.id, 'id_ds':cl2.id,
'kspacing':cl1.set.kspacing, 'time':cl1.time/3600.,
'mdstep':cl1.mdstep, 'ecut':cl1.set.ecut, 'niter':cl1.iterat/cl1.mdstep,
'set_is':cl1.id[1], 'vol_red':vol_red }
except:
results_dic = {'redox_pot':redox, 'vol_red':vol_red}
return results_dic
def voltage_profile(objs, xs = None, invert = 1, xlabel = 'x in K$_{1-x}$TiPO$_4$F',
ax = None, first = None, last = None, fmt = 'r-', label = None, color =None):
"""
objs - dict of objects with concentration of alkali (*invert* = 1) or vacancies (*invert* = 0) as a key
xs - choose specific concentrations
invert - 0 or 1 for concentration axis, see above
ax - matplotlib object, if more profiles on one plot are needed
"""
if xs is None:
xs = sorted(objs.keys())
es2 = []
xs2 = []
x_prev = None
V_prev = None
for i in range(len(xs))[:-1] :
x = xs[i]
# process_cathode_material('KTiPO4F', step = 3, target_x = x, params = params , update = 0 ) #
# es.append(obj.e0)
# objs[xs[i]].res()
# objs[xs[i]].run('1uTU32r', add = 0, up = 'up1')
V = calc_redox(objs[xs[i+1]], objs[xs[i]])['redox_pot']
# print(V)
if V_prev is not None:
es2.append(V_prev)
xs2.append(x)
es2.append(V)
xs2.append(x)
V_prev = V
xs2.append(1)
es2.append(V_prev)
if invert:
es_inv = list(reversed(es2))
else:
es_inv = es2
# xs_inv = list(reversed(xs2))
# print(es_inv)
# print(xs_inv)
fit_and_plot(ax = ax, first = first, last = last,
dE1 = {'x':xs2, 'y':es_inv, 'fmt':fmt, 'label':label, 'color':color, },
ylim = (1.8, 5.7),
legend = 'best', ver=0, alpha = 1,
filename = 'figs/ktp_voltage_curve', fig_format = 'pdf',
ylabel = 'Voltage, V', xlabel = xlabel, linewidth = 2)
return
def matrix_diff(cl1, cl2, energy_ref = 0):
#energy of substitutional impurity
e = cl1.energy_sigma0
v = cl1.end.vol
n_m = cl1.end.nznucl[0]
e_b = cl2.energy_sigma0
n_m_b = cl2.end.nznucl[0]
v_b = cl2.end.vol
print(n_m_b, n_m)
diffE = e - e_b/n_m_b*n_m - energy_ref
return diffE, v - v_b
def form_en(sources, products, norm_el = None):
"""
Calculate formation energy of reaction.
sources, products - list of tuples (x, cl), where x is multiplier and cl is calculation
norm_el - which element to use for normalization
'all' - normalize by total number of atoms
'el' - normalize by this element
int - divide by this number
"""
El = []
Nzl = []
for ls in [sources, products]:
E = 0
Nz = {}
for x, cl in ls:
E += x*cl.e0
for i, z in enumerate(cl.end.znucl):
if z not in Nz:
Nz[z] = 0
Nz[z] += x*cl.end.nznucl[i]
El.append(E)
Nzl.append(Nz)
for z in Nzl[0]:
if abs(Nzl[0][z] - Nzl[1][z]) > 1e-5:
printlog('Error! Number of', invert(z), 'atoms in source and product are different!')
# norm = 1
if 'all' == norm_el:
norm = sum(Nzl[0].values())
elif type(norm_el) == str:
norm = Nzl[0][invert(norm_el)]
elif norm_el != None:
norm = norm_el
else:
norm = 1
# print('Normalizing by ', norm_el, norm, 'atoms')
dE = (El[1]-El[0])/norm
print('dE = {:4.2f} eV'.format(dE))
return dE
def chgsum(cll, el, site, silent = 1):
"""
calculate sum of Bader charges for particular atoms
"""
for cl in cll:
# print(cl.id, end = ' ')
try:
cl.chgsum[(el, site)] = 0
except:
pass
if not hasattr(cl, 'charges') or len(cl.charges) == 0:
cl.get_bader_ACF()
# determine_symmetry_positions(cl.end, el, silent = 0)
# print('')
try:
pos = determine_symmetry_positions(cll[0].end, el, silent = 1)
except:
printlog('chgsum() Warning!', cll[0].id, 'is broken!')
return 0
for p in pos[site]:
''
for cl in cll:
if not hasattr(cl, 'chgsum'):
cl.chgsum = {}
cl.chgsum[(el, site)] = 0
cl.chgsum[(el, site)] += cl.charges[p]
# print('{:5.3f}'.format(cl.charges[p]), end = ' ')
# print('')
if not silent:
print('Sum of charges for ', el+str(site+1), ':')
el_ind = cl.init.znucl.index(invert(el)) # index of element in znucl and zval and nznucl
zval = cl.init.zval[el_ind] # number of electrons in chosen potential
for cl in cll:
cl.chgsum[(el, site)]/=len(pos[site])
chgsum = zval - cl.chgsum[(el, site)]
if cl == cll[0]:
chgsum_ref = chgsum
if not silent:
print('{:5.2f}({:4.2f})'.format(chgsum, chgsum_ref-chgsum), )
if not silent:
print('\n')
# print(cl.charges)
return chgsum
def fit_a(conv, n, description_for_archive, analysis_type, show, push2archive):
"""Fit equation of state for bulk systems.
The following equation is used::
sjeos (default)
A third order inverse polynomial fit 10.1103/PhysRevB.67.026103
2 3 -1/3
E(V) = c + c t + c t + c t , t = V
0 1 2 3
taylor
A third order Taylor series expansion about the minimum volume
murnaghan
PRB 28, 5480 (1983)
birch
Intermetallic compounds: Principles and Practice,
Vol I: Principles. pages 195-210
birchmurnaghan
PRB 70, 224107
pouriertarantola
PRB 70, 224107
vinet
PRB 70, 224107
antonschmidt
Intermetallics 11, 23-32 (2003)
p3
A third order polynomial fit
Use::
eos = EquationOfState(volumes, energies, eos='sjeos')
v0, e0, B = eos.fit()
eos.plot()
"""
# e, v, emin, vmin = plot_conv( conv[n], calc, "fit_gb_volume2")
alist = []
vlist = []
etotlist = []
magn1 = []
magn2 = []
alphas= []
for id in conv[n]:
cl = db[id]
st = cl.end
alist.append(cl.end.rprimd[0][0])
etotlist.append(cl.energy_sigma0)
vlist.append(cl.end.vol)
magn1.append(cl.magn1)
magn2.append(cl.magn2)
alpha, beta, gamma = st.get_angles()
alphas.append(alpha)
print('alpha, energy: {:4.2f}, {:6.3f}'.format(alpha, cl.energy_sigma0))
fit_and_plot(U1 = (alphas, etotlist, 'o-r'),
image_name = 'figs/angle', ylabel = 'Total energy, eV', xlabel = 'Angle, deg', xlim = (89, 92.6))
if ase_flag:
if 'angle' in analysis_type:
eos = EquationOfState(alphas, etotlist, eos = 'sjeos')
else:
eos = EquationOfState(vlist, etotlist, eos = 'sjeos')
# import inspect
# print (inspect.getfile(EquationOfState))
v0, e0, B = eos.fit()
#print "c = ", clist[2]
printlog( '''
v0 = {0} A^3
a0 = {1} A
E0 = {2} eV
B = {3} eV/A^3'''.format(v0, v0**(1./3), e0, B), imp = 'Y' )
savedpath = 'figs/'+cl.name+'.png'
makedir(savedpath)
cl.B = B*160.218
# plt.close()
# plt.clf()
# plt.close('all')
if 'fit' in show:
mpl.rcParams.update({'font.size': 14})
eos.plot(savedpath, show = True)
printlog('fit results are saved in ',savedpath, imp = 'y')
else:
printlog('To use fitting install ase: pip install ase')
# plt.clf()
if push2archive:
push_figure_to_archive(local_figure_path = savedpath, caption = description_for_archive)
return
def around_alkali(st, nn, alkali_ion_number):
#return numbers and distances to
#alkali_ion_number - number of interesting cation from 0
#nn - number of neighbours
n_neighbours = nn
alkali_ions = []
dist = []
ifmaglist = st.get_maglist()
for i, typ, x in zip(range(st.natom), st.typat, st.xcart):
z = st.znucl[typ-1]
if z in header.ALKALI_ION_ELEMENTS:
alkali_ions.append([i, z, x])
if len(alkali_ions) > 0:
if alkali_ion_number:
kk = alkali_ion_number
chosen_ion = (kk, st.znucl[st.typat[kk]-1], st.xcart[kk])
else:
chosen_ion = alkali_ions[0] #just the first one is used
# alkali_ions[min(alkali_ions)]
sur = local_surrounding(chosen_ion[2], st, n_neighbours = n_neighbours, control = 'atoms',
periodic = True, only_elements = header.TRANSITION_ELEMENTS)
# print (sur)
dist = np.array(sur[3]).round(2)
numb = np.array(sur[2])
else:
numb = ifmaglist # if no alk ions show for all mag atoms
chosen_ion = None
return numb, dist, chosen_ion
def find_polaron(st, i_alk_ion, out_prec = 1):
"""
Find TM atoms with outlying magnetic moments, which
is a good indication of being a small polaron
Can be problems with charged-ordered materials
INPUT:
i_alk_ion - number of ion from 0 to calculate distances to transition metals
out_prec (int) - precision of magmom output
RETURN:
pol (dict of int) - numbers of atoms, where polarons are detected for each TM element
magmom_tm (list of float) - just magmom for TM
TODO:
1. Add analysis of bond lengths to distinguish small polarons
Janh-Teller
2. Add treatment of charged-ordered
"""
def zscore(s):
# print(np.std(s))
return (s - np.mean(s)) / np.std(s)
magmom = np.array(st.magmom)
if len(magmom) == 0 :
printlog('Warning! magmom is empty')
_, mag_numbers = st.get_maglist()
pol = {}
# for z in mag_numbers:
# pos = determine_symmetry_positions(st, invert(z))
# sys.exit()
magmom_tm = None
for z in mag_numbers:
printlog('Looking at polarons on transition atoms: ',invert(z) )
numbs = np.array(mag_numbers[z])
# print(numbs)
# print(magmom)
magmom_tm = magmom[numbs]
dev = np.absolute( zscore(magmom_tm) )
# print(magmom_tm)
# print(list(zip(magmom_tm, dev.round(1))))
# p = np.where(dev>2)[0] # 2 standard deviations
# print(dev>2)
# print (type(numbs))
nstd = 1.5
# nstd = 4
i_pols = numbs[dev>nstd]
if len(i_pols) > 0:
x1 = st.xcart[i_alk_ion]
d_to_pols = []
for j in i_pols:
x2 = st.xcart[j]
d, _ = st.image_distance(x1, x2, st.rprimd)
d_to_pols.append(d)
print('polarons are detected on atoms', [i for i in i_pols], 'with magnetic moments:', magmom[i_pols], 'and distances: '+', '.join('{:2.2f}'.format(d) for d in d_to_pols), 'A' )
print('mag moments on trans. atoms:', magmom_tm.round(out_prec))
pol[z] = i_pols
else:
print('no polarons is detected with nstd', nstd)
print('mag moments on trans. atoms:', magmom_tm.round(out_prec))
# print(' deviations :', dev.round(1))
pol[z] = None
return pol, magmom_tm
def neb_analysis(cl, show, up = None, push2archive = None, old_behaviour = None, results_dic = None, fitplot_args = None, style_dic = None, params = None):
"""
Analyse traectories and polarons
params
mep_shift_vector
"""
def determing_rms_for_surrounding_atoms(sts):
# change of rms on each step compared to first structure
#here first and last structures should correspond to first and last images
st1 = sts[0]
st_interp = interpolate(sts[0], sts[-1], 1)[0]
rms_list = []
for st in sts:
rms = rms_pos_diff(st_interp, st)
rms_list.append(rms)
print('rms is {:.3f}'.format(rms) )
print('d rms is {:.3f}'.format(abs(rms_list[3]-rms_list[0])) )
rms_change = abs(min(rms_list) - max(rms_list))
return rms_change
def determing_born_barrier(sts):
#here first and last structures should correspond to first and last images
local_born_e = []
i = find_moving_atom(sts[0], sts[-1])
for st in sts:
local_born_e.append( site_repulsive_e(st, i) )
# import matplotlib.pyplot as plt
# plt.plot(local_born_e)
# plt.show()
return abs(min(local_born_e) - max(local_born_e))
if params is None:
params = {}
if results_dic is None:
results_dic = {}
calc = header.calc
path2mep_s = cl.project_path_cluster+'/'+cl.dir+'/mep.eps'
itise = cl.id[0]+'.'+cl.id[1]
# print(cl.ldauu)
# sys.exit()
name_without_ext = 'mep.'+itise+'.U'+str(max(cl.ldauu))
path2mep_l = cl.dir+name_without_ext+'.eps'
# print(path2mep_l)
if not os.path.exists(path2mep_l) or '2' in up:
''
get_from_server(files = path2mep_s, to_file = path2mep_l, addr = cl.cluster_address, )
movie_to = cl.dir+'/movie.xyz'
get_from_server(files = cl.project_path_cluster+'/'+cl.dir+'/movie.xyz', to_file = movie_to, addr = cl.cluster_address, )
if os.path.exists(movie_to):
makedir('figs/'+name_without_ext+'.xyz')
shutil.copyfile(movie_to, 'figs/'+name_without_ext+'.xyz')
# trying to get one image closest to the saddle point
if old_behaviour and cl.version == 2: #old behaviour, now created automatically in add callc
im = cl.set.vasp_params['IMAGES']
# if im % 2 > 0: #odd
# i = im//2 + 1
# else:
# i = im/2
# if choose_image:
# i = choose_image
for i in range(im):
i+=1
cl_i = copy.deepcopy(cl)
cl_i.version+=i
cl_i.id = (cl.id[0], cl.id[1], cl_i.version)
cl_i.name = str(cl_i.id[0])+'.'+str(cl_i.id[1])+'.'+str(cl_i.id[2])
# print cl_i.name
cl_i.path["output"] = cl_i.dir+'0'+str(i)+"/OUTCAR"
# for i in range():
cl_i.associated_outcars = [ aso[2:] for aso in cl_i.associated_outcars ]
# print cl_i.path["output"]
cl_i.state = '2. Ready to read outcar'
# if not os.path.exists(cl_i.path["output"]):
# load = 'o'
outst2 = ("%s"%cl_i.name).ljust(name_field_length)
if readfiles:
print(outst2+'|'+cl_i.read_results(loadflag, show = show, choose_outcar = choose_outcar) )
else:
print_and_log(outst2+' | File was not read')
if cl_i.id in calc: #move creation of calcs with images to add_neb
''
# print_and_log('Please test code below this message to save prev calcs')
# if cl_i != calc[cl_i.id]
# if hasattr(calc[cl_i.id], 'prev') and calc[cl_i.id].prev:
# prevlist = calc[cl_i.id].prev
# else:
# prevlist = [calc[cl_i.id]]
# cl_i.prev = prevlist
# calc[cl_i.id] = cl_i
else:
calc[cl_i.id] = cl_i
# print path2mep_l
if 0:
if os.path.exists(path2mep_l):
# get_from_server(file = path2mep_s, to = path2mep_l, addr = cluster_address)
runBash('evince '+path2mep_l)
else:
a = glob.glob(cl.dir+'*mep*')
if a:
runBash('evince '+a[0])
cl1 = calc[cl.id[0], cl.id[1], 1]
cl2 = calc[cl.id[0], cl.id[1], 2]
atom_num = find_moving_atom(cl1.end, cl2.end)
# cl1.poscar()
# cl2.poscar()
# print('atom_num',atom_num)
# sys.exit()
#prepare lists
ni = cl.set.vasp_params['IMAGES']
vlist = [1]+list(range(3, ni+3) )+[2]
# print( vlist)
mep_energies = []
atom_pos = []
pols = []
sts = []
sts_loc = []
dAO2 = [] # A-(O,F) distance for each image
dAO4 = [] # A-(O,F) distance for each image
dAO6 = []
dAO6harm = []
dAO6dev = []
for v in vlist:
cli = calc[cl.id[0], cl.id[1], v]
# if v == 1:
# cli = db['NaVP2O7_a.su.s101015v100.n5Na1v1ms.ifn.1mls.1']
# print(cl.id[0], cl.id[1], v, cli.state)
if '4' not in cli.state and 'un' not in up:
printlog('Attention! res_loop(): analys_type == neb, Calc',cli.id,'is not finished; return')
return {}, []
# print cli.id
# cli.end = return_to_cell(cli.end)
# mep_energies.append( min(cli.list_e_sigma0) ) #use minimum energy - not very good, sometimes unconverged energy could be lower!
e0 = cli.energy_sigma0
if params and params.get('neb_penult_e'): # allows to take e from the previous relaxation step in case the calculation was aborted
e0 = cli.list_e_sigma0[-2]
mep_energies.append( e0 ) #use last energy
atom_pos.append( cli.end.xcart[atom_num] )
# Find polaron positions
if 'polaron' in show: # if 1 cause error for nomag calc
pol, mag = find_polaron(cli.end, atom_num)
if pol:
for key in pol:
if np.any(pol[key]):
for n in pol[key]:
if n not in pols:
pols.append(n)
else:
''
# print('Mag_moments on trans,', mag.round(1))
if 0 or 'neb_geo' in show:
#visualization of path
# print(atom_num)
st = copy.deepcopy(cli.end)
# print('moving_atom', st.xcart[atom_num])
info = st.nn(atom_num, 15, from_one = False, silent = 1)
st.moving_atom_i = atom_num
st_loc = info['st']
# print(st_loc.xcart)
# st_loc = st_loc.shift
if v == vlist[0]:
st1 = copy.deepcopy(st)
vec = st.center_on(atom_num)
# vec = np.asarray([0.,0.,0.])
if params is not None and 'mep_shift_vector' in params: