forked from MHoutput/1e2ph-spectral
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphonopyReaders.py
More file actions
4210 lines (3805 loc) · 184 KB
/
Copy pathphonopyReaders.py
File metadata and controls
4210 lines (3805 loc) · 184 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
"""
Classes that read and handle PhonoPy output .yaml files
Exported classes
----------------
PhonopyCalculation: base class
PhonopyMeshCalculation: read mesh calculation and calculate DOS
PhonopyBandCalculation: read band calculation along a path
PhonopyCommensurateCalculation: read and process commensurate points data
YCalculation: read finite E-field calculations and calculate T(omega)
Exported functions
------------------
get_modular_indices: get digits of number in a varying base
round_plot_range: get ronded axis limits for plotting
create_path: create a path if it doesn't already exist
n_BE: Bose-Einstein distribution function
Written by Matthew Houtput (matthew.houtput@uantwerpen.be)
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms
import scipy
import yaml
import warnings
import joblib
import itertools
def get_modular_indices(number, mod_list):
""" Breaks the input number up into a list of "digits"
Arguments
---------
number: int, number to be written in modular indices
mod_list: list of int, moduli used for digits
Returns
-------
modular_indices: list of int, the digits for the number
Most commonly used to traverse or create arrays with shape mod_list.
If mod_list = [b, b, b, ...], the digits correspond to the digits
of the input number in base b.
"""
mod = np.prod(mod_list)
if len(mod_list) == 0:
return np.array([number])
if len(mod_list) == 1:
return np.array([number % mod, number // mod])
else:
new_list = mod_list[0:-1]
return np.append(get_modular_indices(number % mod, new_list),
number // mod)
def round_plot_range(ymin, ymax, clamp_min=None, clamp_max=None, targets=None):
""" Returns rounded plot limits based on min and max of data
Arguments
---------
ymin: minimum y-value of the data on the plot
ymax: maximum y-value of the data on the plot
clamp_min: fixed lower limit, default None
clamp_max: fixed upper limit, default None
targets: list of real, round numbers used as rounding targets
Default: [0.0, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0,
3.5, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
Returns
-------
ymin_rounded: lower limit for the plot, equals clamp_min if not None
ymax_rounded: upper limit for the plot, equals clamp_max if not None
"""
if targets is None:
targets = [0.0, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0,
3.5, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
ceil_to = lambda x: targets[np.nonzero(targets > x)[0][0]]
if clamp_min is not None:
ymin_rounded = clamp_min
if clamp_max is not None:
ymax_rounded = clamp_max
else:
# ymax > clamp_min
rounding_scale = 10**np.floor(np.log10(ymax-clamp_min))
ymax_rounded = clamp_min+ceil_to((ymax-clamp_min)/rounding_scale)\
*rounding_scale
else:
if clamp_max is not None:
# ymin < clamp_max
ymax_rounded = clamp_max
rounding_scale = 10**np.floor(np.log10(clamp_max-ymin))
ymin_rounded = clamp_max-ceil_to((clamp_max-ymin)/rounding_scale)\
*rounding_scale
else:
# ymax > ymin
scale_avg = 10**np.floor(np.log10(ymax-ymin))
avg = 0.5*(ymin+ymax)
avg_round = round(avg/scale_avg)*scale_avg
scale_min = 10**np.floor(np.log10(avg_round-ymin))
ymin_rounded = avg_round-ceil_to((avg_round-ymin)/scale_min)\
*scale_min
scale_max = 10**np.floor(np.log10(ymax-avg_round))
ymax_rounded = avg_round+ceil_to((ymax-avg_round)/scale_max)\
*scale_max
return ymin_rounded, ymax_rounded
def create_path(filename):
""" Create necessary directories to save a file
When trying to save a file with a filename that contains
directories, the save fails if those directories do not exist yet.
This function creates the necessary directories that are present
in the name of the file, if they do not exist yet.
Arguments
---------
filename: str
Name of the file to be saved, or path to be created
"""
path_name, _ = os.path.split(filename)
path_norm = os.path.normpath(path_name)
spl_char = os.path.sep
dirs_to_check = [spl_char.join(path_norm.split(spl_char)[:i])
for i in range(1, len(path_norm.split(spl_char))+1)]
for direc in dirs_to_check:
if not os.path.isdir(direc):
os.mkdir(direc)
def n_BE(omega, temp):
""" Bose-Einstein distribution for phonon frequencies
Arguments
---------
omega: np.array of real
Phonon cycle frequencies at which to evaluate n_BE(omega),
in units of THz
temp: real
Temperature at which to evaluate n_BE
Returns
-------
n_BE: np.array of real, same shape as omega
Bose-Einstein distribution of the given omega
Raises
------
ValueError
when temp is smaller than zero
"""
if temp < 0:
raise ValueError("negative temperatures are not allowed")
if temp < 1e-10:
return (omega >= 0)-1
else:
return 1/(np.exp(47.9924307*omega/temp)-1)
class PhonopyCalculation:
""" Base class that all other classes inherit from
This class cannot be instanciated. Create instances of the
following child classes instead:
- PhonopyMeshCalculation
- PhonopyBandCalculation
- PhonopyCommensurateCalculation
- YCalculation
Attributes
----------
supercell_size: np.array of int
shape (3,)
reciprocal_lattice_vectors: np.array of real
shape (3,3), units of inverse Angstroms
lattice_vectors: np.array of real
shape (3,3), units of Angstroms
unitcell_volume: real
units of cubic Angstroms
num_dimensions: int
Equal to 3
natom: int
numqpoints: int
labels: list of (list of str) if band calculation, else None
segment_nqpoint: list of int if band calculation, else None
numbands: int
Equal to 3*natom
qpoints: np.array of real
shape (numqpoints, 3), in direct coordinates
distances: np.array of real
shape (numqpoints,)
weights: np.array of int
shape (numqpoints,)
frequencies: np.array of real
shape (numqpoints, numbands), stored as cycle frequencies in THz
eigenvectors: np.array of complex,
shape (numqpoints, numbands, natom, 3)
atom_names: np.array of str
shape (natom,)
atom_masses: np.array of real
shape (natom,), in atomic mass units
atom_positions: np.array of real
shape (natom, 3), in direct coordinates
born_is_set: bool
True if born_filename is read
born_charges: np.array of real
shape (natom, 3, 3)
dielectric_tensor: np.array of real
shape (3,3)
Raises
------
TypeError
when trying to create an instance of this class
"""
def __new__(cls, *args, **kwargs):
""" Ensure this class cannot be instanciated """
if cls is PhonopyCalculation:
raise TypeError(f"""only children of '{cls.__name__}'
may be instantiated""")
return object.__new__(cls)
def __init__(self, yaml_filename, born_filename=None):
""" PhonopyCalculation(yaml_filename, born_filename)
Arguments
---------
yaml_filename: string
.yaml file exported by PhonoPy
born_filename: string
BORN file that contains the Born effective charge tensors
and dielectric tensors.
Important: this function expects a BORN file with a line
for each atom, since no symmetry is implemented. PhonoPy
exports a BORN file with less lines based on symmetry,
which is not compatible with this code.
"""
self.load_yaml(yaml_filename)
self.load_BORN(born_filename)
def load_yaml(self, yaml_filename):
""" Load data from PhonoPy .yaml file
Automatically called from the constructor. Reads all data from
the PhonoPy .yaml file and stores them in the relevant class
attributes.
Arguments
---------
yaml_filename: string
.yaml file exported by PhonoPy to load in
"""
with open(yaml_filename, 'r') as file:
yaml_string = file.read()
file.close()
mesh_dict = yaml.safe_load(yaml_string)
self.supercell_size = np.array(mesh_dict.get('mesh', None))
self.reciprocal_lattice_vectors = \
np.array(mesh_dict['reciprocal_lattice'])
self.lattice_vectors = np.array(mesh_dict['lattice'])
self.unitcell_volume = np.abs(np.linalg.det(self.lattice_vectors))
self.num_dimensions = len(self.lattice_vectors[0])
self.natom = mesh_dict['natom']
self.numqpoints = mesh_dict['nqpoint']
self.labels = mesh_dict.get('labels', None)
self.segment_nqpoint = mesh_dict.get('segment_nqpoint', None)
phonon_props = mesh_dict['phonon']
eigenvectors_exist = 'eigenvector' in phonon_props[0]['band'][0]
self.numbands = self.num_dimensions*self.natom
self.qpoints = np.empty((self.numqpoints,self.num_dimensions))
self.distances = np.empty((self.numqpoints,))
self.weights = np.empty((self.numqpoints,))
self.frequencies = np.empty((self.numqpoints, self.numbands))
if eigenvectors_exist:
self.eigenvectors = np.empty((self.numqpoints, self.numbands,
self.natom, self.num_dimensions),
dtype=np.complex_)
else:
self.eigenvectors = None
for index, point in enumerate(phonon_props):
self.qpoints[index] = point['q-position']
if 'distance_from_gamma' in point:
self.distances[index] = point['distance_from_gamma']
if 'distance' in point:
self.distances[index] = point['distance']
self.weights[index] = point.get('weight', 1)
bands = point['band']
for nu, band in enumerate(bands):
self.frequencies[index, nu] = band['frequency']
if eigenvectors_exist:
eigenvector_list = np.array(band['eigenvector'])
self.eigenvectors[index, nu] = \
eigenvector_list[:,:,0]+eigenvector_list[:,:,1]*1j
atom_info = mesh_dict.get('points')
self.atom_names = np.empty((self.natom,), dtype=np.dtypes.StrDType)
self.atom_masses = np.empty((self.natom,))
self.atom_positions = np.empty((self.natom, self.num_dimensions))
for index, atom in enumerate(atom_info):
self.atom_names[index] = atom['symbol']
self.atom_masses[index] = atom['mass']
self.atom_positions[index] = atom['coordinates']
def load_BORN(self, born_filename):
""" Load data from BORN file
Automatically called from the constructor. Reads all data from
the PhonoPy BORN file and stores them in the relevant class
attributes.
Important: this function expects a BORN file with a line
for each atom, since no symmetry is implemented. PhonoPy
exports a BORN file with less lines based on symmetry,
which is not compatible with this code.
Arguments
---------
born_filename: string
BORN file to load in
"""
if born_filename is None:
self.born_is_set = False
self.born_charges = None
self.dielectric_tensor = None
else:
self.born_is_set = True
loaded_array = np.loadtxt(born_filename, dtype=float, comments="#")
self.dielectric_tensor = loaded_array[0,...].reshape((3,3))
self.born_charges = loaded_array[1:,...].reshape((-1,3,3))
def get_supercell_size(self):
""" Return the supercell size """
return self.supercell_size
def get_unitcell_volume(self):
""" Return the unit cell volume in cubic Angstroms """
return self.unitcell_volume
def get_distances(self):
""" Return the distances along a q-point path """
return self.distances
def get_eigenvectors(self, convention="c-type"):
""" Return the phonon eigenvectors as a 4D array
Can return either the eigenvectors in the c-type convention
(default convention used by PhonoPy), or the d-type convention.
Arguments
---------
convention: string
Must be either "c-type" or "d-type"
Returns
-------
eigenvectors: np.array of complex
shape (numqpoints, numbands, natom, num_dimensions)
Raises
------
NameError
when input convention is neither "c-type" nor "d-type"
"""
match convention:
case "c-type":
return self.eigenvectors
case "d-type":
phases = np.exp(2*np.pi*1j* self.get_qpoints()
@ self.get_atom_positions().T)
return ((phases.T) * (self.eigenvectors.transpose((3,1,2,0))))\
.transpose(3,1,2,0)
case _:
raise NameError("convention must be c-type or d-type")
def get_eigenvectors_matrices(self, convention="c-type"):
""" Return the phonon eigenvectors as a 3D array
Can return either the eigenvectors in the c-type convention
(default convention used by PhonoPy), or the d-type convention.
Arguments
---------
convention: string
Must be either "c-type" or "d-type"
Returns
-------
eigenvectors: np.array of complex
shape (numqpoints, numbands, numbands)
Raises
------
NameError
when input convention is neither "c-type" nor "d-type"
"""
return self.get_eigenvectors(convention)\
.reshape(-1,self.numbands,self.numbands)
def get_frequencies(self, unit="THz"):
""" Return the phonon frequencies in the desired units
Arguments
---------
unit: string
Must be one of the units supported in convert_units
Returns
-------
frequencies: np.array of real
shape (numqpoints, numbands)
Imaginary frequencies are output as negative frequencies
Raises
------
NameError
when input unit is not one of the recognized units
"""
return self.convert_units(self.frequencies, to_unit=unit)
def get_frequencies_matrices(self, unit="THz"):
""" Return phonon frequencies as a stack of diagonal matrices
Arguments
---------
unit: string
Must be one of the units supported in convert_units
Returns
-------
frequencies: np.array of real
shape (numqpoints, numbands, numbands)
Imaginary frequencies are output as negative frequencies
Raises
------
NameError
when input unit is not one of the recognized units
"""
frequencies = self.get_frequencies(unit)
frequencies_matrices = np.empty((self.numqpoints, self.numbands,
self.numbands))
for index, freqs in enumerate(frequencies):
frequencies_matrices[index,...] = np.diag(freqs)
return frequencies_matrices
def get_dynamical_matrices(self, unit="THz", convention="c-type"):
""" Calculate and return dynamical matrices
Arguments
---------
unit: string
Must be one of the units supported in convert_units
convention: string
Must be either "c-type" or "d-type"
Returns
-------
dynamical_matrices: np.array of complex
shape (numqpoints, numbands, numbands)
Dynamical matrices evaluated at self.qpoints
Raises
------
NameError
when input unit is not one of the recognized units
"""
frequencies_matrices = self.get_frequencies_matrices(unit)
eigenvectors_matrices = self.get_eigenvectors_matrices(convention)
dynamical_matrices = np.empty((self.numqpoints, self.numbands,
self.numbands), dtype=np.complex_)
for index, freqs_vecs in enumerate(zip(frequencies_matrices,
eigenvectors_matrices)):
freqs_squared = np.sign(freqs_vecs[0])*np.power(freqs_vecs[0], 2)
eigvecs = freqs_vecs[1]
dynamical_matrices[index,...] = \
eigvecs.T @ freqs_squared @ eigvecs.conj()
return dynamical_matrices
def get_lattice_vectors(self):
""" Return the lattice vectors in Angstroms """
return self.lattice_vectors
def get_reciprocal_lattice_vectors(self):
""" Return the reciprocal lattice vectors in inverse Angstroms """
return self.reciprocal_lattice_vectors
def get_qpoints(self):
""" Return the list of q-points included in the dataset """
return self.qpoints
def get_lpoints(self):
""" Return a list of lattice vectors in the supercell """
modulos = self.supercell_size
return np.array([get_modular_indices(n, modulos[0:-1])
for n in range(np.prod(modulos))])
def get_dense_qmesh(self, size, fixed_indices=np.array([]),
num_dimensions=None):
""" Return a mesh of q-points for Brillouin zone integration
Arguments
---------
size: int or np.ndarray() of int, shape (3,)
Number of q-points in each direction (e.g. 16x16x16)
If int, uses the same number for all directions
If np.ndarray(), uses these numbers for each direction
fixed_indices: np.ndarray() of real
Keep one or more coordinates fixed. For example, if
fixed_indices = np.array([0.1, 0.2]), the coordinates will
be of the form [q1, 0.1, 0.2] with varying q1
Useful for very large meshes where it is impractical to
store the entire mesh in one array
Default: No indices fixed
num_dimensions: int
Number of coordinates, usually 3
Default: self.num_dimensions
Returns
-------
q_mesh: np.array of real
shape (size**3, 3) or (prod(size), 3)
Array of q-points in the mesh, in direct coordinates
Raises
------
ValueError
when size is not an int or np.ndarray()
"""
if num_dimensions is None:
num_dimensions=self.num_dimensions
num_free = num_dimensions - len(fixed_indices)
match size:
case int():
modulos = np.repeat(size, num_free)
case np.ndarray():
modulos = np.floor(size).astype(int).flatten()[0:num_free]
case _:
raise ValueError("""size must be one integer
or a numpy array of integers""")
total_size = np.prod(modulos)
result = np.empty((total_size,num_dimensions))
result[:,:num_free] = np.array([get_modular_indices(n, modulos[0:-1])
for n in range(total_size)]) / modulos
result[:,num_free:] = fixed_indices
return result
def get_Gpoints(self, cutoff_radius, include_zero=True):
""" Generate list of reciprocal lattice points around Gamma
Arguments
---------
cutoff_radius: real
All reciprocal lattice points within a reciprocal distance
cutoff_radius of Gamma are included in the list
include_zero: bool
Output does not include G=0 if set to false
Returns
-------
Gpoints: np.array of real
shape (:, 3), array of reciprocal lattice points
"""
metric = self.reciprocal_lattice_vectors @ \
self.reciprocal_lattice_vectors.T
Gnorm = lambda G: np.linalg.norm(G @ self.reciprocal_lattice_vectors,
axis=-1)
eigenvalues, eigenvectors = np.linalg.eigh(metric)
m_cutoff = np.ceil(cutoff_radius \
/np.sqrt(np.min(eigenvalues))).astype(int)
modulos = (2*m_cutoff+1)*np.ones((self.num_dimensions-1,), dtype=int)
Gpoints = np.array([get_modular_indices(n, modulos) - m_cutoff
for n in range((2*m_cutoff+1)**self.num_dimensions)
if Gnorm(get_modular_indices(n, modulos) - m_cutoff)
< cutoff_radius])
if not include_zero:
for zero_index in np.nonzero(np.linalg.norm(Gpoints, ord=2, axis=1)
< 1e-10)[0]:
Gpoints = np.delete(Gpoints, zero_index, axis=0)
return Gpoints
def get_weights(self):
"""Return weights for Brillouin zone integration"""
return self.weights
def get_atom_names(self):
"""Return names of atoms in the unit cell"""
return self.atom_names
def get_atom_masses(self):
"""Return masses of atoms in the unit cell"""
return self.atom_masses
def get_mass_matrix(self):
"""Return masses of atoms in diagonal matrix form
Returns
-------
maxx_matrix: np.array of real
shape (self.numbands, self.numbands)
"""
return np.diag(np.tile(self.get_atom_masses(),
(self.num_dimensions,1)).T.reshape(-1))
def get_atom_positions(self):
"""Return positions of atoms in the unit cell"""
return self.atom_positions
def get_atom_positions_3N(self):
""" Returns the atom positions repeated 3 times in a single array
Useful for the dynamical matrix conventions
"""
return np.reshape(np.array([np.tile(self.get_atom_positions()[i],
(self.num_dimensions,1))
for i in range(self.natom)]),
(self.numbands, self.num_dimensions))
def get_tauk_difference(self):
""" Returns the quantity tau_k - tau_k'
Useful to change between dynamical matrix conventions
Returns
-------
tauk_difference: np.array of real
shape (self.numbands, self.numbands, 3)
"""
return ( self.get_atom_positions_3N().reshape(self.numbands, 1,
self.num_dimensions)
-self.get_atom_positions_3N().reshape(1, self.numbands,
self.num_dimensions) )
def get_c_to_d_factors(self, qs):
""" Factors to convert from c-type to d-type convention
Arguments
---------
qs: np.array of real
shape (:, 3)
q-points in which the dynamical matrix is to be calculated
Returns
-------
conversion_factors: np.array of complex
shape (len(qs), self.numbands, self.numbands)
Conversion factors to convert a stack of dynamical matrices
in the c-type convention to the d-type convention
"""
return np.exp(2*np.pi*1j*np.moveaxis(self.get_tauk_difference() @ qs.T,
[0,1,2], [1,2,0]))
def get_d_to_c_factors(self, qs):
""" Factors to convert from d-type to c-type convention
Equal to the complex conjugate of self.get_d_to_c_factors
Arguments
---------
qs: np.array of real
shape (:, 3)
q-points in which the dynamical matrix is to be calculated
Returns
-------
conversion_factors: np.array of complex
shape (len(qs), self.numbands, self.numbands)
Conversion factors to convert a stack of dynamical matrices
in the d-type convention to the c-type convention
"""
return np.exp(-2*np.pi*1j*np.moveaxis(self.get_tauk_difference() @ qs.T,
[0,1,2], [1,2,0]))
def convert_units(self, frequencies, from_unit="THz", to_unit="THz"):
""" Convert phonon frequencies between units
The supported units are:
- "THz": cycle frequencies in THz
- "rad/s": radial frequencies in rad/s
- "cm-1": inverse wavelengths in inverse cm
- "eV": phonon energies in eV
- "PhonoPy": internal units used by PhonoPy
Arguments
---------
frequencies: np.array of real
Frequencies expressed in from_unit
from_unit: string
to_unit: string
Returns
-------
frequencies: np.array of real
Frequencies expressed in to_unit
Raises
------
warning
when from_unit or to_unit is not one of the supported units
"""
match from_unit:
case "THz":
frequencies_in_THz = frequencies
case "rad/s":
frequencies_in_THz = frequencies/(2*np.pi*1e12)
case "cm-1":
frequencies_in_THz = frequencies/33.356409529
case "eV":
frequencies_in_THz = frequencies/4.135667696e-3
case "PhonoPy":
frequencies_in_THz = frequencies*15.633302
case _:
warn_string = str(from_unit)+\
""" is not a recognized phonon frequency unit.
Currently only 'THz', 'rad/s', 'cm-1', 'eV', and 'PhonoPy'
are supported. It is assumed that the input frequencies
were in THz."""
warnings.warn(warn_string)
frequencies_in_THz = frequencies
match to_unit:
case "THz":
return frequencies_in_THz
case "rad/s":
return frequencies_in_THz*(2*np.pi*1e12)
case "cm-1":
return frequencies_in_THz*33.356409529
case "eV":
return frequencies_in_THz*4.135667696e-3
case "PhonoPy":
return frequencies_in_THz/15.633302
case _:
warn_string = str(to_unit)+\
""" is not a recognized phonon frequency unit.
Currently only 'THz', 'rad/s', 'cm-1', 'eV', and 'PhonoPy'
are supported. Frequencies in THz were returned instead."""
warnings.warn(warn_string)
return frequencies_in_THz
def get_clean_frequencies(self, unit='THz', cutoff=None, min_value=None,
frequencies_to_clean=None):
""" Remove any negative frequencies and small frequencies
Default behavior: Set any negative requencies to 1e-10 THz
if their absolute value is smaller than 0.1 THz
Throws a warning when large negative frequencies are detected
Arguments
---------
unit: string, frequency unit in which inputs are given
Default: "THz"
cutoff: real, threshold for determining small frequencies
Default: 0.1 THz
min_value: real, set small frequencies to this value
Default: 1e-10 THz
frequencies_to_clean: np.array of real
Array of frequencies that must be cleaned in the above way
Default: self.frequencies
Returns
-------
clean frequencies: np.array of real
Array of positive frequencies with shape equal to that
of frequencies_to_clean
Raises
------
warning
when one of the frequencies is smaller than -cutoff, which
indicates a significantly unstable phonon mode
"""
if frequencies_to_clean is None:
clean_frequencies = self.get_frequencies(unit=unit)
else:
clean_frequencies = 1.0*frequencies_to_clean
if cutoff is None:
cutoff = self.convert_units(0.1, from_unit='THz', to_unit=unit)
if min_value is None:
min_value = self.convert_units(1e-10, from_unit='THz', to_unit=unit)
indices = np.nonzero(clean_frequencies < min_value)
throw_warning = False
for index, frequency in enumerate(clean_frequencies[indices]):
clean_frequencies[indices[0][index], indices[1][index]] = min_value
if frequency < -cutoff:
throw_warning = True
if throw_warning:
warn_string = "Negative frequencies smaller than -"+str(cutoff)+" "\
+unit+" detected: material is likely unstable"
warnings.warn(warn_string)
return clean_frequencies
def clean_frequencies(self, cutoff=0.1):
""" Call get_clean_frequencies() on self.clean_frequencies """
self.frequencies = self.get_clean_frequencies(cutoff=cutoff)
return self.frequencies
def clean_qpoints(self):
""" Reduce all q-point coordinates to the range ]-0.5,0.5] """
normalize_to_range = lambda x: ((x - 0.5) % -1) + 0.5
self.qpoints = normalize_to_range(self.qpoints)
return self.qpoints
def parse_path(self, path, path_labels, npoints=51):
"""Convert a given path to a list of q-points and plot inputs
Arguments
---------
path: list of list of list of real
High-symmetry path, written in direct coordinates in the same
conventions as PhonoPy and pathsLabels.py
- First level: list of connected path segments
- Second level: list of points that mark path segments
- Third level: direct coordinates of points
path_labels: list of str
List of names of the edge points of the path, in order,
written in LaTeX markup
npoints: number of q-points on each segment
Returns
-------
qs: np.array of real
shape(:, 3), list of q-points on the path
distances: np.array of real
shape(:), reciprocal distances along the path, used as
x-axis data on a plot of phonon bands
xaxis_labels: list of str
Size: one more than number of segments in the path
List of labels of special points, to plot on the x-axis
on a plot of phonon bands
jump_indices: np.array of int
Indices where the path shows a discontinuous jump
"""
qs = []
distances_to_nearest = []
xaxis_labels = [path_labels[0]]
label_count = 1
do_between_code = False
for mini_path in path:
if do_between_code:
# Change the last label A to something of the form "A|B"
# to indicate a discontinuous jump
xaxis_labels[-1] += "$|$" + path_labels[label_count]
label_count += 1
else:
do_between_code = True
qs_mini = []
for i in range(len(mini_path)-1):
qs_to_append = np.linspace(mini_path[i], mini_path[i+1],
npoints)
qs.append(qs_to_append)
qs_mini.append(qs_to_append)
xaxis_labels.append(path_labels[label_count])
label_count += 1
qs_mini = np.array(qs_mini).reshape((-1,3))
# Calculate list of distances between two neighbouring points
qs_cartesian = qs_mini @ self.get_reciprocal_lattice_vectors()
distances_mini = np.zeros((len(qs_mini),), dtype=float)
distances_mini[1:] = np.linalg.norm(qs_cartesian[1:]-\
qs_cartesian[:-1], axis=1)
distances_to_nearest.extend(distances_mini.tolist())
jump_indices = np.cumsum((np.array([len(x) for x in path])-1)\
*npoints)[:-1] - 1
qs = np.array(qs).reshape((-1,3))
distances = np.cumsum(np.array(distances_to_nearest))
return qs, distances, xaxis_labels, jump_indices
def get_Brillouin_boundary(self, reciprocal_lattice_vectors=None):
""" Calculates corners, edges, and planes of the Brillouin zone
Returns the Miller indices of the planes that make up the edge
of the first Brillouin zone, as well as a list of all the
corners and edges on its surface. This is useful for plotting
the Brillouin zone.
Only works when self.num_dimensions = 3
This code is heavily based off the code found at
http://lampz.tugraz.at/~hadley/ss1/bzones/drawing_BZ.php
Arguments
---------
reciprocal_lattice_vectors: np.array of real
shape (3,3), units of inverse Angstroms
Default: self.reciprocal_lattice_vectors
Returns
-------
miller_indices: np.array of int
shape (:,3)
Miller indices of faces of the Brillouin zone
corners: np.array of real
shape (:,3)
Cartesian coordinates of the corners of the Brillouin zone
edges: np.array of real
shape (:,2,3)
Cartesian coordinates of pairs of corners that define
the edges of the Brillouin zone
edge_planes: np.array of int
shape (:,2,3)
Miller indices of pairs of planes that intersect at the
edges of the Brillouin zone
"""
if reciprocal_lattice_vectors is None:
reciprocal_lattice_vectors = self.get_reciprocal_lattice_vectors()
num_dimensions = len(reciprocal_lattice_vectors)
# Get the 26 G-vectors surrounding Gamma
cutoff = 1
modulos = (2*cutoff+1)*np.ones((num_dimensions-1,), dtype=int)
Gpoints = np.array([get_modular_indices(n, modulos) - cutoff
for n in range((2*cutoff+1)**num_dimensions)])
for zero_index in np.nonzero(np.linalg.norm(Gpoints, ord=2, axis=1)
< 1e-10)[0]:
Gpoints = np.delete(Gpoints, zero_index, axis=0)
Gcart = Gpoints @ reciprocal_lattice_vectors
# Find the distances from the planes to Gamma and the other reciprocal
# points
accepted_Gs = []
accepted_Gscart = []
for index, G1cart in enumerate(Gcart):
gamma_distance = np.linalg.norm(0.5*G1cart, ord=2)
G_distances = np.linalg.norm(0.5*G1cart - Gcart, ord=2, axis=1)
G_distances[index] = np.nan
if np.nanmin(G_distances) > gamma_distance:
accepted_Gs.append(Gpoints[index])
accepted_Gscart.append(G1cart)
# Find all corners as intersections of three planes
corners = []
for G1, G2, G3 in itertools.combinations(accepted_Gscart, 3):
# Iterate over all triplets of planes
system_matrix = np.array([G1,G2,G3])
if np.linalg.det(system_matrix) != 0:
system_RHS = 0.5*np.linalg.norm(system_matrix, ord=2, axis=1)**2
solution = np.linalg.solve(system_matrix, system_RHS)
corners.append(solution)
accepted_corners = []
for index, corner in enumerate(corners):
gamma_distance = np.linalg.norm(corner, ord=2)
G_distances = np.linalg.norm(corner - Gcart, ord=2, axis=1)
if np.nanmin(G_distances) - gamma_distance >= -1e-10:
accept_corner = True
for corner2 in accepted_corners:
if np.min(np.linalg.norm(corner-corner2, ord=2)) < 1e-10:
accept_corner = False # Only accept unique corners
if accept_corner:
accepted_corners.append(corner)
# Find all edges, by checking every pair of corners and whether they
# are both on the same two planes
accepted_edges = []
accepted_edge_planes = []
for G1, G2 in itertools.combinations(accepted_Gs, 2):
# Iterate over all pairs of planes
G1_cart = G1 @ reciprocal_lattice_vectors
G2_cart = G2 @ reciprocal_lattice_vectors
for corner1, corner2 in itertools.combinations(accepted_corners, 2):
# Iterate over all pairs of corners
distance_11 = np.abs(G1_cart@corner1-0.5*G1_cart@G1_cart)
distance_12 = np.abs(G2_cart@corner1-0.5*G2_cart@G2_cart)
distance_21 = np.abs(G1_cart@corner2-0.5*G1_cart@G1_cart)
distance_22 = np.abs(G2_cart@corner2-0.5*G2_cart@G2_cart)
if (distance_11 < 1e-10 and distance_12 < 1e-10 \
and distance_21 < 1e-10 and distance_22 < 1e-10):
# The edge is defined by two corners
accepted_edges.append([corner1, corner2])
# We also keep the two planes that the edges are on
accepted_edge_planes.append([G1, G2])
miller_indices = np.array(accepted_Gs)
corners = np.array(accepted_corners)
edges = np.array(accepted_edges)
edge_planes = np.array(accepted_edge_planes)
return miller_indices, corners, edges, edge_planes
def plot_Brillouin(self, reciprocal_lattice_vectors=None, path=[],
path_labels=[], label_shifts=None, view_angles=None,
save_filename=None, save_bbox_extents=None,
quiver_plot=None, quiver_labels=None,
visible_linestyle=None, invisible_linestyle=None,
path_linestyle=None, label_style=None,
quiver_style=None, quiver_label_style=None):
""" Makes a plot of the first Brillouin zone in 3D