← 返回首页
OPTIMADE Data Models - OPTIMADE Python tools
Skip to content
OPTIMADE Python tools
OPTIMADE Data Models
optimade-python-tools
OPTIMADE Python tools
Table of contents

OPTIMADE Data Models

This page provides documentation for the optimade.models submodule, where all the OPTIMADE (and JSON:API)-defined data models are located.

For example, the three OPTIMADE entry types, structures, references and links, are defined primarily through the corresponding attribute models:

As well as validating data types when creating instances of these models, this package defines several OPTIMADE-specific validators that ensure consistency between fields (e.g., the value of nsites matches the number of positions provided in cartesian_site_positions).

ATOMIC_NUMBERS = {} module-attribute

CHEMICAL_SYMBOLS = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'] module-attribute

EXTRA_SYMBOLS = ['X', 'vacancy'] module-attribute

Vector3D = Annotated[list[Annotated[float, BeforeValidator(float)]], Field(min_length=3, max_length=3)] module-attribute

Assembly

Bases: BaseModel

A description of groups of sites that are statistically correlated.

  • 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).
Source code in optimade/models/structures.py
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
class Assembly(BaseModel): """A description of groups of sites that are statistically correlated. - **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). """ sites_in_groups: Annotated[ list[list[int]], OptimadeField( description="""Index of the sites (0-based) that belong to each group for each assembly. - **Examples**: - `[[1], [2]]`: two groups, one with the second site, one with the third. - `[[1,2], [3]]`: one group with the second and third site, one with the fourth.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] group_probabilities: Annotated[ list[float], OptimadeField( description="""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`.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] @field_validator("sites_in_groups", mode="after") @classmethod def validate_sites_in_groups(cls, value: list[list[int]]) -> list[list[int]]: sites = [] for group in value: sites.extend(group) if len(set(sites)) != len(sites): raise ValueError( f"A site MUST NOT appear in more than one group. Given value: {value}" ) return value @model_validator(mode="after") def check_self_consistency(self) -> "Assembly": if len(self.group_probabilities) != len(self.sites_in_groups): raise ValueError( f"sites_in_groups and group_probabilities MUST be of same length, " f"but are {len(self.sites_in_groups)} and {len(self.group_probabilities)}, " "respectively" ) return self

group_probabilities instance-attribute

sites_in_groups instance-attribute

check_self_consistency()

Source code in optimade/models/structures.py
266 267 268 269 270 271 272 273 274
@model_validator(mode="after") def check_self_consistency(self) -> "Assembly": if len(self.group_probabilities) != len(self.sites_in_groups): raise ValueError( f"sites_in_groups and group_probabilities MUST be of same length, " f"but are {len(self.sites_in_groups)} and {len(self.group_probabilities)}, " "respectively" ) return self

validate_sites_in_groups(value) classmethod

Source code in optimade/models/structures.py
254 255 256 257 258 259 260 261 262 263 264
@field_validator("sites_in_groups", mode="after") @classmethod def validate_sites_in_groups(cls, value: list[list[int]]) -> list[list[int]]: sites = [] for group in value: sites.extend(group) if len(set(sites)) != len(sites): raise ValueError( f"A site MUST NOT appear in more than one group. Given value: {value}" ) return value

Attributes

Bases: BaseModel

Members of the attributes object ("attributes") represent information about the resource object in which it's defined. The keys for Attributes MUST NOT be: relationships links id type

Source code in optimade/models/jsonapi.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
class Attributes(BaseModel): """ Members of the attributes object ("attributes\") represent information about the resource object in which it's defined. The keys for Attributes MUST NOT be: relationships links id type """ model_config = ConfigDict(extra="allow") @model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

AvailableApiVersion

Bases: BaseModel

A JSON object containing information about an available API version

Source code in optimade/models/baseinfo.py
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
class AvailableApiVersion(BaseModel): """A JSON object containing information about an available API version""" url: Annotated[ AnyHttpUrl, StrictField( description="A string specifying a versioned base URL that MUST adhere to the rules in section Base URL", json_schema_extra={ "pattern": VERSIONED_BASE_URL_PATTERN, }, ), ] version: Annotated[ SemanticVersion, StrictField( description="""A string containing the full version number of the API served at that versioned base URL. The version number string MUST NOT be prefixed by, e.g., 'v'. Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] @field_validator("url", mode="after") @classmethod def url_must_be_versioned_base_Url(cls, value: AnyHttpUrl) -> AnyHttpUrl: """The URL must be a versioned base URL""" if not re.match(VERSIONED_BASE_URL_PATTERN, str(value)): raise ValueError( f"URL {value} must be a versioned base URL (i.e., must match the " f"pattern '{VERSIONED_BASE_URL_PATTERN}')" ) return value @model_validator(mode="after") def crosscheck_url_and_version(self) -> "AvailableApiVersion": """Check that URL version and API version are compatible.""" url = ( str(self.url) .split("/")[-2 if str(self.url).endswith("/") else -1] .replace("v", "") ) # as with version urls, we need to split any release tags or build metadata out of these URLs url_version = tuple( int(val) for val in url.split("-")[0].split("+")[0].split(".") ) api_version = tuple( int(val) for val in str(self.version).split("-")[0].split("+")[0].split(".") ) if any(a != b for a, b in zip(url_version, api_version)): raise ValueError( f"API version {api_version} is not compatible with url version {url_version}." ) return self

url instance-attribute

version instance-attribute

crosscheck_url_and_version()

Check that URL version and API version are compatible.

Source code in optimade/models/baseinfo.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
@model_validator(mode="after") def crosscheck_url_and_version(self) -> "AvailableApiVersion": """Check that URL version and API version are compatible.""" url = ( str(self.url) .split("/")[-2 if str(self.url).endswith("/") else -1] .replace("v", "") ) # as with version urls, we need to split any release tags or build metadata out of these URLs url_version = tuple( int(val) for val in url.split("-")[0].split("+")[0].split(".") ) api_version = tuple( int(val) for val in str(self.version).split("-")[0].split("+")[0].split(".") ) if any(a != b for a, b in zip(url_version, api_version)): raise ValueError( f"API version {api_version} is not compatible with url version {url_version}." ) return self

url_must_be_versioned_base_Url(value) classmethod

The URL must be a versioned base URL

Source code in optimade/models/baseinfo.py
38 39 40 41 42 43 44 45 46 47
@field_validator("url", mode="after") @classmethod def url_must_be_versioned_base_Url(cls, value: AnyHttpUrl) -> AnyHttpUrl: """The URL must be a versioned base URL""" if not re.match(VERSIONED_BASE_URL_PATTERN, str(value)): raise ValueError( f"URL {value} must be a versioned base URL (i.e., must match the " f"pattern '{VERSIONED_BASE_URL_PATTERN}')" ) return value

BaseInfoAttributes

Bases: BaseModel

Attributes for Base URL Info endpoint

Source code in optimade/models/baseinfo.py
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
class BaseInfoAttributes(BaseModel): """Attributes for Base URL Info endpoint""" api_version: Annotated[ SemanticVersion, StrictField( description="""Presently used full version of the OPTIMADE API. The version number string MUST NOT be prefixed by, e.g., "v". Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] available_api_versions: Annotated[ list[AvailableApiVersion], StrictField( description="A list of dictionaries of available API versions at other base URLs", ), ] formats: Annotated[ list[str], StrictField(description="List of available output formats.") ] = ["json"] available_endpoints: Annotated[ list[str], StrictField( description="List of available endpoints (i.e., the string to be appended to the versioned base URL).", ), ] entry_types_by_format: Annotated[ dict[str, list[str]], StrictField( description="Available entry endpoints as a function of output formats." ), ] is_index: Annotated[ bool | None, StrictField( description="If true, this is an index meta-database base URL (see section Index Meta-Database). " "If this member is not provided, the client MUST assume this is not an index meta-database base URL " "(i.e., the default is for `is_index` to be `false`).", ), ] = False license: Annotated[ Link | AnyHttpUrl | None, StrictField( ..., description="""A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) giving a URL to a web page containing a human-readable text describing the license (or licensing options if there are multiple) covering all the data and metadata provided by this database. Clients are advised not to try automated parsing of this link or its content, but rather rely on the field `available_licenses` instead.""", ), ] = None available_licenses: Annotated[ list[str] | None, StrictField( ..., description="""List of [SPDX license identifiers](https://spdx.org/licenses/) specifying a set of alternative licenses available to the client for licensing the complete database, i.e., all the entries, metadata, and the content and structure of the database itself. If more than one license is available to the client, the identifier of each one SHOULD be included in the list. Inclusion of a license identifier in the list is a commitment of the database that the rights are in place to grant clients access to all the individual entries, all metadata, and the content and structure of the database itself according to the terms of any of these licenses (at the choice of the client). If the licensing information provided via the field license omits licensing options specified in `available_licenses`, or if it otherwise contradicts them, a client MUST still be allowed to interpret the inclusion of a license in `available_licenses` as a full commitment from the database without exceptions, under the respective licenses. If the database cannot make that commitment, e.g., if only part of the database is available under a license, the corresponding license identifier MUST NOT appear in `available_licenses` (but, rather, the field license is to be used to clarify the licensing situation.) An empty list indicates that none of the SPDX licenses apply and that the licensing situation is clarified in human readable form in the field `license`. An unknown value means that the database makes no commitment.""", ), ] = None available_licenses_for_entries: Annotated[ list[str] | None, StrictField( ..., description="""List of [SPDX license identifiers](https://spdx.org/licenses/) specifying a set of additional alternative licenses available to the client for licensing individual, and non-substantial sets of, database entries, metadata, and extracts from the database that do not constitute substantial parts of the database. Note that the definition of the field `available_licenses` implies that licenses specified in that field are available also for the licensing specified by this field, even if they are not explicitly included in the field `available_licenses_for_entries` or if it is `null` (however, the opposite relationship does not hold). If `available_licenses` is unknown, only the licenses in `available_licenses_for_entries` apply.""", ), ] = None @model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

api_version instance-attribute

available_api_versions instance-attribute

available_endpoints instance-attribute

available_licenses = None class-attribute instance-attribute

available_licenses_for_entries = None class-attribute instance-attribute

entry_types_by_format instance-attribute

formats = ['json'] class-attribute instance-attribute

is_index = False class-attribute instance-attribute

license = None class-attribute instance-attribute

formats_and_endpoints_must_be_valid()

Source code in optimade/models/baseinfo.py
145 146 147 148 149 150 151 152 153 154 155
@model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

BaseInfoResource

Bases: Resource

Source code in optimade/models/baseinfo.py
158 159 160 161
class BaseInfoResource(Resource): id: Literal["/"] = "/" type: Literal["info"] = "info" attributes: BaseInfoAttributes

attributes instance-attribute

id = '/' class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'info' class-attribute instance-attribute

BaseRelationshipMeta

Bases: Meta

Specific meta field for base relationship resource

Source code in optimade/models/optimade_json.py
421 422 423 424 425 426 427 428 429
class BaseRelationshipMeta(jsonapi.Meta): """Specific meta field for base relationship resource""" description: Annotated[ str, StrictField( description="OPTIONAL human-readable description of the relationship." ), ]

description instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

BaseRelationshipResource

Bases: BaseResource

Minimum requirements to represent a relationship resource

Source code in optimade/models/optimade_json.py
432 433 434 435 436 437 438 439 440
class BaseRelationshipResource(jsonapi.BaseResource): """Minimum requirements to represent a relationship resource""" meta: Annotated[ BaseRelationshipMeta | None, StrictField( description="Relationship meta field. MUST contain 'description' if supplied.", ), ] = None

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type instance-attribute

BaseResource

Bases: BaseModel

Minimum requirements to represent a Resource

Source code in optimade/models/jsonapi.py
218 219 220 221 222 223 224
class BaseResource(BaseModel): """Minimum requirements to represent a Resource""" model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) id: Annotated[str, StrictField(description="Resource ID")] type: Annotated[str, StrictField(description="Resource type")]

id instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type instance-attribute

DataType

Bases: Enum

Optimade Data types

See the section "Data types" in the OPTIMADE API specification for more information.

Source code in optimade/models/optimade_json.py
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
class DataType(Enum): """Optimade Data types See the section "Data types" in the OPTIMADE API specification for more information. """ STRING = "string" INTEGER = "integer" FLOAT = "float" BOOLEAN = "boolean" TIMESTAMP = "timestamp" LIST = "list" DICTIONARY = "dictionary" UNKNOWN = "unknown" @classmethod def get_values(cls) -> list[str]: """Get OPTIMADE data types (enum values) as a (sorted) list""" return sorted(_.value for _ in cls) @classmethod def from_python_type(cls, python_type: type | str | object) -> Optional["DataType"]: """Get OPTIMADE data type from a Python type""" mapping = { "bool": cls.BOOLEAN, "int": cls.INTEGER, "float": cls.FLOAT, "complex": None, "generator": cls.LIST, "list": cls.LIST, "tuple": cls.LIST, "range": cls.LIST, "hash": cls.INTEGER, "str": cls.STRING, "bytes": cls.STRING, "bytearray": None, "memoryview": None, "set": cls.LIST, "frozenset": cls.LIST, "dict": cls.DICTIONARY, "dict_keys": cls.LIST, "dict_values": cls.LIST, "dict_items": cls.LIST, "Nonetype": cls.UNKNOWN, "None": cls.UNKNOWN, "datetime": cls.TIMESTAMP, "date": cls.TIMESTAMP, "time": cls.TIMESTAMP, "datetime.datetime": cls.TIMESTAMP, "datetime.date": cls.TIMESTAMP, "datetime.time": cls.TIMESTAMP, } if isinstance(python_type, type): python_type = python_type.__name__ elif isinstance(python_type, object): if str(python_type) in mapping: python_type = str(python_type) else: python_type = type(python_type).__name__ return mapping.get(python_type, None) @classmethod def from_json_type(cls, json_type: str) -> Optional["DataType"]: """Get OPTIMADE data type from a named JSON type""" mapping = { "string": cls.STRING, "integer": cls.INTEGER, "number": cls.FLOAT, # actually includes both integer and float "object": cls.DICTIONARY, "array": cls.LIST, "boolean": cls.BOOLEAN, "null": cls.UNKNOWN, # OpenAPI "format"s: "double": cls.FLOAT, "float": cls.FLOAT, "int32": cls.INTEGER, "int64": cls.INTEGER, "date": cls.TIMESTAMP, "date-time": cls.TIMESTAMP, "password": cls.STRING, "byte": cls.STRING, "binary": cls.STRING, # Non-OpenAPI "format"s, but may still be used by pydantic/FastAPI "email": cls.STRING, "uuid": cls.STRING, "uri": cls.STRING, "hostname": cls.STRING, "ipv4": cls.STRING, "ipv6": cls.STRING, } return mapping.get(json_type, None)

BOOLEAN = 'boolean' class-attribute instance-attribute

DICTIONARY = 'dictionary' class-attribute instance-attribute

FLOAT = 'float' class-attribute instance-attribute

INTEGER = 'integer' class-attribute instance-attribute

LIST = 'list' class-attribute instance-attribute

STRING = 'string' class-attribute instance-attribute

TIMESTAMP = 'timestamp' class-attribute instance-attribute

UNKNOWN = 'unknown' class-attribute instance-attribute

from_json_type(json_type) classmethod

Get OPTIMADE data type from a named JSON type

Source code in optimade/models/optimade_json.py
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
@classmethod def from_json_type(cls, json_type: str) -> Optional["DataType"]: """Get OPTIMADE data type from a named JSON type""" mapping = { "string": cls.STRING, "integer": cls.INTEGER, "number": cls.FLOAT, # actually includes both integer and float "object": cls.DICTIONARY, "array": cls.LIST, "boolean": cls.BOOLEAN, "null": cls.UNKNOWN, # OpenAPI "format"s: "double": cls.FLOAT, "float": cls.FLOAT, "int32": cls.INTEGER, "int64": cls.INTEGER, "date": cls.TIMESTAMP, "date-time": cls.TIMESTAMP, "password": cls.STRING, "byte": cls.STRING, "binary": cls.STRING, # Non-OpenAPI "format"s, but may still be used by pydantic/FastAPI "email": cls.STRING, "uuid": cls.STRING, "uri": cls.STRING, "hostname": cls.STRING, "ipv4": cls.STRING, "ipv6": cls.STRING, } return mapping.get(json_type, None)

from_python_type(python_type) classmethod

Get OPTIMADE data type from a Python type

Source code in optimade/models/optimade_json.py
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
@classmethod def from_python_type(cls, python_type: type | str | object) -> Optional["DataType"]: """Get OPTIMADE data type from a Python type""" mapping = { "bool": cls.BOOLEAN, "int": cls.INTEGER, "float": cls.FLOAT, "complex": None, "generator": cls.LIST, "list": cls.LIST, "tuple": cls.LIST, "range": cls.LIST, "hash": cls.INTEGER, "str": cls.STRING, "bytes": cls.STRING, "bytearray": None, "memoryview": None, "set": cls.LIST, "frozenset": cls.LIST, "dict": cls.DICTIONARY, "dict_keys": cls.LIST, "dict_values": cls.LIST, "dict_items": cls.LIST, "Nonetype": cls.UNKNOWN, "None": cls.UNKNOWN, "datetime": cls.TIMESTAMP, "date": cls.TIMESTAMP, "time": cls.TIMESTAMP, "datetime.datetime": cls.TIMESTAMP, "datetime.date": cls.TIMESTAMP, "datetime.time": cls.TIMESTAMP, } if isinstance(python_type, type): python_type = python_type.__name__ elif isinstance(python_type, object): if str(python_type) in mapping: python_type = str(python_type) else: python_type = type(python_type).__name__ return mapping.get(python_type, None)

get_values() classmethod

Get OPTIMADE data types (enum values) as a (sorted) list

Source code in optimade/models/optimade_json.py
54 55 56 57
@classmethod def get_values(cls) -> list[str]: """Get OPTIMADE data types (enum values) as a (sorted) list""" return sorted(_.value for _ in cls)

EntryInfoProperty

Bases: BaseModel

Source code in optimade/models/entries.py
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
class EntryInfoProperty(BaseModel): description: Annotated[ str, StrictField(description="A human-readable description of the entry property"), ] unit: Annotated[ str | None, StrictField( description="""The physical unit of the entry property. This MUST be a valid representation of units according to version 2.1 of [The Unified Code for Units of Measure](https://unitsofmeasure.org/ucum.html). It is RECOMMENDED that non-standard (non-SI) units are described in the description for the property.""", ), ] = None sortable: Annotated[ bool | None, StrictField( description="""Defines whether the entry property can be used for sorting with the "sort" parameter. If the entry listing endpoint supports sorting, this key MUST be present for sortable properties with value `true`.""", ), ] = None type: Annotated[ DataType | None, StrictField( title="Type", description="""The type of the property's value. This MUST be any of the types defined in the Data types section. For the purpose of compatibility with future versions of this specification, a client MUST accept values that are not `string` values specifying any of the OPTIMADE Data types, but MUST then also disregard the `type` field. Note, if the value is a nested type, only the outermost type should be reported. E.g., for the entry resource `structures`, the `species` property is defined as a list of dictionaries, hence its `type` value would be `list`.""", ), ] = None

description instance-attribute

sortable = None class-attribute instance-attribute

type = None class-attribute instance-attribute

unit = None class-attribute instance-attribute

EntryInfoResource

Bases: BaseModel

Source code in optimade/models/entries.py
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
class EntryInfoResource(BaseModel): id: Annotated[ str, StrictField( optimade_version=">= 1.2", description="Must precisely match the entry type name for the given info endpoint.", ), ] type: Annotated[ str, StrictField( optimade_version=">= 1.2", description="The type of this response.", default="info", ), ] formats: Annotated[ list[str], StrictField( description="List of output formats available for this type of entry." ), ] description: Annotated[str, StrictField(description="Description of the entry.")] properties: Annotated[ dict[ValidIdentifier, EntryInfoProperty], StrictField( description="A dictionary describing queryable properties for this entry type, where each key is a property name.", ), ] output_fields_by_format: Annotated[ dict[str, list[ValidIdentifier]], StrictField( description="Dictionary of available output fields for this entry type, where the keys are the values of the `formats` list and the values are the keys of the `properties` dictionary.", ), ]

description instance-attribute

formats instance-attribute

id instance-attribute

output_fields_by_format instance-attribute

properties instance-attribute

type instance-attribute

EntryInfoResponse

Bases: Success

Source code in optimade/models/responses.py
58 59 60 61 62
class EntryInfoResponse(Success): data: Annotated[ EntryInfoResource, StrictField(description="OPTIMADE information for an entry endpoint."), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

EntryRelationships

Bases: Relationships

This model wraps the JSON API Relationships to include type-specific top level keys.

Source code in optimade/models/entries.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
class EntryRelationships(Relationships): """This model wraps the JSON API Relationships to include type-specific top level keys.""" references: Annotated[ ReferenceRelationship | None, StrictField( description="Object containing links to relationships with entries of the `references` type.", ), ] = None structures: Annotated[ StructureRelationship | None, StrictField( description="Object containing links to relationships with entries of the `structures` type.", ), ] = None

references = None class-attribute instance-attribute

structures = None class-attribute instance-attribute

check_illegal_relationships_fields()

Source code in optimade/models/jsonapi.py
296 297 298 299 300 301 302 303 304
@model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

EntryResource

Bases: Resource

The base model for an entry resource.

Source code in optimade/models/entries.py
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
class EntryResource(Resource): """The base model for an entry resource.""" id: Annotated[ str, OptimadeField( description="""An entry's ID as defined in section Definition of Terms. - **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. - **Examples**: - `"db/1234567"` - `"cod/2000000"` - `"cod/2000000@1234567"` - `"nomad/L1234567890"` - `"42"`""", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] type: Annotated[ str, OptimadeField( 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. - **Example**: `"structures"`""", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] attributes: Annotated[ EntryResourceAttributes, StrictField( description="""A dictionary, containing key-value pairs representing the entry's properties, except for `type` and `id`. Database-provider-specific properties need to include the database-provider-specific prefix (see section on Database-Provider-Specific Namespace Prefixes).""", ), ] relationships: Annotated[ EntryRelationships | None, StrictField( description="""A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships). The OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.""", ), ] = None

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type instance-attribute

EntryResourceAttributes

Bases: Attributes

Contains key-value pairs representing the entry's properties.

Source code in optimade/models/entries.py
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
class EntryResourceAttributes(Attributes): """Contains key-value pairs representing the entry's properties.""" immutable_id: Annotated[ str | None, OptimadeField( description="""The entry's immutable ID (e.g., an UUID). This is important for databases having preferred IDs that point to "the latest version" of a record, but still offer access to older variants. This ID maps to the version-specific record, in case it changes in the future. - **Type**: string. - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: MUST be a queryable property with support for all mandatory filter features. - **Examples**: - `"8bd3e750-b477-41a0-9b11-3a799f21b44f"` - `"fjeiwoj,54;@=%<>#32"` (Strings that are not URL-safe are allowed.)""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.MUST, ), ] = None last_modified: Annotated[ datetime | None, OptimadeField( description="""Date and time representing when the entry was last modified. - **Type**: timestamp. - **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. - **Response**: REQUIRED in the response unless the query parameter `response_fields` is present and does not include this property. - **Example**: - As part of JSON response format: `"2007-04-05T14:30:20Z"` (i.e., encoded as an [RFC 3339 Internet Date/Time Format](https://tools.ietf.org/html/rfc3339#section-5.6) string.)""", support=SupportLevel.SHOULD, queryable=SupportLevel.MUST, ), ] @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

immutable_id = None class-attribute instance-attribute

last_modified instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

EntryResponseMany

Bases: Success

Source code in optimade/models/responses.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
class EntryResponseMany(Success): data: Annotated[ # type: ignore[assignment] list[EntryResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ] included: Annotated[ list[EntryResource] | list[dict[str, Any]] | None, StrictField( description="A list of unique included OPTIMADE entry resources.", uniqueItems=True, union_mode="left_to_right", ), ] = None # type: ignore[assignment]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

EntryResponseOne

Bases: Success

Source code in optimade/models/responses.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
class EntryResponseOne(Success): data: Annotated[ EntryResource | dict[str, Any] | None, StrictField( description="The single entry resource returned by this query.", union_mode="left_to_right", ), ] = None # type: ignore[assignment] included: Annotated[ list[EntryResource] | list[dict[str, Any]] | None, StrictField( description="A list of unique included OPTIMADE entry resources.", uniqueItems=True, union_mode="left_to_right", ), ] = None # type: ignore[assignment]

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

Bases: BaseModel

A Links object specific to Error objects

Source code in optimade/models/jsonapi.py
112 113 114 115 116 117 118 119 120
class ErrorLinks(BaseModel): """A Links object specific to Error objects""" about: Annotated[ JsonLinkType | None, StrictField( description="A link that leads to further details about this particular occurrence of the problem.", ), ] = None

about = None class-attribute instance-attribute

ErrorResponse

Bases: Response

errors MUST be present and data MUST be skipped

Source code in optimade/models/responses.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
class ErrorResponse(Response): """errors MUST be present and data MUST be skipped""" meta: Annotated[ ResponseMeta, StrictField(description="A meta object containing non-standard information."), ] errors: Annotated[ list[OptimadeError], StrictField( description="A list of OPTIMADE-specific JSON API error objects, where the field detail MUST be present.", uniqueItems=True, ), ] @model_validator(mode="after") def data_must_be_skipped(self) -> "ErrorResponse": if self.data or "data" in self.model_fields_set: raise ValueError("data MUST be skipped for failures reporting errors.") return self

data = None class-attribute instance-attribute

errors instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

data_must_be_skipped()

Source code in optimade/models/responses.py
45 46 47 48 49
@model_validator(mode="after") def data_must_be_skipped(self) -> "ErrorResponse": if self.data or "data" in self.model_fields_set: raise ValueError("data MUST be skipped for failures reporting errors.") return self

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
403 404 405 406 407 408 409 410 411 412
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self

ErrorSource

Bases: BaseModel

an object containing references to the source of the error

Source code in optimade/models/jsonapi.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
class ErrorSource(BaseModel): """an object containing references to the source of the error""" pointer: Annotated[ str | None, StrictField( description="a JSON Pointer [RFC6901] to the associated entity in the request document " '[e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].', ), ] = None parameter: Annotated[ str | None, StrictField( description="a string indicating which URI query parameter caused the error.", ), ] = None

parameter = None class-attribute instance-attribute

pointer = None class-attribute instance-attribute

Implementation

Bases: BaseModel

Information on the server implementation

Source code in optimade/models/optimade_json.py
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
class Implementation(BaseModel): """Information on the server implementation""" name: Annotated[ str | None, StrictField(description="name of the implementation") ] = None version: Annotated[ str | None, StrictField(description="version string of the current implementation"), ] = None homepage: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the homepage of the implementation.", ), ] = None source_url: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the implementation source, either downloadable archive or version control system.", ), ] = None maintainer: Annotated[ ImplementationMaintainer | None, StrictField( description="A dictionary providing details about the maintainer of the implementation.", ), ] = None issue_tracker: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the implementation's issue tracker.", ), ] = None

homepage = None class-attribute instance-attribute

issue_tracker = None class-attribute instance-attribute

maintainer = None class-attribute instance-attribute

name = None class-attribute instance-attribute

source_url = None class-attribute instance-attribute

version = None class-attribute instance-attribute

ImplementationMaintainer

Bases: BaseModel

Details about the maintainer of the implementation

Source code in optimade/models/optimade_json.py
238 239 240 241 242 243
class ImplementationMaintainer(BaseModel): """Details about the maintainer of the implementation""" email: Annotated[ EmailStr, StrictField(description="the maintainer's email address") ]

email instance-attribute

IndexInfoAttributes

Bases: BaseInfoAttributes

Attributes for Base URL Info endpoint for an Index Meta-Database

Source code in optimade/models/index_metadb.py
17 18 19 20 21 22 23 24 25
class IndexInfoAttributes(BaseInfoAttributes): """Attributes for Base URL Info endpoint for an Index Meta-Database""" is_index: Annotated[ bool, StrictField( description="This must be `true` since this is an index meta-database (see section Index Meta-Database).", ), ] = True

api_version instance-attribute

available_api_versions instance-attribute

available_endpoints instance-attribute

available_licenses = None class-attribute instance-attribute

available_licenses_for_entries = None class-attribute instance-attribute

entry_types_by_format instance-attribute

formats = ['json'] class-attribute instance-attribute

is_index = True class-attribute instance-attribute

license = None class-attribute instance-attribute

formats_and_endpoints_must_be_valid()

Source code in optimade/models/baseinfo.py
145 146 147 148 149 150 151 152 153 154 155
@model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

IndexInfoResource

Bases: BaseInfoResource

Index Meta-Database Base URL Info endpoint resource

Source code in optimade/models/index_metadb.py
46 47 48 49 50 51 52 53 54 55 56 57
class IndexInfoResource(BaseInfoResource): """Index Meta-Database Base URL Info endpoint resource""" attributes: IndexInfoAttributes relationships: Annotated[ # type: ignore[assignment] dict[Literal["default"], IndexRelationship] | None, StrictField( title="Relationships", description="""Reference to the Links identifier object under the `links` endpoint that the provider has chosen as their 'default' OPTIMADE API database. A client SHOULD present this database as the first choice when an end-user chooses this provider.""", ), ]

attributes instance-attribute

id = '/' class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships instance-attribute

type = 'info' class-attribute instance-attribute

IndexInfoResponse

Bases: Success

Source code in optimade/models/responses.py
52 53 54 55
class IndexInfoResponse(Success): data: Annotated[ IndexInfoResource, StrictField(description="Index meta-database /info data.") ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

IndexRelationship

Bases: BaseModel

Index Meta-Database relationship

Source code in optimade/models/index_metadb.py
34 35 36 37 38 39 40 41 42 43
class IndexRelationship(BaseModel): """Index Meta-Database relationship""" data: Annotated[ RelatedLinksResource | None, StrictField( description="""[JSON API resource linkage](http://jsonapi.org/format/1.0/#document-links). It MUST be either `null` or contain a single Links identifier object with the fields `id` and `type`""", ), ]

data instance-attribute

InfoResponse

Bases: Success

Source code in optimade/models/responses.py
65 66 67 68
class InfoResponse(Success): data: Annotated[ BaseInfoResource, StrictField(description="The implementations /info data.") ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

JsonApi

Bases: BaseModel

An object describing the server's implementation

Source code in optimade/models/jsonapi.py
58 59 60 61 62 63 64 65 66
class JsonApi(BaseModel): """An object describing the server's implementation""" version: Annotated[str, StrictField(description="Version of the json API used")] = ( "1.0" ) meta: Annotated[ Meta | None, StrictField(description="Non-standard meta information") ] = None

meta = None class-attribute instance-attribute

version = '1.0' class-attribute instance-attribute

Bases: BaseModel

A link MUST be represented as either: a string containing the link's URL or a link object.

Source code in optimade/models/jsonapi.py
41 42 43 44 45 46 47 48 49 50 51 52
class Link(BaseModel): """A link **MUST** be represented as either: a string containing the link's URL or a link object.""" href: Annotated[ AnyUrl, StrictField(description="a string containing the link's URL.") ] meta: Annotated[ Meta | None, StrictField( description="a meta object containing non-standard meta-information about the link.", ), ] = None

href instance-attribute

meta = None class-attribute instance-attribute

LinksResource

Bases: EntryResource

A Links endpoint resource object

Source code in optimade/models/links.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
class LinksResource(EntryResource): """A Links endpoint resource object""" type: Annotated[ Literal["links"], StrictField( description="These objects are described in detail in the section Links Endpoint", pattern="^links$", ), ] = "links" attributes: Annotated[ LinksResourceAttributes, StrictField( description="A dictionary containing key-value pairs representing the Links resource's properties.", ), ] @model_validator(mode="after") def relationships_must_not_be_present(self) -> "LinksResource": if self.relationships or "relationships" in self.model_fields_set: raise ValueError('"relationships" is not allowed for links resources') return self

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'links' class-attribute instance-attribute

relationships_must_not_be_present()

Source code in optimade/models/links.py
116 117 118 119 120
@model_validator(mode="after") def relationships_must_not_be_present(self) -> "LinksResource": if self.relationships or "relationships" in self.model_fields_set: raise ValueError('"relationships" is not allowed for links resources') return self

LinksResourceAttributes

Bases: Attributes

Links endpoint resource object attributes

Source code in optimade/models/links.py
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
class LinksResourceAttributes(Attributes): """Links endpoint resource object attributes""" name: Annotated[ str, StrictField( description="Human-readable name for the OPTIMADE API implementation, e.g., for use in clients to show the name to the end-user.", ), ] description: Annotated[ str, StrictField( description="Human-readable description for the OPTIMADE API implementation, e.g., for use in clients to show a description to the end-user.", ), ] base_url: Annotated[ JsonLinkType | None, StrictField( description="JSON API links object, pointing to the base URL for this implementation", ), ] homepage: Annotated[ JsonLinkType | None, StrictField( description="JSON API links object, pointing to a homepage URL for this implementation", ), ] link_type: Annotated[ LinkType, StrictField( title="Link Type", description="""The type of the linked relation. MUST be one of these values: 'child', 'root', 'external', 'providers'.""", ), ] aggregate: Annotated[ Aggregate | None, StrictField( title="Aggregate", description="""A string indicating whether a client that is following links to aggregate results from different OPTIMADE implementations should follow this link or not. This flag SHOULD NOT be indicated for links where `link_type` is not `child`. If not specified, clients MAY assume that the value is `ok`. If specified, and the value is anything different than `ok`, the client MUST assume that the server is suggesting not to follow the link during aggregation by default (also if the value is not among the known ones, in case a future specification adds new accepted values). Specific values indicate the reason why the server is providing the suggestion. A client MAY follow the link anyway if it has reason to do so (e.g., if the client is looking for all test databases, it MAY follow the links marked with `aggregate`=`test`). If specified, it MUST be one of the values listed in section Link Aggregate Options.""", ), ] = Aggregate.OK no_aggregate_reason: Annotated[ str | None, StrictField( description="""An OPTIONAL human-readable string indicating the reason for suggesting not to aggregate results following the link. It SHOULD NOT be present if `aggregate`=`ok`.""", ), ] = None

aggregate = Aggregate.OK class-attribute instance-attribute

base_url instance-attribute

description instance-attribute

homepage instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

name instance-attribute

no_aggregate_reason = None class-attribute instance-attribute

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

LinksResponse

Bases: EntryResponseMany

Source code in optimade/models/responses.py
108 109 110 111 112 113 114 115 116
class LinksResponse(EntryResponseMany): data: Annotated[ list[LinksResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE links resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

Meta

Bases: BaseModel

Non-standard meta-information that can not be represented as an attribute or relationship.

Source code in optimade/models/jsonapi.py
35 36 37 38
class Meta(BaseModel): """Non-standard meta-information that can not be represented as an attribute or relationship.""" model_config = ConfigDict(extra="allow")

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

OptimadeError

Bases: Error

detail MUST be present

Source code in optimade/models/optimade_json.py
135 136 137 138 139 140 141 142 143
class OptimadeError(jsonapi.Error): """detail MUST be present""" detail: Annotated[ str, StrictField( description="A human-readable explanation specific to this occurrence of the problem.", ), ]

code = None class-attribute instance-attribute

detail instance-attribute

id = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

source = None class-attribute instance-attribute

status = None class-attribute instance-attribute

title = None class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191 192
def __hash__(self): return hash(self.model_dump_json())

Periodicity

Bases: IntEnum

Integer enumeration of dimension_types values

Source code in optimade/models/structures.py
49 50 51 52 53
class Periodicity(IntEnum): """Integer enumeration of dimension_types values""" APERIODIC = 0 PERIODIC = 1

APERIODIC = 0 class-attribute instance-attribute

PERIODIC = 1 class-attribute instance-attribute

Person

Bases: BaseModel

A person, i.e., an author, editor or other.

Source code in optimade/models/references.py
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
class Person(BaseModel): """A person, i.e., an author, editor or other.""" name: Annotated[ str, OptimadeField( description="""Full name of the person, REQUIRED.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] firstname: Annotated[ str | None, OptimadeField( description="""First name of the person.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None lastname: Annotated[ str | None, OptimadeField( description="""Last name of the person.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None

firstname = None class-attribute instance-attribute

lastname = None class-attribute instance-attribute

name instance-attribute

Provider

Bases: BaseModel

Information on the database provider of the implementation.

Source code in optimade/models/optimade_json.py
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
class Provider(BaseModel): """Information on the database provider of the implementation.""" name: Annotated[ str, StrictField(description="a short name for the database provider") ] description: Annotated[ str, StrictField(description="a longer description of the database provider") ] prefix: Annotated[ str, StrictField( pattern=r"^[a-z]([a-z]|[0-9]|_)*$", description="database-provider-specific prefix as found in section Database-Provider-Specific Namespace Prefixes.", ), ] homepage: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="a [JSON API links object](http://jsonapi.org/format/1.0#document-links) " "pointing to homepage of the database provider, either " "directly as a string, or as a link object.", ), ] = None

description instance-attribute

homepage = None class-attribute instance-attribute

name instance-attribute

prefix instance-attribute

ReferenceResource

Bases: EntryResource

The references entries describe bibliographic references.

The following properties are used to provide the bibliographic details:

  • address, annote, booktitle, chapter, crossref, edition, howpublished, institution, journal, key, month, note, number, organization, pages, publisher, school, series, title, volume, year: meanings of these properties match the BibTeX specification, values are strings;
  • bib_type: type of the reference, corresponding to type property in the BibTeX specification, value is string;
  • authors and editors: lists of person objects which are dictionaries with the following keys:
    • name: Full name of the person, REQUIRED.
    • firstname, lastname: Parts of the person's name, OPTIONAL.
  • doi and url: values are strings.
  • Requirements/Conventions:
    • Support: OPTIONAL support in implementations, i.e., any of the properties MAY be null.
    • Query: Support for queries on any of these properties is OPTIONAL. If supported, filters MAY support only a subset of comparison operators.
    • Every references entry MUST contain at least one of the properties.
Source code in optimade/models/references.py
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
class ReferenceResource(EntryResource): """The `references` entries describe bibliographic references. The following properties are used to provide the bibliographic details: - **address**, **annote**, **booktitle**, **chapter**, **crossref**, **edition**, **howpublished**, **institution**, **journal**, **key**, **month**, **note**, **number**, **organization**, **pages**, **publisher**, **school**, **series**, **title**, **volume**, **year**: meanings of these properties match the [BibTeX specification](http://bibtexml.sourceforge.net/btxdoc.pdf), values are strings; - **bib_type**: type of the reference, corresponding to **type** property in the BibTeX specification, value is string; - **authors** and **editors**: lists of *person objects* which are dictionaries with the following keys: - **name**: Full name of the person, REQUIRED. - **firstname**, **lastname**: Parts of the person's name, OPTIONAL. - **doi** and **url**: values are strings. - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., any of the properties MAY be `null`. - **Query**: Support for queries on any of these properties is OPTIONAL. If supported, filters MAY support only a subset of comparison operators. - Every references entry MUST contain at least one of the properties. """ type: Annotated[ Literal["references"], OptimadeField( 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. - **Example**: `"structures"`""", pattern="^references$", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] = "references" attributes: ReferenceResourceAttributes @field_validator("attributes", mode="before") @classmethod def validate_attributes(cls, value: Any) -> dict[str, Any]: if not isinstance(value, dict): if isinstance(value, BaseModel): value = value.model_dump() else: raise TypeError("attributes field must be a mapping") if not any(prop[1] is not None for prop in value): raise ValueError("reference object must have at least one field defined") return value

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'references' class-attribute instance-attribute

validate_attributes(value) classmethod

Source code in optimade/models/references.py
323 324 325 326 327 328 329 330 331 332 333
@field_validator("attributes", mode="before") @classmethod def validate_attributes(cls, value: Any) -> dict[str, Any]: if not isinstance(value, dict): if isinstance(value, BaseModel): value = value.model_dump() else: raise TypeError("attributes field must be a mapping") if not any(prop[1] is not None for prop in value): raise ValueError("reference object must have at least one field defined") return value

ReferenceResourceAttributes

Bases: EntryResourceAttributes

Model that stores the attributes of a reference.

Many properties match the meaning described in the BibTeX specification.

Source code in optimade/models/references.py
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
class ReferenceResourceAttributes(EntryResourceAttributes): """Model that stores the attributes of a reference. Many properties match the meaning described in the [BibTeX specification](http://bibtexml.sourceforge.net/btxdoc.pdf). """ authors: Annotated[ list[Person] | None, OptimadeField( description="List of person objects containing the authors of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None editors: Annotated[ list[Person] | None, OptimadeField( description="List of person objects containing the editors of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None doi: Annotated[ str | None, OptimadeField( description="The digital object identifier of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None url: Annotated[ AnyUrl | None, OptimadeField( description="The URL of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None address: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None annote: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None booktitle: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None chapter: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None crossref: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None edition: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None howpublished: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None institution: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None journal: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None key: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None month: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None note: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None number: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None organization: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None pages: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None publisher: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None school: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None series: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None title: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None bib_type: Annotated[ str | None, OptimadeField( description="Type of the reference, corresponding to the **type** property in the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None volume: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None year: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None

address = None class-attribute instance-attribute

annote = None class-attribute instance-attribute

authors = None class-attribute instance-attribute

bib_type = None class-attribute instance-attribute

booktitle = None class-attribute instance-attribute

chapter = None class-attribute instance-attribute

crossref = None class-attribute instance-attribute

doi = None class-attribute instance-attribute

edition = None class-attribute instance-attribute

editors = None class-attribute instance-attribute

howpublished = None class-attribute instance-attribute

immutable_id = None class-attribute instance-attribute

institution = None class-attribute instance-attribute

journal = None class-attribute instance-attribute

key = None class-attribute instance-attribute

last_modified instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

month = None class-attribute instance-attribute

note = None class-attribute instance-attribute

number = None class-attribute instance-attribute

organization = None class-attribute instance-attribute

pages = None class-attribute instance-attribute

publisher = None class-attribute instance-attribute

school = None class-attribute instance-attribute

series = None class-attribute instance-attribute

title = None class-attribute instance-attribute

url = None class-attribute instance-attribute

volume = None class-attribute instance-attribute

year = None class-attribute instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

ReferenceResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
150 151 152 153 154 155 156 157 158
class ReferenceResponseMany(EntryResponseMany): data: Annotated[ list[ReferenceResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE references entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

ReferenceResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
140 141 142 143 144 145 146 147
class ReferenceResponseOne(EntryResponseOne): data: Annotated[ ReferenceResource | dict[str, Any] | None, StrictField( description="A single references entry resource.", union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

RelatedLinksResource

Bases: BaseResource

A related Links resource object

Source code in optimade/models/index_metadb.py
28 29 30 31
class RelatedLinksResource(BaseResource): """A related Links resource object""" type: Literal["links"] = "links"

id instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type = 'links' class-attribute instance-attribute

Relationship

Bases: Relationship

Similar to normal JSON API relationship, but with addition of OPTIONAL meta field for a resource.

Source code in optimade/models/optimade_json.py
443 444 445 446 447 448 449
class Relationship(jsonapi.Relationship): """Similar to normal JSON API relationship, but with addition of OPTIONAL meta field for a resource.""" data: Annotated[ BaseRelationshipResource | list[BaseRelationshipResource] | None, StrictField(description="Resource linkage", uniqueItems=True), ] = None

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

Bases: BaseModel

A resource object MAY contain references to other resource objects ("relationships"). Relationships may be to-one or to-many. Relationships can be specified by including a member in a resource's links object.

Source code in optimade/models/jsonapi.py
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
class RelationshipLinks(BaseModel): """A resource object **MAY** contain references to other resource objects ("relationships"). Relationships may be to-one or to-many. Relationships can be specified by including a member in a resource's links object. """ self: Annotated[ JsonLinkType | None, StrictField( description="""A link for the relationship itself (a 'relationship link'). This link allows the client to directly manipulate the relationship. When fetched successfully, this link returns the [linkage](https://jsonapi.org/format/1.0/#document-resource-object-linkage) for the related resources as its primary data. (See [Fetching Relationships](https://jsonapi.org/format/1.0/#fetching-relationships).)""", ), ] = None related: Annotated[ JsonLinkType | None, StrictField( description="A [related resource link](https://jsonapi.org/format/1.0/#document-resource-object-related-resource-links).", ), ] = None @model_validator(mode="after") def either_self_or_related_must_be_specified(self) -> "RelationshipLinks": if self.self is None and self.related is None: raise ValueError( "Either 'self' or 'related' MUST be specified for RelationshipLinks" ) return self

related = None class-attribute instance-attribute

self = None class-attribute instance-attribute

Source code in optimade/models/jsonapi.py
250 251 252 253 254 255 256
@model_validator(mode="after") def either_self_or_related_must_be_specified(self) -> "RelationshipLinks": if self.self is None and self.related is None: raise ValueError( "Either 'self' or 'related' MUST be specified for RelationshipLinks" ) return self

Relationships

Bases: BaseModel

Members of the relationships object ("relationships") represent references from the resource object in which it's defined to other resource objects. Keys MUST NOT be: type id

Source code in optimade/models/jsonapi.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
class Relationships(BaseModel): """ Members of the relationships object (\"relationships\") represent references from the resource object in which it's defined to other resource objects. Keys MUST NOT be: type id """ @model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

check_illegal_relationships_fields()

Source code in optimade/models/jsonapi.py
296 297 298 299 300 301 302 303 304
@model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

Resource

Bases: BaseResource

Resource objects appear in a JSON API document to represent resources.

Source code in optimade/models/jsonapi.py
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
class Resource(BaseResource): """Resource objects appear in a JSON API document to represent resources.""" links: Annotated[ ResourceLinks | None, StrictField( description="a links object containing links related to the resource." ), ] = None meta: Annotated[ Meta | None, StrictField( description="a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.", ), ] = None attributes: Annotated[ Attributes | None, StrictField( description="an attributes object representing some of the resource’s data.", ), ] = None relationships: Annotated[ Relationships | None, StrictField( description="""[Relationships object](https://jsonapi.org/format/1.0/#document-resource-object-relationships) describing relationships between the resource and other JSON API resources.""", ), ] = None

attributes = None class-attribute instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type instance-attribute

Bases: BaseModel

A Resource Links object

Source code in optimade/models/jsonapi.py
307 308 309 310 311 312 313 314 315
class ResourceLinks(BaseModel): """A Resource Links object""" self: Annotated[ JsonLinkType | None, StrictField( description="A link that identifies the resource represented by the resource object.", ), ] = None

self = None class-attribute instance-attribute

Response

Bases: BaseModel

A top-level response.

Source code in optimade/models/jsonapi.py
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
class Response(BaseModel): """A top-level response.""" data: Annotated[ None | Resource | list[Resource] | None, StrictField(description="Outputted Data", uniqueItems=True), ] = None meta: Annotated[ Meta | None, StrictField( description="A meta object containing non-standard information related to the Success", ), ] = None errors: Annotated[ list[Error] | None, StrictField(description="A list of unique errors", uniqueItems=True), ] = None included: Annotated[ list[Resource] | None, StrictField( description="A list of unique included resources", uniqueItems=True ), ] = None links: Annotated[ ToplevelLinks | None, StrictField(description="Links associated with the primary data or errors"), ] = None jsonapi: Annotated[ JsonApi | None, StrictField(description="Information about the JSON API used"), ] = None @model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self model_config = ConfigDict( json_encoders={ datetime: lambda v: v.astimezone(timezone.utc).strftime( "%Y-%m-%dT%H:%M:%SZ" ) } ) """The specification mandates that datetimes must be encoded following [RFC3339](https://tools.ietf.org/html/rfc3339), which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results. """

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
403 404 405 406 407 408 409 410 411 412
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self

ResponseMeta

Bases: Meta

A JSON API meta member that contains JSON API meta objects of non-standard meta-information.

OPTIONAL additional information global to the query that is not specified in this document, MUST start with a database-provider-specific prefix.

Source code in optimade/models/optimade_json.py
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
class ResponseMeta(jsonapi.Meta): """ A [JSON API meta member](https://jsonapi.org/format/1.0#document-meta) that contains JSON API meta objects of non-standard meta-information. OPTIONAL additional information global to the query that is not specified in this document, MUST start with a database-provider-specific prefix. """ query: Annotated[ ResponseMetaQuery, StrictField(description="Information on the Query that was requested"), ] api_version: Annotated[ SemanticVersion, StrictField( description="""Presently used full version of the OPTIMADE API. The version number string MUST NOT be prefixed by, e.g., "v". Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] more_data_available: Annotated[ bool, StrictField( description="`false` if the response contains all data for the request (e.g., a request issued to a single entry endpoint, or a `filter` query at the last page of a paginated response) and `true` if the response is incomplete in the sense that multiple objects match the request, and not all of them have been included in the response (e.g., a query with multiple pages that is not at the last page).", ), ] # start of "SHOULD" fields for meta response optimade_schema: Annotated[ jsonapi.JsonLinkType | None, StrictField( alias="schema", description="""A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) that points to a schema for the response. If it is a string, or a dictionary containing no `meta` field, the provided URL MUST point at an [OpenAPI](https://swagger.io/specification/) schema. It is possible that future versions of this specification allows for alternative schema types. Hence, if the `meta` field of the JSON API links object is provided and contains a field `schema_type` that is not equal to the string `OpenAPI` the client MUST not handle failures to parse the schema or to validate the response against the schema as errors.""", ), ] = None time_stamp: Annotated[ datetime | None, StrictField( description="A timestamp containing the date and time at which the query was executed.", ), ] = None data_returned: Annotated[ int | None, StrictField( description="An integer containing the total number of data resource objects returned for the current `filter` query, independent of pagination.", ge=0, ), ] = None provider: Annotated[ Provider | None, StrictField( description="information on the database provider of the implementation." ), ] = None # start of "MAY" fields for meta response data_available: Annotated[ int | None, StrictField( description="An integer containing the total number of data resource objects available in the database for the endpoint.", ), ] = None last_id: Annotated[ str | None, StrictField(description="a string containing the last ID returned"), ] = None response_message: Annotated[ str | None, StrictField(description="response string from the server") ] = None request_delay: Annotated[ NonNegativeFloat | None, StrictField( description="""A non-negative float giving time in seconds that the client is suggested to wait before issuing a subsequent request. Implementation note: the functionality of this field overlaps to some degree with features provided by the HTTP error `429 Too Many Requests` and the `Retry-After` HTTP header. Implementations are suggested to provide consistent handling of request overload through both mechanisms.""" ), ] = None implementation: Annotated[ Implementation | None, StrictField(description="a dictionary describing the server implementation"), ] = None warnings: Annotated[ list[Warnings] | None, StrictField( description="""A list of warning resource objects representing non-critical errors or warnings. A warning resource object is defined similarly to a [JSON API error object](http://jsonapi.org/format/1.0/#error-objects), but MUST also include the field `type`, which MUST have the value `"warning"`. The field `detail` MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features. The field `status`, representing a HTTP response status code, MUST NOT be present for a warning resource object. This is an exclusive field for error resource objects.""", uniqueItems=True, ), ] = None

api_version instance-attribute

data_available = None class-attribute instance-attribute

data_returned = None class-attribute instance-attribute

implementation = None class-attribute instance-attribute

last_id = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

more_data_available instance-attribute

optimade_schema = None class-attribute instance-attribute

provider = None class-attribute instance-attribute

query instance-attribute

request_delay = None class-attribute instance-attribute

response_message = None class-attribute instance-attribute

time_stamp = None class-attribute instance-attribute

warnings = None class-attribute instance-attribute

ResponseMetaQuery

Bases: BaseModel

Information on the query that was requested.

Source code in optimade/models/optimade_json.py
195 196 197 198 199 200 201 202 203 204 205 206
class ResponseMetaQuery(BaseModel): """Information on the query that was requested.""" representation: Annotated[ str, StrictField( description="""A string with the part of the URL following the versioned or unversioned base URL that serves the API. Query parameters that have not been used in processing the request MAY be omitted. In particular, if no query parameters have been involved in processing the request, the query part of the URL MAY be excluded. Example: `/structures?filter=nelements=2`""", ), ]

representation instance-attribute

Species

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
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
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[ list[float] | None, 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[ str | None, 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[ list[str] | None, 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[ list[int] | None, 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: list[float] | None, info: "ValidationInfo" ) -> list[float] | None: 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: list[str] | list[int] | None ) -> list[str] | list[int] | None: 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

attached = None class-attribute instance-attribute

chemical_symbols instance-attribute

concentration instance-attribute

mass = None class-attribute instance-attribute

name instance-attribute

nattached = None class-attribute instance-attribute

original_name = None class-attribute instance-attribute

attached_nattached_mutually_exclusive()

Source code in optimade/models/structures.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
@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

validate_concentration_and_mass(value, info)

Source code in optimade/models/structures.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
@field_validator("concentration", "mass", mode="after") def validate_concentration_and_mass( cls, value: list[float] | None, info: "ValidationInfo" ) -> list[float] | None: 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." )

validate_minimum_list_length(value) classmethod

Source code in optimade/models/structures.py
182 183 184 185 186 187 188 189 190 191 192
@field_validator("attached", "nattached", mode="after") @classmethod def validate_minimum_list_length( cls, value: list[str] | list[int] | None ) -> list[str] | list[int] | None: 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

StructureFeatures

Bases: Enum

Enumeration of structure_features values

Source code in optimade/models/structures.py
56 57 58 59 60 61 62
class StructureFeatures(Enum): """Enumeration of structure_features values""" DISORDER = "disorder" IMPLICIT_ATOMS = "implicit_atoms" SITE_ATTACHMENTS = "site_attachments" ASSEMBLIES = "assemblies"

ASSEMBLIES = 'assemblies' class-attribute instance-attribute

DISORDER = 'disorder' class-attribute instance-attribute

IMPLICIT_ATOMS = 'implicit_atoms' class-attribute instance-attribute

SITE_ATTACHMENTS = 'site_attachments' class-attribute instance-attribute

StructureResource

Bases: EntryResource

Representing a structure.

Source code in optimade/models/structures.py
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
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

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'structures' class-attribute instance-attribute

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
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 1166 1167 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 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
class StructureResourceAttributes(EntryResourceAttributes): """This class contains the Field for the attributes used to represent a structure, e.g. unit cell, atoms, positions.""" elements: Annotated[ list[str] | None, 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[ int | None, 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[ list[float] | None, 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[ str | None, 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[ str | None, 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[ str | None, 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[ str | None, 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[ list[Periodicity] | None, 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[ int | None, 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[ list[Vector3D_unknown] | None, 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 space_group_symmetry_operations_xyz: Annotated[ list[SymmetryOperation] | None, OptimadeField( description="""A list of symmetry operations given as general position x, y and z coordinates in algebraic form. - **Type**: list of strings - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - The property is RECOMMENDED if coordinates are returned in a form to which these operations can or must be applied (e.g. fractional atom coordinates of an asymmetric unit). - The property is REQUIRED if symmetry operations are necessary to reconstruct the full model of the material and no other symmetry information (e.g., the Hall symbol) is provided that would allow the user to derive symmetry operations unambiguously. - **Query***: Support for queries on this property is not required and in fact is NOT RECOMMENDED. - MUST be `null` if `nperiodic_dimensions` is equal to 0. - Each symmetry operation is described by a string that gives that symmetry operation in Jones' faithful representation (Bradley & Cracknell, 1972: pp. 35-37), adapted for computer string notation. - The letters `x`, `y` and `z` that are typesetted with overbars in printed text represent coordinate values multiplied by -1 and are encoded as `-x`, `-y` and `-z`, respectively. - The syntax of the strings representing symmetry operations MUST conform to regular expressions given in appendix The Symmetry Operation String Regular Expressions. - The interpretation of the strings MUST follow the conventions of the IUCr CIF core dictionary (IUCr, 2023). In particular, this property MUST explicitly provide all symmetry operations needed to generate all the atoms in the unit cell from the atoms in the asymmetric unit, for the setting used. - This symmetry operation set MUST always include the `x,y,z` identity operation. - The symmetry operations are to be applied to fractional atom coordinates. In case only Cartesian coordinates are available, these Cartesian coordinates must be converted to fractional coordinates before the application of the provided symmetry operations. - If the symmetry operation list is present, it MUST be compatible with other space group specifications (e.g. the ITC space group number, the Hall symbol, the Hermann-Mauguin symbol) if these are present. - **Examples**: - Space group operations for the space group with ITC number 3 (H-M symbol `P 2`, extended H-M symbol `P 1 2 1`, Hall symbol `P 2y`): `["x,y,z", "-x,y,-z"]` - Space group operations for the space group with ITC number 5 (H-M symbol `C 2`, extended H-M symbol `C 1 2 1`, Hall symbol `C 2y`): `["x,y,z", "-x,y,-z", "x+1/2,y+1/2,z", "-x+1/2,y+1/2,-z"]` - **Notes**: The list of space group symmetry operations applies to the whole periodic array of atoms and together with the lattice translations given in the `lattice_vectors` property provides the necessary information to reconstruct all atom site positions of the periodic material. Thus, the symmetry operations described in this property are only applicable to material models with at least one periodic dimension. This property is not meant to represent arbitrary symmetries of molecules, non-periodic (finite) collections of atoms or non-crystallographic symmetry. - **Bibliographic References**: - Bradley, C. J. and Cracknell, A. P. (1972) The Mathematical Theory of Symmetry in Solids. Oxford, Clarendon Press (paperback edition 2010) 745 p. ISBN 978-0-19-958258-7. - IUCr (2023) Core dictionary (coreCIF) version 2.4.5; data name `_space_group_symop_operation_xyz`. Available from: https://www.iucr.org/__data/iucr/cifdic_html/1/cif_core.dic/Ispace_group_symop_operation_xyz.html [Accessed 2023-06-18T16:46+03:00].""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None space_group_symbol_hall: Annotated[ str | None, OptimadeField( description="""A Hall space group symbol representing the symmetry of the structure as defined in (Hall, 1981, 1981a). - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The change-of-basis operations are used as defined in the International Tables of Crystallography (ITC) Vol. B, Sect. 1.4, Appendix A1.4.2 (IUCr, 2001). - Each component of the Hall symbol MUST be separated by a single space symbol. - If there exists a standard Hall symbol which represents the symmetry it SHOULD be used. - MUST be `null` if `nperiodic_dimensions` is not equal to 3. - **Examples**: - Space group symbols with explicit origin (the Hall symbols): - `P 2c -2ac` - `I 4bd 2ab 3` - Space group symbols with change-of-basis operations: - `P 2yb (-1/2*x+z,1/2*x,y)` - `-I 4 2 (1/2*x+1/2*y,-1/2*x+1/2*y,z)` - **Bibliographic References**: - Hall, S. R. (1981) Space-group notation with an explicit origin. Acta Crystallographica Section A, 37, 517-525, International Union of Crystallography (IUCr), DOI: https://doi.org/10.1107/s0567739481001228 - Hall, S. R. (1981a) Space-group notation with an explicit origin; erratum. Acta Crystallographica Section A, 37, 921-921, International Union of Crystallography (IUCr), DOI: https://doi.org/10.1107/s0567739481001976 - IUCr (2001). International Tables for Crystallography vol. B. Reciprocal Space. Ed. U. Shmueli. 2-nd edition. Dordrecht/Boston/London, Kluwer Academic Publishers.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None space_group_symbol_hermann_mauguin: Annotated[ str | None, OptimadeField( description="""A human- and machine-readable string containing the short Hermann-Mauguin (H-M) symbol which specifies the space group of the structure in the response. - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The H-M symbol SHOULD aim to convey the closest representation of the symmetry information that can be specified using the short format used in the International Tables for Crystallography vol. A (IUCr, 2005), Table 4.3.2.1 as described in the accompanying text. - The symbol MAY be a non-standard short H-M symbol. - The H-M symbol does not unambiguously communicate the axis, cell, and origin choice, and the given symbol SHOULD NOT be amended to convey this information. - To encode as character strings, the following adaptations MUST be made when representing H-M symbols given in their typesetted form: - the overbar above the numbers MUST be changed to the minus sign in front of the digit (e.g. '-2'); - subscripts that denote screw axes are written as digits immediately after the axis designator without a space (e.g. 'P 32') - the space group generators MUST be separated by a single space (e.g. 'P 21 21 2'); - there MUST be no spaces in the space group generator designation (i.e. use 'P 21/m', not the 'P 21 / m'); - **Examples**: - `C 2` - `P 21 21 21` - **Bibliographic References**: - IUCr (2005). International Tables for Crystallography vol. A. Space-Group Symmetry. Ed. Theo Hahn. 5-th edition. Dordrecht, Springer. """, support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, pattern=HM_SYMBOL_REGEXP, ), ] = None space_group_symbol_hermann_mauguin_extended: Annotated[ str | None, OptimadeField( description="""A human- and machine-readable string containing the extended Hermann-Mauguin (H-M) symbol which specifies the space group of the structure in the response. - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The H-M symbols SHOULD be given as specified in the International Tables for Crystallography vol. A (IUCr, 2005), Table 4.3.2.1. - The change-of-basis operation SHOULD be provided for the non-standard axis and cell choices. - The extended H-M symbol does not unambiguously communicate the origin choice, and the given symbol SHOULD NOT be amended to convey this information. - The description of the change-of-basis SHOULD follow conventions of the ITC Vol. B, Sect. 1.4, Appendix A1.4.2 (IUCr, 2001). - The same character string encoding conventions MUST be used as for the specification of the `space_group_symbol_hermann_mauguin` property. - **Examples**: - `C 1 2 1` - **Bibliographic References**: - IUCr (2001). International Tables for Crystallography vol. B. Reciprocal Space. Ed. U. Shmueli. 2-nd edition. Dordrecht/Boston/London, Kluwer Academic Publishers. - IUCr (2005). International Tables for Crystallography vol. A. Space-Group Symmetry. Ed. Theo Hahn. 5-th edition. Dordrecht, Springer. """, support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, pattern=HM_SYMBOL_REGEXP, ), ] = None space_group_it_number: Annotated[ int | None, OptimadeField( description="""Space group number which specifies the space group of the structure as defined in the International Tables for Crystallography Vol. A. (IUCr, 2005). - **Type**: integer - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The integer value MUST be between 1 and 230. - MUST be null if `nperiodic_dimensions` is not equal to 3.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ge=1, le=230, ), ] = None cartesian_site_positions: Annotated[ list[Vector3D] | None, 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[ int | None, 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[ list[Species] | None, 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[ list[str] | None, 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[ list[Assembly] | None, 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: str | None, info: "ValidationInfo" ) -> str | None: 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: str | None) -> str | None: 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: str | None, info: "ValidationInfo" ) -> str | None: 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: list[str] | None) -> list[str] | None: 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: list[float] | None) -> list[float] | None: 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: None | (Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]), ) -> Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)] | None: 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: list[Species] | None) -> list[Species] | None: 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 check_symmetry_operations(self) -> "StructureResourceAttributes": if self.nperiodic_dimensions == 0 and self.space_group_symmetry_operations_xyz: raise ValueError( "Non-periodic structures MUST NOT have space group symmetry operations." ) if ( self.space_group_symmetry_operations_xyz and "x,y,z" not in self.space_group_symmetry_operations_xyz ): raise ValueError( "The identity operation 'x,y,z' MUST be included in the space group symmetry operations, if provided." ) return self @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 # 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

assemblies = None class-attribute instance-attribute

cartesian_site_positions = None class-attribute instance-attribute

chemical_formula_anonymous = None class-attribute instance-attribute

chemical_formula_descriptive = None class-attribute instance-attribute

chemical_formula_hill = None class-attribute instance-attribute

chemical_formula_reduced = None class-attribute instance-attribute

dimension_types = None class-attribute instance-attribute

elements = None class-attribute instance-attribute

elements_ratios = None class-attribute instance-attribute

immutable_id = None class-attribute instance-attribute

last_modified instance-attribute

lattice_vectors = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

nelements = None class-attribute instance-attribute

nperiodic_dimensions = None class-attribute instance-attribute

nsites = None class-attribute instance-attribute

space_group_it_number = None class-attribute instance-attribute

space_group_symbol_hall = None class-attribute instance-attribute

space_group_symbol_hermann_mauguin = None class-attribute instance-attribute

space_group_symbol_hermann_mauguin_extended = None class-attribute instance-attribute

space_group_symmetry_operations_xyz = None class-attribute instance-attribute

species = None class-attribute instance-attribute

species_at_sites = None class-attribute instance-attribute

structure_features instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_anonymous_formula(value) classmethod

Source code in optimade/models/structures.py
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
@field_validator("chemical_formula_anonymous", mode="after") @classmethod def check_anonymous_formula(cls, value: str | None) -> str | None: 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

check_dimensions_types_dependencies()

Source code in optimade/models/structures.py
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
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

check_ordered_formula(value, info) classmethod

Source code in optimade/models/structures.py
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
@field_validator("chemical_formula_reduced", "chemical_formula_hill", mode="after") @classmethod def check_ordered_formula( cls, value: str | None, info: "ValidationInfo" ) -> str | None: 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

check_reduced_formulae(value, info) classmethod

Source code in optimade/models/structures.py
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
@field_validator( "chemical_formula_anonymous", "chemical_formula_reduced", mode="after" ) @classmethod def check_reduced_formulae( cls, value: str | None, info: "ValidationInfo" ) -> str | None: 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

check_symmetry_operations()

Source code in optimade/models/structures.py
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
@model_validator(mode="after") def check_symmetry_operations(self) -> "StructureResourceAttributes": if self.nperiodic_dimensions == 0 and self.space_group_symmetry_operations_xyz: raise ValueError( "Non-periodic structures MUST NOT have space group symmetry operations." ) if ( self.space_group_symmetry_operations_xyz and "x,y,z" not in self.space_group_symmetry_operations_xyz ): raise ValueError( "The identity operation 'x,y,z' MUST be included in the space group symmetry operations, if provided." ) return self

elements_must_be_alphabetical(value) classmethod

Source code in optimade/models/structures.py
1102 1103 1104 1105 1106 1107 1108 1109 1110
@field_validator("elements", mode="after") @classmethod def elements_must_be_alphabetical(cls, value: list[str] | None) -> list[str] | None: if value is None: return value if sorted(value) != value: raise ValueError(f"elements must be sorted alphabetically, but is: {value}") return value

null_values_for_whole_vector(value) classmethod

Source code in optimade/models/structures.py
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
@field_validator("lattice_vectors", mode="after") @classmethod def null_values_for_whole_vector( cls, value: None | (Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]), ) -> Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)] | None: 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

ratios_must_sum_to_one(value) classmethod

Source code in optimade/models/structures.py
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
@field_validator("elements_ratios", mode="after") @classmethod def ratios_must_sum_to_one(cls, value: list[float] | None) -> list[float] | None: 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

validate_nsites()

Source code in optimade/models/structures.py
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
@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

validate_species(value) classmethod

Source code in optimade/models/structures.py
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
@field_validator("species", mode="after") @classmethod def validate_species(cls, value: list[Species] | None) -> list[Species] | None: 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

validate_species_at_sites()

Source code in optimade/models/structures.py
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
@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

validate_structure_features()

Source code in optimade/models/structures.py
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
@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 # 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

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
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
@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

StructureResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
129 130 131 132 133 134 135 136 137
class StructureResponseMany(EntryResponseMany): data: Annotated[ list[StructureResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE structures entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

StructureResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
119 120 121 122 123 124 125 126
class StructureResponseOne(EntryResponseOne): data: Annotated[ StructureResource | dict[str, Any] | None, StrictField( description="A single structures entry resource.", union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

Success

Bases: Response

errors are not allowed

Source code in optimade/models/optimade_json.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
class Success(jsonapi.Response): """errors are not allowed""" meta: Annotated[ ResponseMeta, StrictField(description="A meta object containing non-standard information"), ] @model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

SupportLevel

Bases: Enum

OPTIMADE property/field support levels

Source code in optimade/models/utils.py
32 33 34 35 36 37
class SupportLevel(Enum): """OPTIMADE property/field support levels""" MUST = "must" SHOULD = "should" OPTIONAL = "optional"

MUST = 'must' class-attribute instance-attribute

OPTIONAL = 'optional' class-attribute instance-attribute

SHOULD = 'should' class-attribute instance-attribute

Bases: BaseModel

A set of Links objects, possibly including pagination

Source code in optimade/models/jsonapi.py
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
class ToplevelLinks(BaseModel): """A set of Links objects, possibly including pagination""" model_config = ConfigDict(extra="allow") self: Annotated[ JsonLinkType | None, StrictField(description="A link to itself") ] = None related: Annotated[ JsonLinkType | None, StrictField(description="A related resource link") ] = None # Pagination first: Annotated[ JsonLinkType | None, StrictField(description="The first page of data") ] = None last: Annotated[ JsonLinkType | None, StrictField(description="The last page of data") ] = None prev: Annotated[ JsonLinkType | None, StrictField(description="The previous page of data") ] = None next: Annotated[ JsonLinkType | None, StrictField(description="The next page of data") ] = None @model_validator(mode="after") def check_additional_keys_are_links(self) -> "ToplevelLinks": """The `ToplevelLinks` class allows any additional keys, as long as they are also Links or Urls themselves. """ for field, value in self: if field not in self.model_fields: setattr( self, field, TypeAdapter(Optional[JsonLinkType]).validate_python(value), ) return self

first = None class-attribute instance-attribute

last = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

next = None class-attribute instance-attribute

prev = None class-attribute instance-attribute

related = None class-attribute instance-attribute

self = None class-attribute instance-attribute

The ToplevelLinks class allows any additional keys, as long as they are also Links or Urls themselves.

Source code in optimade/models/jsonapi.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
@model_validator(mode="after") def check_additional_keys_are_links(self) -> "ToplevelLinks": """The `ToplevelLinks` class allows any additional keys, as long as they are also Links or Urls themselves. """ for field, value in self: if field not in self.model_fields: setattr( self, field, TypeAdapter(Optional[JsonLinkType]).validate_python(value), ) return self

Warnings

Bases: OptimadeError

OPTIMADE-specific warning class based on OPTIMADE-specific JSON API Error.

From the specification:

A warning resource object is defined similarly to a JSON API error object, but MUST also include the field type, which MUST have the value "warning". The field detail MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features.

Note: Must be named "Warnings", since "Warning" is a built-in Python class.

Source code in optimade/models/optimade_json.py
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
class Warnings(OptimadeError): """OPTIMADE-specific warning class based on OPTIMADE-specific JSON API Error. From the specification: A warning resource object is defined similarly to a JSON API error object, but MUST also include the field type, which MUST have the value "warning". The field detail MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features. Note: Must be named "Warnings", since "Warning" is a built-in Python class. """ model_config = ConfigDict(json_schema_extra=warnings_json_schema_extra) type: Annotated[ Literal["warning"], StrictField( description='Warnings must be of type "warning"', pattern="^warning$", ), ] = "warning" @model_validator(mode="after") def status_must_not_be_specified(self) -> "Warnings": if self.status or "status" in self.model_fields_set: raise ValueError("status MUST NOT be specified for warnings") return self

code = None class-attribute instance-attribute

detail instance-attribute

id = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=warnings_json_schema_extra) class-attribute instance-attribute

source = None class-attribute instance-attribute

status = None class-attribute instance-attribute

title = None class-attribute instance-attribute

type = 'warning' class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191 192
def __hash__(self): return hash(self.model_dump_json())

status_must_not_be_specified()

Source code in optimade/models/optimade_json.py
188 189 190 191 192
@model_validator(mode="after") def status_must_not_be_specified(self) -> "Warnings": if self.status or "status" in self.model_fields_set: raise ValueError("status MUST NOT be specified for warnings") return self

baseinfo

VERSIONED_BASE_URL_PATTERN = '^.+/v[0-1](\\.[0-9]+)*/?$' module-attribute

AvailableApiVersion

Bases: BaseModel

A JSON object containing information about an available API version

Source code in optimade/models/baseinfo.py
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
class AvailableApiVersion(BaseModel): """A JSON object containing information about an available API version""" url: Annotated[ AnyHttpUrl, StrictField( description="A string specifying a versioned base URL that MUST adhere to the rules in section Base URL", json_schema_extra={ "pattern": VERSIONED_BASE_URL_PATTERN, }, ), ] version: Annotated[ SemanticVersion, StrictField( description="""A string containing the full version number of the API served at that versioned base URL. The version number string MUST NOT be prefixed by, e.g., 'v'. Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] @field_validator("url", mode="after") @classmethod def url_must_be_versioned_base_Url(cls, value: AnyHttpUrl) -> AnyHttpUrl: """The URL must be a versioned base URL""" if not re.match(VERSIONED_BASE_URL_PATTERN, str(value)): raise ValueError( f"URL {value} must be a versioned base URL (i.e., must match the " f"pattern '{VERSIONED_BASE_URL_PATTERN}')" ) return value @model_validator(mode="after") def crosscheck_url_and_version(self) -> "AvailableApiVersion": """Check that URL version and API version are compatible.""" url = ( str(self.url) .split("/")[-2 if str(self.url).endswith("/") else -1] .replace("v", "") ) # as with version urls, we need to split any release tags or build metadata out of these URLs url_version = tuple( int(val) for val in url.split("-")[0].split("+")[0].split(".") ) api_version = tuple( int(val) for val in str(self.version).split("-")[0].split("+")[0].split(".") ) if any(a != b for a, b in zip(url_version, api_version)): raise ValueError( f"API version {api_version} is not compatible with url version {url_version}." ) return self

url instance-attribute

version instance-attribute

crosscheck_url_and_version()

Check that URL version and API version are compatible.

Source code in optimade/models/baseinfo.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
@model_validator(mode="after") def crosscheck_url_and_version(self) -> "AvailableApiVersion": """Check that URL version and API version are compatible.""" url = ( str(self.url) .split("/")[-2 if str(self.url).endswith("/") else -1] .replace("v", "") ) # as with version urls, we need to split any release tags or build metadata out of these URLs url_version = tuple( int(val) for val in url.split("-")[0].split("+")[0].split(".") ) api_version = tuple( int(val) for val in str(self.version).split("-")[0].split("+")[0].split(".") ) if any(a != b for a, b in zip(url_version, api_version)): raise ValueError( f"API version {api_version} is not compatible with url version {url_version}." ) return self

url_must_be_versioned_base_Url(value) classmethod

The URL must be a versioned base URL

Source code in optimade/models/baseinfo.py
38 39 40 41 42 43 44 45 46 47
@field_validator("url", mode="after") @classmethod def url_must_be_versioned_base_Url(cls, value: AnyHttpUrl) -> AnyHttpUrl: """The URL must be a versioned base URL""" if not re.match(VERSIONED_BASE_URL_PATTERN, str(value)): raise ValueError( f"URL {value} must be a versioned base URL (i.e., must match the " f"pattern '{VERSIONED_BASE_URL_PATTERN}')" ) return value

BaseInfoAttributes

Bases: BaseModel

Attributes for Base URL Info endpoint

Source code in optimade/models/baseinfo.py
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
class BaseInfoAttributes(BaseModel): """Attributes for Base URL Info endpoint""" api_version: Annotated[ SemanticVersion, StrictField( description="""Presently used full version of the OPTIMADE API. The version number string MUST NOT be prefixed by, e.g., "v". Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] available_api_versions: Annotated[ list[AvailableApiVersion], StrictField( description="A list of dictionaries of available API versions at other base URLs", ), ] formats: Annotated[ list[str], StrictField(description="List of available output formats.") ] = ["json"] available_endpoints: Annotated[ list[str], StrictField( description="List of available endpoints (i.e., the string to be appended to the versioned base URL).", ), ] entry_types_by_format: Annotated[ dict[str, list[str]], StrictField( description="Available entry endpoints as a function of output formats." ), ] is_index: Annotated[ bool | None, StrictField( description="If true, this is an index meta-database base URL (see section Index Meta-Database). " "If this member is not provided, the client MUST assume this is not an index meta-database base URL " "(i.e., the default is for `is_index` to be `false`).", ), ] = False license: Annotated[ Link | AnyHttpUrl | None, StrictField( ..., description="""A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) giving a URL to a web page containing a human-readable text describing the license (or licensing options if there are multiple) covering all the data and metadata provided by this database. Clients are advised not to try automated parsing of this link or its content, but rather rely on the field `available_licenses` instead.""", ), ] = None available_licenses: Annotated[ list[str] | None, StrictField( ..., description="""List of [SPDX license identifiers](https://spdx.org/licenses/) specifying a set of alternative licenses available to the client for licensing the complete database, i.e., all the entries, metadata, and the content and structure of the database itself. If more than one license is available to the client, the identifier of each one SHOULD be included in the list. Inclusion of a license identifier in the list is a commitment of the database that the rights are in place to grant clients access to all the individual entries, all metadata, and the content and structure of the database itself according to the terms of any of these licenses (at the choice of the client). If the licensing information provided via the field license omits licensing options specified in `available_licenses`, or if it otherwise contradicts them, a client MUST still be allowed to interpret the inclusion of a license in `available_licenses` as a full commitment from the database without exceptions, under the respective licenses. If the database cannot make that commitment, e.g., if only part of the database is available under a license, the corresponding license identifier MUST NOT appear in `available_licenses` (but, rather, the field license is to be used to clarify the licensing situation.) An empty list indicates that none of the SPDX licenses apply and that the licensing situation is clarified in human readable form in the field `license`. An unknown value means that the database makes no commitment.""", ), ] = None available_licenses_for_entries: Annotated[ list[str] | None, StrictField( ..., description="""List of [SPDX license identifiers](https://spdx.org/licenses/) specifying a set of additional alternative licenses available to the client for licensing individual, and non-substantial sets of, database entries, metadata, and extracts from the database that do not constitute substantial parts of the database. Note that the definition of the field `available_licenses` implies that licenses specified in that field are available also for the licensing specified by this field, even if they are not explicitly included in the field `available_licenses_for_entries` or if it is `null` (however, the opposite relationship does not hold). If `available_licenses` is unknown, only the licenses in `available_licenses_for_entries` apply.""", ), ] = None @model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

api_version instance-attribute

available_api_versions instance-attribute

available_endpoints instance-attribute

available_licenses = None class-attribute instance-attribute

available_licenses_for_entries = None class-attribute instance-attribute

entry_types_by_format instance-attribute

formats = ['json'] class-attribute instance-attribute

is_index = False class-attribute instance-attribute

license = None class-attribute instance-attribute

formats_and_endpoints_must_be_valid()

Source code in optimade/models/baseinfo.py
145 146 147 148 149 150 151 152 153 154 155
@model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

BaseInfoResource

Bases: Resource

Source code in optimade/models/baseinfo.py
158 159 160 161
class BaseInfoResource(Resource): id: Literal["/"] = "/" type: Literal["info"] = "info" attributes: BaseInfoAttributes

attributes instance-attribute

id = '/' class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'info' class-attribute instance-attribute

entries

EntryInfoProperty

Bases: BaseModel

Source code in optimade/models/entries.py
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
class EntryInfoProperty(BaseModel): description: Annotated[ str, StrictField(description="A human-readable description of the entry property"), ] unit: Annotated[ str | None, StrictField( description="""The physical unit of the entry property. This MUST be a valid representation of units according to version 2.1 of [The Unified Code for Units of Measure](https://unitsofmeasure.org/ucum.html). It is RECOMMENDED that non-standard (non-SI) units are described in the description for the property.""", ), ] = None sortable: Annotated[ bool | None, StrictField( description="""Defines whether the entry property can be used for sorting with the "sort" parameter. If the entry listing endpoint supports sorting, this key MUST be present for sortable properties with value `true`.""", ), ] = None type: Annotated[ DataType | None, StrictField( title="Type", description="""The type of the property's value. This MUST be any of the types defined in the Data types section. For the purpose of compatibility with future versions of this specification, a client MUST accept values that are not `string` values specifying any of the OPTIMADE Data types, but MUST then also disregard the `type` field. Note, if the value is a nested type, only the outermost type should be reported. E.g., for the entry resource `structures`, the `species` property is defined as a list of dictionaries, hence its `type` value would be `list`.""", ), ] = None

description instance-attribute

sortable = None class-attribute instance-attribute

type = None class-attribute instance-attribute

unit = None class-attribute instance-attribute

EntryInfoResource

Bases: BaseModel

Source code in optimade/models/entries.py
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
class EntryInfoResource(BaseModel): id: Annotated[ str, StrictField( optimade_version=">= 1.2", description="Must precisely match the entry type name for the given info endpoint.", ), ] type: Annotated[ str, StrictField( optimade_version=">= 1.2", description="The type of this response.", default="info", ), ] formats: Annotated[ list[str], StrictField( description="List of output formats available for this type of entry." ), ] description: Annotated[str, StrictField(description="Description of the entry.")] properties: Annotated[ dict[ValidIdentifier, EntryInfoProperty], StrictField( description="A dictionary describing queryable properties for this entry type, where each key is a property name.", ), ] output_fields_by_format: Annotated[ dict[str, list[ValidIdentifier]], StrictField( description="Dictionary of available output fields for this entry type, where the keys are the values of the `formats` list and the values are the keys of the `properties` dictionary.", ), ]

description instance-attribute

formats instance-attribute

id instance-attribute

output_fields_by_format instance-attribute

properties instance-attribute

type instance-attribute

EntryRelationships

Bases: Relationships

This model wraps the JSON API Relationships to include type-specific top level keys.

Source code in optimade/models/entries.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
class EntryRelationships(Relationships): """This model wraps the JSON API Relationships to include type-specific top level keys.""" references: Annotated[ ReferenceRelationship | None, StrictField( description="Object containing links to relationships with entries of the `references` type.", ), ] = None structures: Annotated[ StructureRelationship | None, StrictField( description="Object containing links to relationships with entries of the `structures` type.", ), ] = None

references = None class-attribute instance-attribute

structures = None class-attribute instance-attribute

check_illegal_relationships_fields()

Source code in optimade/models/jsonapi.py
296 297 298 299 300 301 302 303 304
@model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

EntryResource

Bases: Resource

The base model for an entry resource.

Source code in optimade/models/entries.py
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
class EntryResource(Resource): """The base model for an entry resource.""" id: Annotated[ str, OptimadeField( description="""An entry's ID as defined in section Definition of Terms. - **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. - **Examples**: - `"db/1234567"` - `"cod/2000000"` - `"cod/2000000@1234567"` - `"nomad/L1234567890"` - `"42"`""", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] type: Annotated[ str, OptimadeField( 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. - **Example**: `"structures"`""", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] attributes: Annotated[ EntryResourceAttributes, StrictField( description="""A dictionary, containing key-value pairs representing the entry's properties, except for `type` and `id`. Database-provider-specific properties need to include the database-provider-specific prefix (see section on Database-Provider-Specific Namespace Prefixes).""", ), ] relationships: Annotated[ EntryRelationships | None, StrictField( description="""A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships). The OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.""", ), ] = None

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type instance-attribute

EntryResourceAttributes

Bases: Attributes

Contains key-value pairs representing the entry's properties.

Source code in optimade/models/entries.py
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
class EntryResourceAttributes(Attributes): """Contains key-value pairs representing the entry's properties.""" immutable_id: Annotated[ str | None, OptimadeField( description="""The entry's immutable ID (e.g., an UUID). This is important for databases having preferred IDs that point to "the latest version" of a record, but still offer access to older variants. This ID maps to the version-specific record, in case it changes in the future. - **Type**: string. - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: MUST be a queryable property with support for all mandatory filter features. - **Examples**: - `"8bd3e750-b477-41a0-9b11-3a799f21b44f"` - `"fjeiwoj,54;@=%<>#32"` (Strings that are not URL-safe are allowed.)""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.MUST, ), ] = None last_modified: Annotated[ datetime | None, OptimadeField( description="""Date and time representing when the entry was last modified. - **Type**: timestamp. - **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. - **Response**: REQUIRED in the response unless the query parameter `response_fields` is present and does not include this property. - **Example**: - As part of JSON response format: `"2007-04-05T14:30:20Z"` (i.e., encoded as an [RFC 3339 Internet Date/Time Format](https://tools.ietf.org/html/rfc3339#section-5.6) string.)""", support=SupportLevel.SHOULD, queryable=SupportLevel.MUST, ), ] @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

immutable_id = None class-attribute instance-attribute

last_modified instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

ReferenceRelationship

Bases: TypedRelationship

Source code in optimade/models/entries.py
43 44
class ReferenceRelationship(TypedRelationship): _req_type: ClassVar[Literal["references"]] = "references"

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

check_rel_type(data) classmethod

Source code in optimade/models/entries.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40
@field_validator("data", mode="after") @classmethod def check_rel_type( cls, data: BaseRelationshipResource | list[BaseRelationshipResource] ) -> list[BaseRelationshipResource]: if not isinstance(data, list): # All relationships at this point are empty-to-many relationships in JSON:API: # https://jsonapi.org/format/1.0/#document-resource-object-linkage raise ValueError("`data` key in a relationship must always store a list.") if any(obj.type != cls._req_type for obj in data): raise ValueError("Object stored in relationship data has wrong type") return data

StructureRelationship

Bases: TypedRelationship

Source code in optimade/models/entries.py
47 48
class StructureRelationship(TypedRelationship): _req_type: ClassVar[Literal["structures"]] = "structures"

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

check_rel_type(data) classmethod

Source code in optimade/models/entries.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40
@field_validator("data", mode="after") @classmethod def check_rel_type( cls, data: BaseRelationshipResource | list[BaseRelationshipResource] ) -> list[BaseRelationshipResource]: if not isinstance(data, list): # All relationships at this point are empty-to-many relationships in JSON:API: # https://jsonapi.org/format/1.0/#document-resource-object-linkage raise ValueError("`data` key in a relationship must always store a list.") if any(obj.type != cls._req_type for obj in data): raise ValueError("Object stored in relationship data has wrong type") return data

TypedRelationship

Bases: Relationship

Source code in optimade/models/entries.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
class TypedRelationship(Relationship): _req_type: ClassVar[str] @field_validator("data", mode="after") @classmethod def check_rel_type( cls, data: BaseRelationshipResource | list[BaseRelationshipResource] ) -> list[BaseRelationshipResource]: if not isinstance(data, list): # All relationships at this point are empty-to-many relationships in JSON:API: # https://jsonapi.org/format/1.0/#document-resource-object-linkage raise ValueError("`data` key in a relationship must always store a list.") if any(obj.type != cls._req_type for obj in data): raise ValueError("Object stored in relationship data has wrong type") return data

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

check_rel_type(data) classmethod

Source code in optimade/models/entries.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40
@field_validator("data", mode="after") @classmethod def check_rel_type( cls, data: BaseRelationshipResource | list[BaseRelationshipResource] ) -> list[BaseRelationshipResource]: if not isinstance(data, list): # All relationships at this point are empty-to-many relationships in JSON:API: # https://jsonapi.org/format/1.0/#document-resource-object-linkage raise ValueError("`data` key in a relationship must always store a list.") if any(obj.type != cls._req_type for obj in data): raise ValueError("Object stored in relationship data has wrong type") return data

index_metadb

IndexInfoAttributes

Bases: BaseInfoAttributes

Attributes for Base URL Info endpoint for an Index Meta-Database

Source code in optimade/models/index_metadb.py
17 18 19 20 21 22 23 24 25
class IndexInfoAttributes(BaseInfoAttributes): """Attributes for Base URL Info endpoint for an Index Meta-Database""" is_index: Annotated[ bool, StrictField( description="This must be `true` since this is an index meta-database (see section Index Meta-Database).", ), ] = True

api_version instance-attribute

available_api_versions instance-attribute

available_endpoints instance-attribute

available_licenses = None class-attribute instance-attribute

available_licenses_for_entries = None class-attribute instance-attribute

entry_types_by_format instance-attribute

formats = ['json'] class-attribute instance-attribute

is_index = True class-attribute instance-attribute

license = None class-attribute instance-attribute

formats_and_endpoints_must_be_valid()

Source code in optimade/models/baseinfo.py
145 146 147 148 149 150 151 152 153 154 155
@model_validator(mode="after") def formats_and_endpoints_must_be_valid(self) -> "BaseInfoAttributes": for format_, endpoints in self.entry_types_by_format.items(): if format_ not in self.formats: raise ValueError(f"'{format_}' must be listed in formats to be valid") for endpoint in endpoints: if endpoint not in self.available_endpoints: raise ValueError( f"'{endpoint}' must be listed in available_endpoints to be valid" ) return self

IndexInfoResource

Bases: BaseInfoResource

Index Meta-Database Base URL Info endpoint resource

Source code in optimade/models/index_metadb.py
46 47 48 49 50 51 52 53 54 55 56 57
class IndexInfoResource(BaseInfoResource): """Index Meta-Database Base URL Info endpoint resource""" attributes: IndexInfoAttributes relationships: Annotated[ # type: ignore[assignment] dict[Literal["default"], IndexRelationship] | None, StrictField( title="Relationships", description="""Reference to the Links identifier object under the `links` endpoint that the provider has chosen as their 'default' OPTIMADE API database. A client SHOULD present this database as the first choice when an end-user chooses this provider.""", ), ]

attributes instance-attribute

id = '/' class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships instance-attribute

type = 'info' class-attribute instance-attribute

IndexRelationship

Bases: BaseModel

Index Meta-Database relationship

Source code in optimade/models/index_metadb.py
34 35 36 37 38 39 40 41 42 43
class IndexRelationship(BaseModel): """Index Meta-Database relationship""" data: Annotated[ RelatedLinksResource | None, StrictField( description="""[JSON API resource linkage](http://jsonapi.org/format/1.0/#document-links). It MUST be either `null` or contain a single Links identifier object with the fields `id` and `type`""", ), ]

data instance-attribute

RelatedLinksResource

Bases: BaseResource

A related Links resource object

Source code in optimade/models/index_metadb.py
28 29 30 31
class RelatedLinksResource(BaseResource): """A related Links resource object""" type: Literal["links"] = "links"

id instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type = 'links' class-attribute instance-attribute

jsonapi

This module should reproduce JSON API v1.0 https://jsonapi.org/format/1.0/

JsonLinkType = Union[AnyUrl, Link] module-attribute

Attributes

Bases: BaseModel

Members of the attributes object ("attributes") represent information about the resource object in which it's defined. The keys for Attributes MUST NOT be: relationships links id type

Source code in optimade/models/jsonapi.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
class Attributes(BaseModel): """ Members of the attributes object ("attributes\") represent information about the resource object in which it's defined. The keys for Attributes MUST NOT be: relationships links id type """ model_config = ConfigDict(extra="allow") @model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

BaseResource

Bases: BaseModel

Minimum requirements to represent a Resource

Source code in optimade/models/jsonapi.py
218 219 220 221 222 223 224
class BaseResource(BaseModel): """Minimum requirements to represent a Resource""" model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) id: Annotated[str, StrictField(description="Resource ID")] type: Annotated[str, StrictField(description="Resource type")]

id instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type instance-attribute

Error

Bases: BaseModel

An error response

Source code in optimade/models/jsonapi.py
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
class Error(BaseModel): """An error response""" id: Annotated[ str | None, StrictField( description="A unique identifier for this particular occurrence of the problem.", ), ] = None links: Annotated[ ErrorLinks | None, StrictField(description="A links object storing about") ] = None status: Annotated[ Annotated[str, BeforeValidator(str)] | None, StrictField( description="the HTTP status code applicable to this problem, expressed as a string value.", ), ] = None code: Annotated[ str | None, StrictField( description="an application-specific error code, expressed as a string value.", ), ] = None title: Annotated[ str | None, StrictField( description="A short, human-readable summary of the problem. " "It **SHOULD NOT** change from occurrence to occurrence of the problem, except for purposes of localization.", ), ] = None detail: Annotated[ str | None, StrictField( description="A human-readable explanation specific to this occurrence of the problem.", ), ] = None source: Annotated[ ErrorSource | None, StrictField( description="An object containing references to the source of the error" ), ] = None meta: Annotated[ Meta | None, StrictField( description="a meta object containing non-standard meta-information about the error.", ), ] = None def __hash__(self): return hash(self.model_dump_json())

code = None class-attribute instance-attribute

detail = None class-attribute instance-attribute

id = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

source = None class-attribute instance-attribute

status = None class-attribute instance-attribute

title = None class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191 192
def __hash__(self): return hash(self.model_dump_json())

Bases: BaseModel

A Links object specific to Error objects

Source code in optimade/models/jsonapi.py
112 113 114 115 116 117 118 119 120
class ErrorLinks(BaseModel): """A Links object specific to Error objects""" about: Annotated[ JsonLinkType | None, StrictField( description="A link that leads to further details about this particular occurrence of the problem.", ), ] = None

about = None class-attribute instance-attribute

ErrorSource

Bases: BaseModel

an object containing references to the source of the error

Source code in optimade/models/jsonapi.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
class ErrorSource(BaseModel): """an object containing references to the source of the error""" pointer: Annotated[ str | None, StrictField( description="a JSON Pointer [RFC6901] to the associated entity in the request document " '[e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].', ), ] = None parameter: Annotated[ str | None, StrictField( description="a string indicating which URI query parameter caused the error.", ), ] = None

parameter = None class-attribute instance-attribute

pointer = None class-attribute instance-attribute

JsonApi

Bases: BaseModel

An object describing the server's implementation

Source code in optimade/models/jsonapi.py
58 59 60 61 62 63 64 65 66
class JsonApi(BaseModel): """An object describing the server's implementation""" version: Annotated[str, StrictField(description="Version of the json API used")] = ( "1.0" ) meta: Annotated[ Meta | None, StrictField(description="Non-standard meta information") ] = None

meta = None class-attribute instance-attribute

version = '1.0' class-attribute instance-attribute

Bases: BaseModel

A link MUST be represented as either: a string containing the link's URL or a link object.

Source code in optimade/models/jsonapi.py
41 42 43 44 45 46 47 48 49 50 51 52
class Link(BaseModel): """A link **MUST** be represented as either: a string containing the link's URL or a link object.""" href: Annotated[ AnyUrl, StrictField(description="a string containing the link's URL.") ] meta: Annotated[ Meta | None, StrictField( description="a meta object containing non-standard meta-information about the link.", ), ] = None

href instance-attribute

meta = None class-attribute instance-attribute

Meta

Bases: BaseModel

Non-standard meta-information that can not be represented as an attribute or relationship.

Source code in optimade/models/jsonapi.py
35 36 37 38
class Meta(BaseModel): """Non-standard meta-information that can not be represented as an attribute or relationship.""" model_config = ConfigDict(extra="allow")

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

Relationship

Bases: BaseModel

Representation references from the resource object in which it's defined to other resource objects.

Source code in optimade/models/jsonapi.py
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
class Relationship(BaseModel): """Representation references from the resource object in which it's defined to other resource objects.""" links: Annotated[ RelationshipLinks | None, StrictField( description="a links object containing at least one of the following: self, related", ), ] = None data: Annotated[ BaseResource | list[BaseResource] | None, StrictField(description="Resource linkage"), ] = None meta: Annotated[ Meta | None, StrictField( description="a meta object that contains non-standard meta-information about the relationship.", ), ] = None @model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

Bases: BaseModel

A resource object MAY contain references to other resource objects ("relationships"). Relationships may be to-one or to-many. Relationships can be specified by including a member in a resource's links object.

Source code in optimade/models/jsonapi.py
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
class RelationshipLinks(BaseModel): """A resource object **MAY** contain references to other resource objects ("relationships"). Relationships may be to-one or to-many. Relationships can be specified by including a member in a resource's links object. """ self: Annotated[ JsonLinkType | None, StrictField( description="""A link for the relationship itself (a 'relationship link'). This link allows the client to directly manipulate the relationship. When fetched successfully, this link returns the [linkage](https://jsonapi.org/format/1.0/#document-resource-object-linkage) for the related resources as its primary data. (See [Fetching Relationships](https://jsonapi.org/format/1.0/#fetching-relationships).)""", ), ] = None related: Annotated[ JsonLinkType | None, StrictField( description="A [related resource link](https://jsonapi.org/format/1.0/#document-resource-object-related-resource-links).", ), ] = None @model_validator(mode="after") def either_self_or_related_must_be_specified(self) -> "RelationshipLinks": if self.self is None and self.related is None: raise ValueError( "Either 'self' or 'related' MUST be specified for RelationshipLinks" ) return self

related = None class-attribute instance-attribute

self = None class-attribute instance-attribute

Source code in optimade/models/jsonapi.py
250 251 252 253 254 255 256
@model_validator(mode="after") def either_self_or_related_must_be_specified(self) -> "RelationshipLinks": if self.self is None and self.related is None: raise ValueError( "Either 'self' or 'related' MUST be specified for RelationshipLinks" ) return self

Relationships

Bases: BaseModel

Members of the relationships object ("relationships") represent references from the resource object in which it's defined to other resource objects. Keys MUST NOT be: type id

Source code in optimade/models/jsonapi.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
class Relationships(BaseModel): """ Members of the relationships object (\"relationships\") represent references from the resource object in which it's defined to other resource objects. Keys MUST NOT be: type id """ @model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

check_illegal_relationships_fields()

Source code in optimade/models/jsonapi.py
296 297 298 299 300 301 302 303 304
@model_validator(mode="after") def check_illegal_relationships_fields(self) -> "Relationships": illegal_fields = ("id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Relationships" ) return self

Resource

Bases: BaseResource

Resource objects appear in a JSON API document to represent resources.

Source code in optimade/models/jsonapi.py
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
class Resource(BaseResource): """Resource objects appear in a JSON API document to represent resources.""" links: Annotated[ ResourceLinks | None, StrictField( description="a links object containing links related to the resource." ), ] = None meta: Annotated[ Meta | None, StrictField( description="a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.", ), ] = None attributes: Annotated[ Attributes | None, StrictField( description="an attributes object representing some of the resource’s data.", ), ] = None relationships: Annotated[ Relationships | None, StrictField( description="""[Relationships object](https://jsonapi.org/format/1.0/#document-resource-object-relationships) describing relationships between the resource and other JSON API resources.""", ), ] = None

attributes = None class-attribute instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type instance-attribute

Bases: BaseModel

A Resource Links object

Source code in optimade/models/jsonapi.py
307 308 309 310 311 312 313 314 315
class ResourceLinks(BaseModel): """A Resource Links object""" self: Annotated[ JsonLinkType | None, StrictField( description="A link that identifies the resource represented by the resource object.", ), ] = None

self = None class-attribute instance-attribute

Response

Bases: BaseModel

A top-level response.

Source code in optimade/models/jsonapi.py
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
class Response(BaseModel): """A top-level response.""" data: Annotated[ None | Resource | list[Resource] | None, StrictField(description="Outputted Data", uniqueItems=True), ] = None meta: Annotated[ Meta | None, StrictField( description="A meta object containing non-standard information related to the Success", ), ] = None errors: Annotated[ list[Error] | None, StrictField(description="A list of unique errors", uniqueItems=True), ] = None included: Annotated[ list[Resource] | None, StrictField( description="A list of unique included resources", uniqueItems=True ), ] = None links: Annotated[ ToplevelLinks | None, StrictField(description="Links associated with the primary data or errors"), ] = None jsonapi: Annotated[ JsonApi | None, StrictField(description="Information about the JSON API used"), ] = None @model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self model_config = ConfigDict( json_encoders={ datetime: lambda v: v.astimezone(timezone.utc).strftime( "%Y-%m-%dT%H:%M:%SZ" ) } ) """The specification mandates that datetimes must be encoded following [RFC3339](https://tools.ietf.org/html/rfc3339), which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results. """

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
403 404 405 406 407 408 409 410 411 412
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self

Bases: BaseModel

A set of Links objects, possibly including pagination

Source code in optimade/models/jsonapi.py
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
class ToplevelLinks(BaseModel): """A set of Links objects, possibly including pagination""" model_config = ConfigDict(extra="allow") self: Annotated[ JsonLinkType | None, StrictField(description="A link to itself") ] = None related: Annotated[ JsonLinkType | None, StrictField(description="A related resource link") ] = None # Pagination first: Annotated[ JsonLinkType | None, StrictField(description="The first page of data") ] = None last: Annotated[ JsonLinkType | None, StrictField(description="The last page of data") ] = None prev: Annotated[ JsonLinkType | None, StrictField(description="The previous page of data") ] = None next: Annotated[ JsonLinkType | None, StrictField(description="The next page of data") ] = None @model_validator(mode="after") def check_additional_keys_are_links(self) -> "ToplevelLinks": """The `ToplevelLinks` class allows any additional keys, as long as they are also Links or Urls themselves. """ for field, value in self: if field not in self.model_fields: setattr( self, field, TypeAdapter(Optional[JsonLinkType]).validate_python(value), ) return self

first = None class-attribute instance-attribute

last = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

next = None class-attribute instance-attribute

prev = None class-attribute instance-attribute

related = None class-attribute instance-attribute

self = None class-attribute instance-attribute

The ToplevelLinks class allows any additional keys, as long as they are also Links or Urls themselves.

Source code in optimade/models/jsonapi.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
@model_validator(mode="after") def check_additional_keys_are_links(self) -> "ToplevelLinks": """The `ToplevelLinks` class allows any additional keys, as long as they are also Links or Urls themselves. """ for field, value in self: if field not in self.model_fields: setattr( self, field, TypeAdapter(Optional[JsonLinkType]).validate_python(value), ) return self

resource_json_schema_extra(schema, model)

Ensure id and type are the first two entries in the list required properties.

Note

This requires that id and type are the first model fields defined for all sub-models of BaseResource.

Source code in optimade/models/jsonapi.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
def resource_json_schema_extra( schema: dict[str, Any], model: type["BaseResource"] ) -> None: """Ensure `id` and `type` are the first two entries in the list required properties. Note: This _requires_ that `id` and `type` are the _first_ model fields defined for all sub-models of `BaseResource`. """ if "id" not in schema.get("required", []): schema["required"] = ["id"] + schema.get("required", []) if "type" not in schema.get("required", []): required = [] for field in schema.get("required", []): required.append(field) if field == "id": # To make sure the property order match the listed properties, # this ensures "type" is added immediately after "id". required.append("type") schema["required"] = required

Aggregate

Bases: Enum

Enumeration of aggregate values

Source code in optimade/models/links.py
25 26 27 28 29 30 31
class Aggregate(Enum): """Enumeration of aggregate values""" OK = "ok" TEST = "test" STAGING = "staging" NO = "no"

NO = 'no' class-attribute instance-attribute

OK = 'ok' class-attribute instance-attribute

STAGING = 'staging' class-attribute instance-attribute

TEST = 'test' class-attribute instance-attribute

LinkType

Bases: Enum

Enumeration of link_type values

Source code in optimade/models/links.py
16 17 18 19 20 21 22
class LinkType(Enum): """Enumeration of link_type values""" CHILD = "child" ROOT = "root" EXTERNAL = "external" PROVIDERS = "providers"

CHILD = 'child' class-attribute instance-attribute

EXTERNAL = 'external' class-attribute instance-attribute

PROVIDERS = 'providers' class-attribute instance-attribute

ROOT = 'root' class-attribute instance-attribute

LinksResource

Bases: EntryResource

A Links endpoint resource object

Source code in optimade/models/links.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
class LinksResource(EntryResource): """A Links endpoint resource object""" type: Annotated[ Literal["links"], StrictField( description="These objects are described in detail in the section Links Endpoint", pattern="^links$", ), ] = "links" attributes: Annotated[ LinksResourceAttributes, StrictField( description="A dictionary containing key-value pairs representing the Links resource's properties.", ), ] @model_validator(mode="after") def relationships_must_not_be_present(self) -> "LinksResource": if self.relationships or "relationships" in self.model_fields_set: raise ValueError('"relationships" is not allowed for links resources') return self

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'links' class-attribute instance-attribute

relationships_must_not_be_present()

Source code in optimade/models/links.py
116 117 118 119 120
@model_validator(mode="after") def relationships_must_not_be_present(self) -> "LinksResource": if self.relationships or "relationships" in self.model_fields_set: raise ValueError('"relationships" is not allowed for links resources') return self

LinksResourceAttributes

Bases: Attributes

Links endpoint resource object attributes

Source code in optimade/models/links.py
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
class LinksResourceAttributes(Attributes): """Links endpoint resource object attributes""" name: Annotated[ str, StrictField( description="Human-readable name for the OPTIMADE API implementation, e.g., for use in clients to show the name to the end-user.", ), ] description: Annotated[ str, StrictField( description="Human-readable description for the OPTIMADE API implementation, e.g., for use in clients to show a description to the end-user.", ), ] base_url: Annotated[ JsonLinkType | None, StrictField( description="JSON API links object, pointing to the base URL for this implementation", ), ] homepage: Annotated[ JsonLinkType | None, StrictField( description="JSON API links object, pointing to a homepage URL for this implementation", ), ] link_type: Annotated[ LinkType, StrictField( title="Link Type", description="""The type of the linked relation. MUST be one of these values: 'child', 'root', 'external', 'providers'.""", ), ] aggregate: Annotated[ Aggregate | None, StrictField( title="Aggregate", description="""A string indicating whether a client that is following links to aggregate results from different OPTIMADE implementations should follow this link or not. This flag SHOULD NOT be indicated for links where `link_type` is not `child`. If not specified, clients MAY assume that the value is `ok`. If specified, and the value is anything different than `ok`, the client MUST assume that the server is suggesting not to follow the link during aggregation by default (also if the value is not among the known ones, in case a future specification adds new accepted values). Specific values indicate the reason why the server is providing the suggestion. A client MAY follow the link anyway if it has reason to do so (e.g., if the client is looking for all test databases, it MAY follow the links marked with `aggregate`=`test`). If specified, it MUST be one of the values listed in section Link Aggregate Options.""", ), ] = Aggregate.OK no_aggregate_reason: Annotated[ str | None, StrictField( description="""An OPTIONAL human-readable string indicating the reason for suggesting not to aggregate results following the link. It SHOULD NOT be present if `aggregate`=`ok`.""", ), ] = None

aggregate = Aggregate.OK class-attribute instance-attribute

base_url instance-attribute

description instance-attribute

homepage instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

name instance-attribute

no_aggregate_reason = None class-attribute instance-attribute

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

optimade_json

Modified JSON API v1.0 for OPTIMADE API

ValidIdentifier = Annotated[str, Field(pattern=IDENTIFIER_REGEX)] module-attribute

A type that constrains strings to valid OPTIMADE identifiers (e.g., property names, ID strings).

BaseRelationshipMeta

Bases: Meta

Specific meta field for base relationship resource

Source code in optimade/models/optimade_json.py
421 422 423 424 425 426 427 428 429
class BaseRelationshipMeta(jsonapi.Meta): """Specific meta field for base relationship resource""" description: Annotated[ str, StrictField( description="OPTIONAL human-readable description of the relationship." ), ]

description instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

BaseRelationshipResource

Bases: BaseResource

Minimum requirements to represent a relationship resource

Source code in optimade/models/optimade_json.py
432 433 434 435 436 437 438 439 440
class BaseRelationshipResource(jsonapi.BaseResource): """Minimum requirements to represent a relationship resource""" meta: Annotated[ BaseRelationshipMeta | None, StrictField( description="Relationship meta field. MUST contain 'description' if supplied.", ), ] = None

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type instance-attribute

DataType

Bases: Enum

Optimade Data types

See the section "Data types" in the OPTIMADE API specification for more information.

Source code in optimade/models/optimade_json.py
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
class DataType(Enum): """Optimade Data types See the section "Data types" in the OPTIMADE API specification for more information. """ STRING = "string" INTEGER = "integer" FLOAT = "float" BOOLEAN = "boolean" TIMESTAMP = "timestamp" LIST = "list" DICTIONARY = "dictionary" UNKNOWN = "unknown" @classmethod def get_values(cls) -> list[str]: """Get OPTIMADE data types (enum values) as a (sorted) list""" return sorted(_.value for _ in cls) @classmethod def from_python_type(cls, python_type: type | str | object) -> Optional["DataType"]: """Get OPTIMADE data type from a Python type""" mapping = { "bool": cls.BOOLEAN, "int": cls.INTEGER, "float": cls.FLOAT, "complex": None, "generator": cls.LIST, "list": cls.LIST, "tuple": cls.LIST, "range": cls.LIST, "hash": cls.INTEGER, "str": cls.STRING, "bytes": cls.STRING, "bytearray": None, "memoryview": None, "set": cls.LIST, "frozenset": cls.LIST, "dict": cls.DICTIONARY, "dict_keys": cls.LIST, "dict_values": cls.LIST, "dict_items": cls.LIST, "Nonetype": cls.UNKNOWN, "None": cls.UNKNOWN, "datetime": cls.TIMESTAMP, "date": cls.TIMESTAMP, "time": cls.TIMESTAMP, "datetime.datetime": cls.TIMESTAMP, "datetime.date": cls.TIMESTAMP, "datetime.time": cls.TIMESTAMP, } if isinstance(python_type, type): python_type = python_type.__name__ elif isinstance(python_type, object): if str(python_type) in mapping: python_type = str(python_type) else: python_type = type(python_type).__name__ return mapping.get(python_type, None) @classmethod def from_json_type(cls, json_type: str) -> Optional["DataType"]: """Get OPTIMADE data type from a named JSON type""" mapping = { "string": cls.STRING, "integer": cls.INTEGER, "number": cls.FLOAT, # actually includes both integer and float "object": cls.DICTIONARY, "array": cls.LIST, "boolean": cls.BOOLEAN, "null": cls.UNKNOWN, # OpenAPI "format"s: "double": cls.FLOAT, "float": cls.FLOAT, "int32": cls.INTEGER, "int64": cls.INTEGER, "date": cls.TIMESTAMP, "date-time": cls.TIMESTAMP, "password": cls.STRING, "byte": cls.STRING, "binary": cls.STRING, # Non-OpenAPI "format"s, but may still be used by pydantic/FastAPI "email": cls.STRING, "uuid": cls.STRING, "uri": cls.STRING, "hostname": cls.STRING, "ipv4": cls.STRING, "ipv6": cls.STRING, } return mapping.get(json_type, None)

BOOLEAN = 'boolean' class-attribute instance-attribute

DICTIONARY = 'dictionary' class-attribute instance-attribute

FLOAT = 'float' class-attribute instance-attribute

INTEGER = 'integer' class-attribute instance-attribute

LIST = 'list' class-attribute instance-attribute

STRING = 'string' class-attribute instance-attribute

TIMESTAMP = 'timestamp' class-attribute instance-attribute

UNKNOWN = 'unknown' class-attribute instance-attribute

from_json_type(json_type) classmethod

Get OPTIMADE data type from a named JSON type

Source code in optimade/models/optimade_json.py
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
@classmethod def from_json_type(cls, json_type: str) -> Optional["DataType"]: """Get OPTIMADE data type from a named JSON type""" mapping = { "string": cls.STRING, "integer": cls.INTEGER, "number": cls.FLOAT, # actually includes both integer and float "object": cls.DICTIONARY, "array": cls.LIST, "boolean": cls.BOOLEAN, "null": cls.UNKNOWN, # OpenAPI "format"s: "double": cls.FLOAT, "float": cls.FLOAT, "int32": cls.INTEGER, "int64": cls.INTEGER, "date": cls.TIMESTAMP, "date-time": cls.TIMESTAMP, "password": cls.STRING, "byte": cls.STRING, "binary": cls.STRING, # Non-OpenAPI "format"s, but may still be used by pydantic/FastAPI "email": cls.STRING, "uuid": cls.STRING, "uri": cls.STRING, "hostname": cls.STRING, "ipv4": cls.STRING, "ipv6": cls.STRING, } return mapping.get(json_type, None)

from_python_type(python_type) classmethod

Get OPTIMADE data type from a Python type

Source code in optimade/models/optimade_json.py
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
@classmethod def from_python_type(cls, python_type: type | str | object) -> Optional["DataType"]: """Get OPTIMADE data type from a Python type""" mapping = { "bool": cls.BOOLEAN, "int": cls.INTEGER, "float": cls.FLOAT, "complex": None, "generator": cls.LIST, "list": cls.LIST, "tuple": cls.LIST, "range": cls.LIST, "hash": cls.INTEGER, "str": cls.STRING, "bytes": cls.STRING, "bytearray": None, "memoryview": None, "set": cls.LIST, "frozenset": cls.LIST, "dict": cls.DICTIONARY, "dict_keys": cls.LIST, "dict_values": cls.LIST, "dict_items": cls.LIST, "Nonetype": cls.UNKNOWN, "None": cls.UNKNOWN, "datetime": cls.TIMESTAMP, "date": cls.TIMESTAMP, "time": cls.TIMESTAMP, "datetime.datetime": cls.TIMESTAMP, "datetime.date": cls.TIMESTAMP, "datetime.time": cls.TIMESTAMP, } if isinstance(python_type, type): python_type = python_type.__name__ elif isinstance(python_type, object): if str(python_type) in mapping: python_type = str(python_type) else: python_type = type(python_type).__name__ return mapping.get(python_type, None)

get_values() classmethod

Get OPTIMADE data types (enum values) as a (sorted) list

Source code in optimade/models/optimade_json.py
54 55 56 57
@classmethod def get_values(cls) -> list[str]: """Get OPTIMADE data types (enum values) as a (sorted) list""" return sorted(_.value for _ in cls)

Implementation

Bases: BaseModel

Information on the server implementation

Source code in optimade/models/optimade_json.py
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
class Implementation(BaseModel): """Information on the server implementation""" name: Annotated[ str | None, StrictField(description="name of the implementation") ] = None version: Annotated[ str | None, StrictField(description="version string of the current implementation"), ] = None homepage: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the homepage of the implementation.", ), ] = None source_url: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the implementation source, either downloadable archive or version control system.", ), ] = None maintainer: Annotated[ ImplementationMaintainer | None, StrictField( description="A dictionary providing details about the maintainer of the implementation.", ), ] = None issue_tracker: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) pointing to the implementation's issue tracker.", ), ] = None

homepage = None class-attribute instance-attribute

issue_tracker = None class-attribute instance-attribute

maintainer = None class-attribute instance-attribute

name = None class-attribute instance-attribute

source_url = None class-attribute instance-attribute

version = None class-attribute instance-attribute

ImplementationMaintainer

Bases: BaseModel

Details about the maintainer of the implementation

Source code in optimade/models/optimade_json.py
238 239 240 241 242 243
class ImplementationMaintainer(BaseModel): """Details about the maintainer of the implementation""" email: Annotated[ EmailStr, StrictField(description="the maintainer's email address") ]

email instance-attribute

OptimadeError

Bases: Error

detail MUST be present

Source code in optimade/models/optimade_json.py
135 136 137 138 139 140 141 142 143
class OptimadeError(jsonapi.Error): """detail MUST be present""" detail: Annotated[ str, StrictField( description="A human-readable explanation specific to this occurrence of the problem.", ), ]

code = None class-attribute instance-attribute

detail instance-attribute

id = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

source = None class-attribute instance-attribute

status = None class-attribute instance-attribute

title = None class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191 192
def __hash__(self): return hash(self.model_dump_json())

Provider

Bases: BaseModel

Information on the database provider of the implementation.

Source code in optimade/models/optimade_json.py
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
class Provider(BaseModel): """Information on the database provider of the implementation.""" name: Annotated[ str, StrictField(description="a short name for the database provider") ] description: Annotated[ str, StrictField(description="a longer description of the database provider") ] prefix: Annotated[ str, StrictField( pattern=r"^[a-z]([a-z]|[0-9]|_)*$", description="database-provider-specific prefix as found in section Database-Provider-Specific Namespace Prefixes.", ), ] homepage: Annotated[ jsonapi.JsonLinkType | None, StrictField( description="a [JSON API links object](http://jsonapi.org/format/1.0#document-links) " "pointing to homepage of the database provider, either " "directly as a string, or as a link object.", ), ] = None

description instance-attribute

homepage = None class-attribute instance-attribute

name instance-attribute

prefix instance-attribute

Relationship

Bases: Relationship

Similar to normal JSON API relationship, but with addition of OPTIONAL meta field for a resource.

Source code in optimade/models/optimade_json.py
443 444 445 446 447 448 449
class Relationship(jsonapi.Relationship): """Similar to normal JSON API relationship, but with addition of OPTIONAL meta field for a resource.""" data: Annotated[ BaseRelationshipResource | list[BaseRelationshipResource] | None, StrictField(description="Resource linkage", uniqueItems=True), ] = None

data = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279 280 281 282 283 284 285
@model_validator(mode="after") def at_least_one_relationship_key_must_be_set(self) -> "Relationship": if self.links is None and self.data is None and self.meta is None: raise ValueError( "Either 'links', 'data', or 'meta' MUST be specified for Relationship" ) return self

ResponseMeta

Bases: Meta

A JSON API meta member that contains JSON API meta objects of non-standard meta-information.

OPTIONAL additional information global to the query that is not specified in this document, MUST start with a database-provider-specific prefix.

Source code in optimade/models/optimade_json.py
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
class ResponseMeta(jsonapi.Meta): """ A [JSON API meta member](https://jsonapi.org/format/1.0#document-meta) that contains JSON API meta objects of non-standard meta-information. OPTIONAL additional information global to the query that is not specified in this document, MUST start with a database-provider-specific prefix. """ query: Annotated[ ResponseMetaQuery, StrictField(description="Information on the Query that was requested"), ] api_version: Annotated[ SemanticVersion, StrictField( description="""Presently used full version of the OPTIMADE API. The version number string MUST NOT be prefixed by, e.g., "v". Examples: `1.0.0`, `1.0.0-rc.2`.""", ), ] more_data_available: Annotated[ bool, StrictField( description="`false` if the response contains all data for the request (e.g., a request issued to a single entry endpoint, or a `filter` query at the last page of a paginated response) and `true` if the response is incomplete in the sense that multiple objects match the request, and not all of them have been included in the response (e.g., a query with multiple pages that is not at the last page).", ), ] # start of "SHOULD" fields for meta response optimade_schema: Annotated[ jsonapi.JsonLinkType | None, StrictField( alias="schema", description="""A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) that points to a schema for the response. If it is a string, or a dictionary containing no `meta` field, the provided URL MUST point at an [OpenAPI](https://swagger.io/specification/) schema. It is possible that future versions of this specification allows for alternative schema types. Hence, if the `meta` field of the JSON API links object is provided and contains a field `schema_type` that is not equal to the string `OpenAPI` the client MUST not handle failures to parse the schema or to validate the response against the schema as errors.""", ), ] = None time_stamp: Annotated[ datetime | None, StrictField( description="A timestamp containing the date and time at which the query was executed.", ), ] = None data_returned: Annotated[ int | None, StrictField( description="An integer containing the total number of data resource objects returned for the current `filter` query, independent of pagination.", ge=0, ), ] = None provider: Annotated[ Provider | None, StrictField( description="information on the database provider of the implementation." ), ] = None # start of "MAY" fields for meta response data_available: Annotated[ int | None, StrictField( description="An integer containing the total number of data resource objects available in the database for the endpoint.", ), ] = None last_id: Annotated[ str | None, StrictField(description="a string containing the last ID returned"), ] = None response_message: Annotated[ str | None, StrictField(description="response string from the server") ] = None request_delay: Annotated[ NonNegativeFloat | None, StrictField( description="""A non-negative float giving time in seconds that the client is suggested to wait before issuing a subsequent request. Implementation note: the functionality of this field overlaps to some degree with features provided by the HTTP error `429 Too Many Requests` and the `Retry-After` HTTP header. Implementations are suggested to provide consistent handling of request overload through both mechanisms.""" ), ] = None implementation: Annotated[ Implementation | None, StrictField(description="a dictionary describing the server implementation"), ] = None warnings: Annotated[ list[Warnings] | None, StrictField( description="""A list of warning resource objects representing non-critical errors or warnings. A warning resource object is defined similarly to a [JSON API error object](http://jsonapi.org/format/1.0/#error-objects), but MUST also include the field `type`, which MUST have the value `"warning"`. The field `detail` MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features. The field `status`, representing a HTTP response status code, MUST NOT be present for a warning resource object. This is an exclusive field for error resource objects.""", uniqueItems=True, ), ] = None

api_version instance-attribute

data_available = None class-attribute instance-attribute

data_returned = None class-attribute instance-attribute

implementation = None class-attribute instance-attribute

last_id = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

more_data_available instance-attribute

optimade_schema = None class-attribute instance-attribute

provider = None class-attribute instance-attribute

query instance-attribute

request_delay = None class-attribute instance-attribute

response_message = None class-attribute instance-attribute

time_stamp = None class-attribute instance-attribute

warnings = None class-attribute instance-attribute

ResponseMetaQuery

Bases: BaseModel

Information on the query that was requested.

Source code in optimade/models/optimade_json.py
195 196 197 198 199 200 201 202 203 204 205 206
class ResponseMetaQuery(BaseModel): """Information on the query that was requested.""" representation: Annotated[ str, StrictField( description="""A string with the part of the URL following the versioned or unversioned base URL that serves the API. Query parameters that have not been used in processing the request MAY be omitted. In particular, if no query parameters have been involved in processing the request, the query part of the URL MAY be excluded. Example: `/structures?filter=nelements=2`""", ), ]

representation instance-attribute

Success

Bases: Response

errors are not allowed

Source code in optimade/models/optimade_json.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
class Success(jsonapi.Response): """errors are not allowed""" meta: Annotated[ ResponseMeta, StrictField(description="A meta object containing non-standard information"), ] @model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

Warnings

Bases: OptimadeError

OPTIMADE-specific warning class based on OPTIMADE-specific JSON API Error.

From the specification:

A warning resource object is defined similarly to a JSON API error object, but MUST also include the field type, which MUST have the value "warning". The field detail MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features.

Note: Must be named "Warnings", since "Warning" is a built-in Python class.

Source code in optimade/models/optimade_json.py
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
class Warnings(OptimadeError): """OPTIMADE-specific warning class based on OPTIMADE-specific JSON API Error. From the specification: A warning resource object is defined similarly to a JSON API error object, but MUST also include the field type, which MUST have the value "warning". The field detail MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features. Note: Must be named "Warnings", since "Warning" is a built-in Python class. """ model_config = ConfigDict(json_schema_extra=warnings_json_schema_extra) type: Annotated[ Literal["warning"], StrictField( description='Warnings must be of type "warning"', pattern="^warning$", ), ] = "warning" @model_validator(mode="after") def status_must_not_be_specified(self) -> "Warnings": if self.status or "status" in self.model_fields_set: raise ValueError("status MUST NOT be specified for warnings") return self

code = None class-attribute instance-attribute

detail instance-attribute

id = None class-attribute instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=warnings_json_schema_extra) class-attribute instance-attribute

source = None class-attribute instance-attribute

status = None class-attribute instance-attribute

title = None class-attribute instance-attribute

type = 'warning' class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191 192
def __hash__(self): return hash(self.model_dump_json())

status_must_not_be_specified()

Source code in optimade/models/optimade_json.py
188 189 190 191 192
@model_validator(mode="after") def status_must_not_be_specified(self) -> "Warnings": if self.status or "status" in self.model_fields_set: raise ValueError("status MUST NOT be specified for warnings") return self

warnings_json_schema_extra(schema, model)

Update OpenAPI JSON schema model for Warning.

  • Ensure type is in the list required properties and in the correct place.
  • Remove status property. This property is not allowed for Warning, nor is it a part of the OPTIMADE definition of the Warning object.
Note

Since type is the last model field defined, it will simply be appended.

Source code in optimade/models/optimade_json.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
def warnings_json_schema_extra(schema: dict[str, Any], model: type["Warnings"]) -> None: """Update OpenAPI JSON schema model for `Warning`. * Ensure `type` is in the list required properties and in the correct place. * Remove `status` property. This property is not allowed for `Warning`, nor is it a part of the OPTIMADE definition of the `Warning` object. Note: Since `type` is the _last_ model field defined, it will simply be appended. """ if "required" in schema: if "type" not in schema["required"]: schema["required"].append("type") else: schema["required"] = ["type"] schema.get("properties", {}).pop("status", None)

references

Person

Bases: BaseModel

A person, i.e., an author, editor or other.

Source code in optimade/models/references.py
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
class Person(BaseModel): """A person, i.e., an author, editor or other.""" name: Annotated[ str, OptimadeField( description="""Full name of the person, REQUIRED.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] firstname: Annotated[ str | None, OptimadeField( description="""First name of the person.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None lastname: Annotated[ str | None, OptimadeField( description="""Last name of the person.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None

firstname = None class-attribute instance-attribute

lastname = None class-attribute instance-attribute

name instance-attribute

ReferenceResource

Bases: EntryResource

The references entries describe bibliographic references.

The following properties are used to provide the bibliographic details:

  • address, annote, booktitle, chapter, crossref, edition, howpublished, institution, journal, key, month, note, number, organization, pages, publisher, school, series, title, volume, year: meanings of these properties match the BibTeX specification, values are strings;
  • bib_type: type of the reference, corresponding to type property in the BibTeX specification, value is string;
  • authors and editors: lists of person objects which are dictionaries with the following keys:
    • name: Full name of the person, REQUIRED.
    • firstname, lastname: Parts of the person's name, OPTIONAL.
  • doi and url: values are strings.
  • Requirements/Conventions:
    • Support: OPTIONAL support in implementations, i.e., any of the properties MAY be null.
    • Query: Support for queries on any of these properties is OPTIONAL. If supported, filters MAY support only a subset of comparison operators.
    • Every references entry MUST contain at least one of the properties.
Source code in optimade/models/references.py
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
class ReferenceResource(EntryResource): """The `references` entries describe bibliographic references. The following properties are used to provide the bibliographic details: - **address**, **annote**, **booktitle**, **chapter**, **crossref**, **edition**, **howpublished**, **institution**, **journal**, **key**, **month**, **note**, **number**, **organization**, **pages**, **publisher**, **school**, **series**, **title**, **volume**, **year**: meanings of these properties match the [BibTeX specification](http://bibtexml.sourceforge.net/btxdoc.pdf), values are strings; - **bib_type**: type of the reference, corresponding to **type** property in the BibTeX specification, value is string; - **authors** and **editors**: lists of *person objects* which are dictionaries with the following keys: - **name**: Full name of the person, REQUIRED. - **firstname**, **lastname**: Parts of the person's name, OPTIONAL. - **doi** and **url**: values are strings. - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., any of the properties MAY be `null`. - **Query**: Support for queries on any of these properties is OPTIONAL. If supported, filters MAY support only a subset of comparison operators. - Every references entry MUST contain at least one of the properties. """ type: Annotated[ Literal["references"], OptimadeField( 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. - **Example**: `"structures"`""", pattern="^references$", support=SupportLevel.MUST, queryable=SupportLevel.MUST, ), ] = "references" attributes: ReferenceResourceAttributes @field_validator("attributes", mode="before") @classmethod def validate_attributes(cls, value: Any) -> dict[str, Any]: if not isinstance(value, dict): if isinstance(value, BaseModel): value = value.model_dump() else: raise TypeError("attributes field must be a mapping") if not any(prop[1] is not None for prop in value): raise ValueError("reference object must have at least one field defined") return value

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'references' class-attribute instance-attribute

validate_attributes(value) classmethod

Source code in optimade/models/references.py
323 324 325 326 327 328 329 330 331 332 333
@field_validator("attributes", mode="before") @classmethod def validate_attributes(cls, value: Any) -> dict[str, Any]: if not isinstance(value, dict): if isinstance(value, BaseModel): value = value.model_dump() else: raise TypeError("attributes field must be a mapping") if not any(prop[1] is not None for prop in value): raise ValueError("reference object must have at least one field defined") return value

ReferenceResourceAttributes

Bases: EntryResourceAttributes

Model that stores the attributes of a reference.

Many properties match the meaning described in the BibTeX specification.

Source code in optimade/models/references.py
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
class ReferenceResourceAttributes(EntryResourceAttributes): """Model that stores the attributes of a reference. Many properties match the meaning described in the [BibTeX specification](http://bibtexml.sourceforge.net/btxdoc.pdf). """ authors: Annotated[ list[Person] | None, OptimadeField( description="List of person objects containing the authors of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None editors: Annotated[ list[Person] | None, OptimadeField( description="List of person objects containing the editors of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None doi: Annotated[ str | None, OptimadeField( description="The digital object identifier of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None url: Annotated[ AnyUrl | None, OptimadeField( description="The URL of the reference.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None address: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None annote: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None booktitle: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None chapter: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None crossref: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None edition: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None howpublished: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None institution: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None journal: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None key: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None month: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None note: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None number: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None organization: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None pages: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None publisher: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None school: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None series: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None title: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None bib_type: Annotated[ str | None, OptimadeField( description="Type of the reference, corresponding to the **type** property in the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None volume: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None year: Annotated[ str | None, OptimadeField( description="Meaning of property matches the BiBTeX specification.", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None

address = None class-attribute instance-attribute

annote = None class-attribute instance-attribute

authors = None class-attribute instance-attribute

bib_type = None class-attribute instance-attribute

booktitle = None class-attribute instance-attribute

chapter = None class-attribute instance-attribute

crossref = None class-attribute instance-attribute

doi = None class-attribute instance-attribute

edition = None class-attribute instance-attribute

editors = None class-attribute instance-attribute

howpublished = None class-attribute instance-attribute

immutable_id = None class-attribute instance-attribute

institution = None class-attribute instance-attribute

journal = None class-attribute instance-attribute

key = None class-attribute instance-attribute

last_modified instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

month = None class-attribute instance-attribute

note = None class-attribute instance-attribute

number = None class-attribute instance-attribute

organization = None class-attribute instance-attribute

pages = None class-attribute instance-attribute

publisher = None class-attribute instance-attribute

school = None class-attribute instance-attribute

series = None class-attribute instance-attribute

title = None class-attribute instance-attribute

url = None class-attribute instance-attribute

volume = None class-attribute instance-attribute

year = None class-attribute instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

responses

EntryInfoResponse

Bases: Success

Source code in optimade/models/responses.py
58 59 60 61 62
class EntryInfoResponse(Success): data: Annotated[ EntryInfoResource, StrictField(description="OPTIMADE information for an entry endpoint."), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

EntryResponseMany

Bases: Success

Source code in optimade/models/responses.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
class EntryResponseMany(Success): data: Annotated[ # type: ignore[assignment] list[EntryResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ] included: Annotated[ list[EntryResource] | list[dict[str, Any]] | None, StrictField( description="A list of unique included OPTIMADE entry resources.", uniqueItems=True, union_mode="left_to_right", ), ] = None # type: ignore[assignment]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

EntryResponseOne

Bases: Success

Source code in optimade/models/responses.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
class EntryResponseOne(Success): data: Annotated[ EntryResource | dict[str, Any] | None, StrictField( description="The single entry resource returned by this query.", union_mode="left_to_right", ), ] = None # type: ignore[assignment] included: Annotated[ list[EntryResource] | list[dict[str, Any]] | None, StrictField( description="A list of unique included OPTIMADE entry resources.", uniqueItems=True, union_mode="left_to_right", ), ] = None # type: ignore[assignment]

data = None class-attribute instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

ErrorResponse

Bases: Response

errors MUST be present and data MUST be skipped

Source code in optimade/models/responses.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
class ErrorResponse(Response): """errors MUST be present and data MUST be skipped""" meta: Annotated[ ResponseMeta, StrictField(description="A meta object containing non-standard information."), ] errors: Annotated[ list[OptimadeError], StrictField( description="A list of OPTIMADE-specific JSON API error objects, where the field detail MUST be present.", uniqueItems=True, ), ] @model_validator(mode="after") def data_must_be_skipped(self) -> "ErrorResponse": if self.data or "data" in self.model_fields_set: raise ValueError("data MUST be skipped for failures reporting errors.") return self

data = None class-attribute instance-attribute

errors instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

data_must_be_skipped()

Source code in optimade/models/responses.py
45 46 47 48 49
@model_validator(mode="after") def data_must_be_skipped(self) -> "ErrorResponse": if self.data or "data" in self.model_fields_set: raise ValueError("data MUST be skipped for failures reporting errors.") return self

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
403 404 405 406 407 408 409 410 411 412
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Response": required_fields = ("data", "meta", "errors") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response" ) if "errors" in self.model_fields_set and not self.errors: raise ValueError("Errors MUST NOT be an empty or 'null' value.") return self

IndexInfoResponse

Bases: Success

Source code in optimade/models/responses.py
52 53 54 55
class IndexInfoResponse(Success): data: Annotated[ IndexInfoResource, StrictField(description="Index meta-database /info data.") ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

InfoResponse

Bases: Success

Source code in optimade/models/responses.py
65 66 67 68
class InfoResponse(Success): data: Annotated[ BaseInfoResource, StrictField(description="The implementations /info data.") ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

LinksResponse

Bases: EntryResponseMany

Source code in optimade/models/responses.py
108 109 110 111 112 113 114 115 116
class LinksResponse(EntryResponseMany): data: Annotated[ list[LinksResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE links resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

ReferenceResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
150 151 152 153 154 155 156 157 158
class ReferenceResponseMany(EntryResponseMany): data: Annotated[ list[ReferenceResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE references entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

ReferenceResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
140 141 142 143 144 145 146 147
class ReferenceResponseOne(EntryResponseOne): data: Annotated[ ReferenceResource | dict[str, Any] | None, StrictField( description="A single references entry resource.", union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

StructureResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
129 130 131 132 133 134 135 136 137
class StructureResponseMany(EntryResponseMany): data: Annotated[ list[StructureResource] | list[dict[str, Any]], StrictField( description="List of unique OPTIMADE structures entry resource objects.", uniqueItems=True, union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

StructureResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
119 120 121 122 123 124 125 126
class StructureResponseOne(EntryResponseOne): data: Annotated[ StructureResource | dict[str, Any] | None, StrictField( description="A single structures entry resource.", union_mode="left_to_right", ), ]

data instance-attribute

errors = None class-attribute instance-attribute

included = None class-attribute instance-attribute

jsonapi = None class-attribute instance-attribute

meta instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418
@model_validator(mode="after") def either_data_meta_or_errors_must_be_set(self) -> "Success": """Overwriting the existing validation function, since 'errors' MUST NOT be set.""" required_fields = ("data", "meta") if not any(field in self.model_fields_set for field in required_fields): raise ValueError( f"At least one of {required_fields} MUST be specified in the top-level response." ) # errors MUST be skipped if self.errors or "errors" in self.model_fields_set: raise ValueError("'errors' MUST be skipped for a successful response.") return self

structures

CORRELATED_STRUCTURE_FIELDS = ({'dimension_types', 'nperiodic_dimensions'}, {'cartesian_site_positions', 'species_at_sites'}, {'nsites', 'cartesian_site_positions'}, {'species_at_sites', 'species'}) module-attribute

EPS = 2 ** -23 module-attribute

Vector3D = Annotated[list[Annotated[float, BeforeValidator(float)]], Field(min_length=3, max_length=3)] module-attribute

Vector3D_unknown = Annotated[list[Optional[Annotated[float, BeforeValidator(float)]]], Field(min_length=3, max_length=3)] module-attribute

Assembly

Bases: BaseModel

A description of groups of sites that are statistically correlated.

  • 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).
Source code in optimade/models/structures.py
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
class Assembly(BaseModel): """A description of groups of sites that are statistically correlated. - **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). """ sites_in_groups: Annotated[ list[list[int]], OptimadeField( description="""Index of the sites (0-based) that belong to each group for each assembly. - **Examples**: - `[[1], [2]]`: two groups, one with the second site, one with the third. - `[[1,2], [3]]`: one group with the second and third site, one with the fourth.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] group_probabilities: Annotated[ list[float], OptimadeField( description="""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`.""", support=SupportLevel.MUST, queryable=SupportLevel.OPTIONAL, ), ] @field_validator("sites_in_groups", mode="after") @classmethod def validate_sites_in_groups(cls, value: list[list[int]]) -> list[list[int]]: sites = [] for group in value: sites.extend(group) if len(set(sites)) != len(sites): raise ValueError( f"A site MUST NOT appear in more than one group. Given value: {value}" ) return value @model_validator(mode="after") def check_self_consistency(self) -> "Assembly": if len(self.group_probabilities) != len(self.sites_in_groups): raise ValueError( f"sites_in_groups and group_probabilities MUST be of same length, " f"but are {len(self.sites_in_groups)} and {len(self.group_probabilities)}, " "respectively" ) return self

group_probabilities instance-attribute

sites_in_groups instance-attribute

check_self_consistency()

Source code in optimade/models/structures.py
266 267 268 269 270 271 272 273 274
@model_validator(mode="after") def check_self_consistency(self) -> "Assembly": if len(self.group_probabilities) != len(self.sites_in_groups): raise ValueError( f"sites_in_groups and group_probabilities MUST be of same length, " f"but are {len(self.sites_in_groups)} and {len(self.group_probabilities)}, " "respectively" ) return self

validate_sites_in_groups(value) classmethod

Source code in optimade/models/structures.py
254 255 256 257 258 259 260 261 262 263 264
@field_validator("sites_in_groups", mode="after") @classmethod def validate_sites_in_groups(cls, value: list[list[int]]) -> list[list[int]]: sites = [] for group in value: sites.extend(group) if len(set(sites)) != len(sites): raise ValueError( f"A site MUST NOT appear in more than one group. Given value: {value}" ) return value

Periodicity

Bases: IntEnum

Integer enumeration of dimension_types values

Source code in optimade/models/structures.py
49 50 51 52 53
class Periodicity(IntEnum): """Integer enumeration of dimension_types values""" APERIODIC = 0 PERIODIC = 1

APERIODIC = 0 class-attribute instance-attribute

PERIODIC = 1 class-attribute instance-attribute

Species

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
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
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[ list[float] | None, 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[ str | None, 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[ list[str] | None, 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[ list[int] | None, 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: list[float] | None, info: "ValidationInfo" ) -> list[float] | None: 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: list[str] | list[int] | None ) -> list[str] | list[int] | None: 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

attached = None class-attribute instance-attribute

chemical_symbols instance-attribute

concentration instance-attribute

mass = None class-attribute instance-attribute

name instance-attribute

nattached = None class-attribute instance-attribute

original_name = None class-attribute instance-attribute

attached_nattached_mutually_exclusive()

Source code in optimade/models/structures.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
@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

validate_concentration_and_mass(value, info)

Source code in optimade/models/structures.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
@field_validator("concentration", "mass", mode="after") def validate_concentration_and_mass( cls, value: list[float] | None, info: "ValidationInfo" ) -> list[float] | None: 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." )

validate_minimum_list_length(value) classmethod

Source code in optimade/models/structures.py
182 183 184 185 186 187 188 189 190 191 192
@field_validator("attached", "nattached", mode="after") @classmethod def validate_minimum_list_length( cls, value: list[str] | list[int] | None ) -> list[str] | list[int] | None: 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

StructureFeatures

Bases: Enum

Enumeration of structure_features values

Source code in optimade/models/structures.py
56 57 58 59 60 61 62
class StructureFeatures(Enum): """Enumeration of structure_features values""" DISORDER = "disorder" IMPLICIT_ATOMS = "implicit_atoms" SITE_ATTACHMENTS = "site_attachments" ASSEMBLIES = "assemblies"

ASSEMBLIES = 'assemblies' class-attribute instance-attribute

DISORDER = 'disorder' class-attribute instance-attribute

IMPLICIT_ATOMS = 'implicit_atoms' class-attribute instance-attribute

SITE_ATTACHMENTS = 'site_attachments' class-attribute instance-attribute

StructureResource

Bases: EntryResource

Representing a structure.

Source code in optimade/models/structures.py
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
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

attributes instance-attribute

id instance-attribute

meta = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships = None class-attribute instance-attribute

type = 'structures' class-attribute instance-attribute

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
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 1166 1167 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 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
class StructureResourceAttributes(EntryResourceAttributes): """This class contains the Field for the attributes used to represent a structure, e.g. unit cell, atoms, positions.""" elements: Annotated[ list[str] | None, 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[ int | None, 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[ list[float] | None, 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[ str | None, 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[ str | None, 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[ str | None, 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[ str | None, 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[ list[Periodicity] | None, 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[ int | None, 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[ list[Vector3D_unknown] | None, 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 space_group_symmetry_operations_xyz: Annotated[ list[SymmetryOperation] | None, OptimadeField( description="""A list of symmetry operations given as general position x, y and z coordinates in algebraic form. - **Type**: list of strings - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - The property is RECOMMENDED if coordinates are returned in a form to which these operations can or must be applied (e.g. fractional atom coordinates of an asymmetric unit). - The property is REQUIRED if symmetry operations are necessary to reconstruct the full model of the material and no other symmetry information (e.g., the Hall symbol) is provided that would allow the user to derive symmetry operations unambiguously. - **Query***: Support for queries on this property is not required and in fact is NOT RECOMMENDED. - MUST be `null` if `nperiodic_dimensions` is equal to 0. - Each symmetry operation is described by a string that gives that symmetry operation in Jones' faithful representation (Bradley & Cracknell, 1972: pp. 35-37), adapted for computer string notation. - The letters `x`, `y` and `z` that are typesetted with overbars in printed text represent coordinate values multiplied by -1 and are encoded as `-x`, `-y` and `-z`, respectively. - The syntax of the strings representing symmetry operations MUST conform to regular expressions given in appendix The Symmetry Operation String Regular Expressions. - The interpretation of the strings MUST follow the conventions of the IUCr CIF core dictionary (IUCr, 2023). In particular, this property MUST explicitly provide all symmetry operations needed to generate all the atoms in the unit cell from the atoms in the asymmetric unit, for the setting used. - This symmetry operation set MUST always include the `x,y,z` identity operation. - The symmetry operations are to be applied to fractional atom coordinates. In case only Cartesian coordinates are available, these Cartesian coordinates must be converted to fractional coordinates before the application of the provided symmetry operations. - If the symmetry operation list is present, it MUST be compatible with other space group specifications (e.g. the ITC space group number, the Hall symbol, the Hermann-Mauguin symbol) if these are present. - **Examples**: - Space group operations for the space group with ITC number 3 (H-M symbol `P 2`, extended H-M symbol `P 1 2 1`, Hall symbol `P 2y`): `["x,y,z", "-x,y,-z"]` - Space group operations for the space group with ITC number 5 (H-M symbol `C 2`, extended H-M symbol `C 1 2 1`, Hall symbol `C 2y`): `["x,y,z", "-x,y,-z", "x+1/2,y+1/2,z", "-x+1/2,y+1/2,-z"]` - **Notes**: The list of space group symmetry operations applies to the whole periodic array of atoms and together with the lattice translations given in the `lattice_vectors` property provides the necessary information to reconstruct all atom site positions of the periodic material. Thus, the symmetry operations described in this property are only applicable to material models with at least one periodic dimension. This property is not meant to represent arbitrary symmetries of molecules, non-periodic (finite) collections of atoms or non-crystallographic symmetry. - **Bibliographic References**: - Bradley, C. J. and Cracknell, A. P. (1972) The Mathematical Theory of Symmetry in Solids. Oxford, Clarendon Press (paperback edition 2010) 745 p. ISBN 978-0-19-958258-7. - IUCr (2023) Core dictionary (coreCIF) version 2.4.5; data name `_space_group_symop_operation_xyz`. Available from: https://www.iucr.org/__data/iucr/cifdic_html/1/cif_core.dic/Ispace_group_symop_operation_xyz.html [Accessed 2023-06-18T16:46+03:00].""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None space_group_symbol_hall: Annotated[ str | None, OptimadeField( description="""A Hall space group symbol representing the symmetry of the structure as defined in (Hall, 1981, 1981a). - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The change-of-basis operations are used as defined in the International Tables of Crystallography (ITC) Vol. B, Sect. 1.4, Appendix A1.4.2 (IUCr, 2001). - Each component of the Hall symbol MUST be separated by a single space symbol. - If there exists a standard Hall symbol which represents the symmetry it SHOULD be used. - MUST be `null` if `nperiodic_dimensions` is not equal to 3. - **Examples**: - Space group symbols with explicit origin (the Hall symbols): - `P 2c -2ac` - `I 4bd 2ab 3` - Space group symbols with change-of-basis operations: - `P 2yb (-1/2*x+z,1/2*x,y)` - `-I 4 2 (1/2*x+1/2*y,-1/2*x+1/2*y,z)` - **Bibliographic References**: - Hall, S. R. (1981) Space-group notation with an explicit origin. Acta Crystallographica Section A, 37, 517-525, International Union of Crystallography (IUCr), DOI: https://doi.org/10.1107/s0567739481001228 - Hall, S. R. (1981a) Space-group notation with an explicit origin; erratum. Acta Crystallographica Section A, 37, 921-921, International Union of Crystallography (IUCr), DOI: https://doi.org/10.1107/s0567739481001976 - IUCr (2001). International Tables for Crystallography vol. B. Reciprocal Space. Ed. U. Shmueli. 2-nd edition. Dordrecht/Boston/London, Kluwer Academic Publishers.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ), ] = None space_group_symbol_hermann_mauguin: Annotated[ str | None, OptimadeField( description="""A human- and machine-readable string containing the short Hermann-Mauguin (H-M) symbol which specifies the space group of the structure in the response. - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The H-M symbol SHOULD aim to convey the closest representation of the symmetry information that can be specified using the short format used in the International Tables for Crystallography vol. A (IUCr, 2005), Table 4.3.2.1 as described in the accompanying text. - The symbol MAY be a non-standard short H-M symbol. - The H-M symbol does not unambiguously communicate the axis, cell, and origin choice, and the given symbol SHOULD NOT be amended to convey this information. - To encode as character strings, the following adaptations MUST be made when representing H-M symbols given in their typesetted form: - the overbar above the numbers MUST be changed to the minus sign in front of the digit (e.g. '-2'); - subscripts that denote screw axes are written as digits immediately after the axis designator without a space (e.g. 'P 32') - the space group generators MUST be separated by a single space (e.g. 'P 21 21 2'); - there MUST be no spaces in the space group generator designation (i.e. use 'P 21/m', not the 'P 21 / m'); - **Examples**: - `C 2` - `P 21 21 21` - **Bibliographic References**: - IUCr (2005). International Tables for Crystallography vol. A. Space-Group Symmetry. Ed. Theo Hahn. 5-th edition. Dordrecht, Springer. """, support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, pattern=HM_SYMBOL_REGEXP, ), ] = None space_group_symbol_hermann_mauguin_extended: Annotated[ str | None, OptimadeField( description="""A human- and machine-readable string containing the extended Hermann-Mauguin (H-M) symbol which specifies the space group of the structure in the response. - **Type**: string - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The H-M symbols SHOULD be given as specified in the International Tables for Crystallography vol. A (IUCr, 2005), Table 4.3.2.1. - The change-of-basis operation SHOULD be provided for the non-standard axis and cell choices. - The extended H-M symbol does not unambiguously communicate the origin choice, and the given symbol SHOULD NOT be amended to convey this information. - The description of the change-of-basis SHOULD follow conventions of the ITC Vol. B, Sect. 1.4, Appendix A1.4.2 (IUCr, 2001). - The same character string encoding conventions MUST be used as for the specification of the `space_group_symbol_hermann_mauguin` property. - **Examples**: - `C 1 2 1` - **Bibliographic References**: - IUCr (2001). International Tables for Crystallography vol. B. Reciprocal Space. Ed. U. Shmueli. 2-nd edition. Dordrecht/Boston/London, Kluwer Academic Publishers. - IUCr (2005). International Tables for Crystallography vol. A. Space-Group Symmetry. Ed. Theo Hahn. 5-th edition. Dordrecht, Springer. """, support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, pattern=HM_SYMBOL_REGEXP, ), ] = None space_group_it_number: Annotated[ int | None, OptimadeField( description="""Space group number which specifies the space group of the structure as defined in the International Tables for Crystallography Vol. A. (IUCr, 2005). - **Type**: integer - **Requirements/Conventions**: - **Support**: OPTIONAL support in implementations, i.e., MAY be `null`. - **Query**: Support for queries on this property is OPTIONAL. - The integer value MUST be between 1 and 230. - MUST be null if `nperiodic_dimensions` is not equal to 3.""", support=SupportLevel.OPTIONAL, queryable=SupportLevel.OPTIONAL, ge=1, le=230, ), ] = None cartesian_site_positions: Annotated[ list[Vector3D] | None, 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[ int | None, 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[ list[Species] | None, 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[ list[str] | None, 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[ list[Assembly] | None, 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: str | None, info: "ValidationInfo" ) -> str | None: 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: str | None) -> str | None: 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: str | None, info: "ValidationInfo" ) -> str | None: 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: list[str] | None) -> list[str] | None: 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: list[float] | None) -> list[float] | None: 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: None | (Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]), ) -> Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)] | None: 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: list[Species] | None) -> list[Species] | None: 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 check_symmetry_operations(self) -> "StructureResourceAttributes": if self.nperiodic_dimensions == 0 and self.space_group_symmetry_operations_xyz: raise ValueError( "Non-periodic structures MUST NOT have space group symmetry operations." ) if ( self.space_group_symmetry_operations_xyz and "x,y,z" not in self.space_group_symmetry_operations_xyz ): raise ValueError( "The identity operation 'x,y,z' MUST be included in the space group symmetry operations, if provided." ) return self @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 # 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

assemblies = None class-attribute instance-attribute

cartesian_site_positions = None class-attribute instance-attribute

chemical_formula_anonymous = None class-attribute instance-attribute

chemical_formula_descriptive = None class-attribute instance-attribute

chemical_formula_hill = None class-attribute instance-attribute

chemical_formula_reduced = None class-attribute instance-attribute

dimension_types = None class-attribute instance-attribute

elements = None class-attribute instance-attribute

elements_ratios = None class-attribute instance-attribute

immutable_id = None class-attribute instance-attribute

last_modified instance-attribute

lattice_vectors = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

nelements = None class-attribute instance-attribute

nperiodic_dimensions = None class-attribute instance-attribute

nsites = None class-attribute instance-attribute

space_group_it_number = None class-attribute instance-attribute

space_group_symbol_hall = None class-attribute instance-attribute

space_group_symbol_hermann_mauguin = None class-attribute instance-attribute

space_group_symbol_hermann_mauguin_extended = None class-attribute instance-attribute

space_group_symmetry_operations_xyz = None class-attribute instance-attribute

species = None class-attribute instance-attribute

species_at_sites = None class-attribute instance-attribute

structure_features instance-attribute

cast_immutable_id_to_str(value) classmethod

Convenience validator for casting immutable_id to a string.

Source code in optimade/models/entries.py
110 111 112 113 114 115 116 117
@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

check_anonymous_formula(value) classmethod

Source code in optimade/models/structures.py
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
@field_validator("chemical_formula_anonymous", mode="after") @classmethod def check_anonymous_formula(cls, value: str | None) -> str | None: 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

check_dimensions_types_dependencies()

Source code in optimade/models/structures.py
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
@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

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330 331 332 333 334 335 336 337 338
@model_validator(mode="after") def check_illegal_attributes_fields(self) -> "Attributes": illegal_fields = ("relationships", "links", "id", "type") for field in illegal_fields: if hasattr(self, field): raise ValueError( f"{illegal_fields} MUST NOT be fields under Attributes" ) return self

check_ordered_formula(value, info) classmethod

Source code in optimade/models/structures.py
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
@field_validator("chemical_formula_reduced", "chemical_formula_hill", mode="after") @classmethod def check_ordered_formula( cls, value: str | None, info: "ValidationInfo" ) -> str | None: 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

check_reduced_formulae(value, info) classmethod

Source code in optimade/models/structures.py
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
@field_validator( "chemical_formula_anonymous", "chemical_formula_reduced", mode="after" ) @classmethod def check_reduced_formulae( cls, value: str | None, info: "ValidationInfo" ) -> str | None: 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

check_symmetry_operations()

Source code in optimade/models/structures.py
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
@model_validator(mode="after") def check_symmetry_operations(self) -> "StructureResourceAttributes": if self.nperiodic_dimensions == 0 and self.space_group_symmetry_operations_xyz: raise ValueError( "Non-periodic structures MUST NOT have space group symmetry operations." ) if ( self.space_group_symmetry_operations_xyz and "x,y,z" not in self.space_group_symmetry_operations_xyz ): raise ValueError( "The identity operation 'x,y,z' MUST be included in the space group symmetry operations, if provided." ) return self

elements_must_be_alphabetical(value) classmethod

Source code in optimade/models/structures.py
1102 1103 1104 1105 1106 1107 1108 1109 1110
@field_validator("elements", mode="after") @classmethod def elements_must_be_alphabetical(cls, value: list[str] | None) -> list[str] | None: if value is None: return value if sorted(value) != value: raise ValueError(f"elements must be sorted alphabetically, but is: {value}") return value

null_values_for_whole_vector(value) classmethod

Source code in optimade/models/structures.py
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
@field_validator("lattice_vectors", mode="after") @classmethod def null_values_for_whole_vector( cls, value: None | (Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)]), ) -> Annotated[list[Vector3D_unknown], Field(min_length=3, max_length=3)] | None: 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

