Common public contracts
quantas.api.common contains the frontend-neutral contracts shared by
all public workflows. They define how normalized input, results, reports,
plots, and events move between numerical code and frontends.
Data lifecycle
InputData and PhononInputData preserve normalized input and provenance.
ResultData is the common HDF5-compatible result envelope. A module result
is stored as a typed payload inside that envelope and should be retrieved with
the module-specific get_result function or, for generic frontend code,
get_result_payload.
from quantas.api import common, elasticity
result_data = elasticity.run("calcite.dat")
result = common.get_result_payload(
result_data,
module="elasticity",
key="elasticity",
expected_type=elasticity.Result,
)
Input and result contracts
- class quantas.api.common.InputData(source=None, raw=None, data=<factory>)
Bases:
objectContainer for input data read by a Quantas reader.
- Parameters:
- sourcestr or Path or None, optional
Path or textual description of the original source of the input data.
- rawstr or None, optional
Raw content of the input file, when available.
- datadict, optional
Parsed input data.
- Parameters:
source (str | Path | None)
raw (str | None)
data (dict[str, Any])
- class quantas.api.common.PhononInputData(jobname='Unknown', natoms=0, formula_units=1, supercell=None, qpoints=0, volume=None, energy=None, frequencies=None, weights=None, qcoords=None, structure=None, units=<factory>, source=None, metadata=<factory>)
Bases:
objectNormalized structural, energetic, and phonon input data.
- Parameters:
- jobnamestr, optional
Name or short description of the calculation.
- natomsint, optional
Number of atoms in the thermodynamic normalization cell.
- formula_unitsint, optional
Number of chemical formula units in the thermodynamic normalization cell.
- supercellndarray or None, optional
Supercell matrix used to sample phonons, with shape
(3, 3).- qpointsint, optional
Number of phonon q-points stored in the input data.
- volumendarray or None, optional
Unit-cell volumes with shape
(nvol,).- energyndarray or None, optional
Static energies with shape
(nvol,).- frequenciesndarray or None, optional
Phonon frequencies with shape
(qpoints, nmodes, nvol).- weightsndarray or None, optional
Q-point weights with shape
(qpoints,).- qcoordsndarray or None, optional
Q-point fractional coordinates with shape
(qpoints, 3).- structureStructureVolumeSeries or None, optional
Compact primitive structural path, symmetry, and normalization data.
- unitsdict, optional
Explicit physical units carried by the input dataset. Common keys are
"energy","volume","frequency", and"length".- sourcestr or Path or None, optional
Source file from which the data were read.
- metadatadict, optional
Additional parser-specific or workflow-specific metadata.
- Parameters:
jobname (str)
natoms (int)
formula_units (int)
supercell (ndarray | None)
qpoints (int)
volume (ndarray | None)
energy (ndarray | None)
frequencies (ndarray | None)
weights (ndarray | None)
qcoords (ndarray | None)
structure (StructureVolumeSeries | None)
units (dict[str, str])
source (str | Path | None)
metadata (dict[str, Any])
- property natoms_per_formula_unit: float
Return the number of atoms per chemical formula unit.
- Returns:
- float
Number of atoms in one formula unit.
- Raises:
- ValueError
If
formula_unitsis not positive.
- property nvol: int
Return the number of sampled volumes.
- Returns:
- int
Number of volume points, or
0when no volume array is stored.
- property nmodes: int
Return the number of phonon modes per q-point.
- Returns:
- int
Number of modes, or
0when no frequency array is stored.
- property kpoints: int
Return the number of sampled k-points from the supercell matrix.
- Returns:
- int
Rounded determinant of the supercell matrix, or
0when absent.
- property total_q_points: float
Return the sum of q-point weights.
- Returns:
- float
Sum of the stored weights, or
0.0when no weights are stored.
- normalized_weights()
Return q-point weights normalized by their sum.
- Returns:
- ndarray
Normalized q-point weights.
- Raises:
- ValueError
If weights are unavailable or their sum is not positive.
- Return type:
ndarray
- has_structure()
Return whether a compact structural volume series is available.
- Returns:
- bool
Truewhen structural lattices and atomic coordinates are stored alongside phonon data.
- Return type:
bool
- has_phonons()
Return whether phonon frequencies are available.
- Returns:
- bool
Truewhen a frequency array is stored.
- Return type:
bool
- class quantas.api.common.ResultData(metadata, input_data=None, options=<factory>, results=<factory>, warnings=<factory>, events=<factory>)
Bases:
objectContainer for the final result of a Quantas calculation.
- Parameters:
- metadataResultMetadata
Metadata describing how the result was generated.
- input_dataInputData or None, optional
Input data used by the calculator.
- optionsdict, optional
Options used to control the workflow.
- resultsdict, optional
Numerical or textual results generated by the workflow.
- warningslist of str, optional
Warning messages collected during the calculation.
- eventslist of EventRecord, optional
Persistent workflow event log.
- Parameters:
metadata (ResultMetadata)
input_data (InputData | None)
options (dict[str, Any])
results (dict[str, Any])
warnings (list[str])
events (list[EventRecord])
- add_result(key, value)
Store a calculated result.
This method provides a small convenience wrapper around the internal results dictionary and can be used by calculators to add numerical or textual data to the result container.
- Parameters:
- keystr
Name associated with the stored result.
- valueAny
Value to be stored.
- Parameters:
key (str)
value (Any)
- Return type:
None
- add_warning(message)
Store a warning message.
Warning messages are collected during the execution of a workflow and can be reported to the user at the end of the calculation or stored in the output file.
- Parameters:
- messagestr
Warning message to be stored.
- Parameters:
message (str)
- Return type:
None
- class quantas.api.common.ResultMetadata(program='quantas', module='unknown', method='unknown', version='2.0.0b10', created_by=None, created_at=<factory>, schema_version='2.0')
Bases:
objectMetadata associated with a Quantas calculation.
- Parameters:
- programstr, optional
Name of the program that generated the result.
- modulestr, optional
Name of the Quantas module used for the calculation.
- methodstr, optional
Name of the method or workflow used by the module.
- versionstr, optional
Quantas version used to generate the result.
- created_bystr or None, optional
Name of the user or routine that generated the result.
- created_atdatetime, optional
Date and time at which the result was created.
- schema_versionstr, optional
Version of the internal result schema.
- Parameters:
program (str)
module (str)
method (str)
version (str)
created_by (str | None)
created_at (datetime)
schema_version (str)
Reusable scientific input structures
- quantas.api.common.PhononInterface
alias of
Literal[‘crystal’, ‘crystal-qha’, ‘phonopy’]
- class quantas.api.common.StructureVolumeSeries(reference, lattices, fractional_positions, volumes, normalization, symmetry=None, primitive_to_crystallographic=None, diagnostics=(), orientation='crystal', reference_index=0, metadata=<factory>, source_lattices=None, source_fractional_positions=None)
Bases:
objectPrimitive structural path sampled as a function of volume.
- Parameters:
- referenceCrystalStructure
Reference primitive structure used to maintain atom correspondence and cell orientation across the sampled volumes.
- latticesarray_like
Primitive direct lattice matrices with shape
(nvol, 3, 3).- fractional_positionsarray_like
Primitive fractional coordinates with shape
(nvol, natoms, 3).- volumesarray_like
Primitive-cell volumes with shape
(nvol,).- normalizationCellNormalization
Description of the thermodynamic normalization cell.
- symmetrySymmetryMetadata or None, optional
Symmetry metadata for the reference structure.
- primitive_to_crystallographicarray_like or None, optional
CRYSTAL transformation from the primitive to crystallographic cell.
- diagnosticssequence of StructureReconstructionDiagnostics, optional
Reconstruction diagnostics for each sampled volume.
- orientationstr, optional
Description of the Cartesian/basis convention.
"crystal"denotes continuity with the CRYSTAL source orientation.- reference_indexint, optional
Index of the reference structure within the sampled series.
- metadatadict, optional
Additional provenance metadata.
- source_latticesarray_like or None, optional
Full source-cell lattices retained in memory for optional provenance storage.
- source_fractional_positionssequence or None, optional
Full source-cell fractional positions retained in memory for optional provenance storage. Atom counts may differ among entries, so a tuple is used instead of a rectangular array.
- Raises:
- ValueError
If array shapes or atom counts are inconsistent.
- Parameters:
reference (CrystalStructure)
lattices (NDArray[float64])
fractional_positions (NDArray[float64])
volumes (NDArray[float64])
normalization (CellNormalization)
symmetry (SymmetryMetadata | None)
primitive_to_crystallographic (NDArray[float64] | None)
diagnostics (tuple[StructureReconstructionDiagnostics, ...])
orientation (str)
reference_index (int)
metadata (dict[str, Any])
source_lattices (NDArray[float64] | None)
source_fractional_positions (tuple[NDArray[float64], ...] | None)
- property nvol: int
Return the number of sampled structures.
- Returns:
- int
Number of volume points.
- property natoms: int
Return the primitive atom count.
- Returns:
- int
Number of atoms in each compact primitive structure.
- has_source_supercells()
Return whether full source-cell structures are retained.
- Returns:
- bool
Truewhen both source lattices and positions are available.
- Return type:
bool
- as_dict(*, include_source=False)
Return a recursively serializable structural-series mapping.
- Parameters:
- include_sourcebool, optional
Include full source supercells when they are retained. The compact primitive path is always included.
- Returns:
- dict
Structure, symmetry, normalization, and reconstruction data.
- Parameters:
include_source (bool)
- Return type:
dict[str, Any]
- class quantas.api.common.CrystalStructure(lattice, fractional_positions, atomic_numbers, label='', metadata=<factory>)
Bases:
objectCompact periodic crystal structure.
- Parameters:
- latticearray_like
Direct lattice vectors in Cartesian coordinates, stored by rows with shape
(3, 3)and expressed in angstrom.- fractional_positionsarray_like
Fractional atomic coordinates with shape
(natoms, 3).- atomic_numbersarray_like
Atomic numbers with shape
(natoms,).- labelstr, optional
Human-readable description of the structure.
- metadatadict, optional
Additional parser or provenance metadata.
- Raises:
- ValueError
If array shapes are inconsistent or the lattice volume is zero.
- Parameters:
lattice (NDArray[float64])
fractional_positions (NDArray[float64])
atomic_numbers (NDArray[int64])
label (str)
metadata (dict[str, Any])
- property natoms: int
Return the number of atoms in the structure.
- Returns:
- int
Number of stored atoms.
- property volume: float
Return the positive cell volume in cubic angstrom.
- Returns:
- float
Absolute determinant of the direct lattice matrix.
- spglib_cell()
Return the tuple representation consumed by spglib.
- Returns:
- tuple
(lattice, fractional_positions, atomic_numbers)with lattice vectors stored by rows.
- Return type:
tuple[list[list[float]], list[list[float]], list[int]]
- as_dict()
Return a recursively serializable mapping.
- Returns:
- dict
Structural arrays and metadata suitable for YAML or HDF5 output.
- Return type:
dict[str, Any]
- class quantas.api.common.SymmetryMetadata(space_group_number=0, international_symbol='', hall_number=0, hall_symbol='', choice='', point_group='', symprec=1e-05, angle_tolerance=-1.0, equivalent_atoms=None, transformation_matrix=None, origin_shift=None)
Bases:
objectSymmetry information determined for a reference crystal structure.
- Parameters:
- space_group_numberint
International space-group number.
- international_symbolstr
International short Hermann–Mauguin symbol.
- hall_numberint
spglib Hall-number identifier.
- hall_symbolstr
Hall symbol.
- choicestr
Setting or origin choice reported by spglib.
- point_groupstr
Crystallographic point-group symbol.
- symprecfloat
Cartesian tolerance in angstrom used for symmetry detection.
- angle_tolerancefloat
Angular tolerance in degrees used for symmetry detection. A negative value denotes spglib’s internal default.
- equivalent_atomsarray_like or None, optional
Mapping from each atom to its crystallographic equivalence class.
- transformation_matrixarray_like or None, optional
Transformation matrix reported by spglib for its standard setting.
- origin_shiftarray_like or None, optional
Origin shift reported by spglib.
- Parameters:
space_group_number (int)
international_symbol (str)
hall_number (int)
hall_symbol (str)
choice (str)
point_group (str)
symprec (float)
angle_tolerance (float)
equivalent_atoms (NDArray[int64] | None)
transformation_matrix (NDArray[float64] | None)
origin_shift (NDArray[float64] | None)
- as_dict()
Return a recursively serializable symmetry mapping.
- Returns:
- dict
Symmetry identifiers, tolerances, and transformations.
- Return type:
dict[str, Any]
- class quantas.api.common.TensorRotation(matrix, kind=TensorRotationKind.MATRIX, angles=None, angle_unit=None, description=None)
Bases:
objectUser-defined transformation from the source to the analysis frame.
The stored matrix follows the Quantas component convention
T'_{ij...} = R_ia R_jb ... T_ab....- Parameters:
- matrixarray_like
Proper orthogonal matrix with shape
(3, 3). Its rows are the analysis-frame basis vectors expressed in the source frame.- kindTensorRotationKind or str, optional
Description used to construct the matrix.
- anglestuple of float or None, optional
Input angles for an
xyzconstruction.- angle_unitstr or None, optional
Unit of
angles. Currently"degree"or"radian".- descriptionstr or None, optional
Optional user-facing description saved with result provenance.
- Raises:
- ValueError
If the matrix or angular provenance is invalid.
- Parameters:
matrix (NDArray[float64])
kind (TensorRotationKind)
angles (tuple[float, float, float] | None)
angle_unit (str | None)
description (str | None)
- classmethod from_matrix(matrix, *, description=None)
Build a transformation from an explicit rotation matrix.
- Parameters:
- matrixarray_like
Proper orthogonal
3 x 3component-transformation matrix.- descriptionstr or None, optional
Optional provenance note.
- Returns:
- TensorRotation
Validated matrix transformation.
- Parameters:
matrix (ArrayLike)
description (str | None)
- Return type:
- classmethod from_xyz(x, y, z, *, degrees=True, description=None)
Build a transformation from ordered right-handed XYZ rotations.
The rotations are applied about the fixed source axes in the order
x, theny, thenz. For column-vector matrices this givesR = Rz(z) @ Ry(y) @ Rx(x). The resulting matrix is used directly in the Quantas tensor-component transformation.- Parameters:
- x, y, zfloat
Rotation angles about the fixed source Cartesian axes.
- degreesbool, optional
Interpret the supplied angles as degrees when
True.- descriptionstr or None, optional
Optional provenance note.
- Returns:
- TensorRotation
Validated XYZ transformation.
- Parameters:
x (float)
y (float)
z (float)
degrees (bool)
description (str | None)
- Return type:
- as_mapping()
Return a serialization-friendly provenance mapping.
- Returns:
- dict
Rotation kind, convention, matrix and optional angular input.
- Return type:
dict[str, Any]
- class quantas.api.common.TensorRotationKind(*values)
Bases:
str,EnumSupported user descriptions of a tensor-component transformation.
- quantas.api.common.get_result_payload(result, *, module, key, expected_type)
Return and type-check one module-specific result payload.
- Parameters:
- resultResultData
Complete Quantas result envelope.
- modulestr
Expected stable module identifier.
- keystr
Payload key inside
result.results.- expected_typetype
Expected payload class.
- Returns:
- PayloadT
Validated module-specific payload.
- Raises:
- TypeError
If
resultis not aResultDataobject.- ValueError
If module metadata, payload key, or payload type is invalid.
- Parameters:
result (ResultData)
module (str)
key (str)
expected_type (type[PayloadT])
- Return type:
PayloadT
Neutral reporting and plotting
ReportTable stores raw values, labels, units, alignment, and display
metadata without embedding Rich or terminal behavior. PlotCollection
stores frontend-neutral plot specifications. Their concrete public types
are documented in quantas.api.plotting; rendering is delegated to
quantas.api.rendering.
- class quantas.api.common.ReportTable(title, columns, rows, metadata=<factory>)
Bases:
objectDescribe one frontend-neutral table of scientific results.
- Parameters:
- titlestr
Human-readable table title.
- columnslist of str
Ordered column labels.
- rowslist of list
Ordered table rows. Cells retain raw numerical or textual values until a frontend renderer formats them.
- metadatadict, optional
Frontend-neutral formatting and provenance metadata.
- Parameters:
title (str)
columns (list[str])
rows (list[list[Any]])
metadata (dict[str, Any])
- class quantas.api.common.PlotCollection(plots=<factory>, warnings=<factory>)
Bases:
objectCollection of neutral plot specifications and non-fatal warnings.
- Parameters:
- plotslist of PlotSpec, optional
Ordered specifications ready for rendering.
- warningslist of str, optional
Non-fatal conditions encountered while preparing plot data.
- Parameters:
plots (list[LinePlotSpec | ContourPlotSpec | PolarPlotSpec | SurfacePlotSpec | SphericalMapSpec | SphericalSummarySpec | PanelPlotSpec])
warnings (list[str])
Events and observers
Observers are optional sinks for operational events. ListObserver is
useful in notebooks and tests, CallbackObserver adapts an arbitrary
callable, and NullObserver explicitly discards events. Progress events
are operational and are not persisted as scientific history.
from quantas.api import qha
from quantas.api.common import ListObserver
observer = ListObserver()
result = qha.run("phonons.yaml", observer=observer)
for event in observer.events:
print(event.level.value, event.message, event.progress)
- class quantas.api.common.EventLevel(*values)
Bases:
EnumEnumeration of the event levels supported by Quantas.
- Attributes:
- DEBUG
Event used to report detailed information useful during development.
- INFO
Event used to report standard information during a workflow.
- WARNING
Event used to report a non-critical problem.
- ERROR
Event used to report an error.
- PROGRESS
Event used to report the progress of a workflow.
- RESULT
Event used to report that a result, or part of it, is available.
- class quantas.api.common.Event(message, level=EventLevel.INFO, progress=None, data=<factory>, timestamp=<factory>)
Bases:
objectMessage emitted by a Quantas workflow.
- Parameters:
- messagestr
Textual message associated with the event.
- levelEventLevel, optional
Type or severity level of the event.
- progressfloat or None, optional
Progress value associated with the event. When provided, it must be between 0 and 1.
- datadict, optional
Optional payload associated with the event. This can be used to store additional information, such as elapsed time, current step, or partial results.
- timestampdatetime, optional
Date and time at which the event was created.
- Parameters:
message (str)
level (EventLevel)
progress (float | None)
data (dict[str, Any])
timestamp (datetime)
- class quantas.api.common.EventRecord(message, level='info', progress=None, data=<factory>, timestamp=<factory>)
Bases:
objectSerializable record of a Quantas workflow event.
- Parameters:
- messagestr
Textual event message.
- levelstr
Event level stored as its stable string value.
- progressfloat or None, optional
Numerical progress between zero and one.
- datadict, optional
Lightweight structured payload. Numerical arrays and active objects are represented by summaries to avoid duplicating scientific result data.
- timestampdatetime, optional
Time at which the original event was emitted.
- Parameters:
message (str)
level (str)
progress (float | None)
data (dict[str, Any])
timestamp (datetime)
- class quantas.api.common.Observer(*args, **kwargs)
Bases:
ProtocolProtocol for Quantas event observers.
Any callable object accepting an
Eventinstance can be used as an observer. This makes it possible to connect calculators to command-line loggers, graphical widgets, notebooks, lists, or custom user callbacks.
- class quantas.api.common.CallbackObserver(callback)
Bases:
objectObserver that forwards events to a user-defined callback.
- class quantas.api.common.ListObserver(events=<factory>)
Bases:
objectObserver that stores all received events in a list.
This observer is mainly useful for testing, debugging, and workflows where the event log has to be saved after the calculation.
- Attributes:
- eventslist of Event
List containing the received events.
- Parameters:
events (list[Event])
- class quantas.api.common.NullObserver
Bases:
objectObserver that ignores all received events.
This class is used as the default observer when no logging, reporting, or graphical update is required.