contracts
contracts
¶
Backend capability contracts and prepared-session vocabulary.
This module is the single source of truth for how Q2MM talks to a computational backend (MM or reference). It defines:
- :class:
BackendRole/ :class:Capability/ :class:BackendInfo/ :class:BackendProvenance— the vocabulary a backend uses to declare what it can do. Capabilities and functional forms both default to empty; every backend must explicitly enumerate every operation and functional form it supports. - Immutable, typed preparation and evaluation requests, and typed,
canonical-unit results. Requests defensively copy their arrays to
read-only in
__post_init__; results defensively copy and shape-validate their arrays in__post_init__, so direct construction is safe regardless of the producing backend. Every result carries an explicit unit enum and a :class:BackendProvenance. - Typed errors: :class:
BackendUnavailableError, :class:BackendConfigurationError, :class:PreparationError, :class:UnsupportedCapabilityError, :class:EvaluationError— there is no broad silent fallback. - The :class:
Backend/ :class:PreparedBackendlifecycle protocols and the :class:AbstractPreparedBackendbase that enforces capability checks, request-family/role validation, and full-vector dimension validation. A concrete backend exposes onlyinfoandprepare(plus clearly backend-specific serialization/config); the prepared session is the only evaluation surface. - Side-effect-free registry :class:
BackendDescriptor(which carries static capability and functional-form ceilings) / :class:DependencyProbeplumbing used by :mod:q2mm.backends.registry.
Canonical unit contracts (results always carry these units):
- MM energy: kcal/mol (:attr:
EnergyUnit.KCAL_PER_MOL); reference energy: Hartree (:attr:EnergyUnit.HARTREE) — must match :class:BackendRole. - Geometry: Å (:attr:
LengthUnit.ANGSTROM). - Hessian: Hartree/Bohr² (:attr:
HessianUnit.HARTREE_PER_BOHR2). - Frequency: cm⁻¹ (:attr:
FrequencyUnit.INVERSE_CM). - Parameter gradients have length exactly
len(ParameterLayout).
These contracts are the stable public authoring surface for
BACKEND_API_VERSION == 1.
BackendRole
¶
Bases: str, Enum
Whether a backend computes molecular-mechanics or reference data.
Capability
¶
Bases: str, Enum
A discrete operation a backend may declare that it supports.
A backend that lists a capability in its :class:BackendInfo must
implement the corresponding prepared-session method; a backend that does
not list it must raise :class:UnsupportedCapabilityError when the method
is called.
EnergyUnit
¶
Bases: str, Enum
Explicit canonical energy unit for a result.
LengthUnit
¶
Bases: str, Enum
Explicit canonical length unit for coordinates.
HessianUnit
¶
Bases: str, Enum
Explicit canonical Hessian unit (atomic units).
FrequencyUnit
¶
Bases: str, Enum
Explicit canonical vibrational-frequency unit.
CoordinateGradientUnit
¶
Bases: str, Enum
Explicit canonical Cartesian coordinate-gradient unit.
BackendProvenance
dataclass
¶
BackendProvenance(backend: str, role: BackendRole, version: str = '', details: Mapping[str, object] = dict())
Immutable record of which backend produced a result and how.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
Registry key of the backend (e.g. |
required |
role
|
BackendRole
|
Whether the producing backend is MM or reference. |
required |
version
|
str
|
Backend library version string if known (else |
''
|
details
|
Mapping[str, object]
|
Structured JSON-safe implementation, model, calculator, configuration, driver, platform, native-provenance, schema, or conversion details. |
dict()
|
BackendInfo
dataclass
¶
BackendInfo(name: str, role: BackendRole, capabilities: frozenset[Capability] = frozenset(), functional_forms: frozenset[str] = frozenset(), provenance: BackendProvenance | None = None)
Immutable capability declaration for a backend.
Both :attr:capabilities and :attr:functional_forms default to the
empty set: a backend must explicitly declare every operation and every
functional form it supports. Nothing is inferred.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable backend name (e.g. |
required |
role
|
BackendRole
|
MM or reference. |
required |
capabilities
|
frozenset[Capability]
|
Operations the backend supports. |
frozenset()
|
functional_forms
|
frozenset[str]
|
:class: |
frozenset()
|
provenance
|
BackendProvenance | None
|
Canonical provenance stamped onto every result. |
None
|
supports
¶
supports(capability: Capability) -> bool
supports_form
¶
matches
¶
matches(other: BackendInfo) -> bool
Return True if role, capabilities, and functional forms agree.
Compares :attr:role, :attr:capabilities, and
:attr:functional_forms only; the human-readable :attr:name and the
:attr:provenance are intentionally ignored. Descriptor loading checks
the runtime provenance's registry key/role separately (see
:meth:BackendDescriptor.load).
Source code in q2mm/backends/contracts.py
BackendError
¶
Bases: RuntimeError
Base class for all typed backend errors.
BackendUnavailableError
¶
Bases: BackendError
A backend's native dependencies are not installed/importable.
BackendConfigurationError
¶
Bases: BackendError
A backend is installed but mis-configured (bad option, missing path).
PreparationError
¶
Bases: BackendError
Building a prepared session for a training case failed.
UnsupportedCapabilityError
¶
UnsupportedCapabilityError(backend: str, capability: Capability)
Bases: BackendError
A prepared session was asked for an operation it does not declare.
Source code in q2mm/backends/contracts.py
EvaluationError
¶
Bases: BackendError
A prepared-session evaluation failed at runtime.
PreparationRequest
dataclass
¶
PreparationRequest(case_id: str, molecule: Molecule, force_field: ForceField | None = None, options: Mapping[str, object] = dict())
Immutable request to build a prepared session for one training case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
case_id
|
str
|
Stable, non-empty identifier for the training case. Exactly
one prepared session is built per |
required |
molecule
|
Molecule
|
The molecule (with reference geometry) to prepare. |
required |
force_field
|
ForceField | None
|
Base force field (MM backends only; |
None
|
options
|
Mapping[str, object]
|
Backend-specific preparation options (string keys). Copied to an immutable mapping proxy (keys preserved, values deep-frozen) so caller mutation after construction has no effect. |
dict()
|
EnergyRequest
dataclass
¶
Single-point energy for a full parameter vector.
MinimizationRequest
dataclass
¶
MinimizationRequest(parameters: ndarray, max_iterations: int | None = None, tolerance: float | None = None)
Energy-minimize (relax) the geometry for a full parameter vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
ndarray
|
Full parameter vector. |
required |
max_iterations
|
int | None
|
Maximum minimizer iterations, or |
None
|
tolerance
|
float | None
|
Convergence tolerance in the backend's native units, or
|
None
|
HessianRequest
dataclass
¶
Cartesian Hessian for a full parameter vector.
FrequencyRequest
dataclass
¶
Vibrational frequencies for a full parameter vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
ndarray
|
Full parameter vector. |
required |
on_error
|
str
|
Forwarded to
:func: |
'raise'
|
ParameterGradientRequest
dataclass
¶
Energy plus analytical dE/dp for a full parameter vector.
HessianJacobianRequest
dataclass
¶
Hessian plus its analytical dH/dp Jacobian for a full vector.
BatchedEnergyRequest
dataclass
¶
Energies for a batch of full parameter vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter_matrix
|
ndarray
|
Shape |
required |
BatchedHessianRequest
dataclass
¶
Cartesian Hessians for a batch of topology-compatible prepared cases.
Carries one full parameter vector applied to every case in the batch; the batch object owns the compatible cases and their coordinates. No force field crosses this boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
ndarray
|
Full parameter vector (length |
required |
ReferenceFrequencyRequest
dataclass
¶
Reference vibrational-frequency request.
ReferenceGeometryOptimizationRequest
dataclass
¶
Reference geometry optimization request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opt_type
|
str
|
|
'min'
|
ReferenceCoordinateGradientRequest
dataclass
¶
Reference Cartesian coordinate-gradient request.
EnergyResult
dataclass
¶
EnergyResult(energy: float, unit: EnergyUnit, provenance: BackendProvenance)
Single-point energy in a canonical unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
energy
|
float
|
Energy value. |
required |
unit
|
EnergyUnit
|
Explicit canonical unit (kcal/mol for MM, Hartree for reference). |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
GeometryResult
dataclass
¶
GeometryResult(energy: float, energy_unit: EnergyUnit, symbols: tuple[str, ...], coordinates: ndarray, coordinate_unit: LengthUnit, provenance: BackendProvenance)
Optimized geometry and its energy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
energy
|
float
|
Energy at the optimized geometry. |
required |
energy_unit
|
EnergyUnit
|
Canonical energy unit. |
required |
symbols
|
tuple[str, ...]
|
Element symbols, length |
required |
coordinates
|
ndarray
|
|
required |
coordinate_unit
|
LengthUnit
|
Canonical length unit (Å). |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
HessianResult
dataclass
¶
HessianResult(hessian: ndarray, unit: HessianUnit, provenance: BackendProvenance)
Cartesian Hessian in atomic units.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hessian
|
ndarray
|
|
required |
unit
|
HessianUnit
|
Canonical Hessian unit. |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
hessian_provenance
property
¶
hessian_provenance: HessianProvenance
Return molecule-level atomic-unit provenance for this Hessian.
FrequencyResult
dataclass
¶
FrequencyResult(frequencies: ndarray, unit: FrequencyUnit, provenance: BackendProvenance)
Vibrational frequencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies
|
ndarray
|
Array of frequencies (read-only, defensive copy). Values
are finite; a fully-penalized region uses the finite
:data: |
required |
unit
|
FrequencyUnit
|
Canonical frequency unit. |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
ParameterGradientResult
dataclass
¶
ParameterGradientResult(energy: float, gradient: ndarray, unit: EnergyUnit, provenance: BackendProvenance)
Energy plus analytical parameter gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
energy
|
float
|
Energy value. |
required |
gradient
|
ndarray
|
|
required |
unit
|
EnergyUnit
|
Canonical energy unit borne by |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
CoordinateGradientResult
dataclass
¶
CoordinateGradientResult(gradient: ndarray, unit: CoordinateGradientUnit, provenance: BackendProvenance)
Reference Cartesian coordinate gradient in Hartree/Bohr.
HessianJacobianResult
dataclass
¶
HessianJacobianResult(hessian: ndarray, jacobian: ndarray, unit: HessianUnit, provenance: BackendProvenance)
Hessian plus its analytical parameter Jacobian.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hessian
|
ndarray
|
|
required |
jacobian
|
ndarray
|
|
required |
unit
|
HessianUnit
|
Canonical Hessian unit borne by both. |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
BatchedEnergyResult
dataclass
¶
BatchedEnergyResult(energies: ndarray, unit: EnergyUnit, provenance: BackendProvenance)
Energies for a batch of parameter vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
energies
|
ndarray
|
|
required |
unit
|
EnergyUnit
|
Canonical energy unit. |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
BatchedHessianResult
dataclass
¶
BatchedHessianResult(case_ids: tuple[str, ...], hessians: ndarray, unit: HessianUnit, provenance: BackendProvenance)
Cartesian Hessians for a batch of topology-compatible cases.
Produced by a typed batch object (e.g. PreparedJaxBatch) evaluated for
one full parameter vector. Each row corresponds to one prepared case, in
the same order as :attr:case_ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
case_ids
|
tuple[str, ...]
|
Stable case IDs, one per batched case (order matches rows). |
required |
hessians
|
ndarray
|
|
required |
unit
|
HessianUnit
|
Canonical Hessian unit. |
required |
provenance
|
BackendProvenance
|
Producing backend. |
required |
PreparedBackend
¶
Bases: Protocol
One prepared session for one stable training case.
A prepared session owns its molecule, base force field, parameter layout,
and any reusable native state. Evaluation requests carry validated full
parameter vectors/matrices; the session never accepts a ForceField or a
native handle across the boundary. Any operation not declared in
:attr:info raises :class:UnsupportedCapabilityError.
energy
¶
energy(request: EnergyRequest | ReferenceEnergyRequest) -> EnergyResult
minimize
¶
minimize(request: MinimizationRequest) -> GeometryResult
optimize_geometry
¶
optimize_geometry(request: ReferenceGeometryOptimizationRequest) -> GeometryResult
hessian
¶
hessian(request: HessianRequest | ReferenceHessianRequest) -> HessianResult
frequencies
¶
frequencies(request: FrequencyRequest | ReferenceFrequencyRequest) -> FrequencyResult
parameter_gradient
¶
parameter_gradient(request: ParameterGradientRequest) -> ParameterGradientResult
coordinate_gradient
¶
coordinate_gradient(request: ReferenceCoordinateGradientRequest) -> CoordinateGradientResult
hessian_parameter_jacobian
¶
hessian_parameter_jacobian(request: HessianJacobianRequest) -> HessianJacobianResult
batched_energy
¶
batched_energy(request: BatchedEnergyRequest) -> BatchedEnergyResult
Backend
¶
Bases: Protocol
A backend factory that prepares per-case sessions.
A concrete backend exposes only :attr:info and :meth:prepare as its
generic surface (plus clearly backend-specific serialization/config where
unavoidable). All evaluation happens through the returned
:class:PreparedBackend.
prepare
¶
prepare(request: PreparationRequest) -> PreparedBackend
PreparedHessianBatch
¶
Bases: Protocol
A typed batch of topology-compatible prepared cases (Hessian batching).
The batch shares one compiled/native evaluation kernel internally while
each member case keeps its own coordinates/native state. Its only
evaluation surface is :meth:hessians, which takes a typed
:class:BatchedHessianRequest (one full parameter vector applied to every
member) and returns a typed :class:BatchedHessianResult.
case_ids
property
¶
Stable case IDs of the batched members, in result-row order.
hessians
¶
hessians(request: BatchedHessianRequest) -> BatchedHessianResult
HessianBatchPreparer
¶
Bases: Protocol
Optional backend surface that groups prepared sessions into batches.
A backend declaring :attr:Capability.BATCHED_HESSIAN must implement
this protocol. It groups topology-compatible prepared sessions into typed
:class:PreparedHessianBatch objects; the concrete grouping/compilation is
backend-specific and never crosses this boundary.
prepare_hessian_batches
¶
prepare_hessian_batches(sessions: Sequence[PreparedBackend]) -> list[PreparedHessianBatch]
AbstractPreparedBackend
¶
AbstractPreparedBackend(*, info: BackendInfo, case_id: str, molecule: Molecule, force_field: ForceField | None, layout: ParameterLayout | None)
Bases: ABC
Base that enforces capability, request-family, and vector validation.
Concrete prepared sessions override the _energy / _minimize / …
hooks for the capabilities they declare. The public methods verify the
capability is declared, that the request family matches the backend role,
that request parameter vectors have exactly len(layout) finite entries,
and that returned energy units match the role.
Source code in q2mm/backends/contracts.py
energy
¶
energy(request: EnergyRequest | ReferenceEnergyRequest) -> EnergyResult
Single-point energy in the backend's canonical unit.
Source code in q2mm/backends/contracts.py
minimize
¶
minimize(request: MinimizationRequest) -> GeometryResult
Energy-minimize (relax) the geometry (MM).
Source code in q2mm/backends/contracts.py
optimize_geometry
¶
optimize_geometry(request: ReferenceGeometryOptimizationRequest) -> GeometryResult
Geometry-optimize the reference structure.
Source code in q2mm/backends/contracts.py
hessian
¶
hessian(request: HessianRequest | ReferenceHessianRequest) -> HessianResult
Cartesian Hessian in Hartree/Bohr².
Source code in q2mm/backends/contracts.py
frequencies
¶
frequencies(request: FrequencyRequest | ReferenceFrequencyRequest) -> FrequencyResult
Vibrational frequencies in cm⁻¹.
Source code in q2mm/backends/contracts.py
parameter_gradient
¶
parameter_gradient(request: ParameterGradientRequest) -> ParameterGradientResult
Energy plus analytical parameter gradient (MM).
Source code in q2mm/backends/contracts.py
coordinate_gradient
¶
coordinate_gradient(request: ReferenceCoordinateGradientRequest) -> CoordinateGradientResult
Compute a reference Cartesian coordinate gradient in Hartree/Bohr.
Source code in q2mm/backends/contracts.py
hessian_parameter_jacobian
¶
hessian_parameter_jacobian(request: HessianJacobianRequest) -> HessianJacobianResult
Hessian plus its analytical parameter Jacobian (MM).
Source code in q2mm/backends/contracts.py
batched_energy
¶
batched_energy(request: BatchedEnergyRequest) -> BatchedEnergyResult
Energies for a batch of full parameter vectors (MM).
Source code in q2mm/backends/contracts.py
DependencyProbe
dataclass
¶
Cheap, side-effect-free availability probe for a backend.
Only importlib.util.find_spec (for Python modules) and
shutil.which (for executables) are used. No backend is constructed,
no device is enumerated, and no CUDA/XLA/OpenMM platform is initialized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
modules
|
tuple[str, ...]
|
Importable module names that must resolve. |
()
|
executables
|
tuple[str, ...]
|
Executable names that must be found on |
()
|
check
¶
Return (healthy, reason) without importing or constructing.
Source code in q2mm/backends/contracts.py
BackendDescriptor
dataclass
¶
BackendDescriptor(name: str, role: BackendRole, capability_ceiling: frozenset[Capability], functional_form_ceiling: frozenset[str], factory: str, probe: DependencyProbe = DependencyProbe(), backend_api_version: int = BACKEND_API_VERSION)
Validated, lazily-loadable description of a backend.
Static ceilings advertise what an installation may support without
importing it. A loaded backend's :class:BackendInfo is authoritative and
may declare any exact subset of those ceilings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Registry key (e.g. |
required |
role
|
BackendRole
|
Backend role. |
required |
capability_ceiling
|
frozenset[Capability]
|
Potential capabilities for any runtime instance. |
required |
functional_form_ceiling
|
frozenset[str]
|
Potential functional forms for any runtime instance. |
required |
factory
|
str
|
Import string |
required |
probe
|
DependencyProbe
|
Cheap dependency probe used for listing only. |
DependencyProbe()
|
backend_api_version
|
int
|
Backend API version this descriptor targets. |
BACKEND_API_VERSION
|
is_available
¶
load
¶
load(**kwargs: object) -> Backend
Import the factory and construct the backend.
This is the only place that triggers a real import of the backend
module. The probe is not consulted here — explicit configuration
(e.g. an explicit Tinker directory) must be honoured even when a
generic PATH probe is unhealthy. The constructor is responsible for
raising typed :class:BackendUnavailableError /
:class:BackendConfigurationError when the backend truly cannot run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
object
|
Forwarded to the factory callable. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Backend |
Backend
|
The constructed, validated backend. |
Raises:
| Type | Description |
|---|---|
BackendUnavailableError
|
If the backend module cannot be imported or the backend reports itself unavailable. |
BackendConfigurationError
|
If the factory attribute is missing, construction fails, or the runtime info disagrees with the static descriptor info. |
Source code in q2mm/backends/contracts.py
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 | |
BackendStatus
dataclass
¶
BackendStatus(descriptor: BackendDescriptor, healthy: bool, reason: str)
Explicit health report for one descriptor in the catalog.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
descriptor
|
BackendDescriptor
|
The described backend. |
required |
healthy
|
bool
|
Whether the cheap probe passed. |
required |
reason
|
str
|
Human-readable reason when |
required |
readonly_array
¶
Return a contiguous, read-only copy of values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
object
|
Anything array-like. |
required |
dtype
|
DTypeLike
|
Target dtype (default |
float
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A read-only defensive copy. |
Source code in q2mm/backends/contracts.py
prepare_hessian_batches
¶
prepare_hessian_batches(backend: Backend, sessions: Sequence[PreparedBackend]) -> list[PreparedHessianBatch]
Capability-first, backend-neutral entry to batched-Hessian preparation.
This is the only surface callers (e.g. the objective function) should use to batch Hessians. It is fully backend-agnostic: it checks the declared capability and the batch-preparer protocol, delegates grouping to the backend, and validates the returned batch objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Backend
|
The backend to batch with. |
required |
sessions
|
Sequence[PreparedBackend]
|
Prepared sessions to group (must be topology-compatible subsets as the backend defines). |
required |
Returns:
| Type | Description |
|---|---|
list[PreparedHessianBatch]
|
list[PreparedHessianBatch]: Validated typed batch objects. |
Raises:
| Type | Description |
|---|---|
UnsupportedCapabilityError
|
If the backend does not declare
:attr: |
BackendConfigurationError
|
If the backend declares the capability but
does not implement :class: |