ratios_must_sum_to_one(value) classmethod

Source code in optimade/models/structures.py
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
@field_validator("elements_ratios", mode="after") @classmethod def ratios_must_sum_to_one(cls, value: list[float] | None) -> list[float] | None: 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

validate_nsites()

Source code in optimade/models/structures.py
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
@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

validate_species(value) classmethod

Source code in optimade/models/structures.py
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
@field_validator("species", mode="after") @classmethod def validate_species(cls, value: list[Species] | None) -> list[Species] | None: 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

validate_species_at_sites()

Source code in optimade/models/structures.py
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
@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

validate_structure_features()

Source code in optimade/models/structures.py
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
@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 # 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

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
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
@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

types

AnnotatedType = type(ChemicalSymbol) module-attribute

ChemicalSymbol = Annotated[str, Field(pattern=EXTENDED_CHEMICAL_SYMBOLS_PATTERN)] module-attribute

ElementSymbol = Annotated[str, Field(pattern=ELEMENT_SYMBOLS_PATTERN)] module-attribute

NoneType = type(None) module-attribute

OptionalType = type(Optional[str]) module-attribute

SemanticVersion = Annotated[str, Field(pattern=SEMVER_PATTERN, examples=['0.10.1', '1.0.0-rc.2', '1.2.3-rc.5+develop'])] module-attribute

