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: object

Container 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, source=None, metadata=<factory>)

Bases: object

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

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)

  • 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_units is not positive.

property nvol: int

Return the number of sampled volumes.

Returns:
int

Number of volume points, or 0 when no volume array is stored.

property nmodes: int

Return the number of phonon modes per q-point.

Returns:
int

Number of modes, or 0 when 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 0 when absent.

property total_q_points: float

Return the sum of q-point weights.

Returns:
float

Sum of the stored weights, or 0.0 when 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

True when structural lattices and atomic coordinates are stored alongside phonon data.

Return type:

bool

has_phonons()

Return whether phonon frequencies are available.

Returns:
bool

True when 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: object

Container 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

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 result is not a ResultData object.

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; concrete rendering is delegated to quantas.api.rendering.

class quantas.api.common.ReportTable(title, columns, rows, metadata=<factory>)

Bases: object

Describe 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: object

Collection 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: Enum

Enumeration 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: object

Message 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: object

Serializable 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)

classmethod from_event(event)

Create a persistent record from an operational event.

Parameters:
eventEvent

Operational event emitted by a calculator.

Returns:
EventRecord

Frontend-neutral, serializable event record.

Parameters:

event (Event)

Return type:

EventRecord

class quantas.api.common.Observer(*args, **kwargs)

Bases: Protocol

Protocol for Quantas event observers.

Any callable object accepting an Event instance 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: object

Observer that forwards events to a user-defined callback.

Parameters:
callbackcallable

Function or callable object that receives an Event instance.

Parameters:

callback (Callable[[Event], None])

class quantas.api.common.ListObserver(events=<factory>)

Bases: object

Observer 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: object

Observer that ignores all received events.

This class is used as the default observer when no logging, reporting, or graphical update is required.

See also