-
Notifications
You must be signed in to change notification settings - Fork 874
/
outputs.py
2157 lines (1884 loc) · 89 KB
/
outputs.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
"""
Module for reading Lobster output files. For more information
on LOBSTER see www.cohp.de.
If you use this module, please cite:
J. George, G. Petretto, A. Naik, M. Esters, A. J. Jackson, R. Nelson, R. Dronskowski, G.-M. Rignanese, G. Hautier,
"Automated Bonding Analysis with Crystal Orbital Hamilton Populations",
ChemPlusChem 2022, e202200123,
DOI: 10.1002/cplu.202200123.
"""
from __future__ import annotations
import collections
import fnmatch
import itertools
import os
import re
import warnings
from collections import defaultdict
from typing import TYPE_CHECKING
import numpy as np
from monty.io import zopen
from monty.json import MSONable
from pymatgen.core.structure import Structure
from pymatgen.electronic_structure.bandstructure import LobsterBandStructureSymmLine
from pymatgen.electronic_structure.core import Orbital, Spin
from pymatgen.electronic_structure.dos import Dos, LobsterCompleteDos
from pymatgen.io.vasp.inputs import Kpoints
from pymatgen.io.vasp.outputs import Vasprun, VolumetricData
from pymatgen.util.due import Doi, due
if TYPE_CHECKING:
from typing import Any
from pymatgen.core.structure import IStructure
from pymatgen.util.typing import PathLike
__author__ = "Janine George, Marco Esters"
__copyright__ = "Copyright 2017, The Materials Project"
__version__ = "0.2"
__maintainer__ = "Janine George "
__email__ = "[email protected]"
__date__ = "Dec 13, 2017"
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
due.cite(
Doi("10.1002/cplu.202200123"),
description="Automated Bonding Analysis with Crystal Orbital Hamilton Populations",
)
class Cohpcar:
"""Read COHPCAR/COOPCAR/COBICAR files generated by LOBSTER.
Attributes:
cohp_data (dict[str, Dict[str, Any]]): A dictionary containing the COHP data of the form:
{bond: {"COHP": {Spin.up: cohps, Spin.down:cohps},
"ICOHP": {Spin.up: icohps, Spin.down: icohps},
"length": bond length,
"sites": sites corresponding to the bond}
Also contains an entry for the average, which does not have a "length" key.
efermi (float): The Fermi energy in eV.
energies (Sequence[float]): Sequence of energies in eV. Note that LOBSTER shifts the energies
so that the Fermi energy is at zero.
is_spin_polarized (bool): Boolean to indicate if the calculation is spin polarized.
orb_cohp (dict[str, Dict[str, Dict[str, Any]]]): A dictionary containing the orbital-resolved COHPs of the form:
orb_cohp[label] = {bond_data["orb_label"]: {
"COHP": {Spin.up: cohps, Spin.down:cohps},
"ICOHP": {Spin.up: icohps, Spin.down: icohps},
"orbitals": orbitals,
"length": bond lengths,
"sites": sites corresponding to the bond},
}
"""
def __init__(
self,
are_coops: bool = False,
are_cobis: bool = False,
are_multi_center_cobis: bool = False,
filename: PathLike | None = None,
) -> None:
"""
Args:
are_coops: Determines if the file includes COOPs.
Default is False for COHPs.
are_cobis: Determines if the file is a list of COHPs or COBIs.
Default is False for COHPs.
are_multi_center_cobis: Determines if the file include multi-center COBIS.
Default is False for two-center cobis.
filename: Name of the COHPCAR file. If it is None, the default
file name will be chosen, depending on the value of are_coops.
"""
if (
(are_coops and are_cobis)
or (are_coops and are_multi_center_cobis)
or (are_cobis and are_multi_center_cobis)
):
raise ValueError("You cannot have info about COOPs, COBIs and/or multi-center COBIS in the same file.")
self.are_coops = are_coops
self.are_cobis = are_cobis
self.are_multi_center_cobis = are_multi_center_cobis
if filename is None:
if are_coops:
filename = "COOPCAR.lobster"
elif are_cobis or are_multi_center_cobis:
filename = "COBICAR.lobster"
else:
filename = "COHPCAR.lobster"
with zopen(filename, mode="rt") as file:
contents = file.read().split("\n")
# The parameters line is the second line in a COHPCAR file. It
# contains all parameters that are needed to map the file.
parameters = contents[1].split()
# Subtract 1 to skip the average
num_bonds = int(parameters[0]) if self.are_multi_center_cobis else int(parameters[0]) - 1
self.efermi = float(parameters[-1])
self.is_spin_polarized = int(parameters[1]) == 2
spins = [Spin.up, Spin.down] if int(parameters[1]) == 2 else [Spin.up]
cohp_data: dict[str, dict[str, Any]] = {}
if not self.are_multi_center_cobis:
# The COHP data start in row num_bonds + 3
data = np.array([np.array(row.split(), dtype=float) for row in contents[num_bonds + 3 :]]).transpose()
cohp_data = {
"average": {
"COHP": {spin: data[1 + 2 * s * (num_bonds + 1)] for s, spin in enumerate(spins)},
"ICOHP": {spin: data[2 + 2 * s * (num_bonds + 1)] for s, spin in enumerate(spins)},
}
}
else:
# The COBI data start in row num_bonds + 3 if multi-center cobis exist
data = np.array([np.array(row.split(), dtype=float) for row in contents[num_bonds + 3 :]]).transpose()
self.energies = data[0]
orb_cohp: dict[str, Any] = {}
# present for Lobster versions older than Lobster 2.2.0
very_old = False
# the labeling had to be changed: there are more than one COHP for each atom combination
# this is done to make the labeling consistent with ICOHPLIST.lobster
bond_num = 0
bond_data = {}
label = ""
for bond in range(num_bonds):
if not self.are_multi_center_cobis:
bond_data = self._get_bond_data(contents[3 + bond])
label = str(bond_num)
orbs = bond_data["orbitals"]
cohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 3] for s, spin in enumerate(spins)}
icohp = {spin: data[2 * (bond + s * (num_bonds + 1)) + 4] for s, spin in enumerate(spins)}
if orbs is None:
bond_num += 1
label = str(bond_num)
cohp_data[label] = {
"COHP": cohp,
"ICOHP": icohp,
"length": bond_data["length"],
"sites": bond_data["sites"],
"cells": None,
}
elif label in orb_cohp:
orb_cohp[label].update(
{
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
"cells": bond_data["cells"],
}
}
)
else:
# present for Lobster versions older than Lobster 2.2.0
if bond_num == 0:
very_old = True
if very_old:
bond_num += 1
label = str(bond_num)
orb_cohp[label] = {
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
"cells": bond_data["cells"],
}
}
else:
bond_data = self._get_bond_data(contents[2 + bond], are_multi_center_cobis=self.are_multi_center_cobis)
label = str(bond_num)
orbs = bond_data["orbitals"]
cohp = {spin: data[2 * (bond + s * (num_bonds)) + 1] for s, spin in enumerate(spins)}
icohp = {spin: data[2 * (bond + s * (num_bonds)) + 2] for s, spin in enumerate(spins)}
if orbs is None:
bond_num += 1
label = str(bond_num)
cohp_data[label] = {
"COHP": cohp,
"ICOHP": icohp,
"length": bond_data["length"],
"sites": bond_data["sites"],
"cells": bond_data["cells"],
}
elif label in orb_cohp:
orb_cohp[label].update(
{
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
}
)
else:
# present for Lobster versions older than Lobster 2.2.0
if bond_num == 0:
very_old = True
if very_old:
bond_num += 1
label = str(bond_num)
orb_cohp[label] = {
bond_data["orb_label"]: {
"COHP": cohp,
"ICOHP": icohp,
"orbitals": orbs,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
}
# present for lobster older than 2.2.0
if very_old:
for bond_str in orb_cohp:
cohp_data[bond_str] = {
"COHP": None,
"ICOHP": None,
"length": bond_data["length"],
"sites": bond_data["sites"],
}
self.orb_res_cohp = orb_cohp or None
self.cohp_data = cohp_data
@staticmethod
def _get_bond_data(line: str, are_multi_center_cobis: bool = False) -> dict:
"""Subroutine to extract bond label, site indices, and length from
a LOBSTER header line. The site indices are zero-based, so they
can be easily used with a Structure object.
Example header line: No.4:Fe1->Fe9(2.4524893531900283)
Example header line for orbital-resolved COHP:
No.1:Fe1[3p_x]->Fe2[3d_x^2-y^2](2.456180552772262)
Args:
line: line in the COHPCAR header describing the bond.
are_multi_center_cobis: indicates multi-center COBIs
Returns:
Dict with the bond label, the bond length, a tuple of the site
indices, a tuple containing the orbitals (if orbital-resolved),
and a label for the orbitals (if orbital-resolved).
"""
if not are_multi_center_cobis:
line_new = line.rsplit("(", 1)
length = float(line_new[-1][:-1])
sites = line_new[0].replace("->", ":").split(":")[1:3]
site_indices = tuple(int(re.split(r"\D+", site)[1]) - 1 for site in sites)
# TODO: get cells here as well
if "[" in sites[0]:
orbs = [re.findall(r"\[(.*)\]", site)[0] for site in sites]
orb_label, orbitals = get_orb_from_str(orbs)
else:
orbitals = None
orb_label = None
return {
"length": length,
"sites": site_indices,
"cells": None,
"orbitals": orbitals,
"orb_label": orb_label,
}
line_new = line.rsplit(sep="(", maxsplit=1)
sites = line_new[0].replace("->", ":").split(":")[1:]
site_indices = tuple(int(re.split(r"\D+", site)[1]) - 1 for site in sites)
cells = [[int(i) for i in re.split(r"\[(.*?)\]", site)[1].split(" ") if i != ""] for site in sites]
# test orbitalwise implementations!
if sites[0].count("[") > 1:
orbs = [re.findall(r"\]\[(.*)\]", site)[0] for site in sites]
orb_label, orbitals = get_orb_from_str(orbs)
else:
orbitals = None
orb_label = None
return {
"sites": site_indices,
"cells": cells,
"length": None,
"orbitals": orbitals,
"orb_label": orb_label,
}
class Icohplist(MSONable):
"""Read ICOHPLIST/ICOOPLIST files generated by LOBSTER.
Attributes:
are_coops (bool): Indicates whether the object is consisting of COOPs.
is_spin_polarized (bool): Boolean to indicate if the calculation is spin polarized.
Icohplist (dict[str, Dict[str, Union[float, int, Dict[Spin, float]]]]): Dict containing the
listfile data of the form: {
bond: "length": bond length,
"number_of_bonds": number of bonds
"icohp": {Spin.up: ICOHP(Ef) spin up, Spin.down: ...}
}
IcohpCollection (IcohpCollection): IcohpCollection Object.
"""
def __init__(
self,
are_coops: bool = False,
are_cobis: bool = False,
filename: PathLike | None = None,
is_spin_polarized: bool = False,
orbitalwise: bool = False,
icohpcollection=None,
):
"""
Args:
are_coops: Determines if the file is a list of ICOOPs.
Defaults to False for ICOHPs.
are_cobis: Determines if the file is a list of ICOBIs.
Defaults to False for ICOHPs.
filename: Name of the ICOHPLIST file. If it is None, the default
file name will be chosen, depending on the value of are_coops
is_spin_polarized: Boolean to indicate if the calculation is spin polarized
icohpcollection: IcohpCollection Object.
"""
self._filename = filename
self.is_spin_polarized = is_spin_polarized
self.orbitalwise = orbitalwise
self._icohpcollection = icohpcollection
if are_coops and are_cobis:
raise ValueError("You cannot have info about COOPs and COBIs in the same file.")
self.are_coops = are_coops
self.are_cobis = are_cobis
if filename is None:
if are_coops:
filename = "ICOOPLIST.lobster"
elif are_cobis:
filename = "ICOBILIST.lobster"
else:
filename = "ICOHPLIST.lobster"
# LOBSTER list files have an extra trailing blank line
# and we don't need the header.
if self._icohpcollection is None:
with zopen(filename, mode="rt") as file:
data = file.read().split("\n")[1:-1]
if len(data) == 0:
raise RuntimeError("ICOHPLIST file contains no data.")
# Which Lobster version?
if len(data[0].split()) == 8:
version = "3.1.1"
elif len(data[0].split()) == 6:
version = "2.2.1"
warnings.warn("Please consider using the new Lobster version. See www.cohp.de.")
else:
raise ValueError
# If the calculation is spin polarized, the line in the middle
# of the file will be another header line.
# TODO: adapt this for orbital-wise stuff
self.is_spin_polarized = "distance" in data[len(data) // 2]
# check if orbital-wise ICOHPLIST
# include case when there is only one ICOHP!!!
self.orbitalwise = len(data) > 2 and "_" in data[1].split()[1]
data_orbitals: list[str] = []
if self.orbitalwise:
data_without_orbitals = []
data_orbitals = []
for line in data:
if "_" not in line.split()[1]:
data_without_orbitals += [line]
else:
data_orbitals += [line]
else:
data_without_orbitals = data
if "distance" in data_without_orbitals[len(data_without_orbitals) // 2]:
# TODO: adapt this for orbital-wise stuff
n_bonds = len(data_without_orbitals) // 2
if n_bonds == 0:
raise RuntimeError("ICOHPLIST file contains no data.")
else:
n_bonds = len(data_without_orbitals)
labels, atoms1, atoms2, lens, translations, nums, icohps = [], [], [], [], [], [], []
# initialize static variables
label = ""
atom1 = ""
atom2 = ""
length = None
num = None
translation = []
for bond in range(n_bonds):
line = data_without_orbitals[bond].split()
icohp = {}
if version == "2.2.1":
label = f"{line[0]}"
atom1 = str(line[1])
atom2 = str(line[2])
length = float(line[3])
icohp[Spin.up] = float(line[4])
num = int(line[5])
translation = [0, 0, 0]
if self.is_spin_polarized:
icohp[Spin.down] = float(data_without_orbitals[bond + n_bonds + 1].split()[4])
elif version == "3.1.1":
label = f"{line[0]}"
atom1 = str(line[1])
atom2 = str(line[2])
length = float(line[3])
translation = [int(line[4]), int(line[5]), int(line[6])]
icohp[Spin.up] = float(line[7])
num = 1
if self.is_spin_polarized:
icohp[Spin.down] = float(data_without_orbitals[bond + n_bonds + 1].split()[7])
labels += [label]
atoms1 += [atom1]
atoms2 += [atom2]
lens += [length]
translations += [translation]
nums += [num]
icohps += [icohp]
list_orb_icohp: list[dict] | None = None
if self.orbitalwise:
list_orb_icohp = []
n_orbs = len(data_orbitals) // 2 if self.is_spin_polarized else len(data_orbitals)
for i_data_orb in range(n_orbs):
data_orb = data_orbitals[i_data_orb]
icohp = {}
line = data_orb.split()
label = f"{line[0]}"
orbs = re.findall(r"_(.*?)(?=\s)", data_orb)
orb_label, orbitals = get_orb_from_str(orbs)
icohp[Spin.up] = float(line[7])
if self.is_spin_polarized:
icohp[Spin.down] = float(data_orbitals[n_orbs + i_data_orb].split()[7])
if len(list_orb_icohp) < int(label):
list_orb_icohp += [{orb_label: {"icohp": icohp, "orbitals": orbitals}}]
else:
list_orb_icohp[int(label) - 1][orb_label] = {"icohp": icohp, "orbitals": orbitals}
# Avoid circular import
from pymatgen.electronic_structure.cohp import IcohpCollection
self._icohpcollection = IcohpCollection(
are_coops=are_coops,
are_cobis=are_cobis,
list_labels=labels,
list_atom1=atoms1,
list_atom2=atoms2,
list_length=lens,
list_translation=translations,
list_num=nums,
list_icohp=icohps,
is_spin_polarized=self.is_spin_polarized,
list_orb_icohp=list_orb_icohp,
)
@property
def icohplist(self) -> dict[Any, dict[str, Any]]:
"""The ICOHP list compatible with older version of this class."""
icohp_dict = {}
for key, value in self._icohpcollection._icohplist.items():
icohp_dict[key] = {
"length": value._length,
"number_of_bonds": value._num,
"icohp": value._icohp,
"translation": value._translation,
"orbitals": value._orbitals,
}
return icohp_dict
@property
def icohpcollection(self):
"""The IcohpCollection object."""
return self._icohpcollection
class NciCobiList:
"""Read NcICOBILIST (multi-center ICOBI) files generated by LOBSTER.
Attributes:
is_spin_polarized (bool): Boolean to indicate if the calculation is spin polarized.
NciCobiList (dict): Dict containing the listfile data of the form:
{bond: "number_of_atoms": number of atoms involved in the multi-center interaction,
"ncicobi": {Spin.up: Nc-ICOBI(Ef) spin up, Spin.down: ...}},
"interaction_type": type of the multi-center interaction
"""
def __init__(
self,
filename: PathLike | None = "NcICOBILIST.lobster",
) -> None:
"""
LOBSTER < 4.1.0: no COBI/ICOBI/NcICOBI.
Args:
filename: Name of the NcICOBILIST file.
"""
# LOBSTER list files have an extra trailing blank line
# and we don't need the header.
with zopen(filename, mode="rt") as file:
data = file.read().split("\n")[1:-1]
if len(data) == 0:
raise RuntimeError("NcICOBILIST file contains no data.")
# If the calculation is spin-polarized, the line in the middle
# of the file will be another header line.
self.is_spin_polarized = "spin" in data[len(data) // 2] # TODO: adapt this for orbitalwise case
# check if orbitalwise NcICOBILIST
# include case when there is only one NcICOBI
self.orbital_wise = False # set as default
for entry in data: # NcICOBIs orbitalwise and non-orbitalwise can be mixed
if len(data) > 2 and "s]" in str(entry.split()[3:]):
self.orbital_wise = True
warnings.warn(
"This is an orbitalwise NcICOBILIST.lobster file. "
"Currently, the orbitalwise information is not read!"
)
break # condition has only to be met once
if self.orbital_wise:
data_without_orbitals = []
for line in data:
if "_" not in str(line.split()[3:]) and "s]" not in str(line.split()[3:]):
data_without_orbitals += [line]
else:
data_without_orbitals = data
if "spin" in data_without_orbitals[len(data_without_orbitals) // 2]:
# TODO: adapt this for orbitalwise case
n_bonds = len(data_without_orbitals) // 2
if n_bonds == 0:
raise RuntimeError("NcICOBILIST file contains no data.")
else:
n_bonds = len(data_without_orbitals)
self.list_labels = []
self.list_n_atoms = []
self.list_ncicobi = []
self.list_interaction_type = []
self.list_num = []
for bond in range(n_bonds):
line = data_without_orbitals[bond].split()
ncicobi = {}
label = f"{line[0]}"
n_atoms = str(line[1])
ncicobi[Spin.up] = float(line[2])
interaction_type = str(line[3:]).replace("'", "").replace(" ", "")
num = 1
if self.is_spin_polarized:
ncicobi[Spin.down] = float(data_without_orbitals[bond + n_bonds + 1].split()[2])
self.list_labels += [label]
self.list_n_atoms += [n_atoms]
self.list_ncicobi += [ncicobi]
self.list_interaction_type += [interaction_type]
self.list_num += [num]
# TODO: add functions to get orbital resolved NcICOBIs
@property
def ncicobi_list(self) -> dict[Any, dict[str, Any]]:
"""Returns: ncicobilist."""
ncicobi_list = {}
for idx in range(len(self.list_labels)):
ncicobi_list[str(idx + 1)] = {
"number_of_atoms": int(self.list_n_atoms[idx]),
"ncicobi": self.list_ncicobi[idx],
"interaction_type": self.list_interaction_type[idx],
}
return ncicobi_list
class Doscar:
"""Deal with Lobster's projected DOS and local projected DOS.
The beforehand quantum-chemical calculation was performed with VASP.
Attributes:
completedos (LobsterCompleteDos): LobsterCompleteDos Object.
pdos (list): List of Dict including numpy arrays with pdos. Access as
pdos[atomindex]['orbitalstring']['Spin.up/Spin.down'].
tdos (Dos): Dos Object of the total density of states.
energies (numpy.ndarray): Numpy array of the energies at which the DOS was calculated
(in eV, relative to Efermi).
tdensities (dict): tdensities[Spin.up]: numpy array of the total density of states for
the Spin.up contribution at each of the energies. tdensities[Spin.down]: numpy array
of the total density of states for the Spin.down contribution at each of the energies.
If is_spin_polarized=False, tdensities[Spin.up]: numpy array of the total density of states.
itdensities (dict): itdensities[Spin.up]: numpy array of the total density of states for
the Spin.up contribution at each of the energies. itdensities[Spin.down]: numpy array
of the total density of states for the Spin.down contribution at each of the energies.
If is_spin_polarized=False, itdensities[Spin.up]: numpy array of the total density of states.
is_spin_polarized (bool): Boolean. Tells if the system is spin polarized.
"""
def __init__(
self,
doscar: PathLike = "DOSCAR.lobster",
structure_file: PathLike | None = "POSCAR",
structure: IStructure | Structure | None = None,
):
"""
Args:
doscar: DOSCAR file, typically "DOSCAR.lobster"
structure_file: for vasp, this is typically "POSCAR"
structure: instead of a structure file, the structure can be given
directly. structure_file will be preferred.
"""
self._doscar = doscar
self._final_structure = Structure.from_file(structure_file) if structure_file is not None else structure
self._parse_doscar()
def _parse_doscar(self):
doscar = self._doscar
tdensities = {}
itdensities = {}
with zopen(doscar, mode="rt") as file:
n_atoms = int(file.readline().split()[0])
efermi = float([file.readline() for nn in range(4)][3].split()[17])
dos = []
orbitals = []
for _atom in range(n_atoms + 1):
line = file.readline()
ndos = int(line.split()[2])
orbitals += [line.split(";")[-1].split()]
line = file.readline().split()
cdos = np.zeros((ndos, len(line)))
cdos[0] = np.array(line)
for nd in range(1, ndos):
line = file.readline().split()
cdos[nd] = np.array(line)
dos += [cdos]
doshere = np.array(dos[0])
if len(doshere[0, :]) == 5:
self._is_spin_polarized = True
elif len(doshere[0, :]) == 3:
self._is_spin_polarized = False
else:
raise ValueError("There is something wrong with the DOSCAR. Can't extract spin polarization.")
energies = doshere[:, 0]
if not self._is_spin_polarized:
tdensities[Spin.up] = doshere[:, 1]
itdensities[Spin.up] = doshere[:, 2]
pdoss = []
spin = Spin.up
for atom in range(n_atoms):
pdos = defaultdict(dict)
data = dos[atom + 1]
_, ncol = data.shape
for orb_num, j in enumerate(range(1, ncol)):
orb = orbitals[atom + 1][orb_num]
pdos[orb][spin] = data[:, j]
pdoss += [pdos]
else:
tdensities[Spin.up] = doshere[:, 1]
tdensities[Spin.down] = doshere[:, 2]
itdensities[Spin.up] = doshere[:, 3]
itdensities[Spin.down] = doshere[:, 4]
pdoss = []
for atom in range(n_atoms):
pdos = defaultdict(dict)
data = dos[atom + 1]
_, ncol = data.shape
orb_num = 0
for j in range(1, ncol):
spin = Spin.down if j % 2 == 0 else Spin.up
orb = orbitals[atom + 1][orb_num]
pdos[orb][spin] = data[:, j]
if j % 2 == 0:
orb_num += 1
pdoss += [pdos]
self._efermi = efermi
self._pdos = pdoss
self._tdos = Dos(efermi, energies, tdensities)
self._energies = energies
self._tdensities = tdensities
self._itdensities = itdensities
final_struct = self._final_structure
pdossneu = {final_struct[i]: pdos for i, pdos in enumerate(self._pdos)}
self._completedos = LobsterCompleteDos(final_struct, self._tdos, pdossneu)
@property
def completedos(self) -> LobsterCompleteDos:
"""LobsterCompleteDos."""
return self._completedos
@property
def pdos(self) -> list:
"""Projected DOS."""
return self._pdos
@property
def tdos(self) -> Dos:
"""Total DOS."""
return self._tdos
@property
def energies(self) -> np.ndarray:
"""Energies."""
return self._energies
@property
def tdensities(self) -> dict[Spin, np.ndarray]:
"""Total densities as a np.ndarray."""
return self._tdensities
@property
def itdensities(self) -> dict[Spin, np.ndarray]:
"""Integrated total densities as a np.ndarray."""
return self._itdensities
@property
def is_spin_polarized(self) -> bool:
"""Whether run is spin polarized."""
return self._is_spin_polarized
class Charge(MSONable):
"""Read CHARGE files generated by LOBSTER.
Attributes:
atomlist (list[str]): List of atoms in CHARGE.lobster.
types (list[str]): List of types of atoms in CHARGE.lobster.
mulliken (list[float]): List of Mulliken charges of atoms in CHARGE.lobster.
loewdin (list[float]): List of Loewdin charges of atoms in CHARGE.Loewdin.
num_atoms (int): Number of atoms in CHARGE.lobster.
"""
def __init__(
self,
filename: PathLike = "CHARGE.lobster",
num_atoms: int | None = None,
atomlist: list[str] | None = None,
types: list[str] | None = None,
mulliken: list[float] | None = None,
loewdin: list[float] | None = None,
):
"""
Args:
filename: The CHARGE file, typically "CHARGE.lobster".
num_atoms: number of atoms in the structure
atomlist: list of atoms in the structure
types: list of unique species in the structure
mulliken: list of Mulliken charges
loewdin: list of Loewdin charges.
"""
self._filename = filename
self.num_atoms = num_atoms
self.types = [] if types is None else types
self.atomlist = [] if atomlist is None else atomlist
self.mulliken = [] if mulliken is None else mulliken
self.loewdin = [] if loewdin is None else loewdin
if self.num_atoms is None:
with zopen(filename, mode="rt") as file:
data = file.read().split("\n")[3:-3]
if len(data) == 0:
raise RuntimeError("CHARGE file contains no data.")
self.num_atoms = len(data)
for atom in range(self.num_atoms):
line = data[atom].split()
self.atomlist += [line[1] + line[0]]
self.types += [line[1]]
self.mulliken += [float(line[2])]
self.loewdin += [float(line[3])]
def get_structure_with_charges(self, structure_filename: PathLike) -> Structure:
"""Get a Structure with Mulliken and Loewdin charges as site properties.
Args:
structure_filename: filename of POSCAR
Returns:
Structure Object with Mulliken and Loewdin charges as site properties.
"""
struct = Structure.from_file(structure_filename)
mulliken = self.mulliken
loewdin = self.loewdin
site_properties = {"Mulliken Charges": mulliken, "Loewdin Charges": loewdin}
return struct.copy(site_properties=site_properties)
@property
def Mulliken(self):
warnings.warn("`Mulliken` attribute is deprecated. Use `mulliken` instead.", DeprecationWarning, stacklevel=2)
return self.mulliken
@property
def Loewdin(self):
warnings.warn("`Loewdin` attribute is deprecated. Use `loewdin` instead.", DeprecationWarning, stacklevel=2)
return self.loewdin
class Lobsterout(MSONable):
"""Read in the lobsterout and evaluate the spilling, save the basis, save warnings, save infos.
Attributes:
basis_functions (list[str]): List of basis functions that were used in lobster run as strings.
basis_type (list[str]): List of basis type that were used in lobster run as strings.
charge_spilling (list[float]): List of charge spilling (first entry: result for spin 1,
second entry: result for spin 2 or not present).
dft_program (str): String representing the DFT program used for the calculation of the wave function.
elements (list[str]): List of strings of elements that were present in lobster calculation.
has_charge (bool): Whether CHARGE.lobster is present.
has_cohpcar (bool): Whether COHPCAR.lobster and ICOHPLIST.lobster are present.
has_madelung (bool): Whether SitePotentials.lobster and MadelungEnergies.lobster are present.
has_coopcar (bool): Whether COOPCAR.lobster and ICOOPLIST.lobster are present.
has_cobicar (bool): Whether COBICAR.lobster and ICOBILIST.lobster are present.
has_doscar (bool): Whether DOSCAR.lobster is present.
has_doscar_lso (bool): Whether DOSCAR.LSO.lobster is present.
has_projection (bool): Whether projectionData.lobster is present.
has_bandoverlaps (bool): Whether bandOverlaps.lobster is present.
has_density_of_energies (bool): Whether DensityOfEnergy.lobster is present.
has_fatbands (bool): Whether fatband calculation was performed.
has_grosspopulation (bool): Whether GROSSPOP.lobster is present.
info_lines (str): String with additional infos on the run.
info_orthonormalization (str): String with infos on orthonormalization.
is_restart_from_projection (bool): Boolean that indicates that calculation was restarted
from existing projection file.
lobster_version (str): String that indicates Lobster version.
number_of_spins (int): Integer indicating the number of spins.
number_of_threads (int): Integer that indicates how many threads were used.
timing (dict[str, float]): Dictionary with infos on timing.
total_spilling (list[float]): List of values indicating the total spilling for spin
channel 1 (and spin channel 2).
warning_lines (str): String with all warnings.
"""
# valid Lobsterout instance attributes
_ATTRIBUTES = (
"filename",
"is_restart_from_projection",
"lobster_version",
"number_of_threads",
"dft_program",
"number_of_spins",
"charge_spilling",
"total_spilling",
"elements",
"basis_type",
"basis_functions",
"timing",
"warning_lines",
"info_orthonormalization",
"info_lines",
"has_doscar",
"has_doscar_lso",
"has_cohpcar",
"has_coopcar",
"has_cobicar",
"has_charge",
"has_madelung",
"has_projection",
"has_bandoverlaps",
"has_fatbands",
"has_grosspopulation",
"has_density_of_energies",
)
# TODO: add tests for skipping COBI and madelung
# TODO: add tests for including COBI and madelung
def __init__(self, filename: PathLike | None, **kwargs) -> None:
"""
Args:
filename: The lobsterout file.
**kwargs: dict to initialize Lobsterout instance.
"""
self.filename = filename
if kwargs:
for attr, val in kwargs.items():
if attr in self._ATTRIBUTES:
setattr(self, attr, val)
else:
raise ValueError(f"{attr}={val} is not a valid attribute for Lobsterout")
elif filename:
with zopen(filename, mode="rt") as file: # read in file
data = file.read().split("\n")
if len(data) == 0:
raise RuntimeError("lobsterout does not contain any data")
# check if Lobster starts from a projection
self.is_restart_from_projection = "loading projection from projectionData.lobster..." in data
self.lobster_version = self._get_lobster_version(data=data)
self.number_of_threads = int(self._get_threads(data=data))
self.dft_program = self._get_dft_program(data=data)
self.number_of_spins = self._get_number_of_spins(data=data)
chargespilling, totalspilling = self._get_spillings(data=data, number_of_spins=self.number_of_spins)
self.charge_spilling = chargespilling
self.total_spilling = totalspilling
elements, basistype, basisfunctions = self._get_elements_basistype_basisfunctions(data=data)
self.elements = elements
self.basis_type = basistype
self.basis_functions = basisfunctions
wall_time, user_time, sys_time = self._get_timing(data=data)
self.timing = {
"wall_time": wall_time,
"user_time": user_time,
"sys_time": sys_time,
}
warninglines = self._get_all_warning_lines(data=data)
self.warning_lines = warninglines
orthowarning = self._get_warning_orthonormalization(data=data)
self.info_orthonormalization = orthowarning
infos = self._get_all_info_lines(data=data)
self.info_lines = infos
self.has_doscar = "writing DOSCAR.lobster..." in data and "SKIPPING writing DOSCAR.lobster..." not in data
self.has_doscar_lso = (
"writing DOSCAR.LSO.lobster..." in data and "SKIPPING writing DOSCAR.LSO.lobster..." not in data
)
self.has_cohpcar = (
"writing COOPCAR.lobster and ICOOPLIST.lobster..." in data
and "SKIPPING writing COOPCAR.lobster and ICOOPLIST.lobster..." not in data
)
self.has_coopcar = (
"writing COHPCAR.lobster and ICOHPLIST.lobster..." in data
and "SKIPPING writing COHPCAR.lobster and ICOHPLIST.lobster..." not in data
)
self.has_cobicar = (
"writing COBICAR.lobster and ICOBILIST.lobster..." in data
and "SKIPPING writing COBICAR.lobster and ICOBILIST.lobster..." not in data
)
self.has_charge = "SKIPPING writing CHARGE.lobster..." not in data
self.has_projection = "saving projection to projectionData.lobster..." in data
self.has_bandoverlaps = (
"WARNING: I dumped the band overlap matrices to the file bandOverlaps.lobster." in data
)
self.has_fatbands = self._has_fatband(data=data)
self.has_grosspopulation = "writing CHARGE.lobster and GROSSPOP.lobster..." in data