SymmetryOperation = Annotated[str, Field(pattern=SYMMETRY_OPERATION_REGEXP)] module-attribute

utils

ANONYMOUS_ELEMENTS = tuple(itertools.islice(anonymous_element_generator(), 150)) module-attribute

Returns the first 150 values of the anonymous element generator.

ATOMIC_NUMBERS = {} module-attribute

CHEMICAL_FORMULA_REGEXP = '(^$)|^([A-Z][a-z]?([2-9]|[1-9]\\d+)?)+$' module-attribute

CHEMICAL_SYMBOLS = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'] module-attribute

ELEMENT_SYMBOLS_PATTERN = '(' + '|'.join(CHEMICAL_SYMBOLS) + ')' module-attribute

EXTENDED_CHEMICAL_SYMBOLS_PATTERN = '(' + '|'.join(CHEMICAL_SYMBOLS + EXTRA_SYMBOLS) + ')' module-attribute

EXTRA_SYMBOLS = ['X', 'vacancy'] module-attribute

HM_SYMBOL_REGEXP = '^(P|I|F|A|B|C|R)(\\s+\\d+|\\s+[a-z]+|\\s+\\d+/[a-z]+|\\s+\\d+/\\d+|\\s+-\\d*|\\s+\\d+/m|\\s+[a-z]+/m)*$' module-attribute

