This repository was archived by the owner on Jul 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathuctools.py
More file actions
1844 lines (1766 loc) · 83.1 KB
/
Copy pathuctools.py
File metadata and controls
1844 lines (1766 loc) · 83.1 KB
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
# Copyright 2010 Torbjorn Bjorkman
# This file is part of cif2cell
#
# cif2cell is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cif2cell is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cif2cell. If not, see <http://www.gnu.org/licenses/>.
#
#******************************************************************************************
# Description: A set of tools to generate the geometrical
# setup for various electronic structure codes.
# Contains some container classes for structural
# data and methods to extract these from a CIF
# file.
# Currently supports standard (conventional)
# cell settings and from that reduction to the
# primitive cell.
# Author: Torbjorn Bjorkman, torbjorn.bjorkman(at)aalto.fi
# Affiliation: COMP, Aaalto University School of Science,
# Department of Applied Physics, Espoo, Finland
#
# TODO:
#******************************************************************************************
from __future__ import division
import os
import sys
import string
import copy
import CifFile
from types import *
from math import sin,cos,pi,sqrt,pow,ceil,floor
from utils import *
from spacegroupdata import *
from elementdata import *
from random import random, gauss
from fractions import gcd
from functools import reduce
################################################################################################
class CellData(GeometryObject):
"""
Class for a lot of stuff specifying a unit cell.
latticevectors : The Bravais lattice vectors
lengthscale : an overall length scale that multiplies the lattice vectors.
unit : the unit of the lengthscale
alloy : True if the compound is an alloy
atomdata : An array of arrays of AtomSite objects, in other words, a collection of
collections of atoms. The getCrystalStructure method sets up a collection of
all the inequivalent sites, and each such collection contains all the
sites generated by the representative site. So: atomdata[0][2] is the
third atom generated from the first wyckoff position.
Methods:
getFromCIF : obtain data for setting up a cell from a CIF block
crystal_system : return a string with the name of the crystal system
latticevectors : Return the Bravais lattice vectors as a 3x3 matrix
reciprocal_latticevectors: Return the reciprocal lattice vectors as a 3x3 matrix.
volume : Return the unit cell volume
primitive : Returns a CrystalStructure object for the primitive cell
conventional : Returns a CrystalStructure object for the conventional cell.
fill_out_empty : Fill out any site whose concentrations do not add up to 1.0
with an empty sphere.
getCrystalStructure : The 'primitive' and 'conventional' methods are just
wrappers around this method. It requires the following
to be set beforehand:
a, b, c, alpha, beta, gamma : the lattice parameters
spacegroupnr : The space group number
ineqsites : The inequivalent sites (wyckoff positions)
occupations : The occupations of the different inequivalent sites
in the form of a list of dictionaries. Each
inequivalent site is supposed to have a dictionary
with the species occupying it and its occupancy.
Example: Two inequivalent sites, one with iron
and the other with 90% oxygen and 10% flourine:
occupations = [{'Fe':1.0}, {'O':0.9, 'F':0.1}]
getSuperCell : Return a supercell from input supercell dimensions [i,j,k] or a general map
matrix [[],[],[]]. The crystal structure must first have been initialized by
getCrystalStructure(), primitive() or conventional() methods).
"""
def __init__(self):
GeometryObject.__init__(self)
self.initialized = False
self.force = False # Force generation despite problems?
self.cartesianInput = False
self.filename = ""
self.blockname = ""
self.quiet = False
self.coordepsilon = 0.0002
self.HallSymbol = ""
self.spacegroupnr = 0
self.HMSymbol = ""
self.spacegroupsetting = ""
self.cart_trans_matrix = None
self.cart_trans_vector = None
self.lattrans = LatticeMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
self.transvecs = [LatticeVector([zero, zero, zero])]
self.symops = set([])
self.ineqsites = []
self.occupations = []
self.atomdata = []
self.atomset = set([])
self.numberOfAtoms = None
self.ChemicalComposition = dict([])
# initial lattice parameters
self.ainit = 0.
self.binit = 0.
self.cinit = 0.
self.alphainit = 0.
self.betainit = 0.
self.gammainit = 0.
self.coainit = 1.
self.boainit = 1.
# lattice parameters used to generate the cell
self.a = 0.
self.b = 0.
self.c = 0.
self.alpha = 0.
self.beta = 0.
self.gamma = 0.
self.coa = 1.
self.boa = 1.
self.latticevectors = None
self.lengthscale = 1.
self.unit = "angstrom"
self.alloy = False
self.numofineqsites = 0
# Lattice vector choices
self.primcell = False
self.rhomb2hex = False
self.rhombohedral = False
self.supercell = False
def newunit(self,newunit="angstrom"):
""" Set new unit for the length scale. Valid choices are:
* angstrom
* bohr (bohr radii, or a.u. (atomic unit))
* nm (nanometer)
"""
if self.unit == newunit:
return
if self.unit == "angstrom" and newunit == "bohr":
fact = 1.8897261
elif self.unit == "bohr" and newunit == "angstrom":
fact = 0.52917721
elif self.unit == "angstrom" and newunit == "nm":
fact = 0.1
elif self.unit == "nm" and newunit == "angstrom":
fact = 10
elif self.unit == "bohr" and newunit == "nm":
fact = 0.052917721
elif self.unit == "nm" and newunit == "bohr":
fact = 18.897261
else:
raise CellError("newunit: "+newunit+" No such unit.")
self.lengthscale *= fact
self.a *= fact
self.b *= fact
self.c *= fact
self.unit = newunit
def crystal_system(self):
return crystal_system(self.spacegroupnr)
def conventional_latticevectors(self):
# Set up Bravais lattice vectors of the conventional cell
self.coa = self.c / self.a
self.boa = self.b / self.a
alphar = self.alpha*pi/180
betar = self.beta*pi/180
gammar = self.gamma*pi/180
if self.crystal_system() == 'cubic':
latticevectors = LatticeMatrix([[one, zero, zero],
[zero, one, zero],
[zero, zero, one]])
elif self.crystal_system() == 'hexagonal':
latticevectors = LatticeMatrix([[sin(gammar), cos(gammar), zero],
[zero, one, zero],
[zero, zero, self.coa]])
elif self.crystal_system() == 'tetragonal' or self.crystal_system() == 'orthorhombic':
latticevectors = LatticeMatrix([[one, zero, zero],
[zero, self.boa, zero],
[zero, zero, self.coa]])
## elif self.crystal_system() == 'monoclinic':
## latticevectors = LatticeMatrix([[one, zero, zero],
## [zero, self.boa, zero],
## [self.coa*cos(betar), zero, self.coa*sin(betar)]])
elif self.crystal_system() == 'trigonal':
# Hexagonal cell taken as conventional
if not abs(self.gamma-120) < self.coordepsilon:
gammar = 120*pi/180
latticevectors = LatticeMatrix([[sin(gammar), cos(gammar), zero],
[zero, one, zero],
[zero, zero, self.coa]])
elif self.crystal_system() == 'triclinic' or self.crystal_system() == 'monoclinic' or self.crystal_system() == 'unknown':
angfac1 = (cos(alphar) - cos(betar)*cos(gammar))/sin(gammar)
angfac2 = sqrt(sin(gammar)**2 - cos(betar)**2 - cos(alphar)**2
+ 2*cos(alphar)*cos(betar)*cos(gammar))/sin(gammar)
latticevectors = LatticeMatrix([[one, zero, zero],
[self.boa*cos(gammar), self.boa*sin(gammar), zero],
[self.coa*cos(betar), self.coa*angfac1, self.coa*angfac2]])
else:
raise SymmetryError("No support for "+self.crystal_system()+" crystal systems.")
return latticevectors
# The reciprocal lattice vectors corresponding to the lattice vectors of the structure
# (b1, b2, b3)^T = 2 * pi * (a1, a2, a3)^{-1}
def reciprocal_latticevectors(self):
t = minv3(self.latticevectors)
reclatvect = []
for j in range(3):
reclatvect.append([])
for i in range(3):
reclatvect[j].append(t[i][j]*2*pi)
return LatticeMatrix(reclatvect)
# Define comparison functions
def poscomp(self, pos1, pos2):
# Return True if two positions are the same
if abs(pos1[0] - pos2[0]) < self.coordepsilon and \
abs(pos1[1] - pos2[1]) < self.coordepsilon and \
abs(pos1[2] - pos2[2]) < self.coordepsilon:
return True
else:
return False
def transveccomp(self, pos1,pos2):
# Return True if two positions only differ by one
# of the induced lattice translations
match = False
for tv in self.transvecs:
if (abs(pos1[0]-(pos2[0]-tv[0]))<self.coordepsilon and \
abs(pos1[1]-(pos2[1]-tv[1]))<self.coordepsilon and \
abs(pos1[2]-(pos2[2]-tv[2]))<self.coordepsilon):
match = True
return match
def duplicates(self, poslist, compfunc = transveccomp):
# Return list of indices of duplicates in a list,
# sorted in reverse order to be easy to use for removing the duplicates.
# Optionally supply a comparison function for when two coordinates
# are the same, else use 'samecoords' function from above.
removeindices = set([])
for i in range(len(poslist)):
for j in range(len(poslist)-1,i,-1):
if compfunc(self,poslist[i],poslist[j]):
removeindices.add(j)
removeindices = list(removeindices)
removeindices.sort(reverse=True)
return removeindices
def volume(self):
""" Return the volume of the cell. """
return abs(det3(self.latticevectors))
def natoms(self):
""" Return the number of atoms in the cell. """
i = 0
for a in self.atomdata:
i += len(a)
return i
def primitive(self):
""" Return a CrystalStructure object for the primitive cell."""
self.getCrystalStructure(reducecell=True)
return self
def conventional(self):
""" Return a CrystalStructure object for the conventional cell."""
w = self.getCrystalStructure(reducecell=False)
return w
# Fill out sites that are not occupied to 100% with
# empty spheres (optionally giving a label).
def fill_out_empty(self,label="Em"):
for a in self.atomdata:
# Check concentration
t = 0.0
for sp,conc in a[0].species.items():
t += conc
# Add vacuum spheres if partially empty
if abs(1.0-t) > a[0].compeps:
for b in a:
b.species[label] = 1.0-t
# Randomly displace atoms
def randomDisplacements(self, size=0.1, distribution="uniform"):
"""
Randomly displace all atoms. The size parameter gives the maximal
deviation in whatever the real space unit currently is (typically Angstrom).
The random displacements are uniformly distributed in the interval ]-size,size[.
"""
invlatvecs = minv3(self.latticevectors)
tmp = []
i = 0
for a in self.atomdata:
for b in a:
if distribution == "gaussian":
r = gauss(0.0,size)*size
theta = gauss(0.0, size)*pi
phi = gauss(0.0, size)*2*pi
elif distribution == "uniform":
r = random()*size
theta = random()*pi
phi = random()*2*pi
else:
raise SetupError("Unknown distribution for random displacements.")
d = Vector([r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)]).transform(invlatvecs)
b.position = LatticeVector([b.position[i] + d[i] for i in range(3)])
tmp.append([b])
# We need to reset implicit symmetry information here
self.atomdata = tmp
def getCrystalStructure(self, reducecell=False):
"""
Return a CrystalStructure object, either as it is or reduced to the
primitive cell.
"""
# reduce to primitive cell?
self.primcell = reducecell
###################################
# INITIALIZE SPACE GROUP DATA #
###################################
# Try to set Hall symbol, if not set
if self.HallSymbol == "":
if self.HMSymbol == "":
if 0 < self.spacegroupnr <= 230:
try:
self.HallSymbol = Number2Hall[self.spacegroupnr]
except:
raise SymmetryError("Found neither Hall nor H-M symbol and space group %i does not have a unique setting."%self.spacegroupnr)
else:
if self.force:
sys.stderr.write("***Warning: CIF file contains neither space group symbols nor space group number.\n")
sys.stderr.write(" Defaulting to P 1. Check results carefully!\n")
self.HallSymbol = "P 1"
else:
raise SymmetryError("CIF file contains neither space group symbols nor space group number.")
try:
self.HallSymbol = HM2Hall[self.HMSymbol]
except:
sys.stderr.write("***Warning: Cannot convert "+self.HMSymbol+" to Hall symbol.\n")
# Set space group number and H-M symbol if not set
if not 0 < self.spacegroupnr <= 230:
try:
self.spacegroupnr = Hall2Number[self.HallSymbol]
except:
pass
if self.HMSymbol == "":
try:
self.HMSymbol == Hall2HM[self.HallSymbol]
except:
pass
# Check if we know enough:
# To produce the conventional cell (self.primcell=False) we don't need the space group
# symbol or number as long as we have the symmetry operations (equivalent sites).
if self.spacegroupsetting == "":
try:
self.spacegroupsetting = self.HallSymbol.lstrip("-")[0]
except:
try:
self.spacegroupsetting = self.HMSymbol[0]
except:
pass
if self.spacegroupsetting == "":
try:
self.spacegroupsetting = SGnrtoHM[str(self.spacegroupnr)][0]
except:
pass
# Sanity test of lattice parameters
if self.a!=0 and self.b!=0 and self.c!=0 and self.alpha!=0 and self.beta!=0 and self.gamma!=0:
if not 0 < self.spacegroupnr < 231:
if len(self.symops) >= 1:
if self.primcell == True:
if self.spacegroupsetting == 'P':
self.spacegroupnr = 0
else:
raise SymmetryError("Insufficient symmetry information to reduce to primitive cell"+\
" (need space group number or Hermann-Mauguin symbol).\n"+\
" Run with --no-reduce to generate cell in the conventional setting.")
else:
self.spacegroupnr = 0
else:
raise CellError("No crystallographic parameter may be zero.")
# If no symmetry operations are not set, get internally stored.
if not self.symops:
eqsites = SymOpsHall[self.HallSymbol]
# Define the set of space group operations.
self.symops = set([])
for site in eqsites:
self.symops.add(SymmetryOperation(site))
############################
# INITIALIZE LATTICE #
############################
# Special case: trigonal systems in rhombohedral setting
# are first transformed to hexagonal setting
if self.HallSymbol in Rhomb2HexHall and abs(self.gamma - 120) > self.coordepsilon:
self.rhomb2hex = True
self.c = self.a * sqrt(3 + 6*cos(self.alpha*pi/180))
self.a = 2 * self.a * sin(self.alpha*pi/360)
self.b = self.a
self.alpha = 90.0
self.beta = 90.0
self.gamma = 120.0
rhomb2hextrans= LatticeMatrix([[2*third, third, third],
[-third, third, third],
[-third, -2*third, third]])
for i in range(len(self.ineqsites)):
self.ineqsites[i] = Vector(mvmult3(rhomb2hextrans,self.ineqsites[i]))
# We also need the correct symmetry operations.
eqsites = SymOpsHall[Rhomb2HexHall[self.HallSymbol]]
self.symops = set([])
for site in eqsites:
self.symops.add(SymmetryOperation(site))
# set primitive lattice vectors
self.latticevectors = self.conventional_latticevectors()
self.lengthscale = self.a
self.alloy = False
# Transform ineqsites to lattice coordinates if they were given as
# cartesian in the input file.
if self.cartesianInput:
try:
trans_matrix = minv3(self.cart_trans_matrix)
except:
if self.force:
# Fallback on the transformation matrix from default lattice vector choices.
t = []
for i in range(3):
t.append([])
for j in range(3):
t[i].append(self.latticevectors[i][j] * self.lengthscale)
trans_matrix = LatticeMatrix(minv3(t))
else:
raise CellError("Failed to perform transformation from cartesian to lattice coordinates.")
try:
# Primarily use the transformation matrix/translation vector given as input.
for i in range(len(self.ineqsites)):
t = self.ineqsites[i] - self.cart_trans_vector
self.ineqsites[i] = Vector(mvmult3(trans_matrix,t))
except:
raise CellError("Failed to perform transformation from cartesian to lattice coordinates.")
###############################
# LATTICE TRANSLATIONS #
###############################
#
# Choices of lattice vectors made to largely coincide with the choices
# made at http://cst-www.nrl.navy.mil/lattice/
#
# The induced translation vectors are from Zachariasen, "Theory of x-ray
# diffraction in crystals".
#
# Relations between rhombohedral and hexagonal settings of trigonal
# space groups from Tilley, "Crystals and crystal structures"
# Bravais lattice vectors:
#
# a_r = 2/3 a_h + 1/3 b_h + 1/3 c_h
# b_r = -1/3 a_h + 1/3 b_h + 1/3 c_h
# c_r = -1/3 a_h - 2/3 b_h + 1/3 c_h
#
# a_h = a_r - b_r
# b_h = b_r - c_r
# c_h = a_r + b_r + c_r
#
# a, c and rhombohedral angle alpha:
#
# a_h = 2 * a_r * sin(alpha/2)
# c_h = a_r * sqrt(3 + 6*cos(alpha))
#
# a_r = sqrt(3*a_h^2 + c_h^2) / 3
# sin(alpha/2) = 3*a_h / (2 * sqrt(3*a_h^2 + c_h^2))
#
if self.primcell:
if self.spacegroupsetting == 'I':
# Body centered
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([half,half,half])]
if self.crystal_system() == 'cubic':
self.lattrans = LatticeMatrix([[-half, half, half],
[half, -half, half],
[half, half, -half]])
else:
self.lattrans = LatticeMatrix([[one, zero, zero],
[zero, one, zero],
[half, half, half]])
elif self.spacegroupsetting == 'F':
# face centered
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([half,half,zero]),
LatticeVector([half,zero,half]),
LatticeVector([zero,half,half])]
self.lattrans = LatticeMatrix([[half, half, zero],
[half, zero, half],
[zero, half, half]])
elif self.spacegroupsetting == 'A':
# A-centered
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([zero,half,half])]
self.lattrans = LatticeMatrix([[one, zero, zero],
[zero, half, -half],
[zero, half, half]])
elif self.spacegroupsetting == 'B':
# B-centered
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([half,zero,half])]
self.lattrans = LatticeMatrix([[half, zero, -half],
[zero, one, zero],
[half, zero, half]])
elif self.spacegroupsetting == 'C':
# C-centered
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([half,half,zero])]
self.lattrans = LatticeMatrix([[half, -half, zero],
[half, half, zero],
[zero, zero, one]])
elif self.HallSymbol in Hex2RhombHall or self.HallSymbol in Rhomb2HexHall:
if abs(self.gamma - 120) < self.coordepsilon:
# rhombohedral from hexagonal setting
self.rhombohedral = True
self.transvecs = [LatticeVector([zero,zero,zero]),
LatticeVector([third, 2*third, 2*third]),
LatticeVector([2*third, third, third])]
self.lattrans = LatticeMatrix([[2*third, third, third],
[-third, third, third],
[-third, -2*third, third]])
else:
self.transvecs = [LatticeVector([zero,zero,zero])]
self.lattrans = LatticeMatrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
else:
self.transvecs = [LatticeVector([zero,zero,zero])]
self.lattrans = LatticeMatrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
# Transform to primitive cell
tmp = []
for i in range(3):
tmp.append(mvmult3(self.latticevectors,self.lattrans[i]))
self.latticevectors = LatticeMatrix(tmp)
# Improve precision again...
for i in range(3):
for j in range(3):
self.latticevectors[i][j] = improveprecision(self.latticevectors[i][j],self.coordepsilon)
else:
# If no reduction is to be done
self.transvecs = [LatticeVector([zero,zero,zero])]
self.lattrans = LatticeMatrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
# Find inverse lattice transformation matrix
invlattrans = LatticeMatrix(minv3(self.lattrans))
#################################
# SYMMETRY OPERATIONS #
#################################
# If we reduce the cell, remove the symmetry operations that are the
# same up to an induced lattice translation
if self.primcell:
if len(self.transvecs) > 1:
redundant = set([])
for op1 in self.symops:
for op2 in self.symops:
for vec in self.transvecs:
if op1.translation+vec == op2.translation:
if op1.rotation == op2.rotation:
if op1.translation.length() < op2.translation.length():
redundant.add(op2)
self.symops -= redundant
# Space group operations to cartesian representation
lv = self.conventional_latticevectors()
for op in self.symops:
op.rotation = lv.transform(op.rotation)
op.rotation = op.rotation.transform(minv3(lv))
# transform translations
op.translation = op.translation.transform(minv3(self.lattrans))
# Test that the lattice vectors are invariant under all space group operations
# If not, the data is given in some non-standard representation that presently
# can't be handled.
if self.crystal_system() == 'hexagonal' or self.crystal_system() == 'trigonal':
# Hexagonal and trigonal as a special case... check that the hexagonal planes are in the ab plane
for op in self.symops:
if not (op.rotation[2] == Vector([0,0,1]) or op.rotation[2] == Vector([0,0,-1])):
raise SymmetryError("Lattice vectors do not fulfil the given symmetries of the lattice!\n"+
"The cell is given in some non-standard setting presently not handled by the program.")
else:
for op in self.symops:
if not op.translation.length() > self.compeps:
fails = False
for vec1 in lv:
transvec = vec1.transform(op.rotation)
if not (transvec == lv[0] or transvec == lv[1] or transvec == lv[2]
or transvec == -lv[0] or transvec == -lv[1] or transvec == -lv[2]):
fails = True
if fails:
raise SymmetryError("Lattice vectors do not fulfil the given symmetries of the lattice!\n"\
"The cell is given in some non-standard setting presently not handled by the program.")
#########################
# CELL GENERATION #
#########################
# Atomic species and the number of each species. Site occupancies.
for i in range(len(self.ineqsites)):
# Set up atomdata
self.atomdata.append([])
self.atomdata[i].append(AtomSite(position=self.ineqsites[i], label=self.sitelabels[i]))
# Add species and occupations to atomdata
for k,v in self.occupations[i].items():
self.atomdata[i][0].species[k] = v
# Add charge state
for k2,v2 in self.chargedict.items():
if k2.strip(string.punctuation+string.digits) == k:
self.atomdata[i][0].charges[k] = v2
## self.atomdata[i][0].charge = self.charges[i]
# Determine if we have an alloy
for element in self.occupations[i]:
v = self.occupations[i][element]
if abs(1-v) > occepsilon:
self.alloy = True
# Make sites unique with array of occupation info
removeindices = []
# set up atomdata
for i in range(len(self.atomdata)):
for j in range(len(self.atomdata)-1,i,-1):
if self.atomdata[i][0].position == self.atomdata[j][0].position:
# Add the dictionary of site j to that of site i and schedule index j for
# removal. If there is already an instance of the species on this site and
# the occupancy is different from 1, then add the occupancies (this happens
# when different valencies has been recorded).
# Now that the charge is stored, maybe this should be redone.
if self.atomdata[j][0].alloy:
for k in self.atomdata[j][0].species:
if k in self.atomdata[i][0].species:
v = self.atomdata[j][0].species[k] + self.atomdata[i][0].species[k]
self.atomdata[i][0].species[k] = v
else:
self.atomdata[i][0].species[k] = self.atomdata[j][0].species[k]
self.atomdata[i][0].charges.update(self.atomdata[j][0].charges)
removeindices.append(j)
# ...also fix self.occupations
self.occupations[i][list(self.occupations[j].keys())[0]] = list(self.occupations[j].values())[0]
# Remove duplicate elements
removeindices = list(set(removeindices))
removeindices.sort(reverse=True)
for i in removeindices:
self.atomdata.pop(i)
self.ineqsites.pop(i)
self.occupations.pop(i)
# Work out all sites in the cell for atomdata/atomset
for a in self.atomdata:
for op in self.symops:
# position expression string
posexpr = [s for s in op.eqsite]
for k in range(3):
# position expression string, replacing x,y,z with numbers
posexpr[k] = posexpr[k].replace('x',str(a[0].position[0]))
posexpr[k] = posexpr[k].replace('y',str(a[0].position[1]))
posexpr[k] = posexpr[k].replace('z',str(a[0].position[2]))
position = LatticeVector([safe_matheval(pos) for pos in posexpr])
b = AtomSite(position=position,species=a[0].species,charges=a[0].charges,label=a[0].label)
self.atomset.add(b)
append = True
for site in a:
for vec in self.transvecs:
t = vec + b.position
if site.position == t:
append=False
break
if not append:
break
if append:
a.append(b)
# Transform positions. Note that atomdata and atomset alias the same data,
# so we only transform once.
for a in self.atomdata:
for b in a:
b.position = LatticeVector(mvmult3(invlattrans,b.position))
# Weed out remaining duplicates. A weird special case that arises when
# different symmetry equivalent sites where listed in the input file.
# Attempts to handle this on the fly from the beginning made a complete
# mess of the alloy handling...
removeindices = set([])
for i in range(len(self.atomdata)):
for j in range(len(self.atomdata[i])):
for k in range(i+1,len(self.atomdata)):
for l in range(len(self.atomdata[k])):
if self.atomdata[i][j].position == self.atomdata[k][l].position:
removeindices.add((k,l))
removeindices = list(removeindices)
removeindices.sort(reverse=True)
for i,j in removeindices:
self.atomdata[i].pop(j)
# Check if any type is now completely empty
removeindices = []
for i in range(len(self.atomdata)):
if len(self.atomdata[i]) == 0:
removeindices.append(i)
removeindices.sort(reverse=True)
for i in removeindices:
self.atomdata.pop(i)
######################
# MISCELLANEOUS #
######################
# Chemical content dictionary
for a in self.atomdata:
for b in a:
for k,v in b.species.items():
if k in self.ChemicalComposition:
n = self.ChemicalComposition[k]
self.ChemicalComposition[k] = v+n
else:
self.ChemicalComposition[k] = v
if not self.alloy:
L = list(self.ChemicalComposition.values())
divisor = reduce(gcd,L)
for k,v in self.ChemicalComposition.items():
self.ChemicalComposition[k] = v/divisor
# Number of atoms
self.numberOfAtoms = self.natoms()
# Set flag and return the CrystalStructure in the conventional setting
self.initialized = True
return self
def transformCell(self, transformation):
"""
Applies transformation to bravais lattice vectors (and symmetry operations).
Only transformations involving rotations and an overall rescaling of the cell are allowed.
"""
r = LatticeMatrix(transformation)
fac = pow(abs(det3(r)),float(1)/3)
# Check that the transformation does not skew the cell.
oldanglen = set([CellFloat(self.latticevectors[0].angle(self.latticevectors[1])),
CellFloat(self.latticevectors[0].angle(self.latticevectors[2])),
CellFloat(self.latticevectors[1].angle(self.latticevectors[2])),
CellFloat(self.latticevectors[0].length()),
CellFloat(self.latticevectors[1].length()),
CellFloat(self.latticevectors[2].length())])
t = LatticeMatrix(mmmult3(self.latticevectors,r))
newanglen = set([CellFloat(t[0].angle(t[1])),
CellFloat(t[0].angle(t[2])),
CellFloat(t[1].angle(t[2])),
CellFloat(t[0].length()/fac),
CellFloat(t[1].length()/fac),
CellFloat(t[2].length()/fac)])
if oldanglen==newanglen or self.force:
self.latticevectors = t
self.lengthscale /= fac
# Transform symmetry operations
newsymops = set([])
for op in self.symops:
o = copy.copy(op)
o.rotation = LatticeMatrix(mmmult3(mmmult3(minv3(r),o.rotation),r))
o.improveprecision()
newsymops.add(o)
self.symops = newsymops
if oldanglen!=newanglen and self.force:
sys.stderr.write("***Error: The transformation matrix skews the lattice. Only combinations of \n"+
" rotations and rescaling of the whole cell are allowed.")
else:
raise CellError("The transformation matrix skews the lattice. Only combinations of "+
"rotations and rescaling of the whole cell are allowed.")
def getSuperCell(self, supercellmap, vacuum, prevactransvec, postvactransvec=[.0,.0,.0], sort=""):
"""
Returns a supercell based on the input supercell map, vacuum layers and translation vector.
The cell must have been initialized prior to calling getSuperCell.
The cell will be padded with some number of original unit cells of vacuum
by simple rescaling of the lattice vectors and positions. This is controlled by 'vacuum'.
Prior to addition of vacuum, all coordinates will be translated by 'prevactransvec',
which is given in units of the original lattice vectors. After the addition of vacuum,
all coordinates are translated by 'postvactransvec' (given in units of the final lattice).
"""
# Sanity checks
if not self.initialized:
raise CellError("The unit cell must be initialized before a supercell can be generated.")
if len(vacuum) != 3: #or vacuum[0] < 0 or vacuum[1] < 0 or vacuum[2] < 0:
raise CellError("The vacuum padding must be an array of three numbers >= 0.")
# Map matrix
try:
mapmatrix = LatticeMatrix([[supercellmap[0],0,0],[0,supercellmap[1],0],[0,0,supercellmap[2]]])
except:
try:
mapmatrix = supercellmap
except:
raise CellError("The supercell map must be a vector or a matrix.")
# Inverse of map matrix.
try:
invmapmatrix = LatticeMatrix(minv3(mapmatrix))
except:
raise CellError("The supercell map must be invertible.")
volratio = abs(det3(mapmatrix))
# Volume ratio must be a non-zero integer.
if abs(volratio-round(volratio,0)) > self.compeps:
raise CellError("The determinant of the supercell map must be a non-zero integer.")
## sys.stderr.write("***Warning: The determinant of the supercell map is a non-integer.\n")
## sys.stderr.write(" If you did not expect this warning, immediately stop to\n")
## sys.stderr.write(" rethink what you are doing.\n")
# New latticevectors from supercell map.
t = mmmult3(mapmatrix,self.latticevectors)
self.latticevectors = LatticeMatrix(t)
invlatvects = minv3(self.latticevectors)
# Set up new translation group (in new lattice vector coordinates).
# Determine limits for translation vector search
# (adapted from John Wills' cellgen program).
M = mapmatrix
#
lo = []
up = []
for i in range(3):
sumset = set([])
for j in range(3):
sumset.add(int(M[i][j]))
sumset.add(int(M[i][0])+int(M[i][1]))
sumset.add(int(M[i][0])+int(M[i][2]))
sumset.add(int(M[i][1])+int(M[i][2]))
sumset.add(int(M[i][0])+int(M[i][1])+int(M[i][2]))
sumset.add(int(M[i][0])-int(M[i][1]))
sumset.add(int(M[i][0])-int(M[i][2]))
sumset.add(int(M[i][1])-int(M[i][2]))
sumset.add(int(M[i][0])-int(M[i][1])-int(M[i][2]))
lo.append(min(sumset)-1) # Don't really understand why I need to add/subtract
up.append(max(sumset)+1) # 1 here... but things sometimes fail if I don't.
# Translation vector search
newtranslations = set([])
for k in range(lo[0], up[0]+1):
for j in range(lo[1], up[1]+1):
for i in range(lo[2], up[2]+1):
t = LatticeVector(mvmult3(invmapmatrix,[k,j,i])) # convert to new lattice coords
newtranslations.add(t)
# Remove identity translation.
newtranslations.remove(LatticeVector([0,0,0]))
# Transform original coordinates to new basis.
for a in self.atomdata:
for b in a:
b.position = LatticeVector(mvmult3(invmapmatrix,b.position))
for op in self.symops:
op.translation = LatticeVector(mvmult3(invmapmatrix,op.translation))
# Operate with new translation group on coordinates to generate all positions
newsites = []
i = 0
for a in self.atomdata:
newsites.append([])
for b in a:
for translation in newtranslations:
position = LatticeVector(b.position + translation)
t = AtomSite(position=b.position,species=b.species,charges=b.charges)
t.position = position
newsites[i].append(t)
i += 1
i = 0
for a in newsites:
for b in a:
self.atomdata[i].append(b)
self.atomset.add(b)
i += 1
# Move all atoms by prevactransvec
if reduce(lambda x,y: x+y, prevactransvec) != 0:
for i in range(len(self.atomdata)):
for j in range(len(self.atomdata[i])):
for k in range(3):
self.atomdata[i][j].position[k] = self.atomdata[i][j].position[k] + prevactransvec[k]
# Put stuff back in cell
for a in self.atomdata:
for b in a:
b.position.intocell()
# Put positions in cartesian coordinates for vacuum generation
for a in self.atomdata:
for b in a:
b.position = Vector(mvmult3(self.latticevectors,b.position))
# New latticevectors after vacuum padding
vacuummapmatrix = LatticeMatrix([[1,0,0],[0,1,0],[0,0,1]])
if reduce(lambda x,y: x+y, vacuum) > 0:
# add the given number of unit cell units along the lattice vectors
for j in range(len(vacuum)):
for i in range(len(self.latticevectors[j])):
self.latticevectors[j][i] = self.latticevectors[j][i] + self.latticevectors[j][i]*vacuum[j]
vacuummapmatrix[j][j] = vacuummapmatrix[j][j] + vacuum[j]
# Remap coordinates after padding
invlatvect = LatticeMatrix(minv3(self.latticevectors))
for a in self.atomdata:
for b in a:
b.position = LatticeVector(mvmult3(invlatvect, b.position))
# Move all atoms by postvactransvec
if reduce(lambda x,y: x+y, postvactransvec) != 0:
for i in range(len(self.atomdata)):
for j in range(len(self.atomdata[i])):
for k in range(3):
self.atomdata[i][j].position[k] = self.atomdata[i][j].position[k] + postvactransvec[k]
############ New space group operations ############
# Only sort out space group information for diagonal map matrix. !SHOULD BE FIXED GENERALLY!
eps = self.compeps
diagonal = abs(mapmatrix[0][1]) < eps and abs(mapmatrix[0][2]) < eps and abs(mapmatrix[1][2]) < eps and \
abs(mapmatrix[1][0]) < eps and abs(mapmatrix[2][0]) < eps and abs(mapmatrix[2][1]) < eps
if diagonal:
# Multiply group by new translation group
newops = []
i = 0
for vec in newtranslations:
for op in self.symops:
newops.append(SymmetryOperation())
newops[i].rotation = op.rotation
newops[i].translation = vec + op.translation
i += 1
for op in newops:
self.symops.add(op)
# Weed out rotations that are broken by supercell map
lv = self.latticevectors
removeset = set([])
# Ugly set of if's and special cases
# THIS WILL NOT WORK WITH GENERAL SUPERCELL MAP MATRIX
if self.crystal_system()=="hexagonal" or (self.crystal_system()=="trigonal" and not self.primcell):
if abs(lv[0].length()-lv[1].length()) < lv.compeps:
# if a and b are still the same, no rotation symmetry is broken
pass
else:
# if a and b are different, all rotation symmetries except inversion are broken
e = SymmetryOperation(["x","y","z"])
i = SymmetryOperation(["-x","-y","-z"])
for op in self.symops:
if op.rotation == e.rotation or op.rotation == i.rotation:
pass
else:
removeset.add(op)
elif self.crystal_system()=="trigonal" and self.primcell:
# if any latticevector has different length, all symmetries except inversion are broken
if abs(lv[0].length()-lv[1].length()) < lv.compeps and \
abs(lv[1].length()-lv[2].length()) < lv.compeps and \
abs(lv[0].length()-lv[2].length()) < lv.compeps:
pass
else:
e = SymmetryOperation(["x","y","z"])
i = SymmetryOperation(["-x","-y","-z"])
for op in self.symops:
if op.rotation == e.rotation or op.rotation == i.rotation:
pass
else:
removeset.add(op)
else:
for op in self.symops:
for vec in lv:
t = Vector(mvmult3(op.rotation,vec))
r = Vector([-u for u in t])
# Symmetry operation OK if it maps a lattice vector into one of the other lattice vectors
equivalent = t == lv[0] or t == lv[1] or t == lv[2] or \
r == lv[0] or r == lv[1] or r == lv[2]
if not equivalent:
removeset.add(op)
continue
# Weed out translations broken by the vacuum
for op in self.symops:
# check if vacuum padding destroys this translation
t = op.translation
for i in range(3):
if abs(t[i]) > self.compeps and abs(vacuum[i]) > self.compeps:
removeset.add(op)
# Remove broken symmetries
for op in self.symops:
for vec in lv:
t = Vector(mvmult3(op.rotation,vec))
else:
# Otherwise just keep identity
self.symops = set([SymmetryOperation(['x','y','z'])])
# Sort the atomic positions if requested.
if sort != "":