-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodel_method.py
More file actions
1936 lines (1650 loc) · 69.6 KB
/
model_method.py
File metadata and controls
1936 lines (1650 loc) · 69.6 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
import re
from typing import TYPE_CHECKING
import numpy as np
from nomad.datamodel.data import ArchiveSection
from nomad.metainfo import (
URL,
MEnum,
Quantity,
Section,
SubSection,
)
if TYPE_CHECKING:
from nomad.datamodel.context import Context
from nomad.datamodel.datamodel import EntryArchive
from structlog.stdlib import BoundLogger
from nomad_simulations.schema_packages.atoms_state import CoreHole, ElectronicState
from nomad_simulations.schema_packages.data_types import positive_int, unit_float
from nomad_simulations.schema_packages.model_system import ModelSystem
from nomad_simulations.schema_packages.numerical_settings import NumericalSettings
from nomad_simulations.schema_packages.utils.libxc.build import (
spec_from_label,
)
from nomad_simulations.schema_packages.utils.libxc.expand import (
expand_to_libxc_labels,
infer_rung_hint,
)
class BaseModelMethod(ArchiveSection):
"""
A base section used to define the abstract class of a Hamiltonian section. This section is an
abstraction of the `ModelMethod` section, which contains the settings and parameters used in
the mathematical model solved in a simulation. This abstraction is needed in order to allow
`ModelMethod` to be divided into specific `terms`, so that the total Hamiltonian is specified in
`ModelMethod`, while its contributions are defined in `ModelMethod.terms`.
Example: a custom model Hamiltonian containing two terms:
$H = H_{V_{1}(r)}+H_{V_{2}(r)}$
where $H_{V_{1}(r)}$ and $H_{V_{2}(r)}$ are the contributions of two different potentials written in
real space coordinates $r$. These potentials could be defined in terms of a combination of parameters
$(a_{1}, b_{1}, c_{1}...)$ for $V_{1}(r)$ and $(a_{2}, b_{2}, c_{2}...)$ for $V_{2}(r)$. If we name the
total Hamiltonian as `'FF1'`:
`ModelMethod.name = 'FF1'`
`ModelMethod.contributions = [BaseModelMethod(name='V1', parameters=[a1, b1, c1]), BaseModelMethod(name='V2', parameters=[a2, b2, c2])]`
Note: quantities such as `name`, `type`, `external_reference` should be descriptive enough so that the
total Hamiltonian model or each of the terms or contributions can be identified.
"""
normalizer_level = 1
name = Quantity(
type=str,
description="""
Name of the mathematical model. This is typically used to identify the model Hamiltonian used in the
simulation. Typical standard names: 'DFT', 'TB', 'GW', 'BSE', 'DMFT', 'NMR', 'kMC'.
""",
)
type = Quantity(
type=str,
description="""
Identifier used to further specify the kind or sub-type of model Hamiltonian. Example: a TB
model can be 'Wannier', 'DFTB', 'xTB' or 'Slater-Koster'. This quantity should be
rewritten to a MEnum when inheriting from this class.
""",
)
external_reference = Quantity(
type=URL,
description="""
External reference to the model e.g. DOI, URL.
""",
)
numerical_settings = SubSection(sub_section=NumericalSettings.m_def, repeats=True)
class ModelMethod(BaseModelMethod):
"""
A base section containing the mathematical model parameters. These are both the parameters of
the model and the settings used in the simulation. Optionally, this section can be decomposed
in a series of contributions by storing them under the `contributions` quantity.
"""
contributions = SubSection(
sub_section=BaseModelMethod.m_def,
repeats=True,
description="""
Contribution or sub-term of the total model Hamiltonian.
""",
)
class ImplicitSolvationModel(BaseModelMethod):
"""Implicit-solvent or polarizable continuum treatments.
Examples include PCM and its variants (IEF-PCM, CPCM), COSMO, COSMO-RS,
SMD, GBSA, and Poisson-Boltzmann (PB) models. The essential parameters
are the dielectric constant **ε** of the solvent, a description of how
the cavity is constructed, and optional surface-charge or
dispersion terms used by the model.
References
----------
• J. Tomasi, B. Mennucci, R. Cammi, *Chem. Rev.* **105**, 2999 (2005) - PCM overview
• A. Klamt, *J. Phys. Chem.* **99**, 2224 (1995) - COSMO
• A. V. Marenich *et al.*, *J. Chem. Phys. B* **113**, 6378 (2009) - SMD
"""
model = Quantity(
type=MEnum(
# Quantum-chemistry continuum
'PCM',
'IEF-PCM',
'CPCM',
'DCOSMO',
'COSMO',
'COSMO-RS',
'SMD', # SMx family represented by SMD here
# Electrostatics continuum
'PB',
'GB',
'GBSA',
# Solid-state / modern continua
'SCCS',
),
description="""
The implicit-solvent flavour employed.
| Abbrev. | Full name |
|---------|----------------------------------------|
| PCM | Polarizable Continuum Model |
| IEF-PCM | Integral Equation Formalism PCM |
| CPCM | Conductor-like PCM |
| SMD | Solvation Model based on Density |
| COSMO | COnductor-like Screening MOdel |
| COSMO-RS| COSMO for Real Solvents |
| GBSA | Generalised Born Surface Area |
| PB | Poisson-Boltzmann |
""",
)
solvent = Quantity(
type=str,
description="""
Common name or formula of the solvent (e.g. water, acetonitrile).
""",
)
dielectric_constant = Quantity(
type=np.float64,
description="""
Static relative permittivity (ε) of the bulk solvent. (ε at ω=0)
Required for PCM/COSMO/GBSA; may be implicit in SMD parameter sets.
""",
)
dielectric_constant_optical = Quantity(
type=np.float64,
description="""
Optical-frequency (high-frequency) dielectric ε_∞ of the solvent.
Used in TDDFT/non-equilibrium PCM. Often derived from n via ε_∞ ≈ n².
""",
)
is_mixture = Quantity(
type=bool,
description='True if a solvent mixture was modeled (COSMO-RS/JDFT contexts).',
)
refractive_index = Quantity(
type=np.float64,
description="""
Optical-frequency refractive index *n* of the solvent. Needed when a
frequency-dependent dielectric is used (e.g. in TDDFT PCM).
If provided and `dielectric_constant_optical` is missing, normalization sets
dielectric_constant_optical = n**2.
""",
)
cavity_construction = Quantity(
type=MEnum('UFF', 'VdW', 'ISOSURFACE', 'SAS', 'FIXED_RADIUS', 'other'),
description="""
How the solute cavity surface is defined.
• *UFF* / *VdW* : scaled van-der-Waals radii (default for PCM)
• *ISOSURFACE* : electron-density isosurface (IEFPCM/SMD)
• *SAS* : solvent-accessible surface
• *FIXED_RADIUS*: single-sphere (GBSA)
""",
)
def normalize(self, archive, logger):
super().normalize(archive, logger)
# --- derive ε∞ from n (when needed) ---
if (
self.dielectric_constant_optical is None
and self.refractive_index is not None
):
try:
self.dielectric_constant_optical = float(self.refractive_index) ** 2
except Exception:
logger.warning(
'Failed to derive dielectric_constant_optical from refractive_index.'
)
# --- light validation by model type ---
if (
self.model in ['PCM', 'IEF-PCM', 'CPCM', 'DCOSMO', 'COSMO', 'GB', 'GBSA']
and self.dielectric_constant is None
):
logger.warning(
'ImplicitSolvationModel.model requires static dielectric_constant (ε_s), but it is missing.'
)
class EmpiricalDispersionModel(BaseModelMethod):
"""Empirical dispersion correction used together with an ab-initio method.
Covers pairwise-additive (D2/D3/D3(BJ)/D4), density-dependent (TS/TS-SCS),
many-body dispersion (MBD, e.g. MBD@rsSCS), and exchange-hole based XDM.
In literature, `DFT-D` is often used as an umbrella label; this schema stores
the concrete generation explicitly when available (e.g. D2, D3, D3BJ, D4).
References
----------
• S. Grimme, J. Comp. Chem. 27, 1787 (2006) - DFT-D2
• S. Grimme et al., J. Chem. Phys. 132, 154104 (2010) - DFT-D3
• S. Grimme et al., J. Chem. Phys. 136, 154105 (2012) - DFT-D3(BJ)
• A. Tkatchenko, M. Scheffler, Phys. Rev. Lett. 102, 073005 (2009) - TS
• A. Tkatchenko et al., Phys. Rev. Lett. 108, 236402 (2012) - MBD
• C. Steinmann, WIREs Comput. Mol. Sci. 10, e1438 (2020) - overview
"""
model = Quantity(
type=MEnum(
# Pairwise / density-dependent empirical models
'D2',
'D3',
'D3BJ',
'D4',
'OBS',
'JCHS',
'TS',
'TS-SCS',
# Many-body
'MBD',
'MBD@rsSCS',
# Exchange-hole based
'XDM',
),
description="""
Identifier of the empirical dispersion correction model.
""",
)
damping_function = Quantity(
type=MEnum('zero', 'BJ', 'fermi', 'rational'),
description='Short-range damping: D3{zero,BJ}, TS{fermi}, XDM{rational}.',
)
# TODO later: link to XCComponent(s)
xc_partner = Quantity(
type=str,
description="Base XC functional used/tuned for (e.g. 'PBE', 'SCAN', 'B3LYP').",
)
class RelativityModel(BaseModelMethod):
"""
Relativistic treatment of the valence Hamiltonian.
This does not describe core-electron approximations (PP/ECP).
Typical options
--------------
* Four-component Dirac-Coulomb (DC)
* Two-component X2C / DKH / ZORA
* Spin-orbit mean-field (SOMF) for post-HF/BSE
"""
level = Quantity(
type=MEnum(
'non-relativistic',
'scalar',
'two-component',
'four-component',
),
default='non-relativistic',
description="""
Non-relativistic (Schrödinger), scalar (spin-free),
two-component (spin-orbit couple removed variationally, e.g. X2C),
or four-component Dirac treatment.
""",
)
approximation = Quantity(
type=MEnum(
'DKH',
'ZORA',
'FORA',
'IORA',
'X2C',
'BSS',
'NESC',
'Pauli',
'SOMF',
),
description="""
Specific approximation or decoupling scheme.
• DKH : Douglas-Kroll-Hess (all orders)
• ZORA : Zeroth-order regular approximation
• FORA : First-order regular approximation
• IORA : Improved regular approximation
• X2C : Exact two-component
• BSS : Barysz-Sadlej-Snijders
• NESC: Normalized elimination of the small component (Dyall)
• Pauli: Pauli spin-orbit correction
• SOMF : Spin-orbit mean-field added after SCF
""",
)
dkh_order = Quantity(
type=np.int32,
description='Order used for DKH (e.g., 2, 4, ...).',
)
class OrbitalLocalization(BaseModelMethod):
"""Transforming canonical MOs into a localized representation.
Localized orbitals are used by local correlation methods such as
LMP2, DLPNO-CCSD(T), fragment charge analyses, and qualitative bonding pictures.
The transformation is (near) unitary and does not change the total energy by itself,
it merely changes the representation.
References:
- S. F. Boys, "Construction of Some Molecular Orbitals to Be Approximately Invariant for Changes from One Molecule to Another," Rev. Mod. Phys. 32, 296 (1960). https://doi.org/10.1103/RevModPhys.32.296
- J. Pipek and P. G. Mezey, "A fast intrinsic localization procedure applicable for ab initio and semiempirical linear combination of atomic orbital wave functions," J. Chem. Phys. 90, 4916 (1989). https://doi.org/10.1063/1.456588
- C. Edmiston and K. Ruedenberg, "Localized Atomic and Molecular Orbitals," Rev. Mod. Phys. 35, 457 (1963). https://doi.org/10.1103/RevModPhys.35.457
- G. Knizia, "Intrinsic Atomic Orbitals: An Unbiased Bridge between Quantum Theory and Chemical Concepts," J. Chem. Theory Comput. 9, 4834 (2013). https://doi.org/10.1021/ct400687b
- F. Weinhold, C. R. Landis, "Natural bond orbitals and extensions of localized bonding concepts," Chem. Educ. Res. Pract. 2, 91 (2001). https://doi.org/10.1039/B1RP90011K
"""
method = Quantity(
type=MEnum(
'Foster-Boys',
'Pipek-Mezey',
'Edmiston-Ruedenberg',
'IBO',
'NBO',
'AIOPM-NBO',
),
description="""Localization criterion / algorithm.""",
)
n_localized_orbitals = Quantity(
type=np.int32,
description='Number of orbitals actually subjected to the localization (can differ from the full occupied space).',
)
class ModelMethodElectronic(ModelMethod):
"""
A base section used to define the parameters of a model Hamiltonian used in electronic structure
calculations (TB, DFT, GW, BSE, DMFT, etc).
"""
# ? Is this necessary or will it be defined in another way?
# TODO @ndaelman-hu & EBB2675, we need to assess how to reconcile is_spin_polarized and determinant
is_spin_polarized = Quantity(
type=bool,
description="""
If the simulation is done considering the spin degrees of freedom (then there are two spin
channels, 'down' and 'up') or not.
""",
)
# TODO : this part should be revisited once Spin is handled.
# TODO : this part should be revisited in general.
determinant = Quantity(
type=MEnum('unrestricted', 'restricted', 'restricted-open-shell'),
description="""
The spin-coupling form of the determinant used for the
self-consistent field (SCF) calculation.
- **restricted** (RHF/RKS): α and β electrons share the same spatial orbitals
- **unrestricted** (UHF/UKS): α and β orbitals are optimized independently
- **restricted-open-shell** (ROHF/ROKS): closed-shell core with spin-unpaired electrons
sharing spatial orbitals in the open-shell manifold
""",
)
class XCComponent(ArchiveSection):
"""
One exchange-correlation functional component using LibXC nomenclature for standardization.
Note: LibXC IDs and labels are used to provide a unified taxonomy across different codes,
but do not necessarily indicate that the LibXC library was used in the calculation.
Check `XCFunctional.uses_libxc` to determine the actual implementation source.
All taxonomy data are extracted from the LibXC registry; hybrid parameters (α/ω) are
set by parsers when present in inputs/outputs.
LibXC project page: https://libxc.gitlab.io/
"""
# Identity (from LibXC registry)
libxc_id = Quantity(type=np.int64, description='LibXC ID (e.g., 101).')
canonical_label = Quantity(
type=str, description="LibXC label, e.g. 'XC_GGA_X_PBE'."
)
display_name = Quantity(
type=str,
description="""
Human-readable LibXC name.
Note: this can be identical for exchange/correlation partner entries
(for example TPSS), so use `canonical_label` + `kind` for disambiguation.
""",
)
# Taxonomy
family = Quantity(
type=MEnum('LDA', 'GGA', 'meta-GGA', 'hybrid-GGA', 'hybrid-meta-GGA'),
description="Jacob's ladder family.",
)
kind = Quantity(
type=MEnum('exchange', 'correlation', 'xc', 'k'), description='Component kind.'
)
# Hybrid / range-separated parameters — PARSERS fill these if known
# TODO: normalize with defaults if not provided
fraction_exact_exchange = Quantity(type=np.float64, description='HF mixing α.')
range_part = Quantity(
type=MEnum('global', 'short-range', 'long-range'),
description="""
Range domain this component applies to:
'global' (no split), 'short-range', or 'long-range'.
""",
)
range_separation_parameter = Quantity(
type=np.float64, unit='1/m', description='Range separation ω.'
)
range_separation_function = Quantity(
type=MEnum('erf', 'erfc', 'Yukawa', 'exp', 'Gaussian', 'Slater'),
description="""
Functional form of the range-separation kernel used to partition the Coulomb operator.
Common choices:
• erf — error function (used in LC-ωPBE, CAM-B3LYP)
• erfc — complementary error function (equivalent to erf split)
• Yukawa — exponential screening, e.g. HSE-style
• exp — simple exponential decay
• Gaussian — Gaussian screening form
• Slater — Slater-type exponential
Needed to interpret the range-separation parameter ω correctly.
""",
)
weight = Quantity(
type=unit_float(),
description="""
Fractional contribution in the density functional result.
Only applies when the functional is part of a larger, composed functional, that is not included in the LibXC.
All components' fractions should sum up to one.
""",
)
class XCFunctional(ArchiveSection):
"""
Normalized XC information for a calculation (possibly multi-component).
The `components` subsection uses LibXC nomenclature to provide standardized
taxonomy and metadata across different simulation codes. This standardization
does not imply that the LibXC library was actually used in the calculation.
To determine whether the simulation code used its internal XC implementation
or explicitly called the LibXC library, check the `uses_libxc` quantity.
"""
components = SubSection(sub_section=XCComponent.m_def, repeats=True)
functional_key = Quantity(
type=str,
description="""
Canonical functional alias representing one XC functional as a whole.
Used for filtering and display (e.g. 'PBE', 'PBE0', 'B3LYP', 'SCAN+rVV10').
Typically corresponds to the original name reported in the code,
""",
)
# moved & renamed from DFT.exact_exchange_mixing_factor
global_exact_exchange = Quantity(
type=np.float64,
description='Global HF mixing α (if any); derived from XC components.',
)
uses_libxc = Quantity(
type=bool,
default=False,
description="""
`True` if the calculation explicitly used the LibXC library for XC functional evaluation.
Has to be set by the parser. `False` indicates the code used its own internal implementation.
""",
)
def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
super().normalize(archive, logger)
try:
if not self.components and self.functional_key:
labels = expand_to_libxc_labels(self.functional_key)
if labels:
# de-duplicate while preserving order
seen = set()
for lbl in labels:
if lbl in seen:
continue
seen.add(lbl)
spec = spec_from_label(lbl, weight=1.0)
if spec is not None:
comp = XCComponent(**spec)
self.m_add_sub_section(type(self).components, comp)
else:
logger.debug(
'LibXC expansion produced no labels.',
raw=self.functional_key,
)
except Exception:
logger.warning('LibXC expansion failed.')
if self.global_exact_exchange is None:
alphas = [
c.fraction_exact_exchange
for c in (self.components or [])
if c.fraction_exact_exchange is not None
]
if len(alphas) == 1 or (len(alphas) > 1 and len(set(alphas)) == 1):
self.global_exact_exchange = alphas[0]
class DFT(ModelMethodElectronic):
"""
A base section used to define the parameters used in a density functional theory (DFT) calculation.
"""
# TODO : improve and rename this classification
jacobs_ladder = Quantity(
type=MEnum(
'LDA', 'GGA', 'meta-GGA', 'hybrid-GGA', 'hybrid-meta-GGA', 'unavailable'
),
description="""
Highest Jacob's ladder rung present among XC components.
See:
- https://doi.org/10.1063/1.1390175 (original paper)
- https://doi.org/10.1103/PhysRevLett.91.146401 (meta-GGA)
- https://doi.org/10.1063/1.1904565 (hyper-GGA)
""",
)
xc = SubSection(sub_section=XCFunctional.m_def, repeats=False)
def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
super().normalize(archive, logger)
if self.xc is None:
self.xc = XCFunctional()
# XC-specific normalization now handled by XCFunctional
self.xc.normalize(archive, logger)
# Derive Jacob’s ladder from components (highest rung wins)
rank = {
'LDA': 0,
'GGA': 1,
'meta-GGA': 2,
'hybrid-GGA': 3,
'hybrid-meta-GGA': 4,
}
families = [c.family for c in (self.xc.components or []) if c.family]
hinted = infer_rung_hint(getattr(self.xc, 'functional_key', None) or '')
if families:
derived = max(families, key=lambda f: rank.get(f, -1))
if hinted and rank.get(hinted, -1) > rank.get(derived, -1):
self.jacobs_ladder = hinted
else:
self.jacobs_ladder = derived
elif hinted:
self.jacobs_ladder = hinted
else:
self.jacobs_ladder = self.jacobs_ladder or 'unavailable'
class TB(ModelMethodElectronic):
"""
A base section containing the parameters pertaining to a tight-binding (TB) model calculation.
The type of tight-binding model is specified in the `type` quantity.
"""
type = Quantity(
type=MEnum('DFTB', 'xTB', 'Wannier', 'SlaterKoster', 'unavailable'),
default='unavailable',
description="""
Tight-binding model Hamiltonian type. The default is set to `'unavailable'` in case none of the
standard types can be recognized. These can be:
| Value | Reference |
| --------- | ----------------------- |
| `'DFTB'` | https://en.wikipedia.org/wiki/DFTB |
| `'xTB'` | https://xtb-docs.readthedocs.io/en/latest/ |
| `'Wannier'` | https://www.wanniertools.org/theory/tight-binding-model/ |
| `'SlaterKoster'` | https://journals.aps.org/pr/abstract/10.1103/PhysRev.94.1498 |
| `'unavailable'` | - |
""",
)
# ? these 4 quantities will change when `BasisSet` is defined
n_orbitals_per_atom = Quantity(
type=np.int32,
description="""
Number of orbitals per atom in the unit cell used as a basis to obtain the `TB` model. This
quantity is resolved from `orbitals_ref` via normalization.
""",
)
n_atoms_per_unit_cell = Quantity(
type=np.int32,
description="""
Number of atoms per unit cell relevant for the `TB` model. This quantity is resolved from
`n_total_orbitals` and `n_orbitals_per_atom` via normalization.
""",
)
n_total_orbitals = Quantity(
type=np.int32,
description="""
Total number of orbitals used as a basis to obtain the `TB` model. This quantity is parsed by
the specific parsing code. This is related with `n_orbitals_per_atom` and `n_atoms_per_unit_cell` as:
`n_total_orbitals` = `n_orbitals_per_atom` * `n_atoms_per_unit_cell`
""",
)
orbitals_ref = Quantity(
type=ElectronicState,
shape=['n_orbitals_per_atom'],
description="""
References to the `ElectronicState` that contain system's the orbitals (with a mapping to each atom) relevant for the `TB` model. This quantity is resolved from normalization when the active atoms sub-systems `model_system.model_system[*]`
are populated.
The relevant orbitals for the TB model are the `'pz'` ones for each `'C'` atom. Then, we define:
`orbitals_ref= [ElectronicState('pz'), ElectronicState('pz')]`
The relevant atoms information can be accessed from the parent AtomsState sections:
```
atom_state = orbitals_ref[i].m_parent
index = orbitals_ref[i].m_parent_index
atom_position = orbitals_ref[i].m_parent.m_parent.positions[index]
```
""",
)
def resolve_type(self) -> str | None:
"""
Resolves the `type` of the `TB` section if it is not already defined, and from the
`m_def.name` of the section.
Returns:
str | None: The resolved `type` of the `TB` section.
"""
return (
self.m_def.name
if self.m_def.name in ['DFTB', 'xTB', 'Wannier', 'SlaterKoster']
else None
)
def resolve_orbital_references(
self,
model_systems: list[ModelSystem],
logger: 'BoundLogger',
model_index: int = -1,
) -> list[ElectronicState] | None:
"""
Resolves references to the `ElectronicState` sections from the top-level `ModelSystem`
that has child system(s) typed 'active_atom'. This uses the new design:
- The parent ModelSystem stores per-atom data in `particle_states`.
- The child system(s) typed 'active_atom' list indices in `particle_indices`.
- We gather `ElectronicState` from each relevant particle_states entry.
Args:
model_systems (list[ModelSystem]): The list of `ModelSystem` sections.
logger (BoundLogger): The logger to log messages.
model_index (int, optional): The ModelSystem index to use. Defaults to -1 (the last).
Returns:
`list[ElectronicState] | None`: The resolved references to the `ElectronicState` sections.
"""
# Check that the requested ModelSystem exists
try:
model_system = model_systems[model_index]
except IndexError:
logger.warning('No ModelSystem at index %s.', model_index)
return None
# If the system is not representative, bail out of normalization
if not model_system.is_representative:
return None
# If no child ModelSystem sections exist, bail out of normalization
if not model_system.sub_systems:
logger.warning(
'No child ModelSystem found; cannot find active_atom references.'
)
return None
# If no particle_states are present at the top level, we have no orbitals
if not model_system.particle_states:
logger.warning('No particle_states in the parent ModelSystem.')
return None
orbitals_ref: list[ElectronicState] = []
# For each child in sub_systems, if type='active_atom', gather orbitals
for child_sys in model_system.sub_systems:
if child_sys.type != 'active_atom':
continue
# if no particle_indices => skip
# Note: Use 'is None' and len check to avoid numpy array boolean evaluation issues
# (numpy array [0] evaluates to False in boolean context)
if (
child_sys.particle_indices is None
or len(child_sys.particle_indices) == 0
):
logger.warning('Child system is active_atom but no particle_indices.')
continue
# For each index in child_sys.particle_indices => fetch from parent’s particle_states
for idx in child_sys.particle_indices:
if idx < 0 or idx >= len(model_system.particle_states):
logger.warning(
'Particle index %s out of range for particle_states.', idx
)
continue
active_atom_state = model_system.particle_states[idx]
# If no orbitals_state => skip
if not active_atom_state.electronic_state:
logger.warning(
'No electronic_state found in particle_states[%s].', idx
)
continue
orbitals_ref.append(active_atom_state.electronic_state)
# Return the collected orbitals
return orbitals_ref
def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
super().normalize(archive, logger)
# Set `name` to "TB"
self.name = 'TB'
# Resolve `type` to be defined by the lower level class (Wannier, DFTB, xTB or SlaterKoster) if it is not already defined
self.type = self.resolve_type()
# Resolve `orbitals_ref` from the info in the child `ModelSystem` section and the `ElectronicState` sections
model_systems = self.m_xpath('m_parent.model_system', dict=False)
if model_systems is None:
logger.warning(
'Could not find the `ModelSystem` sections. References to `ElectronicState` will not be resolved.'
)
return
# This normalization only considers the last `ModelSystem` (default `model_index` argument set to -1)
orbitals_ref = self.resolve_orbital_references(
model_systems=model_systems, logger=logger
)
if orbitals_ref is not None and len(orbitals_ref) > 0 and not self.orbitals_ref:
self.n_orbitals_per_atom = len(orbitals_ref)
self.orbitals_ref = orbitals_ref
# Resolve `n_atoms_per_unit_cell` from `n_total_orbitals` and `n_orbitals_per_atom`
if self.n_orbitals_per_atom is not None and self.n_total_orbitals is not None:
self.n_atoms_per_unit_cell = (
self.n_total_orbitals // self.n_orbitals_per_atom
)
class Wannier(TB):
"""
A base section used to define the parameters used in a Wannier tight-binding fitting.
"""
is_maximally_localized = Quantity(
type=bool,
description="""
If the projected orbitals are maximally localized or just a single-shot projection.
""",
)
localization_type = Quantity(
type=MEnum('single_shot', 'maximally_localized'),
description="""
Localization type of the Wannier orbitals.
""",
)
n_bloch_bands = Quantity(
type=np.int32,
description="""
Number of input Bloch bands to calculate the projection matrix.
""",
)
energy_window_outer = Quantity(
type=np.float64,
unit='electron_volt',
shape=[2],
description="""
Bottom and top of the outer energy window used for the projection.
""",
)
energy_window_inner = Quantity(
type=np.float64,
unit='electron_volt',
shape=[2],
description="""
Bottom and top of the inner energy window used for the projection.
""",
)
def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
super().normalize(archive, logger)
# Resolve `localization_type` from `is_maximally_localized`
if self.localization_type is None:
if self.is_maximally_localized is not None:
if self.is_maximally_localized:
self.localization_type = 'maximally_localized'
else:
self.localization_type = 'single_shot'
class SlaterKosterBond(ArchiveSection):
"""
A base section used to define the Slater-Koster bond information betwee two orbitals.
"""
orbital_1 = Quantity(
type=ElectronicState,
description="""
Reference to the first `ElectronicState` section.
""",
)
orbital_2 = Quantity(
type=ElectronicState,
description="""
Reference to the second `ElectronicState` section.
""",
)
# ? is this the best naming
bravais_vector = Quantity(
type=np.int32,
default=[0, 0, 0],
shape=[3],
description="""
The Bravais vector of the cell in 3 dimensional. This is defined as the vector that connects the
two atoms that define the Slater-Koster bond. A bond can be defined between orbitals in the
same unit cell (bravais_vector = [0, 0, 0]) or in neighboring cells (bravais_vector = [m, n, p] with m, n, p are integers).
Default is [0, 0, 0].
""",
)
# TODO add more names and in the table
name = Quantity(
type=MEnum('sss', 'sps', 'sds'),
description="""
The name of the Slater-Koster bond. The name is composed by the `l_quantum_symbol` of the orbitals
and the cell index. Table of possible values:
| Value | `orbital_1.l_quantum_symbol` | `orbital_2.l_quantum_symbol` | `bravais_vector` |
| ------- | ---------------------------- | ---------------------------- | ------------ |
| `'sss'` | 's' | 's' | [0, 0, 0] |
| `'sps'` | 's' | 'p' | [0, 0, 0] |
| `'sds'` | 's' | 'd' | [0, 0, 0] |
""",
)
# ? units
integral_value = Quantity(
type=np.float64,
description="""
The Slater-Koster bond integral value.
""",
)
def __init__(self, m_def: 'Section' = None, m_context: 'Context' = None, **kwargs):
super().__init__(m_def, m_context, **kwargs)
# TODO extend this to cover all bond names
self._bond_name_map = {
'sss': ['s', 's', (0, 0, 0)],
'sps': ['s', 'p', (0, 0, 0)],
'sds': ['s', 'd', (0, 0, 0)],
}
def resolve_bond_name_from_references(
self,
orbital_1: ElectronicState | None,
orbital_2: ElectronicState | None,
bravais_vector: tuple | None,
logger: 'BoundLogger',
) -> str | None:
"""
Resolves the `name` of the `SlaterKosterBond` from the references to the `ElectronicState` sections.
Args:
orbital_1 (`ElectronicState | None`): The first `ElectronicState` section.
orbital_2 (`ElectronicState | None`): The second `ElectronicState` section.
bravais_vector (`tuple | None`): The bravais vector of the cell.
logger (`BoundLogger`): The logger to log messages.
Returns:
`[str] | None`: The resolved `name` of the `SlaterKosterBond`.
"""
# Initial check
if orbital_1 is None or orbital_2 is None:
logger.warning('The `ElectronicState` sections are not defined.')
return None
if bravais_vector is None:
logger.warning('The `bravais_vector` is not defined.')
return None
# Check for `l_quantum_symbol` in `ElectronicState` sections
orbital_1_l_symbol = (
getattr(orbital_1.spin_orbit_state, 'l_quantum_symbol', None)
if orbital_1.spin_orbit_state
else None
)
orbital_2_l_symbol = (
getattr(orbital_2.spin_orbit_state, 'l_quantum_symbol', None)
if orbital_2.spin_orbit_state
else None
)
if orbital_1_l_symbol is None or orbital_2_l_symbol is None:
logger.warning(
'The `l_quantum_symbol` of the `ElectronicState` bonds are not defined.'
)
return None
bond_name = None
value = [orbital_1_l_symbol, orbital_2_l_symbol, bravais_vector]
# Check if `value` is found in the `self._bond_name_map` and return the key
for key, val in self._bond_name_map.items():
if val == value:
bond_name = key
break
return bond_name
def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
super().normalize(archive, logger)
# Resolve the SK bond `name` from the `ElectronicState` references and the `bravais_vector`
if self.orbital_1 and self.orbital_2 and self.bravais_vector is not None:
if self.bravais_vector is not None:
bravais_vector = tuple(self.bravais_vector) # transformed for comparing
self.name = self.resolve_bond_name_from_references(
orbital_1=self.orbital_1,
orbital_2=self.orbital_2,
bravais_vector=bravais_vector,
logger=logger,
)
class SlaterKoster(TB):
"""
A base section used to define the parameters used in a Slater-Koster tight-binding fitting.
"""
bonds = SubSection(sub_section=SlaterKosterBond.m_def, repeats=True)
overlaps = SubSection(sub_section=SlaterKosterBond.m_def, repeats=True)
class xTB(TB):