IDENTIFIER_REGEX = '^[a-z_][a-z_0-9]+$' module-attribute

OPTIMADE_SCHEMA_EXTENSION_KEYS = ['support', 'queryable', 'unit', 'sortable'] module-attribute

OPTIMADE_SCHEMA_EXTENSION_PREFIX = 'x-optimade-' module-attribute

SEMVER_PATTERN = '^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$' module-attribute

SPACE_GROUP_SYMMETRY_OPERATION_REGEX = _generate_symmetry_operation_regex() module-attribute

SYMMETRY_OPERATION_REGEXP = '^([-+]?[xyz]([-+][xyz])?([-+](1/2|[12]/3|[1-3]/4|[1-5]/6))?|[-+]?(1/2|[12]/3|[1-3]/4|[1-5]/6)([-+][xyz]([-+][xyz])?)?),([-+]?[xyz]([-+][xyz])?([-+](1/2|[12]/3|[1-3]/4|[1-5]/6))?|[-+]?(1/2|[12]/3|[1-3]/4|[1-5]/6)([-+][xyz]([-+][xyz])?)?),([-+]?[xyz]([-+][xyz])?([-+](1/2|[12]/3|[1-3]/4|[1-5]/6))?|[-+]?(1/2|[12]/3|[1-3]/4|[1-5]/6)([-+][xyz]([-+][xyz])?)?)$' module-attribute

