-
Notifications
You must be signed in to change notification settings - Fork 10
/
build.py
executable file
·1049 lines (912 loc) · 39.2 KB
/
build.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 python3
# -*- coding: utf-8 -*-
""" @author: yyyu200@163.com """
import numpy as np
import copy
import re
BOHR2ANGS=0.52917720859
def ext_euclid(a, b):
# find root of ax+by=gcd(a,b) =q
if b == 0:
return 1, 0, a
else:
x, y, q = ext_euclid(b, a % b) # q = gcd(a, b) = gcd(b, a%b)
x, y = y, (x - (a // b) * y)
return x, y, q
def get_atomic_weight(at):
sym_wt={'H': 1.00794, 'He': 4.00260, 'Li': 6.941, 'Be': 9.01218, 'B': 10.811,
'C': 12.0107, 'N': 14.00674, 'O': 15.9994, 'F': 18.99840, 'Ne': 20.1797,
'Na': 22.98977, 'Mg': 24.3050, 'Al': 26.98154, 'Si': 28.0855, 'P': 30.97376,
'S': 32.066, 'Cl': 35.4527, 'Ar': 39.948, 'K': 39.0983, 'Ca': 40.078,
'Sc': 44.95591, 'Ti': 47.867, 'V': 50.9415, 'Cr': 51.9961, 'Mn': 54.93805,
'Fe': 55.845, 'Co': 58.93320, 'Ni': 58.6934, 'Cu': 63.546, 'Zn': 65.39,
'Ga': 69.723, 'Ge': 72.61, 'As': 74.92160, 'Se': 78.96, 'Br': 79.904,
'Kr': 83.80, 'Rb': 85.4678, 'Sr': 87.62, 'Y': 88.90585, 'Zr': 91.224,
'Nb': 92.90638, 'Mo': 95.94, 'Tc': 98.0, 'Ru': 101.07, 'Rh': 102.90550,
'Pd': 106.42, 'Ag': 107.8682, 'Cd': 112.411, 'In': 114.818, 'Sn': 118.710,
'Sb': 121.760, 'Te': 127.60, 'I': 126.90447, 'Xe': 131.29, 'Cs': 132.90545,
'Ba': 137.327, 'La': 138.9055, 'Ce': 140.116, 'Pr': 140.90765, 'Nd': 144.24,
'Pm': 145.0, 'Sm': 150.36, 'Eu': 151.964, 'Gd': 157.25, 'Tb': 158.92534,
'Dy': 162.50, 'Ho': 164.93032, 'Er': 167.26, '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.078, 'Au': 196.96655, 'Hg': 200.59,
'Tl': 204.3833, 'Pb': 207.2, 'Bi': 208.98038, 'Po': 209.0, 'At': 210.0,
'Rn': 222.0, 'Fr': 223.0, 'Ra': 226.0, 'Ac': 227.0, 'Th': 232.0381,
'Pa': 231.03588, 'U': 238.0289, 'Np': 237.0, 'Pu': 244.0, 'Am': 243.0,
'Cm': 247.0, 'Bk': 247.0, 'Cf': 251.0, 'Es': 252.0, 'Fm': 257.0,
'Md': 258.0, 'No': 259.0, 'Lr': 262.0, 'Rf': 261.0, 'Db': 262.0,
'Sg': 266.0, 'Bh': 264.0, 'Hs': 277.0, 'Mt': 268.0}
if at in sym_wt:
return str(sym_wt[at])
else:
return "1.0"
def parse_lines_float(key, lines):
tmpstr=parse_lines(key, lines)
return np.float64(tmpstr)
def parse_lines_system(filename,key):
import f90nml
nml = f90nml.read(filename)
if 'system' in nml:
if key in nml['system']:
return nml['system'][key]
else:
return None
else:
return None
def parse_lines(key, lines):
res=None
for l in lines:
if not res:
res=parse_str(key,l)
return res
def parse_str(key, line):
# multiple key in a line must seperated by ',', not ';' nor ' ' as in QE native code
findkey=re.search(key, line)
if findkey:
r1=line.split('!')[0].split(',')
for s in r1:
r2=re.search(key, s)
if r2:
return s.split('=')[1]
else:
return None
def fan(v1,v2):
c=np.dot(v1,v2)/np.sqrt(v1.dot(v1))/np.sqrt(v2.dot(v2))
return np.arccos(c)*180/np.pi
def dist2(a,b=[0,0,0]): # TODO: a and b are fractional coordinates
return (a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2
def mixproduct(a,b,c):
return np.cross(a,b).dot(c)
class CELL(object):
eps1=1.0e-8
def __init__(self, fnam, fmt='POSCAR'):
'''
init from POSCAR, test only, use with caution
'''
if fmt=='POSCAR':
fi=open(fnam)
ll=fi.readlines()
self.system=ll[0]
self.alat=float(ll[1]) # Angstrom as unit
self.cell=np.zeros([3,3])
for i in range(3):
for j in range(3):
self.cell[i,j]=float(ll[2+i].split()[j])*self.alat
if mixproduct(self.cell[0],self.cell[1],self.cell[2])< -self.eps1:
print("imported POSCAR should be right-hand system.")
raise RuntimeError
self.ntyp=len(ll[5].split())
self.typ_name=ll[5].split()
self.typ_num=np.zeros([self.ntyp],dtype=np.int32)
for i in range(self.ntyp):
self.typ_num[i]=int(ll[6].split()[i])
self.coordsystem=ll[7] # Direct only, no 'Selective Dynamics' line expected
assert self.coordsystem[0]=='D' or self.coordsystem[0]=='d'
self.nat=int(sum(self.typ_num))
self.attyp=np.zeros([self.nat],dtype=np.int32)
k=0
for i in range(self.ntyp):
for j in range(self.typ_num[i]):
self.attyp[k]=i
k+=1
self.atpos=np.zeros([self.nat,3],dtype=np.float64)
for i in range(self.nat):
for j in range(3):
self.atpos[i,j]=float(ll[8+i].split()[j])
fi.close()
elif fmt=='QE': # experimental
fi=open(fnam)
ll=fi.readlines()
fi.close()
ibrav=parse_lines_system(fnam, 'ibrav')
self.nat=parse_lines_system(fnam, 'nat')
self.ntyp=parse_lines_system(fnam, "ntyp")
# assert ibrav not None
#ibrav, self.nat, self.ntyp=int(ibrav_str), int(nat_str), int(ntyp_str)
cdm=parse_lines_system(fnam, "celldm")
A=parse_lines_system(fnam, "A")
is_celldm=False
is_ABC=False
if cdm:
is_celldm=True
is_ABC=False
cd1=cdm[0]
if A:
is_celldm=False
is_ABC=True
if is_celldm and is_ABC:
raise Exception
elif not is_celldm and not is_ABC:
assert ibrav==0
self.cell=np.zeros([3,3], dtype=np.float64)
if ibrav==0:
i=0
for l in ll:
cpara=re.search("CELL_PARAMETERS",l)
i+=1
if cpara:
is_alat=re.search('alat',l)
is_angstrom=re.search('angstrom',l)
is_bohr=re.search('bohr',l)
for j in range(3):
self.cell[j,0]=np.float64(ll[j+i].split()[0])
self.cell[j,1]=np.float64(ll[j+i].split()[1])
self.cell[j,2]=np.float64(ll[j+i].split()[2])
break
else:
continue
assert cpara
if is_alat:
if is_celldm:
self.cell=self.cell*cd1*BOHR2ANGS
self.alat=cd1*BOHR2ANGS
else:
self.cell=self.cell*A
self.alat=A
elif is_bohr:
self.cell=self.cell*BOHR2ANGS
self.alat=np.sqrt(dist2(self.cell[0]))
elif is_angstrom:
self.cell=self.cell
self.alat=np.sqrt(dist2(self.cell[0]))
elif ibrav==1: # sc
if is_celldm:
self.cell=cd1*np.eye(3, dtype=np.float64)*BOHR2ANGS
elif is_ABC:
self.cell=A*np.eye(3, dtype=np.float64)
elif ibrav==2: # fcc
if is_celldm:
self.cell=cd1*0.5*np.array([[-1,0,1],[0,1,1],[-1,1,0]])*BOHR2ANGS
elif is_ABC:
self.cell=A*0.5*np.array([[-1,0,1],[0,1,1],[-1,1,0]])
else:
assert None
elif ibrav==3: # bcc
if is_celldm:
self.cell=cd1*0.5*np.array([[1,1,1],[-1,1,1],[-1,-1,1]])*BOHR2ANGS
elif is_ABC:
self.cell=A*0.5*np.array([[-1,0,1],[0,1,1],[-1,1,0]])
else:
assert None
elif ibrav==4: # hex
if is_celldm:
cd3=cdm[2]
self.cell=cd1*np.array([[1,0,0],[-1.0/2,np.sqrt(3)/2,0],[0,0,cd3]])*BOHR2ANGS
elif is_ABC:
C=parse_lines_system(fnam, "C")
self.cell=A*np.array([[1,0,0],[-1.0/2,np.sqrt(3)/2,0],[0,0,C/A]])
else:
assert None
elif ibrav==5: # trigonal R
if is_celldm:
cd4=cdm[3]
tx=np.sqrt((1-cd4)/2)
ty=np.sqrt((1-cd4)/6)
tz=np.sqrt((1+2*cd4)/3)
self.cell=cd1*np.array([[tx,-ty,tz],[0.0,2*ty,tz],[-tx,-ty,tz]])*BOHR2ANGS
elif is_ABC:
cosAB=parse_lines_system(fnam, "cosAB")
tx=np.sqrt((1-cosAB)/2)
ty=np.sqrt((1-cosAB)/6)
tz=np.sqrt((1+2*cosAB)/3)
self.cell=A*np.array([[tx,-ty,tz],[0.0,2*ty,tz],[-tx,-ty,tz]])
else:
assert None
elif ibrav==6: # tetra P
if is_celldm:
cd3=cdm[2]
self.cell=cd1*np.array([[1,0,0],[0,1,0],[0,0,cd3]])*BOHR2ANGS
else:
C=parse_lines_system(fnam, "C")
self.cell=A*np.array([[1,0,0],[0,1,0],[0,0,C/A]])
elif ibrav==7: # tetra I
if is_celldm:
cd3=cdm[2]
self.cell=cd1*0.5*np.array([[1,-1,cd3],[1,1,cd3],[-1,-1,cd3]])*BOHR2ANGS
else:
C=parse_lines_system(fnam, "C")
self.cell=A*0.5*np.array([[1,-1,C/A],[1,1,C/A],[-1,-1,C/A]])
elif ibrav==8: # orth P
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
self.cell=cd1*np.array([[1,0,0],[0,cd2,0],[0,0,cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
self.cell=A*np.array([[1,0,0],[0,B/A,0],[0,0,C/A]])
elif ibrav==9: # orth Base
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
self.cell=cd1*np.array([[0.5,cd2*0.5,0],[-0.5,cd2*0.5,0],[0,0,cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
self.cell=np.array([[A*0.5,B*0.5,0],[-A*0.5,B*0.5,0],[0,0,C]])
elif ibrav==10: # orth F
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
self.cell=cd1*np.array([[0.5,0,0.5*cd3],[0.5,0.5*cd2,0],[0,0.5*cd2,0.5*cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
self.cell=np.array([[0.5*A,0,0.5*C],[A*0.5,B*0.5,0],[0,0.5*B,0.5*C]])
elif ibrav==11: # orth Body center
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
self.cell=cd1*np.array([[0.5,0,0.5*cd3],[0.5,0.5*cd2,0],[0,0.5*cd2,0.5*cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
self.cell=np.array([[0.5*A,0,0.5*C],[A*0.5,B*0.5,0],[0,0.5*B,0.5*C]])
elif ibrav==12: # Monoclinic
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
cd4=cdm[3]
self.cell=cd1*np.array([[1.0,0,0],[cd2*cd4,cd2*np.sqrt(1.0-cd4*cd4),0],[0,0,cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
cosAB=parse_lines_system(fnam, "cosAB")
self.cell=np.array([[A,0,0],[B*cosAB,B*np.sqrt(1.0-cosAB*cosAB),0],[0,0,C]])
elif ibrav==13: # Monoclinic Base center
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
cd4=cdm[3]
self.cell=cd1*np.array([[0.5,0,-0.5*cd3],[cd2*cd4,cd2*np.sqrt(1.0-cd4*cd4),0],[0.5,0,0.5*cd3]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
cosAB=parse_lines_system(fnam, "cosAB")
self.cell=np.array([[0.5*A,0,-0.5*C],[B*cosAB,B*np.sqrt(1.0-cosAB*cosAB),0],[0.5*A,0,0.5*C]])
elif ibrav==14: # Triclinic
if is_celldm:
cd2=cdm[1]
cd3=cdm[2]
cd4=cdm[3]
cd5=cdm[4]
cd6=cdm[5]
sin_gamma=np.sqrt(1.0-cd6*cd6)
self.cell=cd1*np.array([[1.0, 0.0, 0.0], [cd2*cd6,cd2*sin_gamma,0.0], [cd3*cd5, cd3*(cd4-cd5*cd6)/sin_gamma, cd3*sqrt(1.0+2.0*cd4*cd5*cd6-cd4*cd4-cd5*cd5-cd6*cd6)/sin_gamma]])*BOHR2ANGS
else:
B=parse_lines_system(fnam, "B")
C=parse_lines_system(fnam, "C")
cosAB=parse_lines_system(fnam, "cosAB")
cosAC=parse_lines_system(fnam, "cosAC")
cosBC=parse_lines_system(fnam, "cosBC")
sin_gamma=np.sqrt(1.0-cosBC*cosBC)
self.cell=A*np.array([[1.0, 0.0, 0.0], [B/A*cosBC,B/A*sin_gamma,0.0], [C/A*cosAC, C/A*(cosAB-cosAC*cosBC)/sin_gamma, C/A*sqrt(1.0+2.0*cosAB*cosAC*cosBC-cosAB*cosAB-cosAC*cosAC-cosBC*cosBC)/sin_gamma]])
else:
# other ibrav
print("ibrav = ",ibrav," not implemented.")
raise NotImplementedError
if ibrav!=0:
if is_celldm:
self.alat=cd1*BOHR2ANGS
elif is_ABC:
self.alat=A
else:
assert None
# parse atomic type names
i=0
self.typ_name=[]
self.typ_num=np.zeros([self.ntyp], dtype=np.int32)
for l in ll:
is_line_atspecies=re.search("ATOMIC_SPECIES",l)
i+=1
if is_line_atspecies:
for j in range(self.ntyp):
tmp=ll[j+i].split()[0]
self.typ_name.append(tmp)
# parse atomic positions
i=0
self.atpos=np.zeros([self.nat,3], dtype=np.float64)
self.attyp=np.zeros([self.nat], dtype=np.int32)
for l in ll:
is_line_atpos=re.search("ATOMIC_POSITIONS",l)
i+=1
if is_line_atpos: # do not support Capital, such as 'ALAT'
is_atpos_alat=re.search('alat',l)
is_atpos_angstrom=re.search('angstrom',l)
is_atpos_bohr=re.search('bohr',l)
is_atpos_crystal_sg=re.search('crystal_sg',l)
if not is_atpos_crystal_sg:
is_atpos_crystal=re.search('crystal',l)
for j in range(self.nat):
tmp_element_name=ll[j+i].split()[0]
tmp_pos0=np.float64(ll[j+i].split()[1])
tmp_pos1=np.float64(ll[j+i].split()[2])
tmp_pos2=np.float64(ll[j+i].split()[3])
tmp_c=np.array([tmp_pos0, tmp_pos1, tmp_pos2], dtype=np.float64)
self.attyp[j]=self.element_name2attyp(tmp_element_name)
self.typ_num[self.attyp[j]]+=1
if is_atpos_crystal:
self.atpos[j]=tmp_c
elif is_atpos_crystal_sg:
raise NotImplementedError
else:
if is_atpos_alat:
self.atpos[j]=self.cart2direct(tmp_c*self.alat)
elif is_atpos_angstrom:
self.atpos[j]=self.cart2direct(tmp_c)
elif is_atpos_bohr:
self.atpos[j]=self.cart2direct(tmp_c*BOHR2ANGS)
else:
assert None
break
else:
continue
if np.dot(np.cross(self.cell[0], self.cell[1]),self.cell[2])<0:
P=np.mat(np.eye(3, dtype=np.float64))
P[0]=(0,1,0)
P[1]=(1,0,0)
P[2]=(0,0,1)
self.cell=((np.mat(self.cell).T)*P).T
self.cell=np.array(self.cell) # mat to array
assert np.linalg.det(self.cell)>0
Q=np.linalg.inv(P)
for i in range(self.nat):
self.atpos[i]=np.array(Q*(np.mat(self.atpos[i]).T)).flatten()
else:
# other code? maybe Abinit, castep
raise NotImplementedError
def __str__(self):
return "cell\n"+self.cell.__str__() + "\natom positions:\n"+ self.atpos.__str__()
def unique(self):
# Bucket sort-like
n=self.nat
i_kind=np.zeros([n],dtype=np.int32)
for i in range(n):
i_kind[i]=i
for i in range(n):
for j in range(i+1,n):
dd=self.atpos[i]-self.atpos[j]
if abs(dd[0])>self.eps1:
continue
if abs(dd[1])>self.eps1:
continue
if abs(dd[2])>self.eps1:
continue
i_kind[j]=i_kind[i]
uniq=[]
typ_of_uniq=[]
for i in np.unique(i_kind):
uniq.append(self.atpos[i])
typ_of_uniq.append(self.attyp[i])
#print(i_kind)
self.nat=len(uniq)
self.atpos=np.array(uniq)
self.attyp=np.array(typ_of_uniq)
for i in range(self.ntyp):
self.typ_num[i]=0
for j in range(self.nat):
if self.attyp[j]==i:
self.typ_num[i]+=1
def at_sort(self): # sort by element type
tmp=self.attyp[:].argsort(kind='mergesort')
self.attyp=self.attyp[tmp]
self.atpos=self.atpos[tmp]
def find_common_min(self, vecs, vecs_frac):
#vecs: list of cartesian coords of inplane vectors for each atoms
#vecs_frac: list of fractional coords of inplane vectors for each atoms
nat=len(vecs)
# nv: number of inplane vec for each atom
nv=np.zeros([nat],dtype=np.int64)
nv[0]=vecs[0].shape[0]
is_common0=np.ones([nv[0]],dtype=np.int64)
for i in range(nat):
#print("vecs_frac",i,vecs_frac[i])
nv[i]=vecs[i].shape[0]
for k in range(nv[0]):
if is_common0[k]==0:
continue
for j in range(nv[i]):
if dist2(vecs[i][j], vecs[0][k])<CELL.eps1:
break
elif j==nv[i]-1:
is_common0[k]=0
else:
pass
com_vec=[]
com_vec_frac=[]
for i in range(nv[0]):
if is_common0[i]==1:
com_vec.append(vecs[0][i])
com_vec_frac.append(vecs_frac[0][i])
N=len(com_vec)
#print(N, " com_vec_frac: ",com_vec_frac)
# generate areas of vector pairs
vol=np.zeros([N,N],dtype=np.float64)
tmp=np.zeros([3],dtype=np.float64)
for i in range(N):
for j in range(N):
tmp=np.cross(com_vec[i],com_vec[j])
vol[i,j]=np.sqrt(tmp[0]*tmp[0]+tmp[1]*tmp[1]+tmp[2]*tmp[2])
# choose from candidates, most small: minarea
minarea=99999999.0
for i in range(N):
for j in range(N):
if vol[i,j]<minarea-CELL.eps1 and vol[i,j]>CELL.eps1:
minarea=vol[i,j]
# which pairs are minarea
cij=[]
for i in range(N):
for j in range(N):
if abs(vol[i,j]-minarea)<CELL.eps1:
cij.append([i,j])
# choose from most small, most closest to 90 degree
athr=0.01 # close thr for angle
most_close_to_rect=999 # the minimum diffence between 90 degree
for ij in cij:
tmpang=fan(com_vec[ij[0]],com_vec[ij[1]])
if abs(tmpang-90)< most_close_to_rect-athr:
most_close_to_rect=abs(tmpang-90)
if abs(most_close_to_rect-30)<athr: # 120 deg.
prim_angle=120.0
elif abs(most_close_to_rect)<athr:
prim_angle=90.0
else:
prim_angle=90.0-most_close_to_rect
# which pairs are most small and close to rectangle angle
# reduce randomness in choice mi,mj
# keep the right-hand system
mij=[]
c_vec=self.direct2cart([0,0,1])
for ij in cij:
tmpang=fan(com_vec[ij[0]],com_vec[ij[1]])
if abs(tmpang-prim_angle)< athr and mixproduct(com_vec[ij[0]],com_vec[ij[1]], c_vec)>CELL.eps1:
mij.append([ij[0],ij[1]])
#print(len(mij), " com_vec_frac: ",com_vec_frac[ij[0]],com_vec_frac[ij[1]])
mi,mj=-1,-1
maxsum=-99999
for ij in mij:
tmpsum=sum(com_vec[ij[0]])+sum(com_vec[ij[1]])
if tmpsum>maxsum:
maxsum=tmpsum
mi=ij[0]
mj=ij[1]
#print("inplane vectors: ", "\nu:\n",com_vec_frac[mi], "\nv:\n", com_vec_frac[mj])
P=np.mat(np.eye(3,dtype=np.float64))
P[0,0]=com_vec_frac[mi][0]
P[1,0]=com_vec_frac[mi][1]
P[2,0]=com_vec_frac[mi][2]
P[0,1]=com_vec_frac[mj][0]
P[1,1]=com_vec_frac[mj][1]
P[2,1]=com_vec_frac[mj][2]
P[2,2]=1.0
#print("P2 = ",P)
return P
def tidy_up(self, do_sort=True): # tanslate to [0-1), sort by element
for i in range(self.nat):
for j in range(3):
tmp_f, tmp_i=np.modf(self.atpos[i][j]) # the fractional part , the interger part
# consider when tmp_i is small negative, e.g. -1e-17 , -1e-17+1=1
if tmp_f < 0.0- self.eps1:
self.atpos[i][j]=tmp_f+1.0
elif abs(tmp_f)<=self.eps1 or abs(tmp_f-1.0)<=self.eps1:
self.atpos[i][j]=0.0
else:
self.atpos[i][j]=tmp_f
assert self.atpos[i][j]<1.0 and self.atpos[i][j]>=0.0- self.eps1
if do_sort:
self.at_sort()
def print_pwinput(self, fnam, aug_sys="",separation=0.04):
control_nml="""&CONTROL
calculation='scf', pseudo_dir='./', outdir='./tmp', verbosity='high'
tprnfor=.true., tstress=.true., forc_conv_thr=1.0d-4, nstep=100,
/
"""
minimal_sys="&SYSTEM\n ibrav= 0, nat= %d, ntyp= %d, %s\n occupations = 'smearing', smearing = 'gauss', degauss = 1.0d-2,\n ecutwfc = 50, ecutrho = 500,\n/\n" % (self.nat, self.ntyp, aug_sys)
minimal_sys+="""&ELECTRONS
conv_thr = 1.0d-8
mixing_beta = 0.7d0
/
&IONS
/
&CELL
/
"""
atomic_species="ATOMIC_SPECIES\n"
for i in range(self.ntyp):
atomic_species+=" "+self.typ_name[i] +" "+ get_atomic_weight(self.typ_name[i]) +" "+self.typ_name[i]+".UPF\n" # TODO:real atomic weights
cell_parameters="CELL_PARAMETERS (angstrom)\n"
for i in range(3):
cell_parameters+=" %13.10f %13.10f %13.10f\n" % (self.cell[i,0],self.cell[i,1],self.cell[i,2])
atomic_positions="ATOMIC_POSITIONS (crystal)\n"
a=np.sqrt(dist2(self.cell[0]))
b=np.sqrt(dist2(self.cell[1]))
c=np.sqrt(dist2(self.cell[2]))
KP_x = max(1,int(1./(a*separation)+0.5))
KP_y = max(1,int(1./(b*separation)+0.5))
KP_z = max(1,int(1./(c*separation)+0.5))
kpoints="K_POINTS {automatic}\n %d %d %d 0 0 0\n"% (KP_x, KP_y, KP_z)
for i in range(self.nat):
atomic_positions+=" %3s %13.10f %13.10f %13.10f\n" % (self.typ_name[self.attyp[i]],self.atpos[i,0],self.atpos[i,1],self.atpos[i,2])
fout=open(fnam, 'w')
fout.write(control_nml+minimal_sys+atomic_species+cell_parameters+atomic_positions+kpoints)
#print(minimal_sys+atomic_species+cell_parameters+atomic_positions)
fout.close()
def print_poscar(self,fnam):
'''
print to POSCAR
'''
fo=open(fnam,"w")
fo.write("system: "+' '.join(self.typ_name)+"\n")
fo.write("1.0\n")
for i in range(3):
for j in range(3):
fo.write(" %15.10f" % self.cell[i,j])
fo.write("\n")
for i in range(self.ntyp):
fo.write(self.typ_name[i]+" ")
fo.write("\n")
for i in range(self.ntyp):
fo.write(str(self.typ_num[i])+" ")
fo.write("\n")
fo.write("Direct\n")
self.at_sort()
for i in range(self.nat):
for j in range(3):
#dig=np.modf(self.atpos[i][j])[0]
#if dig < 0:
# dig=dig+1.0
fo.write(" %.12f" % ( self.atpos[i][j]))
fo.write("\n")
fo.close()
def get_volume(self):
self.volume=np.dot(np.cross(self.cell[0], self.cell[1]),self.cell[2])
assert self.volume>0.0
return self.volume
def get_rec(self):
'''
get reciprocal lattice, crystallographer's definition, without factor of 2 \pi
'''
self.rec=np.zeros([3,3],dtype=np.float64)
self.volume=self.get_volume()
for i in range(3):
self.rec[i]=np.cross(self.cell[(i+1)%3], self.cell[(i+2)%3])/self.volume;
return self.rec
def element_name2attyp(self, element_name):
for i in range(self.ntyp):
if element_name == self.typ_name[i]:
return i
assert None
return -1
def direct2cart(self, a):
b=np.matmul(self.cell.T, a)
return b
def cart2direct(self, a):
b=np.matmul(self.get_rec(), a)
return b
def get_vac(self):
# assume cell is orthgonal, slab is at the center
assert abs(self.cell[2,0])<self.eps1 and abs(self.cell[2,1])<self.eps1
zmax=np.max(self.atpos[:,2])
zmin=np.min(self.atpos[:,2])
return abs(self.cell[2,2])*(1.0-(zmax-zmin))
def add_vacuum(self, vacuum):
assert abs(self.cell[2,0])<self.eps1 and abs(self.cell[2,1])<self.eps1
zmax=np.max(self.atpos[:,2])
zmin=np.min(self.atpos[:,2])
#oldC=np.linalg.norm(slab.cell[2])
oldC=abs(self.cell[2,2])
newC=oldC*(zmax-zmin)+vacuum
self.cell[2,2]*=(newC/oldC)
for i in range(self.nat):
self.atpos[i,2]=(vacuum/2.0+(self.atpos[i,2]-zmin)*oldC)/newC
def append(self, atpos, attyp, update_typ_num=False):
atpos=atpos.reshape(1,3)
attyp=np.array([attyp])
self.atpos=np.concatenate((self.atpos, atpos), axis=0)
self.attyp=np.concatenate((self.attyp, attyp), axis=0)
self.nat+=1
if update_typ_num:
self.typ_num[attyp]+=1
def pop(self, index=-1, position='top', refine_vacuum=True):
vac=self.get_vac()
if index!=-1:
self.atpos=np.delete(self.atpos, index, axis=0)
elif position == 'top':
tmp=self.atpos[:,2].argsort(kind='mergesort')
index=tmp[self.nat-1]
self.atpos=np.delete(self.atpos, index, axis=0)
elif position == 'bottom':
tmp=self.atpos[:,2].argsort(kind='mergesort')
index=tmp[0]
self.atpos=np.delete(self.atpos, index, axis=0)
self.nat-=1
self.typ_num[self.attyp[index]]-=1
self.attyp=np.delete(self.attyp, index, axis=0)
if refine_vacuum:
self.add_vacuum(vac)
def unique_append(self, atpos, attyp):
for i in range(self.nat):
d=atpos-self.atpos[i]
if abs(d[0])+abs(d[1])+abs(d[2])<3*self.eps1:
return
attyp=np.array([attyp])
atpos=atpos.reshape(1,3)
self.atpos=np.concatenate((self.atpos, atpos), axis=0)
self.attyp=np.concatenate((self.attyp, attyp), axis=0)
self.nat+=1
@staticmethod
def is_inside(A, B, La,Ma,Na, Lb,Mb,Nb):
'''
cell A is inside cell B repeat by La~Lb, Ma~Mb, Na~Nb, A and B have the same origin
the 8 corners of A in inside repeated B
'''
if Lb<=La or Mb<=Ma or Nb<=Na:
return False
P=np.mat(np.eye(3,dtype=np.float64))
P[0,0]=Lb-La
P[1,1]=Mb-Ma
P[2,2]=Nb-Na
Brepeat=copy.deepcopy(B)
Brepeat.cell=np.array((np.mat(B.cell).T*P).T)
# fraction coords of A basis vectors in Brepeat basis
Acell=np.zeros([3,3],dtype=np.float64)
for i in range(3):
Acell[i]=Brepeat.cart2direct(A.cell[i])
corner_o=np.array([0.0 if np.fabs(La)<CELL.eps1 else -La/(Lb-La),
0.0 if np.fabs(Ma)<CELL.eps1 else -Ma/(Mb-Ma),
0.0 if np.fabs(Na)<CELL.eps1 else -Na/(Nb-Na)])
for i in range(8): # fraction coords of eight corners of A
corner=corner_o.copy()
for j in range(3):
corner+=(i>>j)%2*Acell[j]
if (corner>1.0+CELL.eps1).any() or (corner<0.0-CELL.eps1).any():
return False
#print(La,Ma,Na,Lb,Mb,Nb,"T",A.cell, Brepeat.cell, Acell)
return True
@staticmethod
def cell2supercell(cell, P, checkunique=True):
'''
use a cell to fill in new cell by translate of base vectors
'''
supercell=copy.deepcopy(cell)
supercell.cell=((np.mat(cell.cell).T)*P).T
supercell.cell=np.array(supercell.cell) # mat to array
#print("\ncell.cell=\n", np.mat(cell.cell),"\nP=\n",P,"\nsupercell.cell=\n", supercell.cell)
assert np.linalg.det(supercell.cell)>0
Q=np.linalg.inv(P)
for i in range(cell.nat):
supercell.atpos[i]=np.array(Q*(np.mat(cell.atpos[i]).T)).flatten()
# trans: fractional coordinates of cell vectors in supercell
# atoms translate by trans is allowed in supercell
trans=np.zeros([3,3], dtype=np.float64)
for i in range(3):
cell_i_frac=cell.cart2direct(cell.cell[i]) # one hot
trans[i]=np.array(Q*(np.mat(cell_i_frac).T)).flatten()
La,Ma,Na=0,0,0
Lb,Mb,Nb=0,0,0
while not CELL.is_inside(supercell,cell,La,Ma,Na,Lb,Mb,Nb):
La-=1;Ma-=1;Na-=1
Lb+=1;Mb+=1;Nb+=1
assert CELL.is_inside(supercell,cell,La,Ma,Na,Lb,Mb,Nb)
while CELL.is_inside(supercell,cell,La+1,Ma,Na,Lb,Mb,Nb):
La+=1
while CELL.is_inside(supercell,cell,La,Ma,Na,Lb-1,Mb,Nb):
Lb-=1
while CELL.is_inside(supercell,cell,La,Ma+1,Na,Lb,Mb,Nb):
Ma+=1
while CELL.is_inside(supercell,cell,La,Ma,Na,Lb,Mb-1,Nb):
Mb-=1
while CELL.is_inside(supercell,cell,La,Ma,Na+1,Lb,Mb,Nb):
Na+=1
while CELL.is_inside(supercell,cell,La,Ma,Na,Lb,Mb,Nb-1):
Nb-=1
N=supercell.nat
for n in range(N):
for i in range(La,Lb):
for j in range(Ma,Mb):
for k in range(Na,Nb):
#print(n,i,j,k)
supercell.append(supercell.atpos[n]+i*trans[0]+j*trans[1]+k*trans[2], supercell.attyp[n])
#print("final:",La,Ma,Na, Lb,Mb,Nb, supercell.nat)
supercell.tidy_up()
if checkunique:
supercell.unique()
return supercell
@staticmethod
def unit2prim(unitcell, ibrav):
primcell=copy.deepcopy(unitcell)
if ibrav in [2,10]: # face center
P=np.mat([[0.0, 0.5, 0.5],[0.5, 0.0, 0.5],[0.5, 0.5, 0.0]],dtype=np.float64)
Q=np.mat([[-1,1,1],[1,-1,1],[1,1,-1]],dtype=np.float64)
elif ibrav in [3,7,11]: # body center
P=np.mat([[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],dtype=np.float64)
Q=np.mat([[0,1,1],[1,0,1],[1,1,0]],dtype=np.float64)
elif ibrav==5: # rhombohedral
P=np.mat([[2/3.0,-1/3.0,-1/3.0],[1/3.0,1/3.0,-2/3.0],[1/3.0,1/3.0,1/3.0]],dtype=np.float64)
Q=np.mat([[1,0,1],[-1,1,1],[0,-1,1]],dtype=np.float64)
elif ibrav in [9,13]: # base center
P=np.mat([[0.5,-0.5,0],[0.5,0.5,0],[0,0,1.0]],dtype=np.float64)
Q=np.mat([[1,1,0],[-1,1,0],[0,0,1]],dtype=np.float64)
else:
print("unit cell is primitive for ibrav: ", ibrav)
P=np.mat([[1,0,0],[0,1,0],[0,0,1]], dtype=np.float64)
Q=np.mat([[1,0,0],[0,1,0],[0,0,1]], dtype=np.float64)
primcell.cell=(np.mat(unitcell.cell).T*P).T
primcell.cell=np.array(primcell.cell)
primcell.cell=np.array(primcell.cell)
assert np.linalg.det(primcell.cell)>0
primcell.nat=unitcell.nat
for i in range(primcell.nat):
primcell.atpos[i]=np.array(Q*(np.mat(unitcell.atpos[i]).T)).flatten()
primcell.tidy_up()
primcell.unique()
# assert transform fully covered the primcell, no need for filling
return primcell
def set_cell(self,cell):
self.cell=np.array(cell)
def cell_redefine(self):
'''Re-define slab cell to have the x-axis parallel with a surface vector
and z perpendicular to the surface. Only keep the inplane periodicity.
First c is projected along z, fractional coords are changed in tis step.
Then the cell is rotated.
'''
from numpy.linalg import norm
a1, a2, a3 = self.cell
carts=np.zeros([self.nat,3],dtype=np.float64)
for i in range(self.nat):
carts[i]=self.direct2cart(self.atpos[i])
self.set_cell([a1, a2, np.cross(a1, a2) * np.dot(a3, np.cross(a1, a2)) /norm(np.cross(a1, a2))**2])
for i in range(self.nat):
self.atpos[i]=self.cart2direct(carts[i])
self.tidy_up()
a1, a2, a3 = np.array(self.cell)
self.set_cell([[norm(a1), 0, 0],
[np.dot(a1, a2) / norm(a1), np.sqrt(norm(a2)**2 - (np.dot(a1, a2) / norm(a1))**2), 0],
[0, 0, norm(a3)]] )
def is_inlattice(self,i,by_s_tau):
tmp=self.atpos[i]+by_s_tau
for k in range(3):
tf,ti=np.modf(tmp[k])
if tf < 0.0- self.eps1:
tf=tf+1.0
elif np.fabs(tf)<=self.eps1 or np.fabs(tf-1.0)<=self.eps1:
tf=0.0
tmp[k]=tf
for k in range(self.nat):
if dist2(self.atpos[k],tmp)<=self.eps1 and self.attyp[k]==self.attyp[i]:
return True
return False
def find_inplane(self,i,search_range=6):
# norm vector, after redefine, n_ is [0,0,c]
n_=np.cross(self.cell[0],self.cell[1])
# find d in plane-equation:hx+ky+lz=d
d=[]
for k in range(self.nat):
d.append(np.dot(self.atpos[k].reshape(3,),n_.reshape(3,)))
# ikind, index of atoms inplane with atom i
ikind=[]
for k in range(self.nat):
if k==i:
continue
if abs(d[k]-d[i])<self.eps1 and self.attyp[i]==self.attyp[k]:
tau=self.atpos[k]-self.atpos[i]
#print(i,k,tau)
is_inplane_and_trans=True
for s in range(1,search_range):
by_s_tau=s*tau
if not self.is_inlattice(i,by_s_tau):
is_inplane_and_trans=False
#print(i,by_s_tau,s)
break
if is_inplane_and_trans:
ikind.append(k)
iin=len(ikind) # number of inplane atoms with the i-th atom
ir=1 # neighbor -ir, -ir+1,..., ir-1, ir
inplane_range=2*ir+1
Nin=inplane_range**2
re=np.zeros([iin*Nin,3],dtype=np.float64)
lat_neighbor=np.zeros([Nin,3],dtype=np.float64)
for il in range(Nin):
rx=il//inplane_range-ir
ry=il%inplane_range-ir
lat_neighbor[il]=np.array([rx,ry,0],dtype=np.float64)
for k in range(iin):
tmp=self.atpos[ikind[k]]-self.atpos[i]
for il in range(Nin):
re[k*Nin+il]=tmp+lat_neighbor[il]
re=np.concatenate((re,lat_neighbor),axis=0)
re2=np.zeros([re.shape[0],re.shape[1]],dtype=np.float64)
for k in range(re.shape[0]):
re2[k]=self.direct2cart(re[k])
#print("re",re.shape)
return re2, re
@staticmethod
def reduce_slab(slab,axis='c'):
# find 2d minimum cell for the slab, assume c is surface norm
vecs=[]
vecs_frac=[]
for i in range(slab.nat):
tmp_cart, tmp_frac=slab.find_inplane(i)
vecs.append(tmp_cart)
vecs_frac.append(tmp_frac)
P=slab.find_common_min(vecs, vecs_frac)
reduced=CELL.cell2supercell(slab,P)
return reduced
def makeslab(self, miller_index, length=-1.0, layer=-1, method="bf", origin_shift=0.0, vacuum=15.0):
'''
self is unit-cell
'''
P=np.mat(np.eye(3, dtype=np.float64))
h,k,l=miller_index
e=np.gcd(h, np.gcd(k,l))
if e>1:
h=h//e
k=k//e
l=l//e
print("find miller index ( ",h,k,l," ) instead.")
if h==0 and k==0 and l==0:
print("miller_index cannot be 0 0 0!")
raise AssertionError
elif h==0 and k==0:
P[2,2]=layer