-
Notifications
You must be signed in to change notification settings - Fork 12
/
geo.py
1558 lines (1062 loc) · 46.3 KB
/
geo.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
import sys, copy, itertools, math
from operator import itemgetter
from tabulate import tabulate
import numpy as np
import header
from header import printlog
from small_functions import red_prec
# from impurity import find_pores
# sys.path.append('/home/aksenov/Simulation_wrapper/')
# sys.path.append('/home/aksenov/Simulation_wrapper/savelyev')
def image_distance(x1, x2, r, order = 1, sort_flag = True, return_n_distances = False):
"""
Calculate smallest distance and the next smallest distance between two atoms
correctly treating periodic boundary conditions and oblique cells.
x1, x2 - vector[3] xcart coordinates of two atoms
r - rprimd of cell
order - the order of periodic images which are accounted in the calcualtion of distances between atoms.
for cubic cells, order = 1 always provide correct result.
For highly oblique cell you should test and find the needed value of 'order' after which results are the same.
sort_flag (bool) - use False if you do not need sorting of distances
return_n_distances(bool) - returns required number of smallest distances, depending on order
return d1, d2 - the smallest and next smallest distances between atoms
"""
d = [] # list of distances between 1st atom and images of 2nd atom
for i in range(-order, order+1):
for j in range(-order, order+1):
for k in range(-order, order+1):
x2i = x2 + (r[0] * i + r[1] * j + r[2] * k) #determine coordinates of image of atom 2 in corresponding image cells
d.append( np.linalg.norm(x1 - x2i) )
if sort_flag:
d.sort()
#print d
# assert d[0] == min(d)
if return_n_distances:
return d[0:return_n_distances]
else:
return d[0], d[1] # old behaviour
def scale_cell_uniformly(st, scale_region = (-4,4), n_scale_images = 7, parent_calc_name = None, ):
"""
Scale uniformly rprimd and xcart of structure() object *st* from *scale_region[0]* to *scale_region[1]* (%) using *n_scale_images* images.
*parent_calc_name* is added to st.des
Return:
list of scaled Structure() objects
TODO: Take care of vol, recip and so on - the best is to create some method st.actual() that update all information
"""
# print scale_region
scales = np.linspace(scale_region[0], scale_region[1], n_scale_images)
printlog('Scales are', scales, imp = 'y')
# print scales
scaled_sts = []
for j, s in enumerate(scales):
st_s = copy.deepcopy(st)
for i in (0,1,2):
st_s.rprimd[i] *= (1 + s/100.)
# print st_s.rprimd
st_s.xred2xcart()
st_s.des = 'obtained from '+str(parent_calc_name)+' by uniform scaling by '+str(s)+' %'
st_s.name = str(j+1)
scaled_sts.append(st_s)
# print st_s.rprimd
# plt.plot([np.linalg.norm(st.rprimd) for st in scaled_sts])
# plt.show()
return scaled_sts
def scale_cell_by_matrix(st, scale_region = (-4,4), n_scale_images = 7, parent_calc_name = None, mul_matrix = None ):
"""
Scale rprimd and xcart of structure() object *st* from *scale_region[0]* to *scale_region[1]* (%) using *n_scale_images* images
and mul_matrix.
*parent_calc_name* is added to st.des
Return:
list of scaled Structure() objects
TODO: Take care of vol, recip and so on - the best is to create some method st.actual() that update all information
"""
scales = np.linspace(scale_region[0], scale_region[1], n_scale_images)
printlog('Scales are', scales, imp = 'y')
# print(np.asarray(st.rprimd))
scaled_sts = []
for j, s in enumerate(scales):
st_s = copy.deepcopy(st)
# print(s)
mul_matrix_f = s*(np.asarray(mul_matrix)-np.identity(3))+np.identity(3)
st_s.rprimd = np.dot(mul_matrix_f, st_s.rprimd)
# st_s.rprimd = np.dot(s/100*np.asarray(mul_matrix)+np.identity(3), st_s.rprimd)
print(mul_matrix_f)
print(np.asarray(st_s.rprimd))
alpha, beta, gamma = st_s.get_angles()
print(alpha, beta, gamma)
st_s.xred2xcart()
st_s.des = 'obtained from '+str(parent_calc_name)+' by scaling by '+str(s)+' % '+str(mul_matrix)
st_s.name = str(j+1)
scaled_sts.append(st_s)
# print st_s.rprimd
# plt.plot([np.linalg.norm(st.rprimd) for st in scaled_sts])
# plt.show()
# sys.exit()
return scaled_sts
def find_moving_atom(st1, st2):
"""
find moving atom
The cells should have the same rprimd!
return number of atom which moves between two cell
"""
for r1, r2 in zip(st1.rprimd, st2.rprimd):
if np.linalg.norm(r1-r2)>0.001:
printlog('Attention! find_moving_atom(): st1 and st2 have different rprimd')
st1 = st1.return_atoms_to_cell()
st2 = st2.return_atoms_to_cell()
# diffv = np.array(st1.xcart) - np.array(st2.xcart)
# diffn = np.linalg.norm(diffv, axis = 1)
diffn = []
for x1, x2 in zip(st1.xcart, st2.xcart):
d1, d2 = image_distance(x1, x2, st1.rprimd)
diffn.append(d1)
# print('max', max(diffn))
return np.argmax(diffn) # number of atom moving along the path
def calc_recip_vectors(rprimd):
#Determine reciprocal vectors
#physics" definition
recip = []
vol = np.dot( rprimd[0], np.cross(rprimd[1], rprimd[2]) ); #volume
#print vol
recip.append( np.cross( rprimd[1], rprimd[2] ) )
recip.append( np.cross( rprimd[2], rprimd[0] ) )
recip.append( np.cross( rprimd[0], rprimd[1] ) )
for i in 0,1,2:
recip[i] = recip[i] * 2 * math.pi / vol;
return recip
def calc_kspacings(ngkpt, rprimd):
"""Calculate kspacing from ngkpt and rprimd (A)
ngkpt (list of int) - k-point mesh
"""
kspacing = []
recip = calc_recip_vectors(rprimd)
for i in 0, 1, 2:
a = np.linalg.norm( recip[i] ) / ngkpt[i]
kspacing.append(red_prec(a))
return kspacing
def xcart2xred(xcart, rprimd):
"""Convert from cartesian coordinates xcart to
dimensionless reduced coordinates
Input: xcart - list of numpy arrays, rprimd - list of numpy arrays
Output: xred - list of numpy arrays"""
xred = []
gprimd = np.asarray( np.matrix(rprimd).I.T ) #Transpose of the inverse matrix of rprimd
#print gprimd
for xc in xcart:
xred.append( np.dot( gprimd , xc) ) #dot product
#print xred
return xred
def xred2xcart(xred, rprimd):
"""Convert from dimensionless reduced coordinates to
cartesian coordinates xcart;
Input: xred - list of numpy arrays, rprimd - list of numpy arrays
Output: xcart - list of numpy arrays"""
xcart = []
#print "rprimd ", rprimd
for xr in xred:
#for j in 0,1,2:
# print xr[0] * rprimd[0][j] + xr[1] * rprimd[1][j] + xr[2] * rprimd[2][j],
#print ""
#print np.dot( xr, rprimd)
xcart.append( np.dot( xr, rprimd) ) #dot product
#print xred
return xcart
def replic(structure, mul = (1,1,1), inv = 1, only_atoms = None, cut_one_cell = None, include_boundary = (1,1) ):
"""
Replicate structure() according to: mul[i]*rprimd[i]
Input:
structure - structure() type
mul[] - is tuple of three integer numbers
Use from structure:
xcart, typat, rprimd, natom, xred
inv - 1 or -1 allows to replicate in different directions
inv = 0 - cell is replicated in both directions by mul[i]; 2 still gives -1 0 1 but 3 gives -2 -1 0 1 2; for 'only_matrix' may work not correctly
only_atoms - allows to replicate only specific atoms; now
'only_matrix'
cut_one_cell - allows to cut only one cell with replicated edge atoms
include_boundary (A) - the width of region to include additional edge atoms (bottom, up)
Return:
replicated structure
"""
st = copy.deepcopy(structure)
# print 'Structure has before replication', st.natom,'atoms'
if hasattr(st, 'init_numbers') and st.init_numbers:
numbers = st.init_numbers
else:
numbers = range(st.natom)
#determine maximum and minimum values before replication
xmax = [-1000000]*3
xmin = [+1000000]*3
for x in st.xcart:
for j in 0,1,2:
if xmax[j] < x[j]: xmax[j] = x[j]
if xmin[j] > x[j]: xmin[j] = x[j]
# print 'xmax, xmin', xmax, xmin
inv_loc = inv
for i in 0, 1, 2:
axis_mul = range(mul[i])
if inv == 0: # does not work propely; mul below is also should be accounted
axis_mul = range(-mul[i]+1, mul[i])
print_and_log('axis_mul = ', axis_mul)
inv_loc = 1
if only_atoms == 'only_matrix':
st.xcart += [ x + inv_loc*k*st.rprimd[i] for x, t in zip(st.xcart[:], st.typat[:]) for k in axis_mul[1:] if t == 1] # fill by axis i by blocks
st.typat += [ t for t in st.typat[:] for k in axis_mul[1:] if t == 1]
st.magmom += [ t for t in st.magmom[:] for k in axis_mul[1:] if t == 1]
else:
st.xcart = [ x + inv_loc*k*st.rprimd[i] for x in st.xcart[:] for k in axis_mul ] # fill by axis i by blocks
st.typat = [ t for t in st.typat[:] for k in axis_mul ]
st.magmom = [ t for t in st.magmom[:] for k in axis_mul ]
numbers = [n for n in numbers[:] for k in axis_mul]
# print numbers
# assert len(st.xcart) == abs(st.natom * reduce(lambda x, y: x*y, mul) )
# print 'before', st.rprimd[i]
if cut_one_cell:
pass
else:
for i in 0, 1, 2:
if inv == 0:
k = 2 * mul[i] - 1
else:
k = mul[i]
st.rprimd[i] = st.rprimd[i] * k
st.init_numbers = numbers
# print st.init_numbers
# print 'after', st.rprimd[i]
# print len(st.xcart)
# print st.natom * reduce(lambda x, y: x*y, mul)
#print st.xcart,
st.xred = xcart2xred(st.xcart, st.rprimd)
if cut_one_cell:
new_xred = []
new_xcart = []
new_typat = []
new_mgmom = []
precb = include_boundary[0]#/max(st.rprimd[2])
precu = include_boundary[1]#/max(st.rprimd[2])
bob = 0 - precb; upb = 1. + precu;
# print bob, upb
n = 0
# print st.xred
for t, xr, m in zip(st.typat, st.xcart, st.magmom):
for j in 0,1,2:
if (xr[j] < xmin[j] - precb) or (xr[j] > xmax[j] + precu): break
else:
new_xcart.append(xr)
new_typat.append(t)
new_magmom.append(m)
st.typat = new_typat
st.xcart = new_xcart
st.magmom = new_magmom
print_and_log('After removing, cell has ', len(st.xred) )
# print st.xred
# st.xcart = xred2xcart(st.xred, st.rprimd)
st.xred = xcart2xred(st.xcart, st.rprimd)
st.get_nznucl()
st.natom = len(st.xcart)
# print 'Structure is replicated; now', st.natom,'atoms'
return st
def local_surrounding(x_central, st, n_neighbours, control = 'sum', periodic = False, only_elements = None, only_numbers = None, round_flag = 1):
"""
Return list of distances to n closest atoms around central atom. (By defauld sum of distances)
Input:
- x_central - cartesian coordinates of central atom; vector
- st - structure with xcart list of coordinates of all atoms in system
- n_neighbours - number of needed closest neighbours
- control - type of output;
sum - sum of distances,
av - average distance,
avsq - average squared dist
'mavm': #min, av, max, av excluding min and max
av_dev - return (average deviation, maximum deviation) from average distance in mA.
list - list of distances;
atoms - coordinates of neighbours
- periodic - if True, then cell is additionaly replicated; needed for small cells
Only for control = atoms
- *only_elements* - list of z of elements to which only the distances are needed;
- only_numbers (list of int) - calc dist only to this atoms
round_flag (bool) - if 1 than reduce distance prec to 2 points
#TODO:
the periodic boundary conditions realized very stupid by replicating the cell!
"""
# round_orig = round
if not round_flag:
# overwrite round function with wrapper that do nothing
def my_round(a, b):
return a
else:
my_round = round
def av_dev():
nonlocal n_neighbours
n_neighbours = float(n_neighbours)
dav = sum(dlistnn)/n_neighbours
av_dev = sum( [abs(d-dav) for d in dlistnn] ) / n_neighbours
max_dev = max([abs(d-dav) for d in dlistnn])
return my_round(av_dev*1000, 0), my_round(max_dev*1000, 0)
st_original = copy.deepcopy(st)
st.init_numbers = None
if periodic:
st = replic(st, mul = (2,2,2), inv = 1 ) # to be sure that impurity is surrounded by atoms
st = replic(st, mul = (2,2,2), inv = -1 )
xcart = st.xcart
typat = st.typat
natom = st.natom
# print x_central
#print len(xcart)
if only_elements:
only_elements = list(set(only_elements))
# print(only_elements)
# sys.exit()
zlist = [int(st.znucl[t-1]) for t in st.typat]
dlist_unsort = [np.linalg.norm(x_central - x) for x in xcart ]# if all (x != x_central)] # list of all distances
if only_elements:
dlist = [np.linalg.norm(x_central - x) for x, z in zip(xcart, zlist) if z in only_elements]
else:
dlist = copy.deepcopy(dlist_unsort)
dlist.sort()
# print('local_surrounding(): dlist', dlist)
if len(dlist) > 0 and abs(dlist[0]) < 0.01:
dlistnn = dlist[1:n_neighbours+1] #without first impurity which is x_central
else:
dlistnn = dlist[:n_neighbours]
# print('dlistnn', dlistnn)
# os._exit(1)
if control == 'list':
output = dlistnn
elif control == 'sum':
output = my_round(sum(dlistnn), 2)
elif control == 'av':
n_neighbours = float(n_neighbours)
dav = sum(dlistnn)/n_neighbours
output = my_round(dav, 2)
elif control == 'avsq':
n_neighbours = float(n_neighbours)
# print(dlistnn)
davsq = sum([d*d for d in dlistnn])/n_neighbours
davsq = davsq**(0.5)
output = my_round(davsq, 2)
elif control == 'mavm': #min, av, max
dsort = sorted(dlistnn)
if n_neighbours > 2:
output = (my_round(dsort[0], 2), sum(dsort[1:-1])/(n_neighbours-2), my_round(dsort[-1], 2) ) #min, av excluding min and max, max
else:
output = (my_round(dsort[0], 2), 0, my_round(dsort[-1], 2) ) #min, av excluding min and max, max
elif control == 'av_dev':
output = av_dev()
elif control == 'sum_av_dev':
output = (my_round(sum(dlistnn), 2), av_dev())
elif control == 'atoms':
# print dlist_unsort
if hasattr(st, 'init_numbers') and st.init_numbers:
numbers = st.init_numbers
else:
numbers = range(natom)
temp = list(zip(dlist_unsort, xcart, typat, numbers, zlist) )
temp.sort(key = itemgetter(0))
if only_elements:
centr_type = temp[0][4]
if centr_type in only_elements:
first = []
else:
first = temp[0:1]
temp = first+[t for t in temp if t[4] in only_elements] #including central; included ionce even if only elements are and central are the same
if only_numbers:
temp = temp[0:1]+[t for t in temp if t[3] in only_numbers]
temp2 = list( zip(*temp) )
dlist = temp2[0][:n_neighbours+1]
xcart_local = temp2[1][:n_neighbours+1]
typat_local = temp2[2][:n_neighbours+1]
numbers = temp2[3][:n_neighbours+1]
# print temp2[0][:n_neighbours]
# print xcart_local[:n_neighbours]
#check if atoms in output are from neighboring cells
if 0:
xred_local = xcart2xred(xcart_local, st_original.rprimd)
# print 'xred_local', xred_local
for x_l in xred_local:
for i, x in enumerate(x_l):
if x > 1:
x_l[i]-=1
# print 'returning to prim cell', x,x_l[i]
if x < 0:
x_l[i]+=1
# print 'returning to prim cell', x,x_l[i]
xcart_local = xred2xcart(xred_local, st_original.rprimd)
# print 'Warning! local_surrounding() can return several atoms in one position due to incomplete PBC implementation; Improve please\n'
output = (xcart_local, typat_local, numbers, dlist )
return output
def local_surrounding2(x_central, st, n_neighbours, control = 'sum', periodic = False, only_elements = None, only_numbers = None, round_flag = 1):
"""
!!! Attempt to improve speed of periodic conditions!
#control = 'atoms' could work wrong!!! check
Return list of distances to n closest atoms around central atom. (By defauld sum of distances)
Input:
- x_central - cartesian coordinates of central atom; vector
- st - structure with xcart list of coordinates of all atoms in system
- n_neighbours - number of needed closest neighbours
- control - type of output;
sum - sum of distances,
av - average distance,
avsq - average squared dist
'mavm': #min, av, max, av excluding min and max
av_dev - return (average deviation, maximum deviation) from average distance in mA.
list - list of distances;
atoms - coordinates of neighbours
- periodic - if True, then cell is additionaly replicated; needed for small cells
Only for control = atoms
- *only_elements* - list of z of elements to which only the distances are needed;
- only_numbers (list of int) - calc dist only to this atoms
round_flag (bool) - if 1 than reduce distance prec to 2 points
#TODO:
the periodic boundary conditions realized very stupid by replicating the cell!
"""
# round_orig = round
if not round_flag:
# overwrite round function with wrapper that do nothing
def my_round(a, b):
return a
else:
my_round = round
def av_dev():
nonlocal n_neighbours
n_neighbours = float(n_neighbours)
dav = sum(dlistnn)/n_neighbours
av_dev = sum( [abs(d-dav) for d in dlistnn] ) / n_neighbours
max_dev = max([abs(d-dav) for d in dlistnn])
return my_round(av_dev*1000, 0), my_round(max_dev*1000, 0)
st_original = copy.deepcopy(st)
st.init_numbers = None
if periodic:
''
# not needed anymore, since image_distance is used,
# however for 'atoms' regime more actions can be needed
# st = replic(st, mul = (2,2,2), inv = 1 ) # to be sure that impurity is surrounded by atoms
# st = replic(st, mul = (2,2,2), inv = -1 )
xcart = st.xcart
typat = st.typat
natom = st.natom
# print x_central
#print len(xcart)
if only_elements:
only_elements = list(set(only_elements))
# print(only_elements)
# sys.exit()
zlist = [int(st.znucl[t-1]) for t in st.typat]
dlist_unsort = [image_distance(x_central, x, st.rprimd)[0] for x in xcart ]# if all (x != x_central)] # list of all distances
if only_elements:
dlist = [image_distance(x_central, x, st.rprimd)[0] for x, z in zip(xcart, zlist) if z in only_elements]
else:
dlist = copy.deepcopy(dlist_unsort)
dlist.sort()
# print('local_surrounding(): dlist', dlist)
if len(dlist) > 0 and abs(dlist[0]) < 0.01:
dlistnn = dlist[1:n_neighbours+1] #without first impurity which is x_central
else:
dlistnn = dlist[:n_neighbours]
# print('dlistnn', dlistnn)
# os._exit(1)
if control == 'list':
output = dlistnn
elif control == 'sum':
output = my_round(sum(dlistnn), 2)
elif control == 'av':
n_neighbours = float(n_neighbours)
dav = sum(dlistnn)/n_neighbours
output = my_round(dav, 2)
elif control == 'avsq':
n_neighbours = float(n_neighbours)
# print(dlistnn)
davsq = sum([d*d for d in dlistnn])/n_neighbours
davsq = davsq**(0.5)
output = my_round(davsq, 2)
elif control == 'mavm': #min, av, max
dsort = sorted(dlistnn)
if n_neighbours > 2:
output = (my_round(dsort[0], 2), sum(dsort[1:-1])/(n_neighbours-2), my_round(dsort[-1], 2) ) #min, av excluding min and max, max
else:
output = (my_round(dsort[0], 2), 0, my_round(dsort[-1], 2) ) #min, av excluding min and max, max
elif control == 'av_dev':
output = av_dev()
elif control == 'sum_av_dev':
output = (my_round(sum(dlistnn), 2), av_dev())
elif control == 'atoms':
# print dlist_unsort
if hasattr(st, 'init_numbers') and st.init_numbers:
numbers = st.init_numbers
else:
numbers = range(natom)
temp = list(zip(dlist_unsort, xcart, typat, numbers, zlist) )
temp.sort(key = itemgetter(0))
if only_elements:
centr_type = temp[0][4]
if centr_type in only_elements:
first = []
else:
first = temp[0:1]
temp = first+[t for t in temp if t[4] in only_elements] #including central; included ionce even if only elements are and central are the same
if only_numbers:
temp = temp[0:1]+[t for t in temp if t[3] in only_numbers]
temp2 = list( zip(*temp) )
dlist = temp2[0][:n_neighbours+1]
xcart_local = temp2[1][:n_neighbours+1]
typat_local = temp2[2][:n_neighbours+1]
numbers = temp2[3][:n_neighbours+1]
# print temp2[0][:n_neighbours]
# print xcart_local[:n_neighbours]
#check if atoms in output are from neighboring cells
if 0:
xred_local = xcart2xred(xcart_local, st_original.rprimd)
# print 'xred_local', xred_local
for x_l in xred_local:
for i, x in enumerate(x_l):
if x > 1:
x_l[i]-=1
# print 'returning to prim cell', x,x_l[i]
if x < 0:
x_l[i]+=1
# print 'returning to prim cell', x,x_l[i]
xcart_local = xred2xcart(xred_local, st_original.rprimd)
# print 'Warning! local_surrounding() can return several atoms in one position due to incomplete PBC implementation; Improve please\n'
output = (xcart_local, typat_local, numbers, dlist )
return output
def ortho_vec_old(rprim, ortho_sizes = None):
"""
old function
Function returns mul_mat - 3 vectors of integer numbers (ndarray)
By calculating np.dot(mul_matrix, st.rprimd) you will get rprim of orthogonal supercell (actually as close as possible to it)
"""
from savelyev import vector_i
a = vector_i.Vector()
a.vec_new_in_vec_old(vec_new = np.diag(ortho_sizes), vec_old = rprim)
mul_matrix = np.array(a.vec_new_in_old)
mul_matrix = mul_matrix.round(0)
mul_matrix = mul_matrix.astype(int)
for i in [0,1,2]:
if mul_matrix[i][i] == 0:
mul_matrix[i][i] = 1
return mul_matrix
def ortho_vec(rprim, ortho_sizes = None):
"""
Function returns mul_mat - 3 vectors of integer numbers (ndarray)
By calculating np.dot(mul_matrix, rprim) you will get rprim of orthogonal supercell (actually as close as possible to it)
"""
printlog('Calculating mul_matrix for ortho:',ortho_sizes, imp = 'y',)
printlog('rprim is;', rprim)
vec_new = np.diag(ortho_sizes)
# print(rprim)
# t = rprim[1]
# rprim[1] = rprim[0]
# rprim[0] = t
mul_matrix_float = np.dot( vec_new, np.linalg.inv(rprim) )
# ortho_test = np.dot(mul_matrix_float, rprim )
# print(ortho_test)
# print(mul_matrix_float)
printlog('mul_matrix_float:\n',mul_matrix_float, imp = 'y', end = '\n')
mul_matrix = np.array(mul_matrix_float)
mul_matrix = mul_matrix.round(0)
mul_matrix = mul_matrix.astype(int)
for i in [0,1,2]:
if mul_matrix[i][i] == 0:
# mul_matrix[i][i] = 1
''
printlog('mul_matrix:\n',mul_matrix, imp = 'y', end = '\n')
return mul_matrix
# def mul_matrix(rprimd1, rprimd2):
# """
# Determines mul matrix needed to obtain rprimd2 from rprimd1
# """
def create_supercell(st, mul_matrix, test_overlap = False, mp = 4, bound = 0.01):
"""
st (Structure) -
mul_matrix (3x3 ndarray of int) - for example created by *ortho_ vec()*
bound (float) - shift (A) allows to correctly account atoms on boundaries
mp (int) include additionall atoms before cutting supecell
test_overlap (bool) - check if atoms are overlapping - quite slow
"""
sc = st.new()
# st = st.return_atoms_to_cell()
sc.name = st.name+'_supercell'
sc.rprimd = list(np.dot(mul_matrix, st.rprimd ))
printlog('Old vectors (rprimd):\n',np.round(st.rprimd,1), imp = 'y', end = '\n')
# printlog('Mul_matrix:\n',mul_matrix, imp = 'y', end = '\n')
printlog('New vectors (rprimd) of supercell:\n',np.round(sc.rprimd,1), imp = 'y', end = '\n')
sc.vol = np.dot( sc.rprimd[0], np.cross(sc.rprimd[1], sc.rprimd[2]) )
st.vol = np.dot( st.rprimd[0], np.cross(st.rprimd[1], st.rprimd[2]) )
# sc_natom_i = int(sc.vol/st.vol*st.natom) # test
# print(st.natom)
if len(st.typat) != len(st.magmom):
st.magmom = [None]*st.natom
mag_flag = False
else:
mag_flag = True
sc_natom = sc.vol/st.vol*st.natom # test
printlog('The supercell should contain', sc_natom, 'atoms ... \n', imp = 'y', end = ' ')
sc.xcart = []
sc.typat = []
sc.xred = []
sc.magmom = []
#find range of multiplication
mi = np.min(mul_matrix, axis = 0)
ma = np.max(mul_matrix, axis = 0)
mi[mi>0] = 0 #
# print(mi, ma)
# find bound values
lengths = np.linalg.norm(sc.rprimd, axis = 1)
bounds = bound/lengths # in reduced coordinates
# print(bounds)
# print(st.xcart)
# print([range(*z) for z in zip(mi-mp, ma+mp)])
# print(st.rprimd)
# print(sc.rprimd)
for uvw in itertools.product(*[range(*z) for z in zip(mi-mp, ma+mp)]): #loop over all ness uvw
# print(uvw)
xcart_mul = st.xcart + np.dot(uvw, st.rprimd) # coordinates of basis for each uvw
# print(xcart_mul)
xred_mul = xcart2xred(xcart_mul, sc.rprimd)
# print(len(xred_mul), len(xcart_mul), len(st.typat), len(st.magmom) )
for xr, xc, t, m in zip(xred_mul, xcart_mul, st.typat, st.magmom):
# if 0<xr[0]<1 and 0<xr[1]<1 and 0<xr[2]<1:
# print (xr)
if all([0-b <= r < 1-b for r, b in zip(xr, bounds)]): #only that in sc.rprimd box are needed
sc.xcart.append( xc )
sc.xred.append ( xr )
sc.typat.append( t )
sc.magmom.append(m)
sc.natom = len(sc.xcart)
if abs(sc.natom - sc_natom)>1e-5: #test 1, number of atoms
printlog('Error! Supercell contains wrong number of atoms:', sc.natom , 'instead of', sc_natom,
'try to increase *mp* of change *bound* ')
else:
printlog('OK', imp = 'y')
if test_overlap: #test 2: overlapping of atoms
enx = list(enumerate(sc.xcart))
for (i1, x1), (i2, x2) in itertools.product(enx, enx):
# print image_distance(x1, x2, sc.rprimd)[0]
if i1 != i2 and image_distance(x1, x2, sc.rprimd)[0] < 0.1: #less than 0.1 Angstrom
printlog('Error! Atoms in supercell are overlapping. Play with *bound*')
sc.recip = sc.get_recip()
sc.znucl = copy.copy(st.znucl)
sc.ntypat = st.ntypat
sc.nznucl = sc.get_nznucl()
if mag_flag is False:
sc.magmom = [None]
return sc
def supercell(st, ortho_sizes):
"""
wrapper
"""
mul_matrix = ortho_vec(st.rprimd, ortho_sizes)
return create_supercell(st, mul_matrix)
def cubic_supercell(st, ortho_sizes):
"""
wrapper
"""
mul_matrix = ortho_vec(st.rprimd, ortho_sizes)
return create_supercell(st, mul_matrix)
def determine_symmetry_positions(st, element, silent = 0):
"""
determine non-equivalent positions for atoms of type *element*
element (str) - name of element, for example Li
return list of lists - atom numbers for each non-equivalent position
"""
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
stp = st.convert2pymatgen()
spg = SpacegroupAnalyzer(stp)
info = spg.get_symmetry_dataset()
positions = {}
for i, (el, pos) in enumerate(zip(st.get_elements(), info['equivalent_atoms'])):
if el == element and pos not in positions:
positions[pos] = []
if el == element:
positions[pos].append(i)
if not silent:
printlog('I have found ', len(positions), 'non-equivalent positions for', element, ':',positions.keys(), imp = 'y', end = '\n')
positions_for_print = {}
for key in positions:
positions_for_print[key] = [p+1 for p in positions[key]]
if not silent:
printlog('Atom numbers: ', positions_for_print, imp = 'y')
sorted_keys = sorted(list(positions.keys()))
pos_lists = [positions[key] for key in sorted_keys ]
return pos_lists
def remove_atoms(st, atoms_to_remove):
"""
remove atoms either of types provided in *atoms_to_remove* or having numbers provided in *atoms_to_remove*
st (Structure)
atoms_to_remove (list) - list of element names or numbers
"""
st = st.remove_atoms(atoms_to_remove)
return st
def remove_one_atom(st, element, del_pos = None, iat = 0):
"""
removes one atom of element type from position del_pos
iat - number of atom inside subset
"""
# if not del_pos:
# del_pos = 1
positions = determine_symmetry_positions(st, element)
if not del_pos and len(positions) > 1:
printlog('Error! More than one symmetry position is found, please choose del position starting from 1')
elif len(positions) == 1:
del_pos = 1
else:
printlog('Position', del_pos, 'was chosen', imp = 'y')
pos = positions[ del_pos - 1 ]
i_del = pos[iat]
st = st.del_atom(i_del) # remove just iat atom
st.name += '.'+element+str(i_del)+'del'
st.magmom = [None]
return st, i_del
def create_deintercalated_structure(st, element, del_pos = 1):
"""