SupportLevel

Bases: Enum

OPTIMADE property/field support levels

Source code in optimade/models/utils.py
32 33 34 35 36 37
class SupportLevel(Enum): """OPTIMADE property/field support levels""" MUST = "must" SHOULD = "should" OPTIONAL = "optional"

MUST = 'must' class-attribute instance-attribute

OPTIONAL = 'optional' class-attribute instance-attribute

SHOULD = 'should' class-attribute instance-attribute

OptimadeField(default=PydanticUndefined, *, support=None, queryable=None, unit=None, **kwargs)

A wrapper around pydantic.Field that adds OPTIMADE-specific field paramters queryable, support and unit, indicating the corresponding support level in the specification and the physical unit of the field.

Parameters:

Name Type Description Default
support str | SupportLevel | None

The support level of the field itself, i.e. whether the field can be null or omitted by an implementation.

None
queryable str | SupportLevel | None

The support level corresponding to the queryablility of this field.

None
unit str | None

A string describing the unit of the field.

None

Returns:

Type Description
Any

The pydantic field with extra validation provided by StrictField.

Source code in optimade/models/utils.py
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
def OptimadeField( default: "Any" = PydanticUndefined, *, support: str | SupportLevel | None = None, queryable: str | SupportLevel | None = None, unit: str | None = None, **kwargs, ) -> Any: """A wrapper around `pydantic.Field` that adds OPTIMADE-specific field paramters `queryable`, `support` and `unit`, indicating the corresponding support level in the specification and the physical unit of the field. Arguments: support: The support level of the field itself, i.e. whether the field can be null or omitted by an implementation. queryable: The support level corresponding to the queryablility of this field. unit: A string describing the unit of the field. Returns: The pydantic field with extra validation provided by [`StrictField`][optimade.models.utils.StrictField]. """ # Collect non-null keyword arguments to add to the Field schema if unit is not None: kwargs["unit"] = unit if queryable is not None: if isinstance(queryable, str): queryable = SupportLevel(queryable.lower()) kwargs["queryable"] = queryable if support is not None: if isinstance(support, str): support = SupportLevel(support.lower()) kwargs["support"] = support return StrictField(default, **kwargs)

