Skip to content

API reference

Schema

qmatbridge.schema

QMatBridge canonical schema — v0.1.

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: "materials_project", "aflow", "icsd", "cod", "doi".

identifier str

The database-native ID string. Examples: "mp-149", "10.1103/PhysRevLett.77.3865".

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: "PBE", "PBE+U", "HSE06".

pseudopotential str | None

Pseudopotential family. Examples: "PAW_PBE", "ONCV_PBE", "SG15".

code str | None

Electronic-structure code used. Examples: "VASP", "QE", "ABINIT".

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. "Fd-3m".

crystal_system str | None

One of "triclinic", "monoclinic", "orthorhombic", "tetragonal", "trigonal", "hexagonal", "cubic".

volume_ang3 float | None

Unit cell volume in ų.

metadata dict[str, Any]

Extra crystallographic fields.

StructureMetadata dataclass

Chemical and geometric identity of the crystal structure.

Attributes:

Name Type Description
formula_reduced str

Reduced formula, e.g. "Si", "GaAs".

formula_unit_cell str

Unit-cell formula, e.g. "Si2".

num_sites int

Number of atomic sites in the simulation cell.

species list[str]

Ordered list of element symbols per site, e.g. ["Si", "Si"].

lattice LatticeMetadata

Bravais lattice and crystallographic parameters.

is_periodic bool

Whether the structure is treated as periodic. False for molecules or clusters.

metadata dict[str, Any]

Extra structure-level fields.

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: "plane_wave", "gaussian", "lcao", "real_space".

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. "cc-pVTZ", "STO-3G".

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: "kinetic", "electron_electron", "electron_nuclear", "xc". Decomposition examples: "lcu_block_0".

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. ["T_G0", "T_G1"]. Empty when coefficient-level detail is not stored.

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: "lcu", "qubitization", "sparse", "tensor_hypercontraction".

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:TermMetadata.

oracle_type str | None

Circuit-level oracle pattern being targeted. Examples: "SELECT", "PREPARE", "SELECT_PREPARE", "QROM", "sparse_access". Canonical values are listed in _ORACLE_TYPES.

index_encoding str | None

How term indices are encoded in qubits. Examples: "binary", "unary", "one_hot". Canonical values are listed in _INDEX_ENCODINGS. None when not yet determined.

coefficient_sampling str | None

Notes on how the PREPARE oracle loads LCU coefficients — e.g. "alias_sampling", "QROM_direct", "uniform_superposition".

complexity dict[str, Any]

Annotated complexity quantities for this oracle. Keys are descriptive strings; values are numeric counts or symbolic expressions. Examples::

                  {
                    "T_count_formula": "O(lambda/delta_e)",
                    "toffoli_count": 123456,
                    "ancilla_qubits": 42,
                  }
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: "openfermion", "pennylane", "qualtran", "pyliqtr", "qiskit".

format str

Output format / object type. Examples: "InteractionOperator", "sparse_matrix", "lcu_coefficients", "FermionOperator".

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: "openfermion_sparse_8e".

status str

Lifecycle status of the export. One of "pending", "complete", "failed". Default: "pending".

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:BasisMetadata.

num_bands int | None

Number of bands / orbitals included in the truncated Hamiltonian. None means all bands up to the cutoff are included.

terms list[TermMetadata]

Physical-term breakdown; see :class:TermMetadata.

oracle OracleMetadata | None

Oracle / decomposition metadata for fault-tolerant algorithms; see :class:OracleMetadata. None until an oracle decomposition is computed.

metadata dict[str, Any]

Extra Hamiltonian-level fields.

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 over the physically meaningful fields of this entry.

The hash is stable across metadata / extra dict changes, tag edits, and export record additions. It changes when any field that alters the physics of the Hamiltonian is modified.

Fields included: upstream source + identifier, reduced formula, spacegroup, electron count, spin polarization, basis type, cutoff energy, number of bands, and oracle eta.

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.

Only the Python standard library is used. No optional extras required.

to_dict(obj)

Recursively convert a dataclass (or nested structure) to a plain dict.

Conversion rules:

  • dataclass instance → dict keyed 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.

Parameters:

Name Type Description Default
entry Any

Any dataclass instance (typically a QMatEntry).

required
path str | Path

Destination file path. Accepts str or pathlib.Path.

required
indent int

JSON indentation width in spaces. Default: 2.

2

Returns:

Type Description
Path

The resolved absolute Path of the written file.

Raises:

Type Description
TypeError

If entry is not a dataclass instance.

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}")

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)

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.

num_plane_waves_from_ecut(lattice, ecut_ev, *, method='exact')

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" (reciprocal-lattice enumeration, default) or "estimate" (continuum formula, rounded to nearest int).

'exact'

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

  1. Pure converters — :func:structure_from_mp_doc and :func:hamiltonian_from_mp_task_doc turn plain-dict MP documents into schema objects. No network, no third-party imports; fully unit-testable.
  2. Live fetchers — :func:fetch_structure_metadata_from_mp, :func:fetch_hamiltonian_metadata_from_mp and :func:fetch_entry_from_mp query the API through mp-api (imported lazily) and feed the converters.
  3. Offline builder — :func:build_material_reference_from_mp builds a MaterialReference from 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 None, the adapter will look for the MP_API_KEY environment variable when making live requests.

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; "GGA", "GGA+U", "r2SCAN", "HSE06" ...). Materials Project stores several static calculations per material, so the choice must be explicit. Default: the standard PBE workflow.

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.

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. "mp-149".

required
formula str | None

Reduced chemical formula, e.g. "Si". Defaults to material_id if not given.

None
formula_unit_cell str | None

Unit-cell formula, e.g. "Si2". Defaults to formula if not given.

None
num_sites int

Number of sites in the unit cell. Use 0 when unknown.

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. "Fd-3m".

None
crystal_system str | None

Crystal system string, e.g. "cubic".

None
functional str

DFT XC functional. Default: "PBE".

'PBE'
pseudopotential str

Pseudopotential family. Default: "PAW_PBE".

'PAW_PBE'
code str

Electronic-structure code. Default: "VASP".

'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.

None

Returns:

Type Description
MaterialReference

A MaterialReference whose structure.lattice contains

MaterialReference

placeholder values (0.0) for the geometric parameters.

MaterialReference

Replace it with the result of fetch_structure_metadata_from_mp

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.

Raises:

Type Description
ValueError

If required keys are missing 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.

Raises:

Type Description
ValueError

If ENCUT or NELECT is absent.

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. "mp-149".

required
api_key str | None

MP API key. Falls back to MPAdapterConfig.api_key then the MP_API_KEY environment variable.

None
config MPAdapterConfig | None

Adapter configuration (honours max_sites).

None

Raises:

Type Description
ImportError

mp-api is not installed.

ValueError

No API key, disordered structure, or max_sites exceeded.

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_structure_metadata_from_mp; also ValueError if the task lacks ENCUT or NELECT.

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.