API reference¶
Schema¶
qmatbridge.schema
¶
QMatBridge canonical schema — v0.3.
Neutral intermediate representation (NIR) connecting classical materials databases to first-quantized Hamiltonians for quantum simulation research.
All dataclasses are intentionally dependency-free. Adapters and exporters import from this module::
from qmatbridge.schema import QMatEntry, MaterialReference, ...
Class hierarchy (leaf → root):
ExternalIdentifier
SourceProvenance ← ExternalIdentifier
LatticeMetadata
StructureMetadata ← LatticeMetadata
BasisMetadata
TermMetadata
OracleMetadata ← TermMetadata
ExportMetadata
MaterialReference ← SourceProvenance, StructureMetadata
HamiltonianMetadata ← BasisMetadata, TermMetadata, OracleMetadata
QMatEntry ← MaterialReference, HamiltonianMetadata, ExportMetadata
ExternalIdentifier
dataclass
¶
A single identifier in one external system.
Used to record the upstream database record this entry was derived from, as well as any cross-references (e.g. ICSD entry, journal DOI).
Attributes:
| Name | Type | Description |
|---|---|---|
source |
str
|
Canonical short name for the database or registry.
Examples: |
identifier |
str
|
The database-native ID string.
Examples: |
url |
str | None
|
Optional direct URL to the record. |
metadata |
dict[str, Any]
|
Adapter-specific extra fields. |
SourceProvenance
dataclass
¶
Full provenance record for one QMatEntry.
Captures which database the material came from, what DFT settings were
used, and when the data was retrieved. The primary identifier is the
canonical source used for the canonical hash; additional_ids record
any known cross-references.
Attributes:
| Name | Type | Description |
|---|---|---|
primary |
ExternalIdentifier
|
Canonical upstream identifier (required). |
additional_ids |
list[ExternalIdentifier]
|
Other known identifiers for the same material. |
functional |
str | None
|
DFT exchange-correlation functional.
Examples: |
pseudopotential |
str | None
|
Pseudopotential family.
Examples: |
code |
str | None
|
Electronic-structure code used.
Examples: |
code_version |
str | None
|
Version string of the DFT code. |
retrieved_at |
str | None
|
ISO 8601 datetime when the record was fetched. |
metadata |
dict[str, Any]
|
Adapter-specific extra fields. |
LatticeMetadata
dataclass
¶
Bravais lattice and crystallographic parameters.
Lattice parameters follow crystallographic convention: lengths in Ångström, angles in degrees.
Attributes:
| Name | Type | Description |
|---|---|---|
a, |
(b, c)
|
Lattice parameter lengths in Å. |
alpha, |
(beta, gamma)
|
Inter-axial angles in degrees. |
spacegroup_number |
int | None
|
International spacegroup number (1–230). |
spacegroup_symbol |
str | None
|
Hermann-Mauguin symbol, e.g. |
crystal_system |
str | None
|
One of |
volume_ang3 |
float | None
|
Unit cell volume in ų. |
metadata |
dict[str, Any]
|
Extra crystallographic fields. |
SiteMetadata
dataclass
¶
One atom in the cell: its element and fractional coordinates.
Attributes:
| Name | Type | Description |
|---|---|---|
element |
str
|
Element symbol, e.g. |
frac_coords |
tuple[float, float, float]
|
Fractional coordinates |
metadata |
dict[str, Any]
|
Extra per-site fields (e.g. magnetic moment). |
StructureMetadata
dataclass
¶
Chemical and geometric identity of the crystal structure.
Attributes:
| Name | Type | Description |
|---|---|---|
formula_reduced |
str
|
Reduced formula, e.g. |
formula_unit_cell |
str
|
Unit-cell formula, e.g. |
num_sites |
int
|
Number of atomic sites in the simulation cell. |
species |
list[str]
|
Ordered list of element symbols per site,
e.g. |
lattice |
LatticeMetadata
|
Bravais lattice and crystallographic parameters. |
is_periodic |
bool
|
Whether the structure is treated as periodic.
|
metadata |
dict[str, Any]
|
Extra structure-level fields. |
sites |
list[SiteMetadata]
|
Atomic positions, one :class: |
BasisMetadata
dataclass
¶
Basis-set specification for the Hamiltonian.
Plane-wave fields are populated for type="plane_wave"; Gaussian/LCAO
fields for type in {"gaussian", "lcao"}. Unused fields are
left as None.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
str
|
Basis type identifier. Recognised values:
|
cutoff_energy_ev |
float | None
|
Plane-wave kinetic-energy cutoff in eV. |
num_plane_waves |
int | None
|
Number of plane waves at the cutoff (|G|² ≤ Ecut). |
grid_dimensions |
tuple[int, int, int] | None
|
Real-space grid dimensions (Nx, Ny, Nz). |
basis_set_name |
str | None
|
Gaussian or LCAO basis set name,
e.g. |
num_basis_functions |
int | None
|
Total number of basis functions. |
metadata |
dict[str, Any]
|
Extra basis-specific fields. |
TermMetadata
dataclass
¶
Metadata for one physical or decomposition term in the Hamiltonian.
A term may be a physical contribution (kinetic, electron-electron Coulomb, electron-nuclear Coulomb, exchange-correlation) or a block in an LCU / qubitization decomposition.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Short identifier. Physical examples:
|
lambda_one_norm |
float | None
|
L1 norm (LCU coefficient sum) for this term, in Hartree. |
lambda_spectral |
float | None
|
Spectral norm of this term, in Hartree. |
num_lcu_terms |
int | None
|
Number of LCU sub-terms in this block. |
truncation_threshold |
float | None
|
Coefficient magnitude below which terms are dropped, in Hartree. |
coefficient_labels |
list[str]
|
Ordered labels for individual LCU coefficients
within this term, e.g. |
implementation_notes |
str | None
|
Free-text notes about how this term is implemented or accessed — e.g. which FFT/QROM circuit is used, or whether it exploits symmetry. |
metadata |
dict[str, Any]
|
Extra per-term fields. |
OracleMetadata
dataclass
¶
Oracle and decomposition parameters for fault-tolerant Hamiltonian simulation.
Captures the quantities needed for T-gate and qubit resource estimates: the LCU 1-norm λ, the number of terms, and per-term breakdowns for the dominant physical contributions.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Decomposition / simulation strategy. Examples:
|
lambda_total |
float | None
|
Total LCU 1-norm λ (sum over all terms), in Ha. |
num_lcu_terms |
int | None
|
Total number of terms in the LCU decomposition. |
eta |
float | None
|
Target energy accuracy ε in Hartree (used to set rotation precision and truncation thresholds). |
delta_e |
float | None
|
Target energy precision for the full simulation, in Hartree. |
num_bits_state |
int | None
|
Number of qubits for the electronic state register. |
num_bits_rot |
int | None
|
Number of bits for rotation synthesis (b_r). |
terms |
list[TermMetadata]
|
Per-physical-term LCU breakdown; see
:class: |
oracle_type |
str | None
|
Circuit-level oracle pattern being targeted.
Examples: |
index_encoding |
str | None
|
How term indices are encoded in qubits.
Examples: |
coefficient_sampling |
str | None
|
Notes on how the PREPARE oracle loads LCU
coefficients — e.g. |
complexity |
dict[str, Any]
|
Annotated complexity quantities for this oracle. Keys are descriptive strings; values are numeric counts or symbolic expressions. Examples:: |
metadata |
dict[str, Any]
|
Extra oracle-level fields. |
ExportMetadata
dataclass
¶
Record of one downstream export generated from a QMatEntry.
Populated by exporter modules when they produce an artifact for a downstream quantum framework.
Attributes:
| Name | Type | Description |
|---|---|---|
framework |
str
|
Target framework name.
Examples: |
format |
str
|
Output format / object type.
Examples: |
target_name |
str | None
|
Human-readable label for this export target, used
when multiple exports target the same framework with
different formats or options.
Example: |
status |
str
|
Lifecycle status of the export. One of
|
version |
str | None
|
Version of the target framework used. |
exported_at |
str | None
|
ISO 8601 datetime of the export. |
artifact_path |
str | None
|
Filesystem or object-store path to the artifact. |
metadata |
dict[str, Any]
|
Extra export-level fields. |
MaterialReference
dataclass
¶
Provenance and structural identity of a material.
Combines the upstream-database provenance with the crystal-structure description so that any downstream component can reconstruct where the material came from and what it looks like geometrically.
Attributes:
| Name | Type | Description |
|---|---|---|
provenance |
SourceProvenance
|
Upstream-database provenance (source, functional, code). |
structure |
StructureMetadata
|
Crystal-structure description (formula, lattice, sites). |
HamiltonianMetadata
dataclass
¶
Full specification of the Hamiltonian derived from a DFT calculation.
Ties together the basis-set choice, the physical-term breakdown, and the oracle-level decomposition parameters needed for fault-tolerant resource estimation.
Attributes:
| Name | Type | Description |
|---|---|---|
num_electrons |
int
|
Number of electrons in the simulation cell (η). |
spin_polarized |
bool
|
Whether spin-up and spin-down are treated separately. |
basis |
BasisMetadata
|
Basis-set specification; see :class: |
num_bands |
int | None
|
Number of bands / orbitals included in the
truncated Hamiltonian. |
terms |
list[TermMetadata]
|
Physical-term breakdown; see :class: |
oracle |
OracleMetadata | None
|
Oracle / decomposition metadata for fault-tolerant
algorithms; see :class: |
metadata |
dict[str, Any]
|
Extra Hamiltonian-level fields. |
valence_charges |
dict[str, float]
|
Valence electrons per atom contributed by the
pseudopotential, keyed by element symbol (e.g.
|
QMatEntry
dataclass
¶
Top-level neutral intermediate representation.
The canonical record that adapters produce and exporters consume. Every entry is serializable to a plain dictionary and carries a deterministic canonical hash over its physically meaningful fields.
Attributes:
| Name | Type | Description |
|---|---|---|
reference |
MaterialReference
|
Material provenance and structure. |
hamiltonian |
HamiltonianMetadata
|
Hamiltonian parameters (basis, terms, oracle). |
exports |
list[ExportMetadata]
|
Downstream export records attached to this entry. |
tags |
list[str]
|
Free-form labels for filtering and grouping. |
schema_version |
str
|
Version of the QMatBridge schema this entry conforms to. |
to_dict()
¶
Serialize the full entry to a JSON-serializable plain dictionary.
canonical_hash()
¶
SHA-256 digest identifying the calculation setup recorded in this entry.
The hash always covers eleven fields: upstream source and identifier,
functional, reduced formula, spacegroup number, electron count, spin
polarization, basis type, cutoff energy, number of bands, and oracle
eta. It is stable across metadata dict changes, tag edits, export
record additions and a different retrieval time, and it changes when any
of the eleven fields changes.
Geometry is covered only when the entry carries positions. If
structure.sites is non-empty, the lattice parameters and the atomic
positions are hashed too (fixed 6-decimal strings; coordinates wrapped
into [0, 1); sites sorted, so their order does not matter). Entries
without sites keep exactly the hash they had before schema 0.2.
The hash is not invariant to a different choice of cell or origin.
It does not cover the pseudopotential family or the plane-wave count.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a lattice parameter or coordinate that would be hashed is NaN or infinite. |
valence_electron_total()
¶
Sum of the per-atom valence charges over structure.sites.
Returns None when the entry has no sites or no
hamiltonian.valence_charges. For a consistent entry this equals
hamiltonian.num_electrons; :meth:check_electron_count tests that.
Raises:
| Type | Description |
|---|---|
KeyError
|
If a site's element has no valence charge. |
check_electron_count()
¶
Raise ValueError if the valence charges disagree with num_electrons.
Does nothing when the entry carries no charges or no sites.
I/O¶
qmatbridge.io
¶
QMatBridge I/O helpers — standard-library-only serialization utilities.
Public API¶
to_dict(obj) Recursively convert any dataclass, list, dict, tuple, or primitive into a plain Python dictionary tree suitable for JSON serialization.
write_entry_json(entry, path, indent=2) Serialize a QMatEntry (or any dataclass) to a JSON file.
from_dict(cls, data)
Rebuild a dataclass (recursively) from the plain dict that to_dict
produces, checking every field's type.
entry_from_dict(data), read_entry_json(path)
Rebuild a QMatEntry from a dict or a JSON file, rejecting
unsupported schema_version values. read_entry_json is the inverse
of write_entry_json.
Only the Python standard library is used. No optional extras required.
EntryFormatError
¶
Bases: ValueError
Raised when data does not match the QMatBridge schema.
The message starts with the dotted path of the offending field, e.g.
hamiltonian.basis.cutoff_energy_ev: expected a number, got str.
to_dict(obj)
¶
Recursively convert a dataclass (or nested structure) to a plain dict.
Conversion rules:
- dataclass instance →
dictkeyed by field name (recursive) list→list(each element converted recursively)tuple→list(JSON has no tuple type)dict→dict(values converted recursively)- everything else → returned as-is (str, int, float, bool, None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Any dataclass instance, collection, or primitive value. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A plain, JSON-serializable Python object. |
Example::
from qmatbridge.io import to_dict
from qmatbridge.schema import LatticeMetadata
lat = LatticeMetadata(a=3.867, b=3.867, c=3.867,
alpha=60.0, beta=60.0, gamma=60.0)
d = to_dict(lat)
assert d["a"] == 3.867
write_entry_json(entry, path, indent=2)
¶
Serialize a QMatEntry (or any dataclass) to a JSON file.
Parent directories are created automatically if they do not exist. The output file is UTF-8 encoded and ends with a trailing newline. The write is atomic: the data is serialised first and written through a temporary file, so a failure never truncates or corrupts an existing file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entry
|
Any
|
Any dataclass instance (typically a |
required |
path
|
str | Path
|
Destination file path. Accepts |
required |
indent
|
int
|
JSON indentation width in spaces. Default: 2. |
2
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved absolute |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the entry contains NaN or Infinity (not valid JSON). |
Example::
from qmatbridge.io import write_entry_json
path = write_entry_json(entry, "output/silicon.json")
print(f"Wrote {path.stat().st_size} bytes to {path}")
from_dict(cls, data, *, _path='')
¶
Rebuild a dataclass cls from a plain dict, the inverse of :func:to_dict.
Nested dataclasses, lists, tuples and optional fields are rebuilt from the
type annotations. Reading is strict so that nothing is silently dropped or
coerced: unknown keys, missing required fields and wrongly typed values
raise :class:EntryFormatError naming the offending field. The only
coercion is integer to float, since JSON may write 520 for 520.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[T]
|
A dataclass type, e.g. |
required |
data
|
Any
|
The dict to decode. |
required |
Raises:
| Type | Description |
|---|---|
EntryFormatError
|
If data does not match the schema. |
Example::
from qmatbridge.io import from_dict, to_dict
from qmatbridge.schema import LatticeMetadata
lat = LatticeMetadata(a=3.8, b=3.8, c=3.8, alpha=60, beta=60, gamma=60)
assert from_dict(LatticeMetadata, to_dict(lat)) == lat
entry_from_dict(data)
¶
Rebuild a :class:~qmatbridge.schema.QMatEntry from a dict.
Raises:
| Type | Description |
|---|---|
EntryFormatError
|
If the data does not match the schema, or its
|
read_entry_json(path)
¶
Read a QMatEntry from a JSON file written by :func:write_entry_json.
The returned entry satisfies
read_entry_json(write_entry_json(e, p)) == e and has the same
canonical_hash().
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If path does not exist (other |
EntryFormatError
|
If the file is not UTF-8 text, is not standard JSON (NaN/Infinity, over-deep nesting and so on), or does not match the schema (the message names the file and the offending field). |
Plane-wave basis¶
qmatbridge.basis
¶
Plane-wave basis utilities.
Helpers for relating a kinetic-energy cutoff to the number of plane waves in a periodic cell. Pure Python, no required dependencies.
Conventions¶
A plane wave exp(i G·r) is included when its kinetic energy satisfies
(ħ²/2mₑ)|G|² ≤ Ecut, with ħ²/2mₑ = 3.80998 eV·Å². Counts are
per k-point (Γ-point enumeration for :func:num_plane_waves_exact) and
spin-independent.
cell_volume(lattice)
¶
Unit-cell volume in ų from lattice lengths and angles.
cutoff_wavevector(ecut_ev)
¶
Cutoff radius k_c = sqrt(Ecut / (ħ²/2m)) in Å⁻¹.
num_plane_waves_estimate(volume_a3, ecut_ev)
¶
Continuum estimate N ≈ V k_c³ / (6π²) (real-valued).
Accurate to a few percent for cells large compared with 1/k_c; use
:func:num_plane_waves_exact for small cells.
num_plane_waves_exact(lattice, ecut_ev, *, max_candidates=DEFAULT_MAX_CANDIDATES)
¶
Count reciprocal-lattice vectors G with (ħ²/2m)|G|² ≤ Ecut.
Enumerates the reciprocal lattice (including the G = 0 term), so the result is the Γ-point basis size. The work grows with the cube of the cell size times the cube of the cutoff wavevector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lattice
|
LatticeMetadata
|
Cell geometry; lengths in Å, angles in degrees. |
required |
ecut_ev
|
float
|
Kinetic-energy cutoff in eV. |
required |
max_candidates
|
int | None
|
Refuse ( |
DEFAULT_MAX_CANDIDATES
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid geometry or cutoff, or if the enumeration exceeds max_candidates. |
num_plane_waves_from_ecut(lattice, ecut_ev, *, method='exact', max_candidates=DEFAULT_MAX_CANDIDATES)
¶
Number of plane waves for a cell and cutoff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lattice
|
LatticeMetadata
|
Cell geometry; lengths in Å, angles in degrees. |
required |
ecut_ev
|
float
|
Kinetic-energy cutoff in eV. |
required |
method
|
str
|
|
'exact'
|
max_candidates
|
int | None
|
Work limit for |
DEFAULT_MAX_CANDIDATES
|
Materials Project adapter¶
qmatbridge.adapters.materials_project
¶
Materials Project adapter for QMatBridge.
Bridges the Materials Project database (https://materialsproject.org) to QMatBridge's neutral intermediate representation.
Layers¶
- Pure converters — :func:
structure_from_mp_docand :func:hamiltonian_from_mp_task_docturn plain-dict MP documents into schema objects. No network, no third-party imports; fully unit-testable. - Live fetchers — :func:
fetch_structure_metadata_from_mp, :func:fetch_hamiltonian_metadata_from_mpand :func:fetch_entry_from_mpquery the API throughmp-api(imported lazily) and feed the converters. - Offline builder — :func:
build_material_reference_from_mpbuilds aMaterialReferencefrom known values without any API call.
Status¶
The converters are covered by unit tests against representative documents.
The live fetchers have not yet been validated against the production
API in CI; run pytest -m integration with MP_API_KEY set to do so.
Dependencies¶
Layers 1 and 3 need nothing. Layer 2 needs the optional extra::
pip install qmatbridge[mp]
MPAdapterConfig
dataclass
¶
Configuration for the Materials Project adapter.
Attributes:
| Name | Type | Description |
|---|---|---|
api_key |
str | None
|
MP API key. If |
endpoint |
str
|
Base URL for the MP REST API. |
timeout_s |
float
|
HTTP request timeout in seconds. |
max_sites |
int | None
|
If set, skip structures with more than this many sites. Useful for keeping resource estimates tractable. |
run_types |
tuple[str, ...]
|
Which calculations to use, in order of preference,
matched against the run type of each static task
(case-insensitive; |
fields |
list[str]
|
Explicit list of MP document fields to request. Empty list means "use adapter defaults." |
metadata |
dict[str, Any]
|
Arbitrary extra config passed through to adapters. |
MaterialsProjectAdapter
¶
The Materials Project adapter as a registry plugin.
Satisfies :class:qmatbridge.registry.Adapter::
from qmatbridge.registry import get_adapter
adapter = get_adapter("materials_project")
entry = adapter.fetch_entry("mp-149", tags=["silicon"])
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
MPAdapterConfig | None
|
Adapter configuration (run types, |
None
|
api_key
|
str | None
|
MP API key; falls back to |
None
|
fetch_entry(identifier, **options)
¶
Fetch identifier (e.g. "mp-149"); accepts tags=[...].
build_material_reference_from_mp(material_id, formula=None, *, formula_unit_cell=None, num_sites=0, species=None, spacegroup_number=None, spacegroup_symbol=None, crystal_system=None, functional='PBE', pseudopotential='PAW_PBE', code='VASP', code_version=None, retrieved_at=None, config=None)
¶
Build a MaterialReference from a known Materials Project ID.
This function requires no network call. It constructs a fully
valid MaterialReference from the arguments provided, filling
lattice parameters with _LATTICE_UNKNOWN (0.0) for fields that
can only be populated by a live fetch_structure_metadata_from_mp
call.
The returned object's provenance is fully populated and its canonical
hash is stable as long as material_id, formula, and
functional are unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
material_id
|
str
|
MP identifier, e.g. |
required |
formula
|
str | None
|
Reduced chemical formula, e.g. |
None
|
formula_unit_cell
|
str | None
|
Unit-cell formula, e.g. |
None
|
num_sites
|
int
|
Number of sites in the unit cell.
Use |
0
|
species
|
list[str] | None
|
Ordered list of element symbols per site. |
None
|
spacegroup_number
|
int | None
|
International spacegroup number (1–230). |
None
|
spacegroup_symbol
|
str | None
|
Hermann-Mauguin symbol, e.g. |
None
|
crystal_system
|
str | None
|
Crystal system string, e.g. |
None
|
functional
|
str
|
DFT XC functional. Default: |
'PBE'
|
pseudopotential
|
str
|
Pseudopotential family. Default: |
'PAW_PBE'
|
code
|
str
|
Electronic-structure code. Default: |
'VASP'
|
code_version
|
str | None
|
Code version string. |
None
|
retrieved_at
|
str | None
|
ISO 8601 datetime string. |
None
|
config
|
MPAdapterConfig | None
|
Adapter configuration. Uses defaults if |
None
|
Returns:
| Type | Description |
|---|---|
MaterialReference
|
A |
MaterialReference
|
placeholder values ( |
MaterialReference
|
Replace it with the result of |
MaterialReference
|
once available. |
Example::
from qmatbridge.adapters.materials_project import (
build_material_reference_from_mp,
)
ref = build_material_reference_from_mp(
"mp-149",
formula="Si",
spacegroup_number=227,
spacegroup_symbol="Fd-3m",
crystal_system="cubic",
)
print(ref.provenance.primary.identifier) # "mp-149"
print(ref.structure.lattice.spacegroup_number) # 227
structure_from_mp_doc(doc)
¶
Convert an MP summary document (as a dict) to StructureMetadata.
Expects structure in pymatgen Structure.as_dict() form
(lattice with a, b, c, alpha, beta, gamma; sites each with a
species list) and, optionally, symmetry with number,
symbol and crystal_system. Disordered sites are rejected.
Fractional coordinates (abc on each site) are recorded as
StructureMetadata.sites when present on every site, so the entry's
canonical_hash() covers the geometry; documents without them still
convert, with sites empty.
Every malformed input raises ValueError: wrong shapes or types, missing
keys, non-finite or non-positive lattice parameters, and invalid cells.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the document is malformed, or a site is disordered. |
hamiltonian_from_mp_task_doc(task, structure)
¶
Convert an MP VASP task document (as a dict) to HamiltonianMetadata.
Reads input.incar.ENCUT (eV), input.incar.ISPIN and
input.parameters.NELECT. The plane-wave count is computed from the
cutoff and structure.lattice via
:func:qmatbridge.basis.num_plane_waves_from_ecut.
Every malformed input raises ValueError: wrong shapes or types, a
missing or non-finite ENCUT/NELECT, non-positive values, a
non-integer electron count, ISPIN other than 1 or 2, or a cell and
cutoff too large for exact plane-wave enumeration.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the task document is malformed or unusable. |
valence_charges_from_mp_task_doc(task)
¶
Per-element valence charges from a VASP task's POTCAR specification.
Pairs input.potcar_spec[*].titel (e.g. "PAW_PBE Li_sv 23Jan2001")
with input.parameters.ZVAL, which VASP lists in POTCAR order. Returns
an empty dict, never an error, when either is absent, the lengths differ,
a title cannot be parsed, or one element appears with two different
charges: a missing charge is better than a guessed one.
functional_from_mp_task_doc(task)
¶
Name the XC functional of an MP task document (e.g. "PBE+U").
Uses run_type when present ("GGA" → "PBE", "GGA+U" →
"PBE+U"; other run types such as "r2SCAN" pass through), else
infers "PBE+U" from a non-empty input.hubbards mapping, else
"PBE".
fetch_structure_metadata_from_mp(material_id, api_key=None, config=None)
¶
Fetch crystal structure from the Materials Project API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
material_id
|
str
|
MP identifier, e.g. |
required |
api_key
|
str | None
|
MP API key. Falls back to |
None
|
config
|
MPAdapterConfig | None
|
Adapter configuration (honours |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
|
ValueError
|
No API key, disordered structure, or |
LookupError
|
Unknown material ID. |
fetch_hamiltonian_metadata_from_mp(material_id, api_key=None, config=None)
¶
Fetch DFT Hamiltonian parameters from the Materials Project API.
Selects the material's static VASP task, reads the plane-wave cutoff, electron count and spin setting from its inputs, and computes the plane-wave count from the fetched cell.
Raises:
| Type | Description |
|---|---|
(ImportError, ValueError, LookupError)
|
as for
:func: |
fetch_entry_from_mp(material_id, api_key=None, config=None, *, tags=None)
¶
Fetch structure and Hamiltonian from MP and assemble a QMatEntry.
Provenance records the retrieval time (UTC) and the MP task used.
Plugin registry¶
qmatbridge.registry
¶
Plugin contract and registry for adapters and exporters.
An adapter turns a record from an upstream source into a
:class:~qmatbridge.schema.QMatEntry; an exporter turns a QMatEntry
into a downstream format and reports what it produced as
:class:~qmatbridge.schema.ExportMetadata. Both are small classes that
satisfy the protocols below, so a third-party package can add one without any
change to this repository.
Registering a plugin¶
Declare an entry point in your package's pyproject.toml::
[project.entry-points."qmatbridge.adapters"]
my_source = "my_package.adapter:MyAdapter"
[project.entry-points."qmatbridge.exporters"]
my_target = "my_package.exporter:MyExporter"
The target must be a class (or any zero-argument-callable) that returns an
object satisfying :class:Adapter / :class:Exporter, whose name equals
the entry-point name.
Using plugins¶
from qmatbridge.registry import list_adapters, get_adapter [p.name for p in list_adapters()] # doctest: +SKIP ['materials_project'] adapter = get_adapter("materials_project") # doctest: +SKIP entry = adapter.fetch_entry("mp-149") # doctest: +SKIP
Listing is lazy: no plugin module is imported until :func:get_adapter /
:func:get_exporter is called, so a plugin's optional dependencies are only
needed when it is actually used. Built-in plugins are listed in this module;
everything else is discovered through the entry-point groups.
Adapter
¶
Bases: Protocol
Fetches a record from an upstream source as a QMatEntry.
fetch_entry(identifier, **options)
¶
Return the entry for identifier (a source-specific ID).
Exporter
¶
Bases: Protocol
Writes a QMatEntry to a downstream format.
export(entry, **options)
¶
Export entry and describe the result.
Implementations should record the framework, format, version and
artifact path in the returned ExportMetadata; attaching it to
entry.exports is left to the caller.
PluginError
¶
Bases: Exception
A plugin is misregistered, cannot be loaded, or breaks the contract.
UnknownPluginError
¶
Bases: PluginError, LookupError
No plugin is registered under the requested name.
PluginInfo
dataclass
¶
What the registry knows about a plugin without importing it.
list_adapters()
¶
Registered adapters, sorted by name. Does not import any plugin.
list_exporters()
¶
Registered exporters, sorted by name. Does not import any plugin.
get_adapter(name, **kwargs)
¶
Load and instantiate the adapter registered as name.
Keyword arguments are passed to the adapter's constructor.
Raises:
| Type | Description |
|---|---|
UnknownPluginError
|
No adapter has that name. |
PluginError
|
The plugin fails to load or breaks the contract. |
get_exporter(name, **kwargs)
¶
Load and instantiate the exporter registered as name.
Raises:
| Type | Description |
|---|---|
UnknownPluginError
|
No exporter has that name. |
PluginError
|
The plugin fails to load or breaks the contract. |