SQD API¶
The SQD API is optional. Install it with uv sync --frozen --extra sqd.
Configuration and result contracts remain importable without the optional
sampling backend. Workflow functions load on access when the environment contains
ffsim and qiskit-addon-sqd.
Public Workflows¶
- q2m3.sqd.orchestrator.run_sqd(symbols, coordinates, *, active_electrons, active_orbitals, charge=0, basis='sto-3g', lucj=None, reference=None, mm_charges=None, mm_coords=None, embedding_mode='diagonal', seed=0, allow_large=False, verbose=True, mode='full')[source]¶
Run SQD from geometry in Angstrom with an explicit closed-shell active space.
- Parameters:
symbols (list[str]) – Atomic element symbols.
coordinates (ndarray) – Atomic coordinates in Angstrom.
active_electrons (int) – Even active electron count.
active_orbitals (int) – Active spatial orbital count.
charge (int) – Molecular charge.
basis (str) – PySCF basis name.
lucj (LUCJConfig | None) – Ansatz and sampling configuration.
reference (ReferenceConfig | None) – Baseline policy and shared run resource budgets.
mm_charges (ndarray | None) – Optional point charges in atomic charge units.
mm_coords (ndarray | None) – Point-charge positions in Angstrom.
embedding_mode (Literal['diagonal', 'full_oneelectron']) – Fixed-frame one-electron embedding treatment.
seed (int) – Nonnegative seed forwarded to all stochastic operations.
allow_large (bool) – Forward soft-policy override where supported. Existing component/model caps remain in force, including 8192 MB.
verbose (bool) – Print a compact energy/status summary.
mode (Literal['full', 'reference_only']) – Full SQD or explicitly requested reference-only calculation.
- Returns:
Validated immutable energies, metadata and resource/timing audit.
- Raises:
ValueError – Inputs or execution environment are unsupported.
ResourceLimitError – Allocation or observed process RSS reaches a cap.
ReferenceTimeoutError – The total shared deadline expires.
- Return type:
- q2m3.sqd.orchestrator.run_sqd_from_integrals(h1, h2, e_core, *, norb, nelec, context, seed_data, lucj=None, reference=None, seed=0, allow_large=False, mode='full')[source]¶
Run the same workflow from real chemist integrals and authenticated provenance.
- Parameters:
h1 (ndarray) – Real one-electron integrals in Hartree.
h2 (ndarray) – Real chemist two-electron tensor, without any additional transposition.
e_core (float) – Core constant in Hartree, already including embedding corrections.
norb (int) – Active spatial orbital count.
nelec (tuple[int, int]) – Balanced alpha/beta electron counts.
context (IntegralContext) – Integral/frame identifiers and constant decomposition.
seed_data (CCSDSeed | None) – Same-frame CCSD seed. Use None only in reference-only mode.
lucj (LUCJConfig | None) – Ansatz and sampling configuration.
reference (ReferenceConfig | None) – Baseline policy and total shared resource budgets.
seed (int) – Nonnegative run seed.
allow_large (bool) – Forward supported overrides within existing component caps.
mode (Literal['full', 'reference_only']) – Full SQD or explicit reference-only calculation.
- Returns:
Validated immutable result, using exactly one copy of e_core in energies.
- Raises:
ValueError – The declared integral contract is invalid.
ResourceLimitError – Predicted or actual resources exceed the budget.
ReferenceTimeoutError – The total shared deadline expires.
- Return type:
Configuration Contracts¶
- class q2m3.sqd.LUCJConfig(n_reps=2, shots=100000, interaction_pairs=None)[source]¶
Spin-balanced ansatz and sampling configuration.
- Parameters:
n_reps (int)
shots (int)
interaction_pairs (tuple[tuple[tuple[int, int], ...] | None, ...] | None)
- class q2m3.sqd.ReferenceConfig(wall_budget_s=900.0, rss_budget_mb=8192.0, allowed_tiers=('T0', 'T1', 'T1+', 'T2'), plugins=(), sci_cutoffs=(0.0001, 1e-05))[source]¶
Reference solver budgets, allowed tiers, and ordered optional plugins.
- Parameters:
wall_budget_s (float)
rss_budget_mb (float)
allowed_tiers (tuple[Literal['T0', 'T1', 'T1+', 'T2'], ...])
plugins (tuple[str, ...])
sci_cutoffs (tuple[float, float])
- class q2m3.sqd.SQDConfig(molecule, lucj=<factory>, reference=<factory>, embedding_mode='diagonal', seed=0, allow_large=False, mode='full')[source]¶
SQD run configuration. The molecule retains its existing mutable semantics.
- Parameters:
molecule (MoleculeConfig)
lucj (LUCJConfig)
reference (ReferenceConfig)
embedding_mode (Literal['diagonal', 'full_oneelectron'])
seed (int)
allow_large (bool)
mode (Literal['full', 'reference_only'])
- class q2m3.sqd.IntegralContext(frame_id, hamiltonian_id, active_indices, n_core_orbitals, vacuum_core_constant, delta_core_constant, embedding_mode, fixed_mo, two_electron_tensor_fixed, hf_reference_kind, source)[source]¶
Immutable metadata describing the supplied fixed orbital Hamiltonian.
- Parameters:
frame_id (str)
hamiltonian_id (str)
active_indices (tuple[int, ...])
n_core_orbitals (int)
vacuum_core_constant (float)
delta_core_constant (float)
embedding_mode (Literal['vacuum', 'diagonal', 'full_oneelectron'])
fixed_mo (bool)
two_electron_tensor_fixed (bool)
hf_reference_kind (Literal['canonical_rhf', 'fixed_frame_determinant'])
source (Mapping[str, Any])
- class q2m3.sqd.CCSDSeed(t1, t2, hf_energy, ccsd_energy, converged, residual_max_abs_ha, frame_id, hamiltonian_id, solver, solver_version)[source]¶
Copied read-only RCCSD amplitudes and declared solver provenance.
- Parameters:
t1 (ndarray)
t2 (ndarray)
hf_energy (float)
ccsd_energy (float)
converged (bool)
residual_max_abs_ha (float)
frame_id (str)
hamiltonian_id (str)
solver (str)
solver_version (str)
Result Contracts¶
See SQD result fields for field units and absence rules.
- class q2m3.sqd.SQDResult(schema_version, status, sqd_energy, hf_energy, hf_reference_kind, baseline_energy, iso_active_space_ccsd_energy, iso_ndet_sci_energy, iso_ndet_random_energy, baseline_tier, baseline_method, baseline_uncertainty_mHa, baseline_uncertainty_kind, baseline_downgrade_reason, baseline_untrustworthy, baseline_t1_residual, t1_diagnostic, t2_diagnostics, reference_attempts, delta_mHa, delta_vs_sci_mHa, ratio_sqd_over_sci, unique_dets_vs_shots, active_space, n_reps, shots, seed, subspace_dim, subspace_dims, full_ci_dim, embedding_mode, two_electron_tensor_fixed, fixed_mo, backend, versions, diagnostics, provenance, timings_s, null_reasons, warnings)[source]¶
Complete SQD report, with absent work represented by None and a reason.
- Parameters:
schema_version (Literal['sqd.result.v1'])
status (Literal['completed', 'reference_only'])
sqd_energy (float | None)
hf_energy (float)
hf_reference_kind (str)
baseline_energy (float)
iso_active_space_ccsd_energy (float | None)
iso_ndet_sci_energy (float | None)
iso_ndet_random_energy (float | None)
baseline_tier (Literal['T0', 'T1', 'T1+', 'T2'])
baseline_method (str)
baseline_uncertainty_mHa (float | None)
baseline_uncertainty_kind (str)
baseline_downgrade_reason (str | None)
baseline_untrustworthy (bool)
baseline_t1_residual (T1Residual | None)
t1_diagnostic (float | None)
t2_diagnostics (T2Diagnostics | None)
reference_attempts (tuple[ReferenceAttempt, ...])
delta_mHa (float | None)
delta_vs_sci_mHa (float | None)
ratio_sqd_over_sci (float | None)
unique_dets_vs_shots (tuple[tuple[int, int], ...] | None)
active_space (tuple[int, int])
n_reps (int | None)
shots (int | None)
seed (int)
subspace_dim (int | None)
subspace_dims (tuple[int, int] | None)
full_ci_dim (int)
embedding_mode (str)
two_electron_tensor_fixed (bool)
fixed_mo (bool)
backend (str | None)
versions (Mapping[str, str])
diagnostics (Mapping[str, Any])
provenance (Mapping[str, Any])
timings_s (Mapping[str, float | None])
null_reasons (Mapping[str, str])
warnings (tuple[str, ...])
- class q2m3.sqd.ReferenceResult(energy, tier, method, uncertainty_mHa, uncertainty_kind, uncertainty_reason, downgrade_reason, t1_residual, t2, untrustworthy, hamiltonian_id, frame_id, attempts, warnings)[source]¶
A reference energy with explicit uncertainty and execution provenance.
- Parameters:
energy (float)
tier (Literal['T0', 'T1', 'T1+', 'T2'])
method (str)
uncertainty_mHa (float | None)
uncertainty_kind (Literal['exact_active_space', 'solver_estimate', 'unknown'])
uncertainty_reason (str | None)
downgrade_reason (str | None)
t1_residual (T1Residual | None)
t2 (T2Diagnostics | None)
untrustworthy (bool)
hamiltonian_id (str)
frame_id (str)
attempts (tuple[ReferenceAttempt, ...])
warnings (tuple[str, ...])
- class q2m3.sqd.ReferenceAttempt(tier, method, outcome, reason, wall_s, peak_rss_mb)[source]¶
One auditable reference selection or execution outcome.
- Parameters:
tier (Literal['T0', 'T1', 'T1+', 'T2'])
method (str)
outcome (Literal['selected', 'disabled', 'unavailable', 'out_of_domain', 'over_budget', 'timeout', 'success'])
reason (str | None)
wall_s (float)
peak_rss_mb (float | None)
- class q2m3.sqd.T1Residual(loose_cutoff, tight_cutoff, loose_energy, tight_energy, loose_residual_mHa, reason)[source]¶
Adjacent-cutoff residual, attributed to the looser executed point.
- Parameters:
loose_cutoff (float | None)
tight_cutoff (float)
loose_energy (float | None)
tight_energy (float)
loose_residual_mHa (float | None)
reason (str | None)
- class q2m3.sqd.T2Diagnostics(t1_diagnostic, ccsd_converged, triples_correction_ha, ccsd_correlation_energy_ha, triples_ratio, high_t1, ccsd_not_converged, high_triples, ratio_reason)[source]¶
Independent coupled-cluster reliability flags for a T2 baseline.
- Parameters:
t1_diagnostic (float)
ccsd_converged (bool)
triples_correction_ha (float)
ccsd_correlation_energy_ha (float)
triples_ratio (float | None)
high_t1 (bool)
ccsd_not_converged (bool)
high_triples (bool)
ratio_reason (str | None)
Authenticated Integral Assembly¶
These lower-level producers create the provenance records required by
run_sqd_from_integrals. The integral tensor uses real chemist ordering.
The solver adds e_core exactly once.
- class q2m3.sqd.integrals.IntegralData(h1, h2, e_core, norb, nelec, mo_coeff, hf_energy, context)[source]¶
Immutable chemist Hamiltonian, complete MO snapshot and its provenance.
hf_energyis the expectation of the firstnelec[0]active orbitals, including e_core. It is not a relaxed-MM SCF minimum. No CCSD amplitudes are constructed here. Downstream seed solvers must consume this same Hamiltonian.- Parameters:
h1 (ndarray)
h2 (ndarray)
e_core (float)
norb (int)
nelec (tuple[int, int])
mo_coeff (ndarray)
hf_energy (float)
context (IntegralContext)
- q2m3.sqd.integrals.build_integrals(molecule, *, mm_charges=None, mm_coords=None, embedding_mode='diagonal', host_available_mb, rss_budget_mb=8192.0, allow_large=False)[source]¶
Build a guarded molecular Hamiltonian in its one vacuum RHF frame.
- Parameters:
molecule (MoleculeConfig) – Molecular geometry in Angstrom and explicit closed-shell space.
mm_charges (ndarray | None) – Optional nonempty point-charge array in elementary charges.
mm_coords (ndarray | None) – Corresponding coordinates in Angstrom.
embedding_mode (Literal['diagonal', 'full_oneelectron']) – Diagonal or full active-space one-electron perturbation.
host_available_mb (float) – Executor’s conservative whole-run memory cap in decimal MB.
rss_budget_mb (float) – User’s whole-run memory cap in decimal MB.
allow_large (bool) – Override only the standard soft resource rejection boundary.
- Returns:
Read-only integrals/MOs and same-frame HF expectation with provenance.
- Raises:
ValueError – Malformed inputs, missing helper frame, or invalid integrals.
RuntimeError – RHF did not converge.
ResourceLimitError – The pre-allocation estimate reaches the run cap.
ResourceModelDomainError – Real-AO work is outside the bounded inventory.
- Return type:
An external process-tree RSS monitor and wall timeout are required. Molecular basis metadata is built first to count AOs. The inventory guard then runs before any RHF or integral transformation. Its estimate is recorded in source and does not certify the later sampling/reference stages or arbitrary hosts.
- q2m3.sqd.integrals.hamiltonian_id(h1, h2, e_core, *, norb, nelec)[source]¶
Hash actual integrals using the
q2m3.hamiltonian.v1byte format.The digest starts with the version and NUL, then compact ASCII JSON
[norb,[nalpha,nbeta]]and NUL. Each h1, h2, e_core field has a compact[name,shape,"<f8"]JSON header and NUL, followed by little-endian float64 C-order bytes. e_core is a scalar with shape []. No labels enter the digest.- Parameters:
h1 (ndarray) – Real one-electron matrix in Hartree.
h2 (ndarray) – Real chemist two-electron tensor in Hartree.
e_core (float) – Core plus nuclear constant in Hartree.
norb (int) – Active spatial orbital count.
nelec (tuple[int, int]) – Balanced spin populations.
- Returns:
Lowercase SHA256 hex digest, invariant to storage order and endianness.
- Raises:
ValueError – Shape, spin populations, or real/finite representation is invalid.
- Return type:
str
- q2m3.sqd.ansatz.build_ccsd_seed(data, *, host_available_mb, rss_budget_mb=8192.0, allow_large=False, max_cycle=200)[source]¶
Solve RCCSD in the supplied fixed frame without rerunning SCF.
- Parameters:
data (IntegralData) – Immutable Hamiltonian and complete molecular-frame source.
host_available_mb (float) – Executor whole-run cap in decimal MB.
rss_budget_mb (float) – User whole-run cap in decimal MB.
allow_large (bool) – Override only the resource soft boundary.
max_cycle (int) – Iteration bound, 0..200. Zero exercises convergence refusal.
- Returns:
Converged read-only amplitudes with independently verified Ha residual.
- Raises:
CCSDConvergenceError – Iterations fail or the physical residual is unacceptable.
ProvenanceMismatchError – Supplied Hamiltonian/frame/energy is inconsistent.
ResourceLimitError – Inventory guard refuses allocation.
- Return type:
- q2m3.sqd.ansatz.build_ccsd_seed_from_integrals(h1, h2, e_core, *, norb, nelec, context, host_available_mb, rss_budget_mb=8192.0, allow_large=False, max_cycle=200)[source]¶
Solve fixed-frame RCCSD from the low-level integral contract.
Only the Hamiltonian hash of
contextis recomputed from the arrays. The frame digest is not reconstructed, so the caller is responsible for theframe_idbinding betweencontextand the integrals.- Parameters:
h1 (ndarray) – Real one-electron integrals in the declared frame.
h2 (ndarray) – Real chemist two-electron tensor in the declared frame.
e_core (float) – Same-Hamiltonian core constant in Hartree.
norb (int) – Active spatial orbital count.
nelec (tuple[int, int]) – Balanced spin populations.
context (IntegralContext) – Frame and Hamiltonian provenance. The source may be empty.
host_available_mb (float) – Executor whole-run cap in decimal MB.
rss_budget_mb (float) – User whole-run cap in decimal MB.
allow_large (bool) – Override only the resource soft boundary.
max_cycle (int) – Iteration bound, 0..200. Zero exercises convergence refusal.
- Returns:
Converged read-only amplitudes carrying the context identifiers.
- Raises:
CCSDConvergenceError – Iterations fail or the physical residual is unacceptable.
ProvenanceMismatchError – Integrals disagree with the context Hamiltonian hash.
ResourceLimitError – Inventory guard refuses allocation.
- Return type:
Result Transport¶
These functions encode frozen SQD records as tagged tuples that pickle without custom reducers, and rebuild them in another process.
- q2m3.sqd.transport.encode_result(value)[source]¶
Encode a value as nested tagged tuples that pickle without custom reducers.
Dataclass records become
("record", module, name, fields). Mappings, including read-only snapshots, become plain dictionaries, so the record constructor must freeze them again on decode.- Parameters:
value (Any) – A dataclass record, mapping, tuple, list or plain value.
- Returns:
The tagged encoding of
value.- Return type:
tuple
- q2m3.sqd.transport.decode_result(value, *, cancelled=None)[source]¶
Rebuild a value encoded by
encode_result().Records are rebuilt through their constructors, so their validation runs again. Only record types defined under
q2m3.sqd.are rebuilt. This limits which types can be constructed; it does not make untrusted payloads safe. Callers must only unpickle payloads that the parent process wrote to its own private directory or pipe.SQDConfigcannot be decoded: itsmoleculefield is aq2m3.molecule.MoleculeConfig.- Parameters:
value (tuple) – The tagged encoding.
cancelled (Event | None) – Flag checked before each node is rebuilt.
- Returns:
The rebuilt value.
- Raises:
ReferenceTimeoutError – If
cancelledis set during reconstruction.ValueError – If a record type is defined outside
q2m3.sqd..
- Return type:
Any
Resource Policy¶
- q2m3.sqd.resources.estimate_rss_mb(norb, nelec, *, stage, subspace_dims=None, retained_mb=0.0, solver_method=None, model)[source]¶
Estimate total simultaneously resident memory for one serial stage.
- Parameters:
norb (int) – Active spatial orbitals.
nelec (tuple[int, int]) – Balanced alpha/beta populations.
stage (Literal['integrals', 'ccsd', 'prepare', 'sample', 'diagonalize', 'reference', 'comparison']) – Operation about to allocate memory.
subspace_dims (tuple[int, int] | None) – Candidate spin-sector sizes, required for fixed spaces.
retained_mb (float) – Additional live inputs outside the model’s workload inventory.
solver_method (str | None) – Required reference solver identity.
model (ResourceModel) – Versioned model already checked against its runtime environment.
- Returns:
Finite decimal MB, including imports, workspace and retained inputs.
- Raises:
ValueError – Malformed counts or retained memory.
ResourceModelDomainError – Missing dimensions, unsupported stage or invalid bound.
- Return type:
float
- q2m3.sqd.resources.guard_allocation(norb, nelec, *, stage, model, host_available_mb, subspace_dims=None, retained_mb=0.0, solver_method=None, rss_budget_mb=None, allow_large=False)[source]¶
Reject an unsafe operation before allocating its working space.
- Parameters:
norb (int) – Active spatial orbitals.
nelec (tuple[int, int]) – Balanced alpha/beta populations.
stage (Literal['integrals', 'ccsd', 'prepare', 'sample', 'diagonalize', 'reference', 'comparison']) – Stage about to run.
model (ResourceModel) – Applicable empirical model.
host_available_mb (float) – Conservative total run cap supplied by the executor.
subspace_dims (tuple[int, int] | None) – Actual candidates, or a proven pre-call dimension bound.
retained_mb (float) – Additional simultaneously live memory outside the inventory.
solver_method (str | None) – Reference solver identity, when applicable.
rss_budget_mb (float | None) – Optional user cap. An override never bypasses this cap.
allow_large (bool) – Permit estimates above the default soft rejection boundary.
- Returns:
The checked estimate in decimal MB.
- Raises:
ResourceLimitError – Estimate reaches any applicable rejection boundary.
ResourceModelDomainError – No applicable bound exists, even with override.
- Return type:
float
- q2m3.sqd.resources.load_resource_model(path=None, *, versions=None, profile=None)[source]¶
Load a validated model and reject incompatible dependencies or workload.
- Parameters:
path (str | Path | None) – Calibration artifact. Defaults to the shipped coefficient file.
versions (Mapping[str, str] | None) – Exact explicit manifest, or installed distribution versions. Only absent optional Catalyst is accepted when inspecting the installation. An installed Catalyst version must still match the calibration.
profile (Mapping[str, object] | None) – Workload overrides to check against the artifact’s bounded profile.
- Returns:
An immutable model. Executors must honor the recorded live-array schedule, solver settings and profile. Arbitrary geometry/AO-basis work is not covered.
- Raises:
ResourceModelDomainError – Missing artifact, unvalidated model or runtime mismatch.
- Return type:
CalibratedResourceModel
Exceptions¶
Typed SQD failures shared by optional numerical backends.
- exception q2m3.sqd.exceptions.ResourceLimitError[source]¶
Bases:
RuntimeErrorA run exceeds its allowed resource budget.
- exception q2m3.sqd.exceptions.ResourceModelDomainError[source]¶
Bases:
ResourceLimitErrorNo calibrated resource bound applies to the requested operation.
- exception q2m3.sqd.exceptions.CCSDConvergenceError[source]¶
Bases:
RuntimeErrorThe ansatz seed did not converge.
Bases:
RuntimeErrorNo permitted reference solver can supply a baseline.
Bases:
RuntimeErrorAn optional reference solver is unavailable.
- exception q2m3.sqd.exceptions.ReferenceTimeoutError[source]¶
Bases:
TimeoutErrorA reference solve exhausted its time budget.
- exception q2m3.sqd.exceptions.ReferenceNumericalError[source]¶
Bases:
RuntimeErrorA reference solve failed its numerical acceptance checks.
- exception q2m3.sqd.exceptions.SamplingIntegrityError[source]¶
Bases:
RuntimeErrorSamples violate the sampling contract.
Bases:
RuntimeErrorA required matched comparison cannot be produced.