StrictField(default=PydanticUndefined, *, description=None, optimade_version=None, **kwargs)

A wrapper around pydantic.Field that does the following:

  • Forbids any "extra" keys that would be passed to pydantic.Field, except those used elsewhere to modify the schema in-place, e.g. "uniqueItems", "pattern" and those added by OptimadeField, e.g. "unit", "queryable" and "sortable".
  • Emits a warning when no description is provided.

Parameters:

Name Type Description Default
default Any

The only non-keyword argument allowed for Field.

PydanticUndefined
description str | None

The description of the Field; if this is not specified then a UserWarning will be emitted.

None
optimade_version str | None

A PEP version specifier indicating which OPTIMADE API version this field is required for.

None
**kwargs Any

Extra keyword arguments to be passed to Field.

{}

Raises:

Type Description
RuntimeError

If **kwargs contains a key not found in the function signature of Field, or in the extensions used by models in this package (see above).

Returns:

Type Description
Any

The pydantic Field.

Source code in optimade/models/utils.py
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
def StrictField( default: "Any" = PydanticUndefined, *, description: str | None = None, optimade_version: str | None = None, **kwargs: "Any", ) -> Any: """A wrapper around `pydantic.Field` that does the following: - Forbids any "extra" keys that would be passed to `pydantic.Field`, except those used elsewhere to modify the schema in-place, e.g. "uniqueItems", "pattern" and those added by OptimadeField, e.g. "unit", "queryable" and "sortable". - Emits a warning when no description is provided. Arguments: default: The only non-keyword argument allowed for Field. description: The description of the `Field`; if this is not specified then a `UserWarning` will be emitted. optimade_version: A PEP version specifier indicating which OPTIMADE API version this field is required for. **kwargs: Extra keyword arguments to be passed to `Field`. Raises: RuntimeError: If `**kwargs` contains a key not found in the function signature of `Field`, or in the extensions used by models in this package (see above). Returns: The pydantic `Field`. """ allowed_schema_and_field_keys = ["pattern"] allowed_keys = [ "pattern", "uniqueItems", ] + OPTIMADE_SCHEMA_EXTENSION_KEYS _banned = [k for k in kwargs if k not in set(_PYDANTIC_FIELD_KWARGS + allowed_keys)] if _banned: raise RuntimeError( f"Not creating StrictField({default!r}, **{kwargs!r}) with " f"forbidden keywords {_banned}." ) # Handle description if description is None: warnings.warn( f"No description provided for StrictField specified by {default!r}, " f"**{kwargs!r}." ) else: kwargs["description"] = description # OPTIMADE schema extensions json_schema_extra: dict[str, Any] = kwargs.pop("json_schema_extra", {}) # Go through all JSON Schema keys and add them to the json_schema_extra. for key in allowed_keys: if key not in kwargs: continue # If they are OPTIMADE schema extensions, add them with the OPTIMADE prefix. schema_key = ( f"{OPTIMADE_SCHEMA_EXTENSION_PREFIX}{key}" if key in OPTIMADE_SCHEMA_EXTENSION_KEYS else key ) for key_variant in (key, schema_key): if key_variant in json_schema_extra: if json_schema_extra.pop(key_variant) != kwargs[key]: raise RuntimeError( f"Conflicting values for {key} in json_schema_extra and kwargs." ) json_schema_extra[schema_key] = ( kwargs[key] if key in allowed_schema_and_field_keys else kwargs.pop(key) ) kwargs["json_schema_extra"] = json_schema_extra return Field(default, **kwargs)

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
212 213 214 215 216 217 218 219 220 221
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)

anonymous_element_generator()

Generator that yields the next symbol in the A, B, Aa, ... Az naming scheme.

Source code in optimade/models/utils.py
168 169 170 171 172 173 174 175 176
def anonymous_element_generator() -> "Generator[str, None, None]": """Generator that yields the next symbol in the A, B, Aa, ... Az naming scheme.""" from string import ascii_lowercase for size in itertools.count(1): for tuple_strings in itertools.product(ascii_lowercase, repeat=size): list_strings = list(tuple_strings) list_strings[0] = list_strings[0].upper() yield "".join(list_strings)

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
224 225 226 227 228 229 230 231 232
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)