Skip to content

pymatgen

Convert an OPTIMADE structure, in the format of StructureResource to a pymatgen Molecule or Structure object.

This conversion function relies on the pymatgen package.

For more information on the pymatgen code see their documentation.

Composition = type('Composition', (), {}) module-attribute

PYMATGEN_NOT_FOUND = 'Pymatgen not found, cannot convert structure to a pymatgen Structure or Molecule' module-attribute

__all__ = ('get_pymatgen', 'from_pymatgen') module-attribute

AdapterPackageNotFound

Bases: OptimadeWarning

The package for an adapter cannot be found.

Source code in optimade/adapters/warnings.py
6
7
class AdapterPackageNotFound(OptimadeWarning):
    """The package for an adapter cannot be found."""

OptimadeStructure

Bases: EntryResource

Representing a structure.

Source code in optimade/models/structures.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
class StructureResource(EntryResource):
    """Representing a structure."""

    type: Annotated[
        Literal["structures"],
        StrictField(
            description="""The name of the type of an entry.

- **Type**: string.

- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - **Response**: REQUIRED in the response.
    - MUST be an existing entry type.
    - The entry of type `<type>` and ID `<id>` MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.

- **Examples**:
    - `"structures"`""",
            pattern="^structures$",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ] = "structures"

    attributes: StructureResourceAttributes

OptimadeStructureSpecies

Bases: BaseModel

A list describing the species of the sites of this structure.

Species can represent pure chemical elements, virtual-crystal atoms representing a statistical occupation of a given site by multiple chemical elements, and/or a location to which there are attached atoms, i.e., atoms whose precise location are unknown beyond that they are attached to that position (frequently used to indicate hydrogen atoms attached to another element, e.g., a carbon with three attached hydrogens might represent a methyl group, -CH3).

  • Examples:
    • [ {"name": "Ti", "chemical_symbols": ["Ti"], "concentration": [1.0]} ]: any site with this species is occupied by a Ti atom.
    • [ {"name": "Ti", "chemical_symbols": ["Ti", "vacancy"], "concentration": [0.9, 0.1]} ]: any site with this species is occupied by a Ti atom with 90 % probability, and has a vacancy with 10 % probability.
    • [ {"name": "BaCa", "chemical_symbols": ["vacancy", "Ba", "Ca"], "concentration": [0.05, 0.45, 0.5], "mass": [0.0, 137.327, 40.078]} ]: any site with this species is occupied by a Ba atom with 45 % probability, a Ca atom with 50 % probability, and by a vacancy with 5 % probability. The mass of this site is (on average) 88.5 a.m.u.
    • [ {"name": "C12", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [12.0]} ]: any site with this species is occupied by a carbon isotope with mass 12.
    • [ {"name": "C13", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [13.0]} ]: any site with this species is occupied by a carbon isotope with mass 13.
    • [ {"name": "CH3", "chemical_symbols": ["C"], "concentration": [1.0], "attached": ["H"], "nattached": [3]} ]: any site with this species is occupied by a methyl group, -CH3, which is represented without specifying precise positions of the hydrogen atoms.
Source code in optimade/models/structures.py
 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
class Species(BaseModel):
    """A list describing the species of the sites of this structure.

    Species can represent pure chemical elements, virtual-crystal atoms representing a
    statistical occupation of a given site by multiple chemical elements, and/or a
    location to which there are attached atoms, i.e., atoms whose precise location are
    unknown beyond that they are attached to that position (frequently used to indicate
    hydrogen atoms attached to another element, e.g., a carbon with three attached
    hydrogens might represent a methyl group, -CH3).

    - **Examples**:
        - `[ {"name": "Ti", "chemical_symbols": ["Ti"], "concentration": [1.0]} ]`: any site with this species is occupied by a Ti atom.
        - `[ {"name": "Ti", "chemical_symbols": ["Ti", "vacancy"], "concentration": [0.9, 0.1]} ]`: any site with this species is occupied by a Ti atom with 90 % probability, and has a vacancy with 10 % probability.
        - `[ {"name": "BaCa", "chemical_symbols": ["vacancy", "Ba", "Ca"], "concentration": [0.05, 0.45, 0.5], "mass": [0.0, 137.327, 40.078]} ]`: any site with this species is occupied by a Ba atom with 45 % probability, a Ca atom with 50 % probability, and by a vacancy with 5 % probability. The mass of this site is (on average) 88.5 a.m.u.
        - `[ {"name": "C12", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [12.0]} ]`: any site with this species is occupied by a carbon isotope with mass 12.
        - `[ {"name": "C13", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [13.0]} ]`: any site with this species is occupied by a carbon isotope with mass 13.
        - `[ {"name": "CH3", "chemical_symbols": ["C"], "concentration": [1.0], "attached": ["H"], "nattached": [3]} ]`: any site with this species is occupied by a methyl group, -CH3, which is represented without specifying precise positions of the hydrogen atoms.

    """

    name: Annotated[
        str,
        OptimadeField(
            description="""Gives the name of the species; the **name** value MUST be unique in the `species` list.""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.OPTIONAL,
        ),
    ]

    chemical_symbols: Annotated[
        list[ChemicalSymbol],
        OptimadeField(
            description="""MUST be a list of strings of all chemical elements composing this species. Each item of the list MUST be one of the following:

- a valid chemical-element symbol, or
- the special value `"X"` to represent a non-chemical element, or
- the special value `"vacancy"` to represent that this site has a non-zero probability of having a vacancy (the respective probability is indicated in the `concentration` list, see below).

If any one entry in the `species` list has a `chemical_symbols` list that is longer than 1 element, the correct flag MUST be set in the list `structure_features`.""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.OPTIONAL,
        ),
    ]

    concentration: Annotated[
        list[float],
        OptimadeField(
            description="""MUST be a list of floats, with same length as `chemical_symbols`. The numbers represent the relative concentration of the corresponding chemical symbol in this species. The numbers SHOULD sum to one. Cases in which the numbers do not sum to one typically fall only in the following two categories:

- Numerical errors when representing float numbers in fixed precision, e.g. for two chemical symbols with concentrations `1/3` and `2/3`, the concentration might look something like `[0.33333333333, 0.66666666666]`. If the client is aware that the sum is not one because of numerical precision, it can renormalize the values so that the sum is exactly one.
- Experimental errors in the data present in the database. In this case, it is the responsibility of the client to decide how to process the data.

Note that concentrations are uncorrelated between different site (even of the same species).""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.OPTIONAL,
        ),
    ]

    mass: Annotated[
        Optional[list[float]],
        OptimadeField(
            description="""If present MUST be a list of floats expressed in a.m.u.
Elements denoting vacancies MUST have masses equal to 0.""",
            unit="a.m.u.",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    original_name: Annotated[
        Optional[str],
        OptimadeField(
            description="""Can be any valid Unicode string, and SHOULD contain (if specified) the name of the species that is used internally in the source database.

Note: With regards to "source database", we refer to the immediate source being queried via the OPTIMADE API implementation.""",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    attached: Annotated[
        Optional[list[str]],
        OptimadeField(
            description="""If provided MUST be a list of length 1 or more of strings of chemical symbols for the elements attached to this site, or "X" for a non-chemical element.""",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    nattached: Annotated[
        Optional[list[int]],
        OptimadeField(
            description="""If provided MUST be a list of length 1 or more of integers indicating the number of attached atoms of the kind specified in the value of the :field:`attached` key.""",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    @field_validator("concentration", "mass", mode="after")
    def validate_concentration_and_mass(
        cls, value: Optional[list[float]], info: "ValidationInfo"
    ) -> Optional[list[float]]:
        if not value:
            return value

        if info.data.get("chemical_symbols"):
            if len(value) != len(info.data["chemical_symbols"]):
                raise ValueError(
                    f"Length of concentration ({len(value)}) MUST equal length of "
                    f"chemical_symbols ({len(info.data['chemical_symbols'])})"
                )
            return value

        raise ValueError(
            f"Could not validate {info.field_name!r} as 'chemical_symbols' is missing/invalid."
        )

    @field_validator("attached", "nattached", mode="after")
    @classmethod
    def validate_minimum_list_length(
        cls, value: Optional[Union[list[str], list[int]]]
    ) -> Optional[Union[list[str], list[int]]]:
        if value is not None and len(value) < 1:
            raise ValueError(
                "The list's length MUST be 1 or more, instead it was found to be "
                f"{len(value)}"
            )
        return value

    @model_validator(mode="after")
    def attached_nattached_mutually_exclusive(self) -> "Species":
        if (self.attached is None and self.nattached is not None) or (
            self.attached is not None and self.nattached is None
        ):
            raise ValueError(
                f"Either both or none of attached ({self.attached}) and nattached "
                f"({self.nattached}) MUST be set."
            )

        if (
            self.attached is not None
            and self.nattached is not None
            and len(self.attached) != len(self.nattached)
        ):
            raise ValueError(
                f"attached ({self.attached}) and nattached ({self.nattached}) MUST be "
                "lists of equal length."
            )

        return self

StructureResourceAttributes

Bases: EntryResourceAttributes

This class contains the Field for the attributes used to represent a structure, e.g. unit cell, atoms, positions.

Source code in optimade/models/structures.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
class StructureResourceAttributes(EntryResourceAttributes):
    """This class contains the Field for the attributes used to represent a structure, e.g. unit cell, atoms, positions."""

    elements: Annotated[
        Optional[list[str]],
        OptimadeField(
            description="""The chemical symbols of the different elements present in the structure.

- **Type**: list of strings.

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - The strings are the chemical symbols, i.e., either a single uppercase letter or an uppercase letter followed by a number of lowercase letters.
    - The order MUST be alphabetical.
    - MUST refer to the same elements in the same order, and therefore be of the same length, as `elements_ratios`, if the latter is provided.
    - Note: This property SHOULD NOT contain the string "X" to indicate non-chemical elements or "vacancy" to indicate vacancies (in contrast to the field `chemical_symbols` for the `species` property).

- **Examples**:
    - `["Si"]`
    - `["Al","O","Si"]`

- **Query examples**:
    - A filter that matches all records of structures that contain Si, Al **and** O, and possibly other elements: `elements HAS ALL "Si", "Al", "O"`.
    - To match structures with exactly these three elements, use `elements HAS ALL "Si", "Al", "O" AND elements LENGTH 3`.
    - Note: length queries on this property can be equivalently formulated by filtering on the `nelements`_ property directly.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
        ),
    ] = None

    nelements: Annotated[
        Optional[int],
        OptimadeField(
            description="""Number of different elements in the structure as an integer.

- **Type**: integer

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - MUST be equal to the lengths of the list properties `elements` and `elements_ratios`, if they are provided.

- **Examples**:
    - `3`

- **Querying**:
    - Note: queries on this property can equivalently be formulated using `elements LENGTH`.
    - A filter that matches structures that have exactly 4 elements: `nelements=4`.
    - A filter that matches structures that have between 2 and 7 elements: `nelements>=2 AND nelements<=7`.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
        ),
    ] = None

    elements_ratios: Annotated[
        Optional[list[float]],
        OptimadeField(
            description="""Relative proportions of different elements in the structure.

- **Type**: list of floats

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - Composed by the proportions of elements in the structure as a list of floating point numbers.
    - The sum of the numbers MUST be 1.0 (within floating point accuracy)
    - MUST refer to the same elements in the same order, and therefore be of the same length, as `elements`, if the latter is provided.

- **Examples**:
    - `[1.0]`
    - `[0.3333333333333333, 0.2222222222222222, 0.4444444444444444]`

- **Query examples**:
    - Note: Useful filters can be formulated using the set operator syntax for correlated values.
      However, since the values are floating point values, the use of equality comparisons is generally inadvisable.
    - OPTIONAL: a filter that matches structures where approximately 1/3 of the atoms in the structure are the element Al is: `elements:elements_ratios HAS ALL "Al":>0.3333, "Al":<0.3334`.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
        ),
    ] = None

    chemical_formula_descriptive: Annotated[
        Optional[str],
        OptimadeField(
            description="""The chemical formula for a structure as a string in a form chosen by the API implementation.

- **Type**: string

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - The chemical formula is given as a string consisting of properly capitalized element symbols followed by integers or decimal numbers, balanced parentheses, square, and curly brackets `(`,`)`, `[`,`]`, `{`, `}`, commas, the `+`, `-`, `:` and `=` symbols. The parentheses are allowed to be followed by a number. Spaces are allowed anywhere except within chemical symbols. The order of elements and any groupings indicated by parentheses or brackets are chosen freely by the API implementation.
    - The string SHOULD be arithmetically consistent with the element ratios in the `chemical_formula_reduced` property.
    - It is RECOMMENDED, but not mandatory, that symbols, parentheses and brackets, if used, are used with the meanings prescribed by [IUPAC's Nomenclature of Organic Chemistry](https://www.qmul.ac.uk/sbcs/iupac/bibliog/blue.html).

- **Examples**:
    - `"(H2O)2 Na"`
    - `"NaCl"`
    - `"CaCO3"`
    - `"CCaO3"`
    - `"(CH3)3N+ - [CH2]2-OH = Me3N+ - CH2 - CH2OH"`

- **Query examples**:
    - Note: the free-form nature of this property is likely to make queries on it across different databases inconsistent.
    - A filter that matches an exactly given formula: `chemical_formula_descriptive="(H2O)2 Na"`.
    - A filter that does a partial match: `chemical_formula_descriptive CONTAINS "H2O"`.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
        ),
    ] = None

    chemical_formula_reduced: Annotated[
        Optional[str],
        OptimadeField(
            description="""The reduced chemical formula for a structure as a string with element symbols and integer chemical proportion numbers.
The proportion number MUST be omitted if it is 1.

- **Type**: string

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property.
      However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).
      Intricate queries on formula components are instead suggested to be formulated using set-type filter operators on the multi valued `elements` and `elements_ratios` properties.
    - Element symbols MUST have proper capitalization (e.g., `"Si"`, not `"SI"` for "silicon").
    - Elements MUST be placed in alphabetical order, followed by their integer chemical proportion number.
    - For structures with no partial occupation, the chemical proportion numbers are the smallest integers for which the chemical proportion is exactly correct.
    - For structures with partial occupation, the chemical proportion numbers are integers that within reasonable approximation indicate the correct chemical proportions. The precise details of how to perform the rounding is chosen by the API implementation.
    - No spaces or separators are allowed.

- **Examples**:
    - `"H2NaO"`
    - `"ClNa"`
    - `"CCaO3"`

- **Query examples**:
    - A filter that matches an exactly given formula is `chemical_formula_reduced="H2NaO"`.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
            pattern=CHEMICAL_FORMULA_REGEXP,
        ),
    ] = None

    chemical_formula_hill: Annotated[
        Optional[str],
        OptimadeField(
            description="""The chemical formula for a structure in [Hill form](https://dx.doi.org/10.1021/ja02046a005) with element symbols followed by integer chemical proportion numbers. The proportion number MUST be omitted if it is 1.

- **Type**: string

- **Requirements/Conventions**:
    - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
      If supported, only a subset of the filter features MAY be supported.
    - The overall scale factor of the chemical proportions is chosen such that the resulting values are integers that indicate the most chemically relevant unit of which the system is composed.
      For example, if the structure is a repeating unit cell with four hydrogens and four oxygens that represents two hydroperoxide molecules, `chemical_formula_hill` is `"H2O2"` (i.e., not `"HO"`, nor `"H4O4"`).
    - If the chemical insight needed to ascribe a Hill formula to the system is not present, the property MUST be handled as unset.
    - Element symbols MUST have proper capitalization (e.g., `"Si"`, not `"SI"` for "silicon").
    - Elements MUST be placed in [Hill order](https://dx.doi.org/10.1021/ja02046a005), followed by their integer chemical proportion number.
      Hill order means: if carbon is present, it is placed first, and if also present, hydrogen is placed second.
      After that, all other elements are ordered alphabetically.
      If carbon is not present, all elements are ordered alphabetically.
    - If the system has sites with partial occupation and the total occupations of each element do not all sum up to integers, then the Hill formula SHOULD be handled as unset.
    - No spaces or separators are allowed.

- **Examples**:
    - `"H2O2"`

- **Query examples**:
    - A filter that matches an exactly given formula is `chemical_formula_hill="H2O2"`.""",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
            pattern=CHEMICAL_FORMULA_REGEXP,
        ),
    ] = None

    chemical_formula_anonymous: Annotated[
        Optional[str],
        OptimadeField(
            description="""The anonymous formula is the `chemical_formula_reduced`, but where the elements are instead first ordered by their chemical proportion number, and then, in order left to right, replaced by anonymous symbols A, B, C, ..., Z, Aa, Ba, ..., Za, Ab, Bb, ... and so on.

- **Type**: string

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property.
      However, support for filters using partial string matching with this property is OPTIONAL (i.e., BEGINS WITH, ENDS WITH, and CONTAINS).

- **Examples**:
    - `"A2B"`
    - `"A42B42C16D12E10F9G5"`

- **Querying**:
    - A filter that matches an exactly given formula is `chemical_formula_anonymous="A2B"`.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
            pattern=CHEMICAL_FORMULA_REGEXP,
        ),
    ] = None

    dimension_types: Annotated[
        Optional[list[Periodicity]],
        OptimadeField(
            min_length=3,
            max_length=3,
            title="Dimension Types",
            description="""List of three integers.
For each of the three directions indicated by the three lattice vectors (see property `lattice_vectors`), this list indicates if the direction is periodic (value `1`) or non-periodic (value `0`).
Note: the elements in this list each refer to the direction of the corresponding entry in `lattice_vectors` and *not* the Cartesian x, y, z directions.

- **Type**: list of integers.

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
    - MUST be a list of length 3.
    - Each integer element MUST assume only the value 0 or 1.

- **Examples**:
    - For a molecule: `[0, 0, 0]`
    - For a wire along the direction specified by the third lattice vector: `[0, 0, 1]`
    - For a 2D surface/slab, periodic on the plane defined by the first and third lattice vectors: `[1, 0, 1]`
    - For a bulk 3D system: `[1, 1, 1]`""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    nperiodic_dimensions: Annotated[
        Optional[int],
        OptimadeField(
            description="""An integer specifying the number of periodic dimensions in the structure, equivalent to the number of non-zero entries in `dimension_types`.

- **Type**: integer

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - The integer value MUST be between 0 and 3 inclusive and MUST be equal to the sum of the items in the `dimension_types` property.
    - This property only reflects the treatment of the lattice vectors provided for the structure, and not any physical interpretation of the dimensionality of its contents.

- **Examples**:
    - `2` should be indicated in cases where `dimension_types` is any of `[1, 1, 0]`, `[1, 0, 1]`, `[0, 1, 1]`.

- **Query examples**:
    - Match only structures with exactly 3 periodic dimensions: `nperiodic_dimensions=3`
    - Match all structures with 2 or fewer periodic dimensions: `nperiodic_dimensions<=2`""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.MUST,
        ),
    ] = None

    lattice_vectors: Annotated[
        Optional[list[Vector3D_unknown]],
        OptimadeField(
            min_length=3,
            max_length=3,
            description="""The three lattice vectors in Cartesian coordinates, in ångström (Å).

- **Type**: list of list of floats or unknown values.

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
      If supported, filters MAY support only a subset of comparison operators.
    - MUST be a list of three vectors *a*, *b*, and *c*, where each of the vectors MUST BE a list of the vector's coordinates along the x, y, and z Cartesian coordinates.
      (Therefore, the first index runs over the three lattice vectors and the second index runs over the x, y, z Cartesian coordinates).
    - For databases that do not define an absolute Cartesian system (e.g., only defining the length and angles between vectors), the first lattice vector SHOULD be set along *x* and the second on the *xy*-plane.
    - MUST always contain three vectors of three coordinates each, independently of the elements of property `dimension_types`.
      The vectors SHOULD by convention be chosen so the determinant of the `lattice_vectors` matrix is different from zero.
      The vectors in the non-periodic directions have no significance beyond fulfilling these requirements.
    - The coordinates of the lattice vectors of non-periodic dimensions (i.e., those dimensions for which `dimension_types` is `0`) MAY be given as a list of all `null` values.
        If a lattice vector contains the value `null`, all coordinates of that lattice vector MUST be `null`.

- **Examples**:
    - `[[4.0,0.0,0.0],[0.0,4.0,0.0],[0.0,1.0,4.0]]` represents a cell, where the first vector is `(4, 0, 0)`, i.e., a vector aligned along the `x` axis of length 4 Å; the second vector is `(0, 4, 0)`; and the third vector is `(0, 1, 4)`.""",
            unit="Å",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    cartesian_site_positions: Annotated[
        Optional[list[Vector3D]],
        OptimadeField(
            description="""Cartesian positions of each site in the structure.
A site is usually used to describe positions of atoms; what atoms can be encountered at a given site is conveyed by the `species_at_sites` property, and the species themselves are described in the `species` property.

- **Type**: list of list of floats

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
      If supported, filters MAY support only a subset of comparison operators.
    - It MUST be a list of length equal to the number of sites in the structure, where every element is a list of the three Cartesian coordinates of a site expressed as float values in the unit angstrom (Å).
    - An entry MAY have multiple sites at the same Cartesian position (for a relevant use of this, see e.g., the property `assemblies`).

- **Examples**:
    - `[[0,0,0],[0,0,2]]` indicates a structure with two sites, one sitting at the origin and one along the (positive) *z*-axis, 2 Å away from the origin.""",
            unit="Å",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    nsites: Annotated[
        Optional[int],
        OptimadeField(
            description="""An integer specifying the length of the `cartesian_site_positions` property.

- **Type**: integer

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.

- **Examples**:
    - `42`

- **Query examples**:
    - Match only structures with exactly 4 sites: `nsites=4`
    - Match structures that have between 2 and 7 sites: `nsites>=2 AND nsites<=7`""",
            queryable=SupportLevel.MUST,
            support=SupportLevel.SHOULD,
        ),
    ] = None

    species: Annotated[
        Optional[list[Species]],
        OptimadeField(
            description="""A list describing the species of the sites of this structure.
Species can represent pure chemical elements, virtual-crystal atoms representing a statistical occupation of a given site by multiple chemical elements, and/or a location to which there are attached atoms, i.e., atoms whose precise location are unknown beyond that they are attached to that position (frequently used to indicate hydrogen atoms attached to another element, e.g., a carbon with three attached hydrogens might represent a methyl group, -CH3).

- **Type**: list of dictionary with keys:
    - `name`: string (REQUIRED)
    - `chemical_symbols`: list of strings (REQUIRED)
    - `concentration`: list of float (REQUIRED)
    - `attached`: list of strings (REQUIRED)
    - `nattached`: list of integers (OPTIONAL)
    - `mass`: list of floats (OPTIONAL)
    - `original_name`: string (OPTIONAL).

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
        If supported, filters MAY support only a subset of comparison operators.
    - Each list member MUST be a dictionary with the following keys:
        - **name**: REQUIRED; gives the name of the species; the **name** value MUST be unique in the `species` list;
        - **chemical_symbols**: REQUIRED; MUST be a list of strings of all chemical elements composing this species.
          Each item of the list MUST be one of the following:
            - a valid chemical-element symbol, or
            - the special value `"X"` to represent a non-chemical element, or
            - the special value `"vacancy"` to represent that this site has a non-zero probability of having a vacancy (the respective probability is indicated in the `concentration` list, see below).

          If any one entry in the `species` list has a `chemical_symbols` list that is longer than 1 element, the correct flag MUST be set in the list `structure_features`.

        - **concentration**: REQUIRED; MUST be a list of floats, with same length as `chemical_symbols`.
          The numbers represent the relative concentration of the corresponding chemical symbol in this species.
          The numbers SHOULD sum to one. Cases in which the numbers do not sum to one typically fall only in the following two categories:

            - Numerical errors when representing float numbers in fixed precision, e.g. for two chemical symbols with concentrations `1/3` and `2/3`, the concentration might look something like `[0.33333333333, 0.66666666666]`. If the client is aware that the sum is not one because of numerical precision, it can renormalize the values so that the sum is exactly one.
            - Experimental errors in the data present in the database. In this case, it is the responsibility of the client to decide how to process the data.

            Note that concentrations are uncorrelated between different sites (even of the same species).

        - **attached**: OPTIONAL; if provided MUST be a list of length 1 or more of strings of chemical symbols for the elements attached to this site, or "X" for a non-chemical element.

        - **nattached**: OPTIONAL; if provided MUST be a list of length 1 or more of integers indicating the number of attached atoms of the kind specified in the value of the `attached` key.

          The implementation MUST include either both or none of the `attached` and `nattached` keys, and if they are provided, they MUST be of the same length.
          Furthermore, if they are provided, the `structure_features` property MUST include the string `site_attachments`.

        - **mass**: OPTIONAL. If present MUST be a list of floats, with the same length as `chemical_symbols`, providing element masses expressed in a.m.u.
          Elements denoting vacancies MUST have masses equal to 0.

        - **original_name**: OPTIONAL. Can be any valid Unicode string, and SHOULD contain (if specified) the name of the species that is used internally in the source database.

          Note: With regards to "source database", we refer to the immediate source being queried via the OPTIMADE API implementation.

          The main use of this field is for source databases that use species names, containing characters that are not allowed (see description of the list property `species_at_sites`).

    - For systems that have only species formed by a single chemical symbol, and that have at most one species per chemical symbol, SHOULD use the chemical symbol as species name (e.g., `"Ti"` for titanium, `"O"` for oxygen, etc.)
      However, note that this is OPTIONAL, and client implementations MUST NOT assume that the key corresponds to a chemical symbol, nor assume that if the species name is a valid chemical symbol, that it represents a species with that chemical symbol.
      This means that a species `{"name": "C", "chemical_symbols": ["Ti"], "concentration": [1.0]}` is valid and represents a titanium species (and *not* a carbon species).
    - It is NOT RECOMMENDED that a structure includes species that do not have at least one corresponding site.

- **Examples**:
    - `[ {"name": "Ti", "chemical_symbols": ["Ti"], "concentration": [1.0]} ]`: any site with this species is occupied by a Ti atom.
    - `[ {"name": "Ti", "chemical_symbols": ["Ti", "vacancy"], "concentration": [0.9, 0.1]} ]`: any site with this species is occupied by a Ti atom with 90 % probability, and has a vacancy with 10 % probability.
    - `[ {"name": "BaCa", "chemical_symbols": ["vacancy", "Ba", "Ca"], "concentration": [0.05, 0.45, 0.5], "mass": [0.0, 137.327, 40.078]} ]`: any site with this species is occupied by a Ba atom with 45 % probability, a Ca atom with 50 % probability, and by a vacancy with 5 % probability. The mass of this site is (on average) 88.5 a.m.u.
    - `[ {"name": "C12", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [12.0]} ]`: any site with this species is occupied by a carbon isotope with mass 12.
    - `[ {"name": "C13", "chemical_symbols": ["C"], "concentration": [1.0], "mass": [13.0]} ]`: any site with this species is occupied by a carbon isotope with mass 13.
    - `[ {"name": "CH3", "chemical_symbols": ["C"], "concentration": [1.0], "attached": ["H"], "nattached": [3]} ]`: any site with this species is occupied by a methyl group, -CH3, which is represented without specifying precise positions of the hydrogen atoms.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    species_at_sites: Annotated[
        Optional[list[str]],
        OptimadeField(
            description="""Name of the species at each site (where values for sites are specified with the same order of the property `cartesian_site_positions`).
The properties of the species are found in the property `species`.

- **Type**: list of strings.

- **Requirements/Conventions**:
    - **Support**: SHOULD be supported by all implementations, i.e., SHOULD NOT be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
      If supported, filters MAY support only a subset of comparison operators.
    - MUST have length equal to the number of sites in the structure (first dimension of the list property `cartesian_site_positions`).
    - Each species name mentioned in the `species_at_sites` list MUST be described in the list property `species` (i.e. for each value in the `species_at_sites` list there MUST exist exactly one dictionary in the `species` list with the `name` attribute equal to the corresponding `species_at_sites` value).
    - Each site MUST be associated only to a single species.
      **Note**: However, species can represent mixtures of atoms, and multiple species MAY be defined for the same chemical element.
      This latter case is useful when different atoms of the same type need to be grouped or distinguished, for instance in simulation codes to assign different initial spin states.

- **Examples**:
    - `["Ti","O2"]` indicates that the first site is hosting a species labeled `"Ti"` and the second a species labeled `"O2"`.
    - `["Ac", "Ac", "Ag", "Ir"]` indicating the first two sites contains the `"Ac"` species, while the third and fourth sites contain the `"Ag"` and `"Ir"` species, respectively.""",
            support=SupportLevel.SHOULD,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    assemblies: Annotated[
        Optional[list[Assembly]],
        OptimadeField(
            description="""A description of groups of sites that are statistically correlated.

- **Type**: list of dictionary with keys:
    - `sites_in_groups`: list of list of integers (REQUIRED)
    - `group_probabilities`: list of floats (REQUIRED)

- **Requirements/Conventions**:
    - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`.
    - **Query**: Support for queries on this property is OPTIONAL.
        If supported, filters MAY support only a subset of comparison operators.
    - The property SHOULD be `null` for entries that have no partial occupancies.
    - If present, the correct flag MUST be set in the list `structure_features`.
    - Client implementations MUST check its presence (as its presence changes the interpretation of the structure).
    - If present, it MUST be a list of dictionaries, each of which represents an assembly and MUST have the following two keys:
        - **sites_in_groups**: Index of the sites (0-based) that belong to each group for each assembly.

            Example: `[[1], [2]]`: two groups, one with the second site, one with the third.
            Example: `[[1,2], [3]]`: one group with the second and third site, one with the fourth.

        - **group_probabilities**: Statistical probability of each group. It MUST have the same length as `sites_in_groups`.
            It SHOULD sum to one.
            See below for examples of how to specify the probability of the occurrence of a vacancy.
            The possible reasons for the values not to sum to one are the same as already specified above for the `concentration` of each `species`.

    - If a site is not present in any group, it means that it is present with 100 % probability (as if no assembly was specified).
    - A site MUST NOT appear in more than one group.

- **Examples** (for each entry of the assemblies list):
    - `{"sites_in_groups": [[0], [1]], "group_probabilities: [0.3, 0.7]}`: the first site and the second site never occur at the same time in the unit cell.
        Statistically, 30 % of the times the first site is present, while 70 % of the times the second site is present.
    - `{"sites_in_groups": [[1,2], [3]], "group_probabilities: [0.3, 0.7]}`: the second and third site are either present together or not present; they form the first group of atoms for this assembly.
        The second group is formed by the fourth site.
        Sites of the first group (the second and the third) are never present at the same time as the fourth site.
        30 % of times sites 1 and 2 are present (and site 3 is absent); 70 % of times site 3 is present (and sites 1 and 2 are absent).

- **Notes**:
    - Assemblies are essential to represent, for instance, the situation where an atom can statistically occupy two different positions (sites).

    - By defining groups, it is possible to represent, e.g., the case where a functional molecule (and not just one atom) is either present or absent (or the case where it it is present in two conformations)

    - Considerations on virtual alloys and on vacancies: In the special case of a virtual alloy, these specifications allow two different, equivalent ways of specifying them.
        For instance, for a site at the origin with 30 % probability of being occupied by Si, 50 % probability of being occupied by Ge, and 20 % of being a vacancy, the following two representations are possible:

        - Using a single species:
            ```json
            {
              "cartesian_site_positions": [[0,0,0]],
              "species_at_sites": ["SiGe-vac"],
              "species": [
              {
                "name": "SiGe-vac",
                "chemical_symbols": ["Si", "Ge", "vacancy"],
                "concentration": [0.3, 0.5, 0.2]
              }
              ]
              // ...
            }
            ```

        - Using multiple species and the assemblies:
            ```json
            {
              "cartesian_site_positions": [ [0,0,0], [0,0,0], [0,0,0] ],
              "species_at_sites": ["Si", "Ge", "vac"],
              "species": [
                { "name": "Si", "chemical_symbols": ["Si"], "concentration": [1.0] },
                { "name": "Ge", "chemical_symbols": ["Ge"], "concentration": [1.0] },
                { "name": "vac", "chemical_symbols": ["vacancy"], "concentration": [1.0] }
              ],
              "assemblies": [
                {
              "sites_in_groups": [ [0], [1], [2] ],
              "group_probabilities": [0.3, 0.5, 0.2]
                }
              ]
              // ...
            }
            ```

    - It is up to the database provider to decide which representation to use, typically depending on the internal format in which the structure is stored.
        However, given a structure identified by a unique ID, the API implementation MUST always provide the same representation for it.

    - The probabilities of occurrence of different assemblies are uncorrelated.
        So, for instance in the following case with two assemblies:
        ```json
        {
          "assemblies": [
            {
              "sites_in_groups": [ [0], [1] ],
              "group_probabilities": [0.2, 0.8],
            },
            {
              "sites_in_groups": [ [2], [3] ],
              "group_probabilities": [0.3, 0.7]
            }
          ]
        }
        ```

        Site 0 is present with a probability of 20 % and site 1 with a probability of 80 %. These two sites are correlated (either site 0 or 1 is present). Similarly, site 2 is present with a probability of 30 % and site 3 with a probability of 70 %.
        These two sites are correlated (either site 2 or 3 is present).
        However, the presence or absence of sites 0 and 1 is not correlated with the presence or absence of sites 2 and 3 (in the specific example, the pair of sites (0, 2) can occur with 0.2*0.3 = 6 % probability; the pair (0, 3) with 0.2*0.7 = 14 % probability; the pair (1, 2) with 0.8*0.3 = 24 % probability; and the pair (1, 3) with 0.8*0.7 = 56 % probability).""",
            support=SupportLevel.OPTIONAL,
            queryable=SupportLevel.OPTIONAL,
        ),
    ] = None

    structure_features: Annotated[
        list[StructureFeatures],
        OptimadeField(
            title="Structure Features",
            description="""A list of strings that flag which special features are used by the structure.

- **Type**: list of strings

- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property.
    Filters on the list MUST support all mandatory HAS-type queries.
    Filter operators for comparisons on the string components MUST support equality, support for other comparison operators are OPTIONAL.
    - MUST be an empty list if no special features are used.
    - MUST be sorted alphabetically.
    - If a special feature listed below is used, the list MUST contain the corresponding string.
    - If a special feature listed below is not used, the list MUST NOT contain the corresponding string.
    - **List of strings used to indicate special structure features**:
        - `disorder`: this flag MUST be present if any one entry in the `species` list has a `chemical_symbols` list that is longer than 1 element.
        - `implicit_atoms`: this flag MUST be present if the structure contains atoms that are not assigned to sites via the property `species_at_sites` (e.g., because their positions are unknown).
           When this flag is present, the properties related to the chemical formula will likely not match the type and count of atoms represented by the `species_at_sites`, `species` and `assemblies` properties.
        - `site_attachments`: this flag MUST be present if any one entry in the `species` list includes `attached` and `nattached`.
        - `assemblies`: this flag MUST be present if the property `assemblies` is present.

- **Examples**: A structure having implicit atoms and using assemblies: `["assemblies", "implicit_atoms"]`""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ]

    @model_validator(mode="after")
    def warn_on_missing_correlated_fields(self) -> "StructureResourceAttributes":
        """Emit warnings if a field takes a null value when a value
        was expected based on the value/nullity of another field.
        """
        accumulated_warnings = []
        for field_set in CORRELATED_STRUCTURE_FIELDS:
            missing_fields = {
                field for field in field_set if getattr(self, field, None) is None
            }
            if missing_fields and len(missing_fields) != len(field_set):
                accumulated_warnings += [
                    f"Structure with attributes {self} is missing fields "
                    f"{missing_fields} which are required if "
                    f"{field_set - missing_fields} are present."
                ]

        for warn in accumulated_warnings:
            warnings.warn(warn, MissingExpectedField)

        return self

    @field_validator("chemical_formula_reduced", "chemical_formula_hill", mode="after")
    @classmethod
    def check_ordered_formula(
        cls, value: Optional[str], info: "ValidationInfo"
    ) -> Optional[str]:
        if value is None:
            return value

        elements = re.findall(r"[A-Z][a-z]?", value)
        expected_elements = sorted(elements)

        if info.field_name == "chemical_formula_hill":
            # Make sure C is first (and H is second, if present along with C).
            if "C" in expected_elements:
                expected_elements = sorted(
                    expected_elements,
                    key=lambda elem: {"C": "0", "H": "1"}.get(elem, elem),
                )

        if any(elem not in CHEMICAL_SYMBOLS for elem in elements):
            raise ValueError(
                f"Cannot use unknown chemical symbols {[elem for elem in elements if elem not in CHEMICAL_SYMBOLS]} in {info.field_name!r}"
            )

        if expected_elements != elements:
            order = (
                "Hill" if info.field_name == "chemical_formula_hill" else "alphabetical"
            )
            raise ValueError(
                f"Elements in {info.field_name!r} must appear in {order} order: {expected_elements} not {elements}."
            )

        return value

    @field_validator("chemical_formula_anonymous", mode="after")
    @classmethod
    def check_anonymous_formula(cls, value: Optional[str]) -> Optional[str]:
        if value is None:
            return value

        elements = tuple(re.findall(r"[A-Z][a-z]*", value))
        numbers = re.split(r"[A-Z][a-z]*", value)[1:]
        numbers = [int(i) if i else 1 for i in numbers]

        expected_labels = ANONYMOUS_ELEMENTS[: len(elements)]
        expected_numbers = sorted(numbers, reverse=True)

        if expected_numbers != numbers:
            raise ValueError(
                f"'chemical_formula_anonymous' {value} has wrong order: elements with "
                f"highest proportion should appear first: {numbers} vs expected "
                f"{expected_numbers}"
            )
        if elements != expected_labels:
            raise ValueError(
                f"'chemical_formula_anonymous' {value} has wrong labels: {elements} vs"
                f" expected {expected_labels}."
            )

        return value

    @field_validator(
        "chemical_formula_anonymous", "chemical_formula_reduced", mode="after"
    )
    @classmethod
    def check_reduced_formulae(
        cls, value: Optional[str], info: "ValidationInfo"
    ) -> Optional[str]:
        if value is None:
            return value

        reduced_formula = reduce_formula(value)
        if reduced_formula != value:
            raise ValueError(
                f"{info.field_name} {value!r} is not properly reduced: expected "
                f"{reduced_formula!r}."
            )

        return value

    @field_validator("elements", mode="after")
    @classmethod
    def elements_must_be_alphabetical(
        cls, value: Optional[list[str]]
    ) -> Optional[list[str]]:
        if value is None:
            return value

        if sorted(value) != value:
            raise ValueError(f"elements must be sorted alphabetically, but is: {value}")
        return value

    @field_validator("elements_ratios", mode="after")
    @classmethod
    def ratios_must_sum_to_one(
        cls, value: Optional[list[float]]
    ) -> Optional[list[float]]:
        if value is None:
            return value

        if abs(sum(value) - 1) > EPS:
            raise ValueError(
                "elements_ratios MUST sum to 1 within (at least single precision) "
                f"floating point accuracy. It sums to: {sum(value)}"
            )
        return value

    @model_validator(mode="after")
    def check_dimensions_types_dependencies(self) -> "StructureResourceAttributes":
        if self.nperiodic_dimensions is not None:
            if self.dimension_types and self.nperiodic_dimensions != sum(
                self.dimension_types
            ):
                raise ValueError(
                    f"nperiodic_dimensions ({self.nperiodic_dimensions}) does not match "
                    f"expected value of {sum(self.dimension_types)} from dimension_types "
                    f"({self.dimension_types})"
                )

        if self.lattice_vectors is not None:
            if self.dimension_types:
                for dim_type, vector in zip(self.dimension_types, self.lattice_vectors):
                    if None in vector and dim_type == Periodicity.PERIODIC.value:
                        raise ValueError(
                            f"Null entries in lattice vectors are only permitted when the "
                            "corresponding dimension type is "
                            f"{Periodicity.APERIODIC.value}. Here: dimension_types = "
                            f"{tuple(getattr(_, 'value', None) for _ in self.dimension_types)},"
                            f" lattice_vectors = {self.lattice_vectors}"
                        )

        return self

    @field_validator("lattice_vectors", mode="after")
    @classmethod
    def null_values_for_whole_vector(
        cls,
        value: Optional[
            Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]
        ],
    ) -> Optional[Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]]:
        if value is None:
            return value

        for vector in value:
            if None in vector and any(isinstance(_, float) for _ in vector):
                raise ValueError(
                    "A lattice vector MUST be either all `null` or all numbers "
                    f"(vector: {vector}, all vectors: {value})"
                )
        return value

    @model_validator(mode="after")
    def validate_nsites(self) -> "StructureResourceAttributes":
        if self.nsites is None:
            return self

        if self.cartesian_site_positions and self.nsites != len(
            self.cartesian_site_positions
        ):
            raise ValueError(
                f"nsites (value: {self.nsites}) MUST equal length of "
                "cartesian_site_positions (value: "
                f"{len(self.cartesian_site_positions)})"
            )
        return self

    @model_validator(mode="after")
    def validate_species_at_sites(self) -> "StructureResourceAttributes":
        if self.species_at_sites is None:
            return self

        if self.nsites and len(self.species_at_sites) != self.nsites:
            raise ValueError(
                f"Number of species_at_sites (value: {len(self.species_at_sites)}) "
                f"MUST equal number of sites (value: {self.nsites})"
            )

        if self.species:
            all_species_names = {_.name for _ in self.species}

            for species_at_site in self.species_at_sites:
                if species_at_site not in all_species_names:
                    raise ValueError(
                        "species_at_sites MUST be represented by a species' name, "
                        f"but {species_at_site} was not found in the list of species "
                        f"names: {all_species_names}"
                    )

        return self

    @field_validator("species", mode="after")
    @classmethod
    def validate_species(
        cls, value: Optional[list[Species]]
    ) -> Optional[list[Species]]:
        if value is None:
            return value

        all_species = [_.name for _ in value]
        unique_species = set(all_species)
        if len(all_species) != len(unique_species):
            raise ValueError(
                f"Species MUST be unique based on their 'name'. Found species names: {all_species}"
            )

        return value

    @model_validator(mode="after")
    def validate_structure_features(self) -> "StructureResourceAttributes":
        if [
            StructureFeatures(value)
            for value in sorted(_.value for _ in self.structure_features)
        ] != self.structure_features:
            raise ValueError(
                "structure_features MUST be sorted alphabetically, structure_features: "
                f"{self.structure_features}"
            )

        # assemblies
        if self.assemblies is not None:
            if StructureFeatures.ASSEMBLIES not in self.structure_features:
                raise ValueError(
                    f"{StructureFeatures.ASSEMBLIES.value} MUST be present, since the "
                    "property of the same name is present"
                )
        elif StructureFeatures.ASSEMBLIES in self.structure_features:
            raise ValueError(
                f"{StructureFeatures.ASSEMBLIES.value} MUST NOT be present, "
                "since the property of the same name is not present"
            )

        if self.species:
            # disorder
            for species in self.species:
                if len(species.chemical_symbols) > 1:
                    if StructureFeatures.DISORDER not in self.structure_features:
                        raise ValueError(
                            f"{StructureFeatures.DISORDER.value} MUST be present when "
                            "any one entry in species has a chemical_symbols list "
                            "greater than one element"
                        )
                    break
            else:
                if StructureFeatures.DISORDER in self.structure_features:
                    raise ValueError(
                        f"{StructureFeatures.DISORDER.value} MUST NOT be present, "
                        "since all species' chemical_symbols lists are equal to or "
                        "less than one element"
                    )

            # site_attachments
            for species in self.species:
                # There is no need to also test "nattached",
                # since a Species validator makes sure either both are present or both are None.
                if species.attached is not None:
                    if (
                        StructureFeatures.SITE_ATTACHMENTS
                        not in self.structure_features
                    ):
                        raise ValueError(
                            f"{StructureFeatures.SITE_ATTACHMENTS.value} MUST be "
                            "present when any one entry in species includes attached "
                            "and nattached"
                        )
                    break
            else:
                if StructureFeatures.SITE_ATTACHMENTS in self.structure_features:
                    raise ValueError(
                        f"{StructureFeatures.SITE_ATTACHMENTS.value} MUST NOT be "
                        "present, since no species includes the attached and nattached"
                        " fields"
                    )

            # implicit_atoms
            for name in [_.name for _ in self.species]:
                if (
                    self.species_at_sites is not None
                    and name not in self.species_at_sites
                ):
                    if StructureFeatures.IMPLICIT_ATOMS not in self.structure_features:
                        raise ValueError(
                            f"{StructureFeatures.IMPLICIT_ATOMS.value} MUST be present"
                            " when any one entry in species is not represented in "
                            "species_at_sites"
                        )
                    break
            else:
                if StructureFeatures.IMPLICIT_ATOMS in self.structure_features:
                    raise ValueError(
                        f"{StructureFeatures.IMPLICIT_ATOMS.value} MUST NOT be "
                        "present, since all species are represented in species_at_sites"
                    )

        return self

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
109
110
111
112
113
114
115
116
@field_validator("immutable_id", mode="before")
@classmethod
def cast_immutable_id_to_str(cls, value: Any) -> str:
    """Convenience validator for casting `immutable_id` to a string."""
    if value is not None and not isinstance(value, str):
        value = str(value)

    return value

warn_on_missing_correlated_fields()

Emit warnings if a field takes a null value when a value was expected based on the value/nullity of another field.

Source code in optimade/models/structures.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
@model_validator(mode="after")
def warn_on_missing_correlated_fields(self) -> "StructureResourceAttributes":
    """Emit warnings if a field takes a null value when a value
    was expected based on the value/nullity of another field.
    """
    accumulated_warnings = []
    for field_set in CORRELATED_STRUCTURE_FIELDS:
        missing_fields = {
            field for field in field_set if getattr(self, field, None) is None
        }
        if missing_fields and len(missing_fields) != len(field_set):
            accumulated_warnings += [
                f"Structure with attributes {self} is missing fields "
                f"{missing_fields} which are required if "
                f"{field_set - missing_fields} are present."
            ]

    for warn in accumulated_warnings:
        warnings.warn(warn, MissingExpectedField)

    return self

_get_molecule(optimade_structure)

Create pymatgen Molecule from OPTIMADE structure

Source code in optimade/adapters/structures/pymatgen.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def _get_molecule(optimade_structure: OptimadeStructure) -> Molecule:
    """Create pymatgen Molecule from OPTIMADE structure"""

    attributes = optimade_structure.attributes

    return Molecule(
        species=_pymatgen_species(
            nsites=attributes.nsites,  # type: ignore[arg-type]
            species=attributes.species,  # type: ignore[arg-type]
            species_at_sites=attributes.species_at_sites,  # type: ignore[arg-type]
        ),
        coords=attributes.cartesian_site_positions,
    )

_get_structure(optimade_structure)

Create pymatgen Structure from OPTIMADE structure

Source code in optimade/adapters/structures/pymatgen.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def _get_structure(optimade_structure: OptimadeStructure) -> Structure:
    """Create pymatgen Structure from OPTIMADE structure"""

    attributes = optimade_structure.attributes

    return Structure(
        lattice=Lattice(attributes.lattice_vectors, attributes.dimension_types),
        species=_pymatgen_species(
            nsites=attributes.nsites,  # type: ignore[arg-type]
            species=attributes.species,
            species_at_sites=attributes.species_at_sites,  # type: ignore[arg-type]
        ),
        coords=attributes.cartesian_site_positions,
        coords_are_cartesian=True,
    )

_pymatgen_species(nsites, species, species_at_sites)

Create list of {"symbol": "concentration"} per site for values to pymatgen species parameters. Remove vacancies, if they are present.

Source code in optimade/adapters/structures/pymatgen.py
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
def _pymatgen_species(
    nsites: int,
    species: Optional[list[OptimadeStructureSpecies]],
    species_at_sites: list[str],
) -> list[dict[str, float]]:
    """
    Create list of {"symbol": "concentration"} per site for values to pymatgen species parameters.
    Remove vacancies, if they are present.
    """
    if species is None:
        # If species is missing, infer data from species_at_sites
        species = species_from_species_at_sites(species_at_sites)

    optimade_species = {_.name: _ for _ in species}

    pymatgen_species = []
    for site_number in range(nsites):
        species_name = species_at_sites[site_number]
        current_species = optimade_species[species_name]

        chemical_symbols = []
        concentration = []
        for index, symbol in enumerate(current_species.chemical_symbols):
            if symbol == "vacancy":
                # Skip. This is how pymatgen handles vacancies;
                # to not include them, while keeping the concentration in a site less than 1.
                continue
            else:
                chemical_symbols.append(symbol)
                concentration.append(current_species.concentration[index])

        pymatgen_species.append(dict(zip(chemical_symbols, concentration)))

    return pymatgen_species

anonymize_formula(formula)

Takes a string representation of a chemical formula of the form [A-Z][a-z]*[0-9]* (potentially with whitespace) and returns the OPTIMADE chemical_formula_anonymous representation, i.e., a reduced chemical formula comprising of element symbols drawn from A, B, C... ordered from largest proportion to smallest.

Returns:

Type Description
str

The anonymous chemical formula in the OPTIMADE representation.

Source code in optimade/models/utils.py
208
209
210
211
212
213
214
215
216
217
def anonymize_formula(formula: str) -> str:
    """Takes a string representation of a chemical formula of the form `[A-Z][a-z]*[0-9]*` (potentially with whitespace) and
    returns the OPTIMADE `chemical_formula_anonymous` representation, i.e., a reduced chemical formula comprising of element symbols
    drawn from A, B, C... ordered from largest proportion to smallest.

    Returns:
        The anonymous chemical formula in the OPTIMADE representation.

    """
    return _reduce_or_anonymize_formula(formula, alphabetize=False, anonymize=True)

from_pymatgen(pmg_structure)

Convert a pymatgen Structure (3D) into an OPTIMADE StructureResourceAttributes model.

Parameters:

Name Type Description Default
pmg_structure Structure

The pymatgen Structure to convert.

required

Returns:

Type Description
StructureResourceAttributes

An OPTIMADE StructureResourceAttributes model, which can be converted to a raw Python dictionary with .model_dump() or to JSON with .model_dump_json().

Source code in optimade/adapters/structures/pymatgen.py
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
def from_pymatgen(pmg_structure: Structure) -> StructureResourceAttributes:
    """Convert a pymatgen `Structure` (3D) into an OPTIMADE `StructureResourceAttributes` model.

    Parameters:
        pmg_structure: The pymatgen `Structure` to convert.

    Returns:
        An OPTIMADE `StructureResourceAttributes` model, which can be converted to a raw Python
            dictionary with `.model_dump()` or to JSON with `.model_dump_json()`.

    """

    if not isinstance(pmg_structure, Structure):
        raise RuntimeError(
            f"Cannot convert type {type(pmg_structure)} into an OPTIMADE `StructureResourceAttributes` model."
        )

    attributes = {}
    attributes["cartesian_site_positions"] = pmg_structure.lattice.get_cartesian_coords(
        pmg_structure.frac_coords
    ).tolist()
    attributes["lattice_vectors"] = pmg_structure.lattice.matrix.tolist()
    attributes["species_at_sites"] = [_.symbol for _ in pmg_structure.species]
    attributes["species"] = [
        {"name": _.symbol, "chemical_symbols": [_.symbol], "concentration": [1]}
        for _ in set(pmg_structure.composition.elements)
    ]
    attributes["dimension_types"] = [int(_) for _ in pmg_structure.lattice.pbc]
    attributes["nperiodic_dimensions"] = sum(attributes["dimension_types"])
    attributes["nelements"] = len(pmg_structure.composition.elements)
    attributes["chemical_formula_anonymous"] = anonymize_formula(
        pmg_structure.composition.formula
    )
    attributes["elements"] = sorted(
        [_.symbol for _ in pmg_structure.composition.elements]
    )
    attributes["chemical_formula_reduced"] = reduce_formula(
        pmg_structure.composition.formula
    )
    attributes["chemical_formula_descriptive"] = pmg_structure.composition.formula
    attributes["elements_ratios"] = [
        pmg_structure.composition.get_atomic_fraction(e) for e in attributes["elements"]
    ]
    attributes["nsites"] = len(attributes["species_at_sites"])

    attributes["last_modified"] = None
    attributes["immutable_id"] = None
    attributes["structure_features"] = []

    return StructureResourceAttributes(**attributes)

get_pymatgen(optimade_structure)

Get pymatgen Structure or Molecule from OPTIMADE structure.

This function will return either a pymatgen Structure or Molecule based on the periodicity or periodic dimensionality of OPTIMADE structure.

For structures that are periodic in one or more dimensions, a pymatgen Structure is returned when valid lattice_vectors are given. This means, if the any of the values in the dimension_types attribute is 1s or if nperiodic_dimesions > 0.

Otherwise, a pymatgen Molecule is returned.

Parameters:

Name Type Description Default
optimade_structure StructureResource

OPTIMADE structure.

required

Returns:

Type Description
Union[Structure, Molecule]

A pymatgen Structure or Molecule based on the periodicity of the

Union[Structure, Molecule]

OPTIMADE structure.

Source code in optimade/adapters/structures/pymatgen.py
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
def get_pymatgen(optimade_structure: OptimadeStructure) -> Union[Structure, Molecule]:
    """Get pymatgen `Structure` or `Molecule` from OPTIMADE structure.

    This function will return either a pymatgen `Structure` or `Molecule` based
    on the periodicity or periodic dimensionality of OPTIMADE structure.

    For structures that are periodic in one or more dimensions, a pymatgen `Structure` is returned when valid lattice_vectors are given.
    This means, if the any of the values in the [`dimension_types`][optimade.models.structures.StructureResourceAttributes.dimension_types]
    attribute is `1`s or if [`nperiodic_dimesions`][optimade.models.structures.StructureResourceAttributes.nperiodic_dimensions] > 0.

    Otherwise, a pymatgen `Molecule` is returned.

    Parameters:
        optimade_structure: OPTIMADE structure.

    Returns:
        A pymatgen `Structure` or `Molecule` based on the periodicity of the
        OPTIMADE structure.

    """
    if "optimade.adapters" in repr(globals().get("Structure")):
        warn(PYMATGEN_NOT_FOUND, AdapterPackageNotFound)
        return None

    if valid_lattice_vector(optimade_structure.attributes.lattice_vectors) and (  # type: ignore[arg-type]
        optimade_structure.attributes.nperiodic_dimensions > 0  # type: ignore[operator]
        or any(optimade_structure.attributes.dimension_types)  # type: ignore[arg-type]
    ):
        return _get_structure(optimade_structure)

    return _get_molecule(optimade_structure)

reduce_formula(formula)

Takes a string representation of a chemical formula of the form [A-Z][a-z]*[0-9]* (potentially with whitespace) and reduces it by the GCD of the proportion integers present in the formula, stripping any leftover "1" values.

Returns:

Type Description
str

The reduced chemical formula in the OPTIMADE representation.

Source code in optimade/models/utils.py
220
221
222
223
224
225
226
227
228
def reduce_formula(formula: str) -> str:
    """Takes a string representation of a chemical formula of the form `[A-Z][a-z]*[0-9]*` (potentially with whitespace) and
    reduces it by the GCD of the proportion integers present in the formula, stripping any leftover "1" values.

    Returns:
        The reduced chemical formula in the OPTIMADE representation.

    """
    return _reduce_or_anonymize_formula(formula, alphabetize=True, anonymize=False)

species_from_species_at_sites(species_at_sites)

When a list of species dictionaries is not provided, this function can be used to infer the species from the provided species_at_sites.

In this use case, species_at_sites is assumed to provide a list of element symbols, and refers to situations with no mixed occupancy, i.e., the constructed species list will contain all unique species with concentration equal to 1 and the species_at_site tag will be used as the chemical symbol.

Parameters:

Name Type Description Default
species_at_sites list[str]

The list found under the species_at_sites field.

required

Returns:

Type Description
list[Species]

An OPTIMADE species list.

Source code in optimade/adapters/structures/utils.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def species_from_species_at_sites(
    species_at_sites: list[str],
) -> list[OptimadeStructureSpecies]:
    """When a list of species dictionaries is not provided, this function
    can be used to infer the species from the provided species_at_sites.

    In this use case, species_at_sites is assumed to provide a list of
    element symbols, and refers to situations with no mixed occupancy, i.e.,
    the constructed species list will contain all unique species with
    concentration equal to 1 and the species_at_site tag will be used as
    the chemical symbol.

    Parameters:
        species_at_sites: The list found under the species_at_sites field.

    Returns:
        An OPTIMADE species list.

    """
    return [
        OptimadeStructureSpecies(name=_, concentration=[1.0], chemical_symbols=[_])
        for _ in set(species_at_sites)
    ]

valid_lattice_vector(lattice_vec)

Source code in optimade/adapters/structures/utils.py
23
24
25
26
27
28
29
30
31
def valid_lattice_vector(lattice_vec: tuple[Vector3D, Vector3D, Vector3D]):
    if len(lattice_vec) != 3:
        return False
    for vector in lattice_vec:
        if (
            (len(vector) != 3) or (None in vector) or (np.linalg.norm(vector) < 1e-15)
        ):  # Due to rounding errors very small values instead of 0.0 may appear for the lattice vectors. therefore I check here whether the value is not too small. I am however not sure what the smallest value is that I can put here.
            return False
    return True