Skip to content

Quantum API Reference

This reference is generated from the public docstrings of quantsmind.quantum and matches the frozen surface in api_manifest.json (117 modules, 669 public symbols) — QuantsMind Quantum 1.0.0 — Stable.

quantum

QuantsMind Quantum — domain-intelligence layer.

quantsmind.quantum is not a quantum computing engine. It is the domain-intelligence layer of the QuantsMind SDK that connects QuantsMind's scientific and domain abstractions to the MicroQuantum quantum SDK.

The dependency direction is always::

Domain Systems -> QuantsMind Quantum -> MicroQuantum

MicroQuantum never imports QuantsMind.

Architecture (QMQ-01 + QMQ-02 + QMQ-03)

  • core — domain objects: QuantumProblem, Variable, Objective, Constraint, DomainContext, ProblemSolution.
  • formulation — structural problem representations: MathematicalModel, OptimizationModel, GraphModel, MLModel, SimulationModel, StatisticalModel; plus :func:formulate and :func:model_from_dict.
  • strategy — computation strategy selection: ComputationStrategy enum + deterministic StrategySelector (QMQ-01 size rules; QMQ-03 reasoned path select_reasoned).
  • intelligence — QMQ-03 algorithm & computational strategy intelligence: ProblemClassifier, FormulationRecommender, AlgorithmSelector + AlgorithmRegistry, CapabilityModel and ComputationPlan.
  • mapping — program -> runtime object: QuantumCircuitMapper (real MicroQuantum path); ProblemMapper / QUBOMapper / IsingMapper implement the automatic problem -> QUBO -> Ising pipeline.
  • optimization — QMQ-02 mathematical formulation: symbolic expressions, QUBOModel, IsingModel, constraint penalties and the classical exhaustive baseline.
  • workflow — end-to-end pipeline: QuantumWorkflow (QMQ-04 adds execution options, a lifecycle state machine and deterministic hybrid comparison/selection).
  • execution — QMQ-04 executors: ClassicalExecutor, QuantumExecutor, HybridExecutor + ExecutionComparison and the typed failure taxonomy (WorkflowError, MicroQuantumUnavailableError, ...).
  • result — domain-level solution artifacts: SolutionReport, Interpretation + Provenance, and QMQ-06 structured result interpretation (ResultInterpreter / ResultInterpretation); low-level QuantumResult lives in :mod:quantsmind.quantum.circuit_result.
  • integration — MicroQuantum facade: lazy require_microquantum, microquantum_available, resolve_backend, and the QMQ-02 QAOA delegation (run_qaoa).
  • finance — QMQ-07/08 Finance domain foundation. QMQ-07 ships Asset / AssetUniverse / FinancialProblem / FinancialContext / RiskMatrix / Budget / allocation weights, financial constraints and objectives, the FinanceFormulationAdapter (finance -> existing QMQ formulation) and deterministic asset <-> variable mapping with solution decoding. QMQ-08 builds the portfolio layer on top: PortfolioOptimizationProblem, PortfolioMetrics, PortfolioComponent / PortfolioSolution / PortfolioOptimizationResult and PortfolioOptimizer (runs the existing workflow/benchmark/interpretation pipeline; binary selection is fully supported, continuous allocation is validated/formulated but the binary-only QUBO pipeline surfaces honest errors instead of approximating, integer allocation raises validation errors). Works entirely from supplied data, never live feeds.
  • data — QMQ-09 Data Intelligence foundation. DataFeature / DataRecord / DataSet / FeatureVector observations, distance & similarity primitives, pairwise DataRelationship builders and deterministic DataQualityReport assessment; feature-selection objectives/constraints and clustering as a real quadratic binary QUBO; the DataProblem type, DataFormulationAdapter (data -> existing QMQ formulation), deterministic DataMapper decoding, DataMetrics, DataSolution and DataOptimizer (runs the existing workflow/benchmark/interpretation pipeline). Works entirely from supplied/synthetic data — no ML framework, no live data.
  • ml — QMQ-10 AI/ML Intelligence foundation. MLFeature / MLRecord / MLDataSet observations with targets, least-squares classification/regression objectives over binary coefficients, one-hot model-selection and per-parameter hyperparameter objectives, and ML constraint families; the MLProblem type, MLFormulationAdapter (ml -> existing QMQ formulation; feature selection and clustering are fully delegated to the QMQ-09 Data layer), deterministic MLMapper decoding, MLMetrics, ML domain ClassificationSolution / RegressionSolution / ModelSelectionSolution / HyperparameterSolution and the MLOptimizer (runs the existing workflow/benchmark/interpretation pipeline). Works entirely from supplied data — no ML framework dependencies, scikit-learn and friends are never required.

Importing this package never requires microquantum to be installed. MicroQuantum is only imported lazily when a quantum execution API is called.

BaselineConfig dataclass

Configuration of the classical baseline (QMQ-05 §4/§8).

The baseline reuses the QMQ-02/04 exact exhaustive solver — no second classical solver exists. kind is fixed to "classical" until the SDK adds another baseline; only that kind is honoured.

Benchmark dataclass

Definition of one benchmark (QMQ-05 §4).

A benchmark is a reusable, serializable recipe: the problem to solve, the strategy to run (defaulting to the problem's preferred strategy), optional algorithm/execution options, the classical baseline configuration, an optional known optimum, and free-form metadata.

resolved_strategy property

Strategy of the benchmark (its own, else the problem's preferred).

strategy_label property

Serialized strategy label of :attr:resolved_strategy.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Benchmark from :meth:to_dict output.

BenchmarkComparison dataclass

Benchmark strategy outcome vs the classical baseline (QMQ-05 §9/§12/§13).

Fields

strategy: Strategy label that was benchmarked. baseline: Baseline label ("classical"). sense: Sense used for ranking ("minimize"/"maximize"). winner: Result classification. objective_delta: Normalized objective delta (strategy - baseline), positive means the strategy outcome is better. strategy_status: "executed" / "failed" / "skipped". baseline_status: Same for the baseline. selected_reason: Human-readable justification. metadata: Free-form (e.g. the QMQ-04 hybrid leg comparison dict).

build(*, strategy, strategy_metrics, baseline_metrics, sense=ObjectiveSense.MINIMIZE, strategy_status='executed', baseline_status='executed', metadata=None) classmethod

Classify a strategy outcome against the classical baseline.

Deterministic policy (QMQ-05 §12/§13):

  1. feasible beats unknown beats infeasible;
  2. both feasible (or both unknown): better normalized objective wins (per sense; energy fallback, lower always better);
  3. both infeasible: fewer constraint violations wins, then objective;
  4. exact equalities are a TIE;
  5. a missing strategy/baseline outcome, a disabled baseline, or a missing objective/energy produces NO_COMPARABLE_RESULT.

A strictly better strategy outcome is classified on the strategy (classical -> CLASSICAL_WIN, quantum -> QUANTUM_WIN, hybrid -> HYBRID_WIN); a worse one is CLASSICAL_WIN.

build_none(*, strategy, sense, strategy_metrics, strategy_status, baseline_status, reason, metadata) classmethod

Build a NO_COMPARABLE_RESULT comparison.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

BenchmarkMetrics dataclass

Measured quality / performance / resource metrics (QMQ-05 §6/§7).

Missing information is None (or 0 for counts) — nothing is invented beyond what the execution layer actually reports.

from_execution(problem, execution, *, sense, reference_optimum=None, wall_clock_time=None, options=None, seed=None, backend='', optimizer='', microquantum_version='', num_qubits=None, status='executed', executions=1, retries=0) classmethod

Build metrics from a normalized QMQ-04 execution result.

execution may be a :class:ClassicalExecutionResult, :class:QuantumExecutionResult, or any leg exposing assignment/objective_value/energy/feasible. reference_optimum is the known optimum (or the baseline optimum) used for the gap/ratio; None leaves them unknown.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

BenchmarkResult dataclass

Serializable report of one benchmark run (QMQ-05 §16).

The in-memory object keeps a reference to the underlying :class:SolutionReport (composition, QMQ-05 §17); serialization carries only lightweight reference metadata — the full solution report is not duplicated inside the benchmark report.

to_dict()

Serialize to a JSON-safe dictionary (report kept as a reference).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

The :class:SolutionReport reference is intentionally not rebuilt (composition reference); all measured fields round-trip exactly.

BenchmarkRunner

Runs benchmarks and produces serializable :class:BenchmarkResult reports.

A runner holds no per-run state; it can be reused across benchmarks and suites. runs > 1 repeats a benchmark and aggregates the repetitions into a :class:BenchmarkRunSummary (QMQ-05 §14).

run(benchmark, *, runs=1, raise_on_error=False)

Run a benchmark once or several times.

Parameters:

Name Type Description Default
benchmark Benchmark

The benchmark definition to execute.

required
runs int

Number of repetitions (1 returns a single-run result).

1
raise_on_error bool

If True, a failing strategy run raises instead of being recorded as a failed run (used in tests/CI).

False

BenchmarkRunSummary dataclass

Aggregates of repeated benchmark runs (QMQ-05 §14).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a summary from :meth:to_dict output.

BenchmarkSuite dataclass

A named collection of benchmarks for reproducible evaluation (QMQ-05 §18).

benchmarks is keyed by benchmark_id so members are addressable and serializable. The canonical suite is produced by :func:quantsmind.quantum.benchmark.suite.default_suite.

ids property

Benchmark ids in registration order.

add(benchmark)

Register a benchmark (duplicate ids are rejected).

get(benchmark_id)

Return a benchmark by id.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a suite from :meth:to_dict output.

BenchmarkWinner

Bases: Enum

Classification of a benchmark run vs its classical baseline (QMQ-05 §13).

  • CLASSICAL_WIN — the classical baseline produced the better result.
  • QUANTUM_WIN — a quantum strategy produced the better result.
  • HYBRID_WIN — a hybrid strategy (its selected leg) produced the better result.
  • TIE — baseline and strategy tied after normalization.
  • NO_COMPARABLE_RESULT — no fair comparison was possible (the strategy leg did not execute, the baseline is disabled, or no comparable objective/energy existed).

These describe measured outcomes only; no "quantum advantage" claim is ever derived from a classification.

parse(value) classmethod

Coerce a label or member to a :class:BenchmarkWinner.

GateParamError

Bases: ValueError

Raised when a gate receives an unexpected number of parameters.

UnknownGateError

Bases: ValueError

Raised when a program references a gate MicroQuantum cannot build.

QuantumResult dataclass

Enriched result of a QuantsMind quantum experiment.

Parameters:

Name Type Description Default
native Any

The underlying MicroQuantum BackendResult.

required
experiment_id str

QuantsMind experiment identity.

''
program_name str

Name of the originating QuantumProgram.

''
domain_metadata dict[str, Any]

Domain metadata attached by the caller.

dict()
provenance dict[str, Any]

Execution provenance details.

dict()
created_at str

UTC ISO timestamp when this enrichment was created.

(lambda: isoformat())()

counts property

Measurement counts from the backend result.

statevector property

State vector from the backend result (when provided).

samples property

Raw samples from the backend result (when provided).

shots property

Number of shots executed.

backend_name property

Name of the backend that produced the result.

num_qubits property

Number of qubits in the executed circuit.

success property

Whether the backend reported success.

from_backend_result(result, *, experiment_id='', program_name='', domain_metadata=None, provenance=None) classmethod

Wrap a MicroQuantum BackendResult with QuantsMind context.

to_dict()

Serialize enrichment and underlying result to a JSON-safe dict.

Constraint dataclass

A constraint of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
expression Callable[[dict[str, Any]], float] | str | None

Callable(assignments) -> float, a symbolic string, or None.

None
operator ConstraintOperator

Comparison operator (<=, >=, ==).

LE
value float

RHS constant the expression is compared against.

0.0
priority ConstraintPriority

HARD or SOFT classification.

HARD
penalty float

Optional penalty weight applied when a SOFT constraint is violated (used by later formulation phases).

0.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the penalty is negative.

le(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a <= constraint.

ge(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a >= constraint.

eq(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create an == constraint.

compare(lhs)

Compare an evaluated expression against the constraint value.

evaluate(assignments)

Evaluate the constraint against variable assignments.

Constraints without an expression report :data:ConstraintStatus.UNKNOWN. Symbolic string (and expression-node) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild a Constraint from :meth:to_dict output.

ConstraintOperator

Bases: Enum

Relational operator of a constraint.

Attributes:

Name Type Description
LE

expression <= value

GE

expression >= value

EQ

expression == value

parse(value) classmethod

Coerce a symbol ("<=", ">=", "==") to an operator.

ConstraintPriority

Bases: Enum

Hard/soft classification of a constraint.

Attributes:

Name Type Description
HARD

Must be satisfied for a solution to be feasible.

SOFT

Desirable; violations may be traded via penalty.

parse(value) classmethod

Coerce "hard"/"soft" (or a member) to a priority.

ConstraintStatus

Bases: Enum

Evaluation status of a constraint against an assignment.

Attributes:

Name Type Description
SATISFIED

The constraint holds for the evaluated assignments.

VIOLATED

The constraint does not hold.

UNKNOWN

The constraint could not be evaluated (no expression).

DomainContext dataclass

Context in which a quantum domain problem exists.

Parameters:

Name Type Description Default
domain str

Top-level domain (e.g. "finance", "fraud", "energy").

required
subdomain str

Optional subdomain (e.g. "portfolio").

''
use_case str

Optional business/scientific use case.

''
context_metadata dict[str, Any]

Domain-specific business/scientific metadata.

dict()
units list[str]

Applicable measurement units (e.g. ["USD", "days"]).

list()
metadata dict[str, Any]

Free-form custom metadata.

dict()

Raises:

Type Description
ValueError

If domain is empty.

qualified()

Return "domain" or "domain/subdomain".

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DomainContext from :meth:to_dict output.

Objective dataclass

A scalar objective of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
sense ObjectiveSense

MINIMIZE or MAXIMIZE.

required
expression Expression

Callable(assignments) -> float, a symbolic string, or None.

None
weight float

Non-negative scaling weight used when objectives are combined.

1.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the weight is negative.

minimize(name, expression=None, *, weight=1.0) classmethod

Create a MINIMIZE objective.

maximize(name, expression=None, *, weight=1.0) classmethod

Create a MAXIMIZE objective.

evaluate(assignments)

Evaluate the objective against variable assignments.

Callable expressions are evaluated directly. Symbolic string (and :class:~quantsmind.quantum.optimization.expression.Expression) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

describe()

Return a human-readable description, e.g. "minimize cost".

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild an Objective from :meth:to_dict output.

ObjectiveSense

Bases: Enum

Optimisation sense of an objective.

Attributes:

Name Type Description
MINIMIZE

Prefer lower objective values (e.g. cost, risk, latency).

MAXIMIZE

Prefer higher objective values (e.g. return, throughput).

parse(value) classmethod

Coerce "min"/"max" (or a member) to :class:ObjectiveSense.

ProblemSolution dataclass

A domain-level solution to a :class:QuantumProblem.

Parameters:

Name Type Description Default
problem_name str

Name of the problem this solution satisfies.

''
assignments dict[str, Any]

Variable name -> assigned value.

dict()
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, ConstraintStatus]

Constraint name -> evaluation status.

dict()
score float | None

Optional combined, sense-aware score (higher is better).

None
feasible bool

Whether all constraints are satisfied (none violated).

False
metadata dict[str, Any]

Free-form solution metadata (backend, shots, ...).

dict()

from_names(problem_name, variable_names, objective_names, constraint_names) classmethod

Build an empty solution skeleton matching a problem's structure.

evaluate(problem)

Populate objective values and constraint status from assignments.

Only callable expressions participate (symbolic strings raise by design until QMQ-02 formulation support lands). Feasibility is recomputed from the resulting statuses.

is_feasible()

Return True when no constraint is violated (unknowns are benign).

compute_score(problem)

Weighted, sense-aware objective score (higher is better).

Maximizing objectives contribute weight * value; minimizing objectives contribute -weight * value. Returns None when no objective could be evaluated.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ProblemSolution from :meth:to_dict output.

QuantumProblem dataclass

A domain problem that a QuantsMind Quantum workflow can process.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
description str

Optional human-readable description.

''
domain DomainContext | str | None

Domain context, or a plain domain string coerced to one.

None
variables list[Variable]

Decision variables of the problem.

list()
objectives list[Objective]

Objectives to optimise.

list()
constraints list[Constraint]

Feasibility constraints.

list()
metadata dict[str, Any]

Free-form metadata (used by formulation detection, e.g. {"model_kind": "graph"} or {"encoding": {...}}).

dict()
formulation Any

Optional formulation model attached to the problem.

None
preferred_strategy Any

Optional preferred computation strategy (a :class:ComputationStrategy or its name).

None
provenance dict[str, Any]

Optional record of how the problem was assembled.

dict()

Raises:

Type Description
ValueError

If the name is empty or names repeat within a category.

variable_names property

Names of all variables.

objective_names property

Names of all objectives.

constraint_names property

Names of all constraints.

size property

Number of decision variables (the problem's effective size).

add_variable(variable)

Add a variable (duplicate names are rejected).

add_objective(objective)

Add an objective (duplicate names are rejected).

add_constraint(constraint)

Add a constraint (duplicate names are rejected).

variable(name)

Return the variable with the given name.

objective(name)

Return the objective with the given name.

constraint(name)

Return the constraint with the given name.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QuantumProblem from :meth:to_dict output.

Variable dataclass

A decision variable of a quantum domain problem.

Parameters:

Name Type Description Default
name str

Unique variable name within the problem.

required
type VariableType

Variable category (binary/integer/continuous/categorical).

CONTINUOUS
lower_bound int | float | None

Inclusive numeric lower bound for non-categorical types.

None
upper_bound int | float | None

Inclusive numeric upper bound for non-categorical types.

None
domain str

Optional namespace the variable belongs to (e.g. "asset").

''
description str

Optional human-readable explanation.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If bounds are inconsistent with the variable type.

binary(name, *, domain='', description='') classmethod

Create a 0/1 decision variable.

integer(name, lower_bound, upper_bound, *, domain='', description='') classmethod

Create an integer variable with inclusive bounds.

continuous(name, lower_bound=None, upper_bound=None, *, domain='', description='') classmethod

Create a real-valued variable with optional inclusive bounds.

categorical(name, *, domain='', description='') classmethod

Create a categorical variable (no numeric bounds).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Variable from :meth:to_dict output.

VariableType

Bases: Enum

Type of a decision variable.

Attributes:

Name Type Description
BINARY

0/1 decision variable.

INTEGER

Discrete integer variable (bounded).

CONTINUOUS

Real-valued variable.

CATEGORICAL

Discrete label variable with no numeric bounds.

parse(value) classmethod

Coerce a name or member to a :class:VariableType (e.g. "binary").

AssignmentConstraint dataclass

Bases: DataConstraint

Every record is assigned to exactly one cluster (sum_c z_i_c = 1).

ClusterCountConstraint dataclass

Bases: DataConstraint

Bound the number of records assigned to every cluster.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_records float

Minimum number of records per cluster (>= 0).

1.0
max_records float | None

Maximum number of records per cluster (None = unbounded).

None
description str

Free-form description.

''

ClusteringDistanceObjective dataclass

Bases: DataObjective

Minimize the total within-cluster pairwise distance.

The quadratic objective sum_cluster sum_{i<j} distance(i, j) * z_i_c * z_j_c runs over the pairwise relationships of the problem's dataset (supplied explicitly as problem.pairwise or computed from the Data context distance metric).

Parameters:

Name Type Description Default
name str

Objective name.

required
description str

Free-form description.

''

DataConstraint dataclass

Base class of all data constraints.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

DataContext dataclass

Data-domain context of a Data problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "feature_selection", "clustering", "analysis").

''
subdomain str

Domain subdomain (e.g. "tabular").

''
distance_metric str

One of :data:DISTANCE_METRICS used for pairwise relationships, similarity and clustering distance objectives.

'euclidean'
feature_weights dict[str, float]

Optional per-feature weights for the weighted Euclidean distance (feature name -> non-negative weight).

dict()
similarity_sigma float

Kernel width of the Gaussian similarity transform.

1.0
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

DataError

Bases: ValueError

Base error of the QuantsMind Quantum Data Intelligence layer.

DataFeature dataclass

One numeric feature/dimension of a :class:DataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
lower_bound float | None

Optional inclusive lower bound for valid values.

None
upper_bound float | None

Optional inclusive upper bound for valid values.

None
weight float

Optional non-negative weight (used by weighted distances and data quality).

1.0
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

allows(value)

Return whether value respects the optional feature bounds.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

DataFormulationAdapter

Converts data problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention for feature selection and the z{record}_{cluster} convention for clustering, objectives keep their senses, and every data constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a data problem (empty = valid).

raise_if_invalid(problem)

Raise :class:DataValidationError when the problem is invalid.

Raises:

Type Description
DataValidationError

If the problem fails validation.

data_metadata(problem) staticmethod

JSON-safe Data provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a data problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem DataProblem

The validated data problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
DataValidationError

If the data problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a data problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

cluster_variable_index(problem, record_index, cluster) classmethod

Return the flat QMQ index of the z{record}_{cluster} variable.

DataMapper dataclass

Maps a validated Data problem to a deterministic variable mapping.

Mirrors the :class:FinanceAssetMapper pattern: validates, then provides :meth:map (which returns a :class:DataMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

DataMapping dataclass

Deterministic mapping between Data variables and QMQ indices.

Created by :meth:DataMapper.map from a validated :class:DataProblem.

variable_names property

QMQ variable names in deterministic order.

feature_variable(feature_name)

Return the QMQ variable name for feature_name.

feature_index(feature_name)

Return the deterministic index of feature_name.

feature(variable_name)

Return the decoded feature for variable_name (or None).

cluster_variable(record_id, cluster_index)

Return the QMQ variable name for record_id and cluster_index.

cluster(record_index, cluster_index)

Return the decoded cluster assignment for the variable at the given indices.

cluster_of(assignments, record_id)

Return the cluster assigned to record_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

DataMetrics dataclass

Deterministic outcome metrics of a Data solve.

Attributes:

Name Type Description
problem_type str

Data problem family ("feature_selection" or "clustering").

selected_feature_count int

Number of selected features (FS).

selected_utility float

Total utility of the selected features (FS).

selection_cost float

Total cost of the selected features (FS).

net_objective float

Primary objective value (utility - penalty*cost for FS, total within-cluster distance for clustering).

cluster_count int

Number of non-empty clusters (clustering).

total_within_cluster_distance float | None

Total within-cluster pairwise distance (clustering).

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

DataObjective dataclass

Base class of all data objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

Data-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

DataOptimizationConfiguration dataclass

Execution/optimization configuration of a Data problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
DataValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

DataOptimizationResult dataclass

Result of a Data solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

DataOptimizer

Solves and benchmarks :class:DataProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Data adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the Data layer.

solve(problem, *, strategy=None, config=None)

Solve a Data problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.data.solution.DataSolution with data metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
DataValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a Data problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem DataProblem

The Data problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config DataOptimizationConfiguration | None

Optional execution/optimization configuration.

None

mapping(problem)

Return the deterministic Data variable mapping of a problem.

DataProblem dataclass

Domain problem of the Data Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset DataSet

The ordered dataset the problem operates on.

required
problem_type DataProblemType

Family (:attr:DataProblemType.FEATURE_SELECTION or :attr:DataProblemType.CLUSTERING).

FEATURE_SELECTION
objectives list[DataObjective]

Ordered list of data objectives (names must be unique).

list()
constraints list[DataConstraint]

Ordered list of data constraints (names must be unique).

list()
context DataContext | None

Optional Data context (distance metric / strategy intent).

None
k int | None

Number of clusters (clustering problems only).

None
pairwise DataRelationship | None

Optional precomputed pairwise relationship (clustering only; recomputed deterministically when None).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
DataValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a clustering/feature selection configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

feature_variables()

Return the binary feature variables x0 .. x{n-1} in feature order.

cluster_variables()

Return the binary assignment variables in record-major order.

decision_variables()

Return the deterministic decision-variable list for this problem.

Feature selection yields one binary variable per feature in dataset order. Clustering yields one binary variable per (record, cluster) pair in record-major order so that record = z` record index blocks are contiguous.

clustering_distance_matrix()

Return the pairwise distance relationship used by clustering.

Uses :attr:pairwise when supplied (after validating the record alignment) and otherwise recomputes the deterministic distance relationship from the Data context distance metric.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:DataValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

DataProblemType

Bases: Enum

Supported data intelligence problem families.

Attributes:

Name Type Description
FEATURE_SELECTION

Binary selection of a subset of features.

CLUSTERING

Assignment of records to k clusters.

parse(value) classmethod

Coerce a name or member to a :class:DataProblemType.

DataQualityReport dataclass

Deterministic quality assessment of one dataset.

Parameters:

Name Type Description Default
valid bool

Whether the dataset is structurally valid (non-empty, no missing/invalid/duplicate entries, feature-consistent records).

False
record_count int

Number of records.

0
feature_count int

Number of features.

0
missing_count int

Number of missing (absent) feature values.

0
invalid_count int

Number of non-finite or out-of-bounds values.

0
duplicate_count int

Number of records identical to an earlier record.

0
feature_consistency bool

Whether every record carries exactly the dataset feature set.

False
issues list[str]

Deterministic, human-readable issue list.

list()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a report from :meth:to_dict output.

DataRecord dataclass

One observation inside a :class:DataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
DataValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

DataRelationship dataclass

Pairwise relationship matrix over ordered record identifiers.

Parameters:

Name Type Description Default
record_order list[str]

Ordered record identifiers.

required
kind str

One of :data:RELATIONSHIP_KINDS.

required
values list[list[float]]

Square symmetric matrix in record_order; row/column index is the record index. Mirrored for bit-for-bit symmetry.

required
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

size property

Number of records.

__len__()

Number of records.

row(record_id)

Return the row of record_id.

record_index(record_id)

Return the deterministic index of record_id.

value(record_a, record_b)

Return the pairwise value between two records.

validate_against(record_ids)

Raise when the relationship does not cover exactly record_ids.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a relationship from :meth:to_dict output.

DataSet dataclass

Ordered collection of features and records.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time, so partial data can be inspected through :func:quantsmind.quantum.data.quality.assess_data_quality.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every Data problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[DataFeature]

Ordered feature list.

list()
records list[DataRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:DataFeature with name.

record(record_id)

Return the :class:DataRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
DataValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:DataValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

DataSolution dataclass

The domain result of solving a Data optimization problem.

Decision fields are derived from the deterministic Data mapping, so they always reflect the feature/record order of the underlying dataset. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating data problem.

''
problem_type str

Data problem family.

''
selected_features list[str]

Selected feature names in feature order (FS).

list()
selected_utility float

Total utility of the selected features (FS).

0.0
selection_cost float

Total cost of the selected features (FS).

0.0
cluster_assignments dict[str, int]

Record id -> cluster id (clustering).

dict()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether no constraint was violated.

False
metrics DataMetrics

Aggregated data metrics.

DataMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark features selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()

cluster_count property

Number of non-empty clusters used by the solution.

total_within_cluster_distance property

Total within-cluster pairwise distance (clustering).

selected()

Return the selected features in feature order (alias).

assigned_clusters()

Return the record id -> cluster id assignments (alias).

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a data solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic Data mapping, computes data metrics from the dataset and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

DataValidationError

Bases: DataError

Raised when a Data model or problem fails domain validation.

DecodedClusterAssignment dataclass

One decoded cluster assignment decision.

Attributes:

Name Type Description
record_id str

Domain record identifier.

record_index int

Deterministic record index.

cluster_index int

Deterministic cluster index.

variable_name str

QMQ variable name (z{record}_{cluster}).

value float

Raw assignment value (0.0 or 1.0).

DecodedDataFeature dataclass

One decoded feature-selection decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (x<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

FeatureCountConstraint dataclass

Bases: DataConstraint

Limit the total number of selected features.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_features float

Minimum number of selected features (>= 0).

1.0
max_features float | None

Maximum number of selected features (None = unbounded).

None
description str

Free-form description.

''

FeatureGroupConstraint dataclass

Bases: DataConstraint

Limit the number of selected features inside one feature group.

Parameters:

Name Type Description Default
name str

Constraint name.

required
group str

Free-form group label (metadata only).

''
members list[str]

Feature names of the group.

list()
lower float

Minimum number of selected members within the group.

0.0
upper float | None

Maximum number of selected members within the group (None = unbounded).

None
description str

Free-form description.

''

FeatureSelectionObjective dataclass

Bases: DataObjective

Combined feature-selection objective utility - penalty * cost.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
costs dict[str, float]

Feature name -> non-negative cost.

dict()
penalty float

Non-negative penalty applied to the total selection cost.

1.0
description str

Free-form description.

''

FeatureUtilityObjective dataclass

Bases: DataObjective

Maximize the sum of selected-feature utilities.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
description str

Free-form description.

''

FeatureVector dataclass

Lightweight immutable numeric feature vector (in feature order).

Parameters:

Name Type Description Default
values tuple[float, ...]

Numeric values in feature order.

required
normalization dict[str, Any]

Free-form normalization metadata (JSON-safe).

dict()

dimension property

Number of numeric dimensions.

to_list()

Return the values as a plain list.

from_sequence(values, *, normalization=None) classmethod

Build a vector from any sequence of finite numbers.

from_record(record, features) classmethod

Build a vector from a record in deterministic feature order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a vector from :meth:to_dict output.

SelectionCostObjective dataclass

Bases: DataObjective

Minimize the sum of selected-feature costs.

Parameters:

Name Type Description Default
name str

Objective name.

required
costs dict[str, float]

Feature name -> non-negative cost.

dict()
description str

Free-form description.

''

DomainBinding dataclass

Explicit binding between a domain and its execution capabilities.

Parameters:

Name Type Description Default
kind DomainKind

The registered :class:DomainKind.

required
label str

Human-readable sub-label of the binding.

required
problem_types tuple[type, ...]

isinstance-matchable problem types this binding owns.

required
validate Callable[[Any], list[str]]

Callable(problem) -> list[str] of validation issues.

required
raise_if_invalid Callable[[Any], None]

Callable(problem) -> None raising the domain's validation error.

required
to_quantum_problem Callable[..., QuantumProblem]

Callable(problem, *, preferred_strategy=None) -> :class:QuantumProblem. Reuses the existing per-domain formulation adapter.

required
solve Callable[..., Any]

Callable(problem, *, strategy=None, config=None, seed=None) through the per-domain optimizer.

required
benchmark Callable[..., Any]

Callable(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None, seed=None).

required
description str

Human-readable description of the binding.

''
metadata dict[str, Any]

Free-form metadata (module path, rule path, ...).

dict()

accepts(problem)

True when this binding owns the given problem instance.

DomainDispatchError

Bases: DomainError

Raised when a problem cannot be dispatched to a registered domain.

DomainError

Bases: ValueError

Base error of the quantum domain intelligence layer.

DomainIntelligence

Cross-domain assessment, planning, solving and benchmarking.

Parameters:

Name Type Description Default
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the four built-in domains.

None
assessor QuantumSuitabilityAssessor | None

:class:QuantumSuitabilityAssessor; defaulted when omitted.

None
interpreter Any | None

Interpreter used by :meth:interpret; defaulted lazily.

None

assess(problem, *, strategy=None, capabilities=None)

Assess a domain problem (classify/formulate/strategy/algorithm/ suitability) without executing anything.

plan(problem, *, strategy=None, capabilities=None)

Build an inspectable :class:ExecutionPlan for a problem.

The plan can be inspected before any execution happens; no quantum work is performed by planning itself.

solve(problem, *, strategy=None, config=None)

Solve a domain problem through its registered optimizer.

The result is wrapped in a :class:DomainRunResult with the honest strategy/algorithm/backend/execution-mode facts and the QMQ-06 interpretation.

Raises:

Type Description
UnsupportedDomainError

When no domain binding matches.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a domain problem against the classical baseline (QMQ-05).

interpret(result)

Return the QMQ-06 interpretation carried by a run result.

Returns:

Name Type Description
The Any

class:ResultInterpretation (QMQ-06) of the run, or raises

Any

class:DomainDispatchError when no interpretation exists.

solve_and_interpret(problem, *, strategy=None, config=None)

Solve and attach the interpretation in a single call.

The interpretation is already carried by the wrapped result from QMQ-06; this method only validates that it is present.

supported_domains()

Serialized labels of the registered domains.

is_supported(problem)

True when a domain binding matches the problem.

DomainKind

Bases: Enum

Registered quantum-enabled domains (QMQ-11).

parse(value) classmethod

Coerce a label or member to a :class:DomainKind.

DomainRegistry

Registered dispatch table for supported domains (QMQ-11 §10).

The registry is extensible through :meth:register: an external domain supplies its own :class:DomainBinding (wrapping any problem types, formulation adapters and optimizers) and becomes dispatachable by the shared :class:~quantsmind.quantum.domain.intelligence.DomainIntelligence layer without changing core code.

register(binding)

Register a :class:DomainBinding (explicit dispatch entry).

register_defaults()

Register the four built-in domain bindings.

The bindings live in :mod:quantsmind.quantum.domain.adapters and wrap the existing per-domain formulation adapters and optimizers. Registration order is stable: finance, portfolio, data, ml.

resolve(problem)

Return the :class:DomainBinding owning problem.

Raises:

Type Description
UnsupportedDomainError

When no binding accepts the problem.

resolve_kind(kind)

Return the binding registered for a :class:DomainKind.

kind_of(problem)

Return the :class:DomainKind of a problem instance.

is_registered(problem)

True when a binding accepts the problem.

domains()

Registered :class:DomainKind values in registration order.

bindings()

Registered bindings (copy) in registration order.

DomainRunResult dataclass

Honest, provenance-rich result of a domain solve or benchmark.

Parameters:

Name Type Description Default
problem_name str

Name of the solved problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the source domain problem.

''
strategy_requested str

Strategy the caller requested ("" = auto).

''
strategy_selected str

Strategy selected by QMQ-03 for execution.

''
strategy_executed str

Strategy that actually produced the outcome (may differ from selected after a fallback/degradation).

''
algorithm str

Algorithm id that ran ("" when classical).

''
backend str

Backend that executed the quantum leg ("" otherwise).

''
execution_mode str

"quantum" / "classical" / "classical" "quantum-inspired".

'classical'
fallback_used bool

True when the executed path differed from the requested/selected path (honest degradation).

False
feasible bool | None

Feasibility of the produced solution or None.

None
objective_value float | None

Leading objective value or None.

None
limitations list[str]

Honest list of what did NOT happen (e.g. quantum runtime missing).

list()
interpretation Any | None

QMQ-06 structured interpretation (optional).

None
report Any | None

The QMQ-04 :class:SolutionReport (in-memory reference).

None
benchmark Any | None

QMQ-05 :class:BenchmarkResult (in-memory reference).

None
domain_result Any | None

The per-domain result object (in-memory reference).

None
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()

interpretation_status()

Serialized QMQ-06 interpretation status ("" when absent).

to_dict()

Serialize to a JSON-safe dictionary (reports as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report, domain_result) are not rebuilt; measured facts round-trip exactly.

DomainValidationError

Bases: DomainError

Raised when a domain problem fails its own validation rules.

ExecutionPlan dataclass

Domain-aware, inspectable execution plan (QMQ-11 §7).

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan (classification, formulation, strategy, algorithm, mapping, executor, fallbacks).

required
domain DomainKind

The dispatched :class:DomainKind.

required
problem_type str

Class name of the source domain problem.

required
strategy_requested str

Explicit strategy the caller requested ("" for automatic).

required
suitability SuitabilityAssessment

Suitability assessment of the plan.

required
classification str

Serialized classification label.

''
formulation_kind str

Serialized formulation kind.

''
reasons list[str]

Rolled-up reasons from the plan and suitability.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()

summary()

One-line human summary of the plan.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

ProblemAssessment dataclass

Full, inspectable assessment of one domain problem (QMQ-11 §7).

Parameters:

Name Type Description Default
problem_name str

Name of the assessed problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the assessed problem.

''
classification ClassificationResult | None

QMQ-03 classification decision.

None
formulation FormulationRecommendation | None

QMQ-03 formulation-kind recommendation.

None
strategy_decision StrategyDecision | None

QMQ-03 strategy decision (with rationale).

None
algorithm_recommendation Any | None

QMQ-03 algorithm recommendation (with executable fallbacks).

None
capabilities CapabilityModel | None

Capability snapshot the decisions used.

None
suitability SuitabilityAssessment | None

:class:SuitabilityAssessment of the plan.

None
computation_plan ComputationPlan | None

The QMQ-03 :class:ComputationPlan built.

None
reasons list[str]

Rolled-up human-readable justification.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()

domain_label property

Serialized domain label (e.g. "ml").

strategy_label property

Serialized selected strategy label.

algorithm property

Selected primary algorithm id ("" when none).

formulation_kind property

Recommended formulation kind (e.g. "qubo").

suitability_label property

Serialized suitability label ("" when unassessed).

is_implementable property

True when a computation plan was built (ready to run).

summary()

One-line human summary of the assessment.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

QuantumSuitability

Bases: Enum

Suitability of a problem for the quantum path (QMQ-11 §5).

parse(value) classmethod

Coerce a label or member to a :class:QuantumSuitability.

QuantumSuitabilityAssessor

Deterministic, evidence-backed suitability assessment (QMQ-11 §5).

Rules (in evaluation order):

  1. No usable plan -> UNKNOWN.
  2. Not QUBO-amenable (plan.formulation != "qubo") -> UNSUITABLE.
  3. Quantum algorithm selected AND runtime + algorithm available -> SUITABLE.
  4. Quantum path exists (quantum/classical-hybrid strategy or quantum algorithm) but is not executable here -> CONDITIONALLY_SUITABLE with the missing prerequisites listed as limitations.
  5. Otherwise (AUTO selected CLASSICAL for a QUBO-amenable problem) -> CONDITIONALLY_SUITABLE with the size policy stated.

assess(*, plan, capabilities=None, problem_name=None)

Assess a :class:ComputationPlan against an environment snapshot.

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan to assess.

required
capabilities CapabilityModel | None

Capability snapshot; re-detected when omitted.

None
problem_name str | None

Optional override of the assessed problem name.

None

Returns:

Name Type Description
SuitabilityAssessment SuitabilityAssessment

Level, reasons, limitations and evidence.

assess_unknown(*, problem_name)

Return an UNKNOWN assessment when no plan could be built.

SuitabilityAssessment dataclass

Evidence-backed suitability of one problem (QMQ-11 §5).

Parameters:

Name Type Description Default
problem_name str

Names the assessed problem.

required
suitability QuantumSuitability

The assigned :class:QuantumSuitability level.

required
reason str

Human-readable justification of the assignment.

required
signals dict[str, Any]

Structural signals driving the decision (strategy, algorithm, formulation, capability flags, ...).

dict()
evidence dict[str, Any]

Exact facts that produced the decision.

dict()
limitations list[str]

Honest list of conditions that are NOT satisfied.

list()
quantum_available bool

Whether a quantum execution runtime was available (MicroQuantum installed and enabled).

False
algorithm_available bool

Whether the selected quantum algorithm was executable in this environment.

False
formulation_amenable bool

Whether a QUBO formulation path exists.

False
provenance dict[str, Any]

Where-and-how metadata for the assessment.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()

label property

Serialized suitability label (e.g. "suitable").

is_suitable property

True for SUITABLE or CONDITIONALLY_SUITABLE.

is_suitable answers "is there a viable quantum path for this problem" — never "quantum was executed". Use :attr:quantum_available / :attr:algorithm_available for the execution readiness facts.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

UnsupportedDomainError

Bases: DomainDispatchError

Raised when no registered domain binding matches a problem.

ClassicalExecutionError

Bases: ExecutionError

The classical baseline could not execute the plan.

ClassicalExecutionResult dataclass

Normalized classical execution result.

Leg identity is "classical"; :attr:executor/:attr:solver keep the legacy label "classical/exhaustive" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_solver(result, *, objective_value, feasible, options) classmethod

Normalize an :class:ClassicalSolverResult into an execution result.

ClassicalExecutor

Bases: Executor

Exact-solution classical leg of an execution.

Parameters:

Name Type Description Default
solver ExhaustiveSolver | None

Optional :class:ExhaustiveSolver override (workflows reuse their configured classical executor solver here).

None

ExecutionComparison dataclass

Explicit comparison of the legs of a hybrid execution.

Parameters:

Name Type Description Default
entries list[ExecutionComparisonEntry]

Comparison entries, one per leg.

list()
winner str | None

Leg id that won selection ("classical" / "quantum" / None when nothing executed).

None
selected_reason str

Human-readable justification for the winner.

''
tie_break str

Tie-break rule description when selection needed one.

''
sense str

Objective sense used for ranking ("minimize"/"maximize").

'minimize'
metadata dict[str, Any]

Free-form metadata.

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

build(entries, *, sense=ObjectiveSense.MINIMIZE) classmethod

Rank executed legs and pick a deterministic winner.

Ranking (QMQ-04 §11): 1. feasible beats infeasible, 2. better objective per the problem's sense (fallback: QUBO energy, lower is better), 3. ties are broken deterministically in favour of the classical exact baseline.

No quantum-advantage/speedup claim is ever derived from this ranking.

ExecutionComparisonEntry dataclass

One leg of a hybrid execution, ready for comparison.

Parameters:

Name Type Description Default
leg str

"classical" or "quantum".

required
algorithm str

Algorithm id that produced the result.

''
executor str

Executor label (e.g. "classical/exhaustive").

''
status str

"executed" / "skipped" / "failed".

_EXECUTED
objective_value float | None

Domain objective value of the returned assignment.

None
energy float | None

QUBO energy of the returned assignment (minimization form).

None
feasible bool | None

Whether the assignment satisfies the domain constraints.

None
message str

Free-form note (skip/failure reason, ...).

''
metadata dict[str, Any]

Free-form metadata.

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an entry from :meth:to_dict output.

from_execution(*, leg, execution, status=_EXECUTED, message='', metadata=None) classmethod

Build an entry from a normalized execution result.

ExecutionError

Bases: ValueError

Base class for execution-layer failures.

ExecutionOptions dataclass

Controlled execution configuration for one workflow run.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Strategy to execute. None defers to the :class:ComputationPlan (QMQ-03 decision).

None
algorithm str | None

Optional algorithm override (echoed into metadata; the plan's recommended algorithm drives execution unless requested_algorithm is set on the workflow).

None
shots int

Shot count for the quantum leg.

1024
seed int | None

Optional RNG seed for reproducible quantum sampling.

None
backend str | None

Backend name (e.g. "statevector") or instance.

None
num_layers int

QAOA layers (p) for the quantum leg.

1
penalty float | None

Optional QUBO constraint penalty multiplier.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (delegated unchanged).

None
optimization_level int

0..3 optimization hint; recorded in metadata (the QAOA path does not consume it).

0
run_classical_baseline bool | None

For HYBRID, whether to run the classical baseline. None means automatic (always run).

None
allow_fallback bool

Whether an unavailable requested algorithm may fall back to an executable replacement (never silent).

False
metadata dict[str, Any]

Free-form execution metadata.

dict()

resolved_strategy property

Strategy parsed to a :class:ComputationStrategy (or None).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild options from :meth:to_dict output.

Executor

Bases: ABC

Common interface for classical / quantum / hybrid executors.

Subclasses identify themselves through :attr:name and :attr:executor_id and declare which strategies they implement in :attr:strategies. Execution is prepare -> execute -> validate; each step may raise the typed :mod:quantsmind.quantum.execution.errors.

is_available(capabilities=None)

Whether this executor can currently execute (default: True).

prepare(context)

Validate inputs and fail fast before any real work.

execute(context) abstractmethod

Run the planned computation and return a normalized result.

validate(result, context)

Validate and normalize an execution result (default: passthrough).

ExecutorContext dataclass

Everything one executor needs to run one plan.

Parameters:

Name Type Description Default
problem Any

The domain problem being executed.

required
plan Any

The QMQ-03 computation plan (the plan drives execution).

required
formulation Any | None

Formulation produced for the problem (optional).

None
qubo Any | None

Mapped QUBO model (used by the classical leg).

None
ising Any | None

Mapped Ising model (used by the quantum leg).

None
options ExecutionOptions

Execution configuration for this run.

ExecutionOptions()
metadata dict[str, Any]

Free-form contextual metadata.

dict()

strategy property

Strategy resolving options override, then the plan, then None.

algorithm property

Algorithm resolving options override, then the plan.

HybridExecutionError

Bases: ExecutionError

A hybrid execution failed because no leg produced a result.

HybridExecutionResult dataclass

Composite result of a hybrid execution.

Parameters:

Name Type Description Default
classical ClassicalExecutionResult | None

Classical leg result (or None when skipped/failed).

None
quantum QuantumExecutionResult | None

Quantum leg result (or None when skipped/failed).

None
comparison ExecutionComparison | None

Explicit comparison + deterministic selection.

None
selected str | None

Selected leg id ("classical" / "quantum").

None
selected_assignment dict[str, int]

Assignment chosen by selection.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()

assignment property

Selected assignment (existing build_solution compatibility).

quantum_unavailable property

True when the quantum leg produced no execution result.

solver property

Selected leg's executor label (provenance compatibility).

energy property

Selected leg's QUBO energy (provenance compatibility).

shots property

Selected leg's shot count.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

HybridExecutor

Bases: Executor

Runs the classical baseline and the QAOA leg, then selects a winner.

Parameters:

Name Type Description Default
classical_executor ClassicalExecutor | None

Optional :class:ClassicalExecutor override.

None
quantum_executor QuantumExecutor | None

Optional :class:QuantumExecutor override.

None

InvalidExecutionOptionError

Bases: ExecutionError

An execution option is invalid for the requested strategy.

InvalidQuantumResultError

Bases: ExecutionError

A decoded quantum result failed validation (variables/values/energy).

MicroQuantumUnavailableError

Bases: ImportError, WorkflowError

MicroQuantum is not importable but a quantum strategy needed it.

Subclasses both :class:ImportError (so except ImportError catches it at the engine boundary) and :class:WorkflowError (so workflow-level callers keep their existing behaviour).

QuantumExecutionError

Bases: ExecutionError

A quantum execution failed while delegating to MicroQuantum.

QuantumExecutionResult dataclass

Validated, normalized quantum execution result.

Leg identity is "quantum"; :attr:executor/:attr:solver keep the legacy label "microquantum/qaoa" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_qaoa(result, *, objective_value, feasible, options) classmethod

Normalize a validated :class:QaoaExecutionResult.

QuantumExecutor

Bases: Executor

QAOA quantum leg of an execution (delegates unchanged to MicroQuantum).

validate(result, context)

Validate a QaoaExecutionResult before it becomes a leg of the run.

Checks (QMQ-04 §9): decoded variable names against the mapped QUBO (slack variables included), binary values, re-computed QUBO energy consistency, domain objective/feasibility. The raw MicroQuantum metadata stays intact.

UnsupportedStrategyError

Bases: ExecutionError

The requested strategy/executor combination is not supported.

WorkflowError

Bases: ValueError

Raised when a workflow step cannot proceed.

Kept in this module (rather than the workflow package) so dependency errors can subclass it without creating an import cycle.

QuantumExperiment

Domain-level quantum experiment that delegates execution to MicroQuantum.

Parameters:

Name Type Description Default
program ProgramOrCircuit

A QuantsMind QuantumProgram, or an already-built MicroQuantum QuantumCircuit.

required
backend str | None

Backend name (e.g. "statevector") or a MicroQuantum Backend instance. None uses MicroQuantum's default.

None
shots int

Number of shots per execution.

1024
seed int | None

Optional RNG seed for reproducibility.

None
name str

Experiment label.

'quantum_experiment'
experiment_id str | None

Optional explicit identity (generated otherwise).

None
domain_metadata dict[str, Any] | None

Domain metadata attached to the result.

None
optimization_level int

MicroQuantum optimization level (0-3).

0
options dict[str, Any] | None

Extra MicroQuantum runtime options.

None

name property

Experiment label.

experiment_id property

Unique experiment identity.

run()

Execute the experiment through MicroQuantum and enrich the result.

Allocation dataclass

A validated asset -> weight allocation over a fixed asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Deterministic order of asset identifiers (must match the asset universe ordering that formulation relies on).

required
weights dict[str, float]

Asset identifier -> weight value. Only identifiers present in asset_order are allowed; missing entries default to 0.

dict()
kind AllocationKind

Reported allocation representation.

CONTINUOUS

Raises:

Type Description
FinanceValidationError

If an identifier is unknown, repeated, or a weight is not finite.

weight(identifier)

Return the weight of an asset (0 when unset).

total()

Return the sum of all weights in asset_order.

from_universe(universe, weights, *, kind=AllocationKind.CONTINUOUS) classmethod

Build an allocation aligned with an asset universe order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Allocation from :meth:to_dict output.

AllocationKind

Bases: Enum

Representation of an allocation decision.

Attributes:

Name Type Description
CONTINUOUS

Real-valued weights (e.g. fractions of capital).

BINARY

0/1 selection of whether an asset is held.

INTEGER

Integer quantities (e.g. number of units).

parse(value) classmethod

Coerce a name or member to an :class:AllocationKind.

Asset dataclass

Bases: FinancialInstrument

An instrument extended with optimization-relevant financial data.

Parameters:

Name Type Description Default
expected_return float

Supplied expected return (may be negative).

0.0
price float | None

Optional unit price/value (must be positive when set).

None
volatility float | None

Optional annualized volatility (>= 0 when set).

None
asset_class str

Optional group label (e.g. "equity", "bond"), used by :class:~quantsmind.quantum.finance.constraints .GroupAllocationConstraint.

''

Raises:

Type Description
FinanceValidationError

If a numeric field is not finite or violates its documented domain.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Asset from :meth:to_dict output.

AssetMapping dataclass

The deterministic asset <-> variable <-> index mapping of a problem.

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
asset_order list[str]

Ordered asset identifiers (universe order).

required
allocation_kind AllocationKind

Allocation representation of the problem.

required
symbols dict[str, str]

Optional asset identifier -> symbol lookup.

dict()

variable_names property

Decision-variable names in asset order (x0, x1, ...).

index(identifier)

Return the variable index of an asset identifier.

variable(identifier)

Return the decision-variable name of an asset identifier.

asset(variable_name)

Return the asset identifier for a decision-variable name.

Raises:

Type Description
KeyError

If the variable name is outside the mapping.

decode_assignments(assignments, *, selected_threshold=0.5)

Decode an assignment back into ordered asset decisions.

Keys may be decision-variable names (x0) or asset identifiers; unknown keys (e.g. QUBO slack variables) are ignored. selected is value > selected_threshold.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetMapping from :meth:to_dict output.

AssetUniverse dataclass

An ordered, validated collection of financial assets.

Deterministic ordering is preserved from construction (insertion order) because QUBO variable mapping depends on deterministic variable indices. Duplicate identifiers are rejected.

Parameters:

Name Type Description Default
assets list[Asset]

Ordered list of assets.

required
name str

Optional universe name (may be empty).

''

Raises:

Type Description
FinanceValidationError

If an identifier is empty or repeated.

has(identifier)

Return whether an asset identifier is in the universe.

asset(identifier)

Return the asset with the given identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

index_of(identifier)

Return the deterministic index of an asset identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

identifier_order()

Return the deterministic ordered asset identifiers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetUniverse from :meth:to_dict output.

Budget dataclass

Validated capital / budget representation.

Parameters:

Name Type Description Default
total float

Total available budget (allocation units).

required
currency str

Optional currency code (metadata only).

''
min_allocation float | None

Optional minimum aggregate allocation.

None
max_allocation float | None

Optional maximum aggregate allocation.

None

Raises:

Type Description
FinanceValidationError

If totals are invalid or bounds inconsistent.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Budget from :meth:to_dict output.

BudgetConstraint dataclass

Bases: FinancialConstraint

Budget limit: sum(cost_i * x_i) <= total.

Without costs the aggregate allocation is bounded: sum(x_i) <= total. costs maps asset identifier -> cost per unit of allocation; missing assets use a unit cost of 1.

CardinalityConstraint dataclass

Bases: FinancialConstraint

Bounded cardinality / aggregate allocation: min <= sum(x_i) <= max.

Under a binary allocation the sum is the number of selected assets (a cardinality bound); under a continuous allocation it bounds the aggregate allocation. Bounds are real values; whole-valued bounds additionally participate in a cardinality sanity check against the universe size.

DecodedAsset dataclass

A decoded asset decision from an assignment.

Parameters:

Name Type Description Default
asset_id str

The asset identifier.

required
index int

Deterministic variable index of the asset.

required
variable_name str

The decision-variable name (x<i>).

required
symbol str

Optional asset symbol.

''
value float

The assigned value in the solution.

0.0
selected bool

Whether the value exceeds the selection threshold.

False

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DecodedAsset from :meth:to_dict output.

ExpectedReturnObjective dataclass

Bases: FinancialObjective

Maximize expected return: maximize sum(expected_return_i * x_i).

FinanceAssetMapper

Builds the deterministic :class:AssetMapping of a financial problem.

map(problem)

Return the asset -> variable mapping of a financial problem.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

FinanceError

Bases: ValueError

Base error of the QuantsMind Quantum Finance domain layer.

FinanceFormulationAdapter

Converts financial problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention in universe order, objectives keep their senses, and every financial constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a financial problem (empty = valid).

raise_if_invalid(problem)

Raise :class:FinanceValidationError when the problem is invalid.

Raises:

Type Description
FinanceValidationError

If the problem fails validation.

finance_metadata(problem) staticmethod

JSON-safe Finance provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a financial problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem FinancialProblem

The validated financial problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
FinanceValidationError

If the financial problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a financial problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

FinanceOptimizationResult

Result of a Finance solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

FinanceOptimizer

Solves and benchmarks :class:~quantsmind.quantum.finance.models .FinancialProblem instances (QMQ-11 §16).

A thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for finance problems.

solve(problem, *, strategy=None, config=None)

Solve a FinancialProblem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:FinancialSolution with asset decisions, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a FinancialProblem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem Any

The financial problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config OptimizationConfiguration | None

Optional execution/optimization configuration.

None

FinanceValidationError

Bases: FinanceError

Raised when a Finance model or problem fails domain validation.

FinancialConstraint dataclass

Base class of financial constraints.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets)

Return validation issues against an asset universe (empty = valid).

to_quantum_constraints(assets)

Materialize into existing QMQ constraints.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

FinancialContext dataclass

Financial metadata and model configuration.

Parameters:

Name Type Description Default
currency str

Optional currency code (metadata only; no conversion).

''
subdomain str

Finance subdomain (e.g. "portfolio").

''
investment_horizon str

Optional horizon label (e.g. "1Y").

''
risk_free_rate float | None

Optional risk-free rate used by risk-adjusted models.

None
transaction_cost_rate float

Assumed proportional transaction-cost rate.

0.0
assumptions dict[str, Any]

Named model assumptions (JSON-safe values).

dict()
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If a numeric field is invalid.

to_domain_context()

Derive the generic QMQ :class:DomainContext for this finance.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialContext from :meth:to_dict output.

FinancialInstrument dataclass

Identity of a financial instrument.

Parameters:

Name Type Description Default
identifier str

Unique, non-empty instrument identifier (e.g. "USD").

required
symbol str

Optional ticker/symbol; defaults to the identifier.

''
name str

Optional human-readable name; defaults to the identifier.

''
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the identifier is empty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialInstrument from :meth:to_dict output.

FinancialObjective dataclass

Base class of financial objectives.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets, risk)

Return validation issues against an asset universe (empty = valid).

to_quantum_objective(assets, context=None, risk=None)

Materialize into an existing QMQ objective.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output (name + description).

Subclasses with extra fields override from_dict.

FinancialProblem dataclass

A complete financial optimization problem definition.

Connects an :class:AssetUniverse, optional :class:FinancialContext and :class:RiskMatrix, financial objectives, financial constraints and an :class:AllocationKind. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints.

list()
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
allocation_kind AllocationKind

How the allocation is represented (continuous / binary / integer).

CONTINUOUS
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the name is empty or objective/constraint names repeat.

size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables following the x<i> convention.

One variable per asset in universe order. continuous yields long-only [0, inf) weights, binary yields 0/1 selection. integer is intentionally not defined here: the portfolio representation is a QMQ-08 decision.

validate()

Return a list of human-actionable validation issues.

An empty list means the problem is a valid input to the formulation adapter. Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_budget_constraint(budget, name='budget')

Convenience: append a budget constraint derived from a :class:Budget.

The aggregate allocation is bounded by budget.total; when min_allocation / max_allocation are set they bound the sum as well (as minimum/maximum aggregate allocation constraints).

constraint_exists(name)

Return whether a constraint with the given name already exists.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialProblem from :meth:to_dict output.

FinancialSolution dataclass

Deterministic decoded solution of a FinancialProblem (QMQ-11).

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
allocation_kind str

Allocation representation of the problem.

'binary'
assets list[DecodedAsset]

Ordered asset decisions.

list()
objective_value float | None

Leading objective value of the solution.

None
objective_values dict[str, float]

Objective name -> value snapshot.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether the solution satisfies all constraints.

False
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver/executor label.

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

0
num_variables int

Number of decision variables after formulation.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark assets selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()

selected_assets()

Selected asset identifiers in universe order.

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a financial solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07) and reuses the existing constraint-evaluation infrastructure for feasibility and constraint status.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

GroupAllocationConstraint dataclass

Bases: FinancialConstraint

Group allocation limits: lower <= sum_{i in group} x_i <= upper.

A group is an :attr:~quantsmind.quantum.finance.models.Asset.asset_class value (e.g. "equity").

OptimizationConfiguration dataclass

Execution/optimization configuration of a portfolio problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
FinanceValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

PortfolioAssetMapper

Deterministic asset <-> variable mapping for portfolios.

Reuses the QMQ-07 solution decoding: an assignment is decoded back into ordered asset decisions, QUBO slack/aux variables are ignored, and selected follows value > selected_threshold.

mapping(portfolio)

Return the asset -> variable :class:AssetMapping of a portfolio.

decode(portfolio, assignments, *, selected_threshold=0.5)

Decode an assignment into ordered asset decisions (:class:DecodedAsset).

variable(portfolio, identifier)

Return the decision-variable name of an asset identifier.

asset(portfolio, variable_name)

Return the asset identifier for a decision-variable name.

PortfolioComponent dataclass

One asset decision inside a :class:PortfolioSolution.

Parameters:

Name Type Description Default
asset_id str

Asset identifier.

required
symbol str

Asset symbol.

required
index int

Deterministic variable index in universe order.

required
variable_name str

Decision-variable name (x<i>).

required
weight float

Assigned value of the asset in the solution.

required
selected bool

Whether the value exceeds the selection threshold.

required
expected_return float

Supplied expected return of the asset.

required
expected_contribution float

weight * expected_return.

required
risk_contribution float | None

Marginal variance contribution when a risk matrix was supplied (None otherwise).

None

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a component from :meth:to_dict output.

PortfolioFormulationAdapter

Portfolio -> QMQ conversion adapter.

Delegates structural conversion to the QMQ-07 :class:FinanceFormulationAdapter and injects portfolio provenance metadata (domain_sublayer="portfolio", the configuration dict, the budget). Reuses the existing QMQ-02 formulation — there is no second portfolio QUBO/Ising representation.

validate(portfolio)

Return the validation issues of a portfolio (empty = valid).

raise_if_invalid(portfolio)

Raise :class:FinanceValidationError when the portfolio is invalid.

Raises:

Type Description
FinanceValidationError

If the portfolio fails validation.

to_quantum_problem(portfolio, *, preferred_strategy=None)

Convert a portfolio into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The validated portfolio problem.

required
preferred_strategy Any

Optional preferred computation strategy; when None the portfolio's optimization configuration decides.

None

formulate(portfolio)

Return the existing QMQ formulation of a portfolio.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

PortfolioMetrics dataclass

Measured metrics of a portfolio selection (QMQ-08).

expected_return / variance / volatility are None whenever the underlying data (e.g. a risk matrix) was not supplied; counts default to 0. Nothing is invented beyond the supplied financial data.

Parameters:

Name Type Description Default
expected_return float | None

Expected portfolio return (supplied returns only).

None
variance float | None

w^T Cov w over the supplied risk matrix.

None
volatility float | None

Square root of the (clamped) variance.

None
selected_count int

Number of assets selected (weight > threshold).

0
allocation_sum float

Sum of all weights in universe order.

0.0
constraint_violations int

Number of violated constraints.

0
constraint_violation_magnitude float

Total excess magnitude of violations.

0.0

compute(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute portfolio metrics from supplied allocations.

Parameters:

Name Type Description Default
universe AssetUniverse

The asset universe (owns the deterministic order).

required
weights Mapping[str, float]

Asset identifier -> weight mapping.

required
risk RiskMatrix | None

Optional risk matrix for variance/volatility.

None
selected_threshold float

Weight strictly above this counts as selected.

0.5
violation_count int

Number of violated constraints (from the existing constraint evaluation infrastructure; 0 when unused).

0
violation_magnitude float

Total excess magnitude (0.0 when unused).

0.0

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild :class:PortfolioMetrics from :meth:to_dict output.

PortfolioOptimizationProblem dataclass

A complete portfolio optimization problem definition.

Connects an :class:AssetUniverse, financial objectives/constraints, an optional :class:Budget, optional :class:~quantsmind.quantum.finance.context.FinancialContext and :class:~quantsmind.quantum.finance.risk.RiskMatrix, an allocation representation and an :class:OptimizationConfiguration. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints (budget/weight/cardinality/ position/group). A :class:Budget additionally materializes its constraints during formulation.

list()
allocation_kind AllocationKind

binary (supported) or continuous (validated/formulated; execution honestly surfaces the binary pipeline limit). integer raises :class:FinanceValidationError.

BINARY
budget Budget | None

Optional budget whose constraints are materialized on formulation.

None
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
optimization_config OptimizationConfiguration

Execution/optimization configuration.

OptimizationConfiguration()
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables in universe order.

binary yields 0/1 selection variables; continuous yields long-only [0, inf) weight variables. integer raises :class:FinanceValidationError — QMQ-08 does not represent integer quantities (honest: nothing is silently approximated).

Raises:

Type Description
FinanceValidationError

If the allocation kind is integer.

to_financial_problem()

Materialize the portfolio as a QMQ-07 :class:FinancialProblem.

Explicit constraints keep their declaration order; a :class:Budget appends its aggregate-allocation constraints (named budget / budget_min_allocation / budget_max_allocation / budget_allocation) after them.

Raises:

Type Description
FinanceValidationError

If a budget-derived name collides with an explicit constraint name.

to_quantum_problem(*, preferred_strategy=None)

Convert the portfolio into a QMQ :class:QuantumProblem.

Delegates to :class:PortfolioFormulationAdapter.

formulate()

Return the existing QMQ formulation of the portfolio.

validate()

Return a list of human-actionable validation issues.

Validation is performed before any formulation: on the portfolio structure, the derived QMQ-07 :class:FinancialProblem (universe, objectives, risk alignment, per-constraint) and portfolio-level feasibility (e.g. a minimum aggregate allocation above the available capital). Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio problem from :meth:to_dict output.

PortfolioOptimizationResult dataclass

Result of a portfolio solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

PortfolioOptimizer

Solves and benchmarks :class:PortfolioOptimizationProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for portfolios.

solve(portfolio, *, strategy=None)

Solve a portfolio problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the optimization configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.finance.portfolio_solution .PortfolioSolution with portfolio metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Reasons

FinanceValidationError: If the portfolio is invalid. MappingError: For a continuous allocation, because the current QUBO pipeline is binary-only (honest failure — no silent approximation). UnsupportedStrategyError: For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(portfolio, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False)

Benchmark a portfolio against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The portfolio problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the optimization configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False

PortfolioSolution dataclass

The domain result of solving a portfolio optimization problem.

Components are ordered by the deterministic universe order. weights() maps every asset identifier (in that order) to its weight. Constraint compliance comes from the existing QMQ constraint-evaluation infrastructure (QMQ-05 metric helpers), never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating portfolio problem.

''
allocation_kind AllocationKind

Allocation representation that was solved.

BINARY
components list[PortfolioComponent]

Ordered per-asset decisions.

list()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> "satisfied"/"violated"/....

dict()
feasible bool

Whether no constraint was violated.

False
metrics PortfolioMetrics

Measured portfolio metrics.

PortfolioMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
optimization_level int

Execution optimization hint.

0
selection_threshold float

Threshold used to mark components selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()

weights()

Deterministic asset identifier -> weight mapping (universe order).

selected_assets()

Selected asset identifiers in universe order.

from_report(portfolio, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a portfolio solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07), computes portfolio metrics from supplied data and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio solution from :meth:to_dict output.

PositionLimitConstraint dataclass

Bases: FinancialConstraint

Position limits on specific assets: lower <= x_i <= upper.

RiskAdjustedObjective dataclass

Bases: FinancialObjective

Maximize risk-adjusted return: maximize return - lambda * risk.

A mean-variance utility objective combining the expected-return terms with a risk penalty scaled by risk_aversion >= 0. A zero aversion degenerates to the pure expected-return objective.

RiskMatrix dataclass

A covariance/risk matrix over a deterministic asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Ordered asset identifiers the matrix rows/columns map to.

required
matrix list[list[float]]

Covariance matrix (n x n); must be square, finite, and symmetric within :data:_SYMMETRY_TOLERANCE (values are normalized to exact symmetry).

required
volatilities list[float | None] | None

Optional per-asset volatility (standard deviation), aligned with asset_order.

None

Raises:

Type Description
FinanceValidationError

On structural or numerical invalidity, or a confirmed non-PSD matrix (only when the PSD check is conclusive).

Attributes:

Name Type Description
psd_validated bool

Whether the positive-semidefinite check was conclusive.

psd bool

Whether the matrix is positive semidefinite (False when the check was inconclusive).

require_psd()

Raise when the matrix is not confirmed positive semidefinite.

Raises:

Type Description
FinanceError

If the matrix fails the PSD requirement (including an inconclusive check, which is reported rather than assumed).

index(identifier)

Return the row/column index of an asset identifier.

covariance(left, right)

Return the covariance entry between two assets.

variance(identifier)

Return the variance (diagonal entry) of an asset.

correlation()

Return the correlation matrix derived from this covariance matrix.

Raises:

Type Description
FinanceError

If volatilities are missing or contain zeros.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a RiskMatrix from :meth:to_dict output.

RiskObjective dataclass

Bases: FinancialObjective

Minimize total variance: minimize w^T Cov w.

Requires a positive-semidefinite :class:RiskMatrix aligned with the asset universe.

WeightBoundsConstraint dataclass

Bases: FinancialConstraint

Per-asset allocation bounds: lower_i <= x_i <= upper_i.

GraphModel dataclass

Bases: MathematicalModel

Structural formulation of a graph problem.

Parameters:

Name Type Description Default
nodes list[str]

Names/labels of graph nodes.

list()
edges list[tuple[str, str]]

Undirected edge pairs (source, target).

list()

n_nodes property

Number of graph nodes.

n_edges property

Number of graph edges.

from_problem(problem) classmethod

Snapshot a graph problem (nodes/edges from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a GraphModel from :meth:to_dict output.

MathematicalModel dataclass

A structural formulation of a domain problem.

Parameters:

Name Type Description Default
name str

Formulation name.

'model'
problem_name str

Name of the originating problem.

''
variables list[str]

Names of the participating variables.

list()
objectives list[str]

Names of the participating objectives.

list()
constraints list[str]

Names of the participating constraints.

list()
metadata dict[str, Any]

Formulation metadata (copied from the problem).

dict()

Attributes:

Name Type Description
kind str

Machine-readable formulation family, overridden by subclasses.

n_variables property

Number of participating variables.

n_objectives property

Number of participating objectives.

n_constraints property

Number of participating constraints.

from_problem(problem) classmethod

Snapshot a domain problem into a mathematical model.

Constructs a concrete instance of cls so subclasses reading extra state after a super().from_problem call are always operating on their own type.

describe()

Return a one-line description of the formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a MathematicalModel from :meth:to_dict output.

Subclasses reuse this constructor because their extra fields have defaults; any subclass-specific keys are re-collected by their own overridden from_dict.

MLModel dataclass

Bases: MathematicalModel

Structural formulation of a machine learning problem.

Parameters:

Name Type Description Default
features list[str]

Feature names/schema.

list()
target str

Target column name.

''
task str

Learning task (e.g. "classification", "regression").

''

from_problem(problem) classmethod

Snapshot an ML problem (schema from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an MLModel from :meth:to_dict output.

OptimizationModel dataclass

Bases: MathematicalModel

Structural formulation of an optimization problem.

Parameters:

Name Type Description Default
objective_senses dict[str, str]

Objective name -> "minimize"/"maximize".

dict()
variable_bounds dict[str, list[Any]]

Variable name -> [lower_bound, upper_bound].

dict()
constant_term float

Additive constant of the (single) objective.

0.0
problem_ref QuantumProblem | None

Reference to the originating problem (not serialized).

None

from_problem(problem) classmethod

Snapshot an optimization problem including senses and bounds.

objective_value(assignment)

Evaluate the first objective against an assignment (or None).

Raises:

Type Description
ValueError

If the model has no source problem reference.

constraint_values(assignment)

Evaluate every constraint expression against an assignment.

Returns a mapping of constraint name -> numeric left-hand side (None when the constraint has no expression).

is_feasible(assignment)

Return whether the assignment satisfies every constraint.

to_dict()

Serialize to a JSON-safe dictionary (problem reference excluded).

from_dict(data) classmethod

Rebuild an OptimizationModel from :meth:to_dict output.

SimulationModel dataclass

Bases: MathematicalModel

Structural formulation of a simulation problem.

Parameters:

Name Type Description Default
time_steps int

Number of discrete evolution steps.

0
dynamics str

Description of the evolution law (e.g. "hamiltonian", "reaction-diffusion").

''

n_steps property

Number of evolution steps.

from_problem(problem) classmethod

Snapshot a simulation problem (solver config from metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a SimulationModel from :meth:to_dict output.

StatisticalModel dataclass

Bases: MathematicalModel

Structural formulation of a statistical problem.

Parameters:

Name Type Description Default
distribution str

Target distribution or family (e.g. "gaussian").

''
assumptions list[str]

Statistical assumptions (e.g. ["iid", "normal"]).

list()

from_problem(problem) classmethod

Snapshot a statistical problem (config from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a StatisticalModel from :meth:to_dict output.

QaoaExecutionResult dataclass

Record of a QUBO/Ising run delegated to MicroQuantum's QAOA.

Parameters:

Name Type Description Default
solver str

Solver identity ("microquantum/qaoa").

'microquantum/qaoa'
algorithm str

Algorithm used ("qaoa").

'qaoa'
backend str

Backend that executed the run.

''
num_layers int

Number of QAOA layers used.

1
bitstring str

Most-frequent measured bitstring.

''
assignment dict[str, int]

QUBO variable name -> 0/1 decoded from the bitstring.

dict()
energy float | None

QUBO energy of the assignment (minimization form, penalties included) when a QUBO was supplied.

None
ising_energy float | None

Ising energy of the assignment (carries the constant).

None
mq_eigenvalue float | None

Raw eigenvalue returned by MicroQuantum (Ising energy without the additive constant).

None
converged bool

Whether MicroQuantum's optimizer reported convergence.

False
iterations int

Optimizer iterations reported by MicroQuantum.

0
shots int

Shot count used for the final sampling.

0
seed int | None

Seed used.

None
metadata dict[str, Any]

Free-form execution metadata.

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

QuantumIntegrationError

Bases: RuntimeError

Raised when a MicroQuantum delegation fails or is unavailable.

AlgorithmAvailability dataclass

Three-level availability of one algorithm.

Parameters:

Name Type Description Default
algorithm str

Canonical algorithm id.

required
architecture_supported bool

QuantsMind Quantum has a descriptor for it.

required
available_in_microquantum bool

The installed MicroQuantum exposes it.

required
currently_executable bool

It can run in this environment right now.

required

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

AlgorithmCategory

Bases: Enum

High-level family an algorithm belongs to.

parse(value) classmethod

Coerce a label or member to an :class:AlgorithmCategory.

AlgorithmDescriptor dataclass

Structural description of an algorithm known to QuantsMind Quantum.

Parameters:

Name Type Description Default
name str

Canonical id (e.g. "qaoa").

required
label str

Human-readable label (e.g. "QAOA").

required
category AlgorithmCategory

High-level algorithm family.

required
description str

What the algorithm does.

required
problem_classes tuple[str, ...]

Problem-class labels the algorithm suits.

()
formulations tuple[str, ...]

Formulation kinds the algorithm consumes.

()
strategies tuple[ComputationStrategy, ...]

Strategies the algorithm participates in.

()
execution_modes tuple[str, ...]

How the algorithm is executed (e.g. "vqe_loop").

()
microquantum_identifier str | None

Public MicroQuantum class name, or None for non-quantum algorithms (e.g. the classical baseline).

None
required_capabilities tuple[str, ...]

Capability names that must be available for the algorithm to run (e.g. "qaoa_available").

()
min_variables int | None

Minimum useful problem size (inclusive).

None
max_variables int | None

Maximum useful problem size (inclusive).

None
metadata dict[str, Any]

Free-form metadata.

dict()

category_label property

Serialized category label (e.g. "optimization").

matches(*, problem_class=None, formulation=None, strategy=None)

Return whether this descriptor is applicable to the given signals.

Only constraints that are provided are checked; unknown signals are not grounds for exclusion.

availability(capabilities)

Compute executive availability against a :class:CapabilityModel.

Classical algorithms are executable when their (classical) capabilities are met; quantum algorithms require the corresponding MicroQuantum probe to have succeeded.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a descriptor from :meth:to_dict output.

AlgorithmRecommendation dataclass

A scored, rule-based algorithm recommendation.

Parameters:

Name Type Description Default
algorithm str | None

Recommended canonical algorithm id, or None when no executable algorithm fits.

required
suitability_score float

Rule-based heuristic score in [0, 1]. This is not ML confidence; it reflects how well deterministic rules match this problem, formulation and strategy.

required
reason str

Human-readable, signal-based explanation.

required
required_capabilities list[str]

Capabilities the recommendation needs.

list()
expected_input_representation str

What the algorithm is handed (e.g. "IsingModel -> microquantum.OptimizationProblem").

''
execution_mode str

How the algorithm runs (e.g. "vqe_loop").

''
fallbacks list[AlgorithmRecommendation]

Executable fallback recommendations (never the only path when a primary is unavailable).

list()
capabilities dict[str, bool]

Snapshot of the capability flags considered.

dict()
user_requested bool

True when the algorithm was explicitly requested.

False
metadata dict[str, Any]

Free-form metadata (e.g. requested_algorithm when a fallback was applied).

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a recommendation from :meth:to_dict output.

AlgorithmRegistry

Registry of algorithm descriptors.

Implements registration, lookup, search and availability queries. The default catalog is loaded on construction and can be replaced or extended.

register(descriptor)

Register descriptor; raise on a duplicate or empty id.

unregister(name)

Remove name; raise :class:UnknownAlgorithmError.

get(name)

Return the descriptor for name or raise UnknownAlgorithmError.

find(*, problem_class=None, formulation=None, category=None, strategy=None)

Return descriptors matching the given signals (sorted by name).

registered()

All registered descriptors sorted by name.

available(capabilities)

Executive availability for every registered algorithm.

executable_algorithms(capabilities)

Sorted ids currently executable against capabilities.

to_dict()

Serialize the registry (descriptors + version).

from_dict(data) classmethod

Rebuild a registry from :meth:to_dict output.

Only the serialized descriptors are registered (the default catalog is not preloaded).

AlgorithmSelectionError

Bases: ValueError

Raised when no rule can select an algorithm for the inputs.

AlgorithmSelector

Deterministic rule-based algorithm selector (QMQ-03 §8–§10).

Parameters:

Name Type Description Default
registry AlgorithmRegistry | None

Algorithm registry (defaults to the standard catalog).

None

select(problem, formulation=None, strategy=None, classification=None, capabilities=None, requested_algorithm=None, *, allow_fallback=False)

Select an algorithm, or raise when no rule applies.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

The chosen formulation (defaults to the problem's).

None
strategy ComputationStrategy | str | None

The chosen :class:ComputationStrategy.

None
classification ClassificationResult | ProblemClass | None

Classification result; re-classified if omitted.

None
capabilities CapabilityModel | None

Capability snapshot; auto-detected if omitted.

None
requested_algorithm str | None

Optional explicit algorithm id.

None
allow_fallback bool

If True and the requested algorithm is not executable, an executable replacement is selected and recorded. A requested algorithm is never silently replaced: the fallback is always marked in metadata.

False

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

A scored recommendation with an

AlgorithmRecommendation

executable fallback chain.

Raises:

Type Description
AlgorithmSelectionError

When the request is impossible (unknown requested algorithm, or - without allow_fallback - an unavailable requested algorithm).

CapabilityModel dataclass

Snapshot of what the current environment can execute.

Parameters:

Name Type Description Default
microquantum_installed bool

The optional microquantum package is importable.

False
quantum_enabled bool

Master switch for quantum-family execution.

True
simulator_available bool

A local simulator backend is exposed by MicroQuantum.

False
backend_available bool

A backend can be resolved for execution.

False
qml_available bool

MicroQuantum exposes a quantum machine-learning class.

False
quantum_execution_enabled bool

MicroQuantum can actually be executed (installed and enabled).

False
classical_baseline_available bool

The QMQ-02 classical exhaustive baseline exists (always true).

True
algorithm_available dict[str, bool]

Algorithm id -> probe result.

dict()
metadata dict[str, Any]

Free-form detection metadata.

dict()

detect(*, quantum_enabled=True, backend_available=None) classmethod

Probe the environment using public APIs only.

Parameters:

Name Type Description Default
quantum_enabled bool

Whether quantum execution is enabled by policy.

True
backend_available bool | None

Explicit backend signal; None falls back to local-simulator availability.

None

is_available(capability)

Return whether a named capability holds.

Accepts canonical aliases: "qaoa_available", "qaoa", "microquantum", or any attribute of this model.

executable_algorithms()

Sorted ids of algorithms currently executable in this environment.

required_caps_met(required_capabilities)

True when every required capability is available.

capability_flags()

All boolean capability flags as a flat dictionary.

Algorithm probes are also included as "<id>_available" keys.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a CapabilityModel from :meth:to_dict output.

ClassificationResult dataclass

Result of a deterministic problem classification.

Parameters:

Name Type Description Default
problem_name str

Name of the classified problem.

required
problem_class ProblemClass

The assigned :class:ProblemClass.

required
reason str

Human-readable explanation of the assignment.

required
signals dict[str, Any]

Structural signals used by the classifier (variable types, formulation kind, counts, ...).

dict()
metadata dict[str, Any]

Free-form classification metadata (e.g. the rule path).

dict()

label property

Serialized label of the problem class (e.g. "binary_optimization").

is_optimization property

True for the optimization family of classes.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ClassificationResult from :meth:to_dict output.

ComputationPlan dataclass

Declarative execution plan for one problem (QMQ-03 §13).

Parameters:

Name Type Description Default
problem_name str

Name of the domain problem.

required
problem_class str

Classification label (e.g. "binary_optimization").

required
formulation str

Formulation kind to execute (e.g. "qubo").

required
strategy ComputationStrategy

Chosen :class:ComputationStrategy.

required
algorithm str | None

Recommended primary algorithm id, or None.

required
recommendation AlgorithmRecommendation

The full algorithm recommendation object.

required
mapping str

Mapping label needed for the chosen algorithm (e.g. "qubo" / "ising" / "none").

'none'
executor str

Executor that will run the plan (e.g. "microquantum/qaoa" / "classical/exhaustive").

''
fallbacks list[str]

Executable fallback algorithm ids in preference order.

list()
capabilities dict[str, bool]

Capability snapshot justifying the recommendation.

dict()
classification ClassificationResult | None

The classification decision used.

None
formulation_recommendation FormulationRecommendation | None

The formulation recommendation used.

None
strategy_decision StrategyDecision | None

The strategy decision used.

None
reason str

Standing human-readable justification.

''
provenance dict[str, Any]

Emergent provenance notes (module, rule path).

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()

strategy_label property

Serialized strategy label (e.g. "hybrid").

is_quantum()

True when the plan executes a quantum algorithm.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

DuplicateAlgorithmError

Bases: ValueError

Raised when registering an id that already exists.

FormulationAlternative dataclass

One alternative formulation the recommender may offer.

Parameters:

Name Type Description Default
kind str

Formulation kind label (e.g. "ising", "qubo").

required
reason str

Why this alternative exists and when it should be preferred.

required
appropriateness float

0.0–1.0 rule-based fit for this problem.

required

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommendation dataclass

Recommended formulation for a problem.

Parameters:

Name Type Description Default
problem_name str

Classified problem name.

required
classification str

Label of the problem class driving the decision.

required
primary str

Recommended formulation kind (e.g. "qubo").

required
alternatives list[FormulationAlternative]

Additional executables, with reasons.

list()
reason str

Human-readable explanation of the primary choice.

''
metadata dict[str, Any]

Free-form metadata (rule path, forced flag, ...).

dict()

is_qubo property

True when the primary recommendation is a QUBO formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommender

Rule-based formulation-kind recommender (QMQ-03 §6).

The evaluator is purely structural: it reads the problem class and the current formulation, never the mathematical content.

Parameters:

Name Type Description Default
registries AlgorithmRegistry | None

Bundled, unused (kept for extensibility); pass the algorithm registry when available.

None

recommend(problem, formulation=None, strategy=None, classification=None, *, force_qubo=False)

Recommend a formulation kind for problem.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand).

None
strategy ComputationStrategy | None

Optional strategy; informs which formulations can be consumed.

None
classification ClassificationResult | ProblemClass | None

Classification result (or just a class) to avoid re-classification.

None
force_qubo bool

When True, QUBO is recommended even for non-binary problems (recorded in metadata; the caller decides whether the problem is actually quantizable).

False

Returns:

Name Type Description
FormulationRecommendation FormulationRecommendation

The recommended primary kind and

FormulationRecommendation

alternatives.

ProblemClass

Bases: Enum

Machine-readable problem category (QMQ-03).

Labels are snake_case so they survive JSON round trips.

parse(value) classmethod

Coerce a snake_case label or member to a :class:ProblemClass.

known_labels() classmethod

All serialized labels of the supported problem classes.

ProblemClassifier

Deterministic structural problem classifier (QMQ-03).

Parameters:

Name Type Description Default
default_class ProblemClass | str

Class assigned when no signal is available.

UNKNOWN

classify(problem, formulation=None)

Classify a domain problem using structural rules only.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand otherwise).

None

Returns:

Name Type Description
ClassificationResult ClassificationResult

The assigned class and its rationale.

UnknownAlgorithmError

Bases: KeyError

Raised when an algorithm id is not registered.

DomainMapper

Bases: ABC

Maps a computational description into a runtime representation.

Subclasses implement one directed mapping. map() validates the input and records the mapping steps; build() materializes the runtime object (a MicroQuantum circuit, a QUBO, ...).

map(program, *, strategy) abstractmethod

Validate the input and record the mapping steps.

build(result) abstractmethod

Materialize the mapped computational representation.

IsingMapper

Maps a :class:QUBOModel to an energy-equivalent :class:IsingModel.

map(qubo, *, strategy=ComputationStrategy.HYBRID)

Record the QUBO -> Ising conversion.

The built :class:~quantsmind.quantum.optimization.ising.IsingModel is attached as the mapping payload; MicroQuantum conversion is deferred to the integration layer.

Raises:

Type Description
MappingError

If qubo is not a :class:QUBOModel.

MappingError

Bases: ValueError

Raised when a domain description cannot be mapped to a computation.

MappingResult dataclass

Record of a domain -> computation mapping.

Parameters:

Name Type Description Default
mapper str

Name of the mapper that produced the record.

required
strategy ComputationStrategy

Strategy the mapping was produced for.

required
source str

A short description of the input representation.

required
target str

A short description of the output representation.

required
steps list[str]

Human-readable mapping steps taken.

list()
metadata dict[str, Any]

Free-form mapping metadata.

dict()
payload Any

Optional non-serializable mapped object.

None

to_dict()

Serialize to a JSON-safe dictionary (payload excluded).

ProblemMapper

Maps a :class:QuantumProblem to an :class:OptimizationModel.

map(problem)

Return the optimization formulation of a problem.

Raises:

Type Description
MappingError

If the problem has no optimization formulation (no objective / unsupported model kind).

QuantumCircuitMapper

Bases: DomainMapper

Real mapping: declarative :class:QuantumProgram -> MicroQuantum circuit.

Validation is performed via :func:validate_program; the actual MicroQuantum circuit is built lazily by :func:build_circuit when :meth:build is called.

Raises:

Type Description
MappingError

If the program is invalid or the strategy is incompatible with quantum execution.

map(program, *, strategy=ComputationStrategy.HYBRID)

Validate the program and record the mapping steps.

Parameters:

Name Type Description Default
program Any

A :class:~quantsmind.quantum.program.QuantumProgram.

required
strategy ComputationStrategy

The chosen computation strategy.

HYBRID

Raises:

Type Description
MappingError

If the strategy is incompatible with quantum execution or the program is not translatable.

build(result)

Materialize the MicroQuantum circuit.

Delegates to :func:quantsmind.quantum.bridge.build_circuit, which in turn calls MicroQuantum's public Operator factories.

QUBOMapper

Maps a binary :class:QuantumProblem to a :class:QUBOModel.

The objective expression (symbolic string or expression node) becomes the quadratic polynomial; a MAXIMIZE objective is negated so the QUBO is always a minimization; supported constraints are folded in as exact penalty terms. The mapping record keeps the original sense and the penalty detail so reports can restore objective and feasibility.

map(problem, *, strategy=ComputationStrategy.HYBRID, penalty=None)

Build the QUBO model and record the mapping.

Raises:

Type Description
MappingError

If the problem cannot be mapped (no objective, non-binary variables, non-symbolic objective, non-quadratic terms, or an unsupported constraint).

ClassificationLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a least-squares fit.

The objective fits y_i ~= sum_f w_f * x_if with binary coefficients selected to minimize :math:SSR = sum_i (y_i - sum_f w_f x_if)^2. Expanding the square turns the problem into a real quadratic binary QUBO whose linear coefficients are sum_i x_if^2 - 2 sum_i y_i x_if and whose pairwise coefficients are 2 sum_i x_if x_ig (diagonal terms fold into the linear part because w_f^2 = w_f). No training is performed; the targets are the supplied numeric class labels.

ClassificationSolution dataclass

Bases: MLBaseSolution

Solution of a classification (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

DecodedHyperparameterChoice dataclass

One decoded hyperparameter-choice decision.

Attributes:

Name Type Description
parameter_name str

Domain hyperparameter name.

param_index int

Deterministic parameter index.

choice_index int

Deterministic choice index.

choice_value Any

The concrete choice value (JSON-safe).

variable_name str

QMQ variable name (h{p}_{c}).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedMLCoefficient dataclass

One decoded fitting-coefficient decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (w<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedModelSelection dataclass

One decoded model-selection decision.

Attributes:

Name Type Description
model_id str

Domain candidate identifier.

index int

Deterministic candidate index.

variable_name str

QMQ variable name (s<c>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

HyperparameterObjective dataclass

Bases: MLObjective

Maximize the total gain of the selected hyperparameter choices.

The one-hot objective sum_{p,c} gain_{p,c} * h_{p,c} is translated as a Qubit MAXIMIZE objective over the per-parameter choice variables. The search space is deterministic and finite (supplied choices only); no search heuristic is involved.

HyperparameterOnePerParameterConstraint dataclass

Bases: MLConstraint

Exactly one choice per hyperparameter (sum_c h_{p,c} = 1 per p).

HyperparameterSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot hyperparameter optimization problem.

Attributes:

Name Type Description
selected_choices dict[str, Any]

Hyperparameter name -> selected choice value.

MLAssignmentConstraint dataclass

Bases: MLConstraint

Delegated: every record assigned to exactly one cluster.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLBaseSolution dataclass

Common domain fields of every ML solution.

Decision fields are derived from the deterministic ML mapping, so they always reflect the feature/candidate/hyperparameter order of the problem. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

MLClusterCountConstraint dataclass

Bases: MLConstraint

Delegated: bound per-cluster record counts.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLClusteringDistanceObjective dataclass

Bases: MLObjective

Delegated clustering distance objective (QMQ-09 Data layer).

Converted into the Data ClusteringDistanceObjective at formulation time; clustering runs as a real quadratic binary QUBO.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

MLCoefficientCountConstraint dataclass

Bases: MLConstraint

Bound the total number of selected fitting coefficients.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_coefficients float

Minimum number of non-zero coefficients (>= 0).

1.0
max_coefficients float | None

Maximum number of non-zero coefficients (None = unbounded).

None
description str

Free-form description.

''

MLConstraint dataclass

Base class of all ML constraints.

domain property

ML-domain label of this constraint.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_data_constraint(problem=None)

Translate into a QMQ-09 data constraint (delegated constraints only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

MLContext dataclass

ML-domain context of an ML problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "classification", "model_selection", "hyperparameter_optimization").

''
subdomain str

Domain subdomain (e.g. "tabular").

'tabular'
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

MLDataSet dataclass

Ordered collection of :class:MLFeature and :class:MLRecord.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every ML problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[MLFeature]

Ordered feature list.

list()
records list[MLRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:MLFeature with name.

record(record_id)

Return the :class:MLRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

targets()

Return target values in deterministic record order.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
MLValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:MLValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

MLError

Bases: ValueError

Base error of the QuantsMind Quantum AI/ML Intelligence layer.

MLFeature dataclass

One numeric feature/dimension of an :class:MLDataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

MLFeatureCountConstraint dataclass

Bases: MLConstraint

Bound the number of selected features (delegated to QMQ-09).

Converted into a Data FeatureCountConstraint at formulation time.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLFeatureSelectionObjective dataclass

Bases: MLObjective

Combined utility-minus-cost objective for delegated feature selection.

Delegated to the QMQ-09 Data layer: converted into a Data FeatureSelectionObjective (utility minus penalty * cost) at formulation time.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

MLFeatureSelectionSolution dataclass

Bases: MLBaseSolution

Wrapper solution of a delegated feature-selection problem (QMQ-09).

Attributes:

Name Type Description
selected_features list[str]

Selected feature names in feature order.

selected_utility float

Total utility of the selected features.

selection_cost float

Total cost of the selected features.

from_data_solution(problem, solution) classmethod

Build the ML wrapper from a delegated QMQ-09 DataSolution.

MLFormulationAdapter

Converts ML problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the w<i> (fitting), s<c> (model selection) and h{p}_{c} (hyperparameter) conventions, objectives keep their senses, and every ML constraint materializes into QMQ constraints. Feature selection and clustering delegate to the QMQ-09 Data layer.

validate(problem)

Return the validation issues of an ML problem (empty = valid).

raise_if_invalid(problem)

Raise :class:MLValidationError when the problem is invalid.

Raises:

Type Description
MLValidationError

If the problem fails validation.

is_delegated(problem)

Return whether the problem is delegated to the QMQ-09 Data layer.

ml_metadata(problem)

JSON-safe ML provenance metadata for the quantum problem.

to_data_problem(problem)

Build the delegated QMQ-09 DataProblem of an ML problem.

Feature selection converts MLFeatureSelectionObjective and MLFeatureCountConstraint into their Data equivalents; clustering converts the ML clustering objective/constraints (with default assignment semantics when absent).

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem (feature selection or clustering).

required

Raises:

Type Description
MLValidationError

If the problem is not a delegated family or cannot be expressed by the Data layer.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert an ML problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
MLValidationError

If the ML problem is invalid.

formulate(problem)

Return the existing QMQ formulation of an ML problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

MLHyperparameter dataclass

One hyperparameter with a deterministic finite choice space.

Parameters:

Name Type Description Default
name str

Unique hyperparameter name.

required
choices list[MLHyperparameterChoice]

Ordered choice list (at least one).

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

choice_count property

Number of choices.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a hyperparameter from :meth:to_dict output.

MLHyperparameterChoice dataclass

One choice of an :class:MLHyperparameter.

Parameters:

Name Type Description Default
value Any

The concrete choice value (free-form but JSON-safe, e.g. a float / string / int). Used only for reporting.

None
gain float

Caller-supplied non-negative gain of this choice. The hyperparameter objective maximizes the total gain of the chosen configuration.

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a choice from :meth:to_dict output.

MLMapper dataclass

Maps a validated ML problem to a deterministic variable mapping.

Mirrors the :class:DataMapper pattern: validates, then provides :meth:map (which returns an :class:MLMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

Raises:

Type Description
MLValidationError

If the problem is delegated to the QMQ-09 Data layer (use the Data mapper on the delegated problem).

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

MLMapping dataclass

Deterministic mapping between ML variables and QMQ indices.

Created by :meth:MLMapper.map from a validated :class:MLProblem.

variable_names property

QMQ variable names in deterministic order.

coefficient(feature_name)

Return the decoded coefficient for feature_name (or None).

candidate(model_id)

Return the decoded model selection for model_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

MLMetrics dataclass

Deterministic outcome metrics of an ML solve.

Attributes:

Name Type Description
problem_type str

ML problem family ("classification", "regression", "model_selection" or "hyperparameter_optimization").

ssr float | None

Sum of squared residuals of the fitted linear model (fitting).

mse float | None

Mean squared error (ssr / num_records, fitting).

selected_feature_count int

Number of selected coefficients (fitting).

selected_model_id str

Selected candidate identifier (model selection).

selected_loss float | None

Validation loss of the selected candidate.

selected_penalty float | None

Complexity penalty of the selected candidate.

total_gain float | None

Total gain of the selected hyperparameter configuration.

objective_value float | None

Primary objective value decoded from the assignment.

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

MLModelCandidate dataclass

One model-selection candidate with caller-supplied validation scores.

Parameters:

Name Type Description Default
model_id str

Unique candidate identifier.

required
validation_loss float

Caller-supplied candidate validation loss (must be finite and non-negative).

0.0
complexity_penalty float

Caller-supplied complexity penalty (must be finite and non-negative).

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

objective()

Return validation_loss + complexity_penalty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a candidate from :meth:to_dict output.

MLObjective dataclass

Base class of all ML objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

ML-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_data_objective(problem=None)

Translate into a QMQ-09 data objective (delegated objectives only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

MLOptimizationConfiguration dataclass

Execution/optimization configuration of an ML problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
MLValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

MLOptimizationResult dataclass

Result of an ML solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult). The solution is an ML domain solution or, for delegated clustering, the QMQ-09 DataSolution.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

MLOptimizer

Solves and benchmarks :class:MLProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the ML adapter (delegating feature selection and clustering to the QMQ-09 Data adapter), workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the ML layer.

solve(problem, *, strategy=None, config=None)

Solve an ML problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into an ML domain solution with ML metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
MLValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark an ML problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem MLProblem

The ML problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config MLOptimizationConfiguration | None

Optional execution/optimization configuration.

None

mapping(problem)

Return the deterministic ML variable mapping of a problem.

MLProblem dataclass

Domain problem of the AI/ML Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset MLDataSet | None

The ordered ML dataset (required for classification, regression, feature selection and clustering; optional for model selection and hyperparameter optimization).

None
problem_type MLProblemType

Family (:class:MLProblemType).

CLASSIFICATION
objectives list[MLObjective]

Ordered list of ML objectives (names must be unique).

list()
constraints list[MLConstraint]

Ordered list of ML constraints (names must be unique).

list()
context MLContext | None

Optional ML context (purpose / strategy intent).

None
candidates list[MLModelCandidate]

Ordered model-selection candidates (model selection only).

list()
hyperparameters list[MLHyperparameter]

Ordered hyperparameter space (hyperparameter optimization only).

list()
k int | None

Number of clusters (clustering only).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
MLValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a dataset/candidate/parameters configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

hyperparameter_choice_counts property

Return per-hyperparameter choice counts in deterministic order.

feature_variables()

Return the binary coefficient variables w0 .. w{n-1} in feature order.

selection_variables()

Return the one-hot model-selection variables s0 .. s{n-1}.

hyperparameter_variables()

Return the one-hot hyperparameter choice variables (parameter-major).

decision_variables()

Return the deterministic decision-variable list for this problem.

Fitting problems yield one binary variable per feature, model selection one binary variable per candidate and hyperparameter problems one binary variable per (parameter, choice) pair in parameter-major order. Feature-selection and clustering problems are delegated to the QMQ-09 Data layer and expose no ML variables here.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:MLValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

MLProblemType

Bases: Enum

Supported AI/ML problem families.

Attributes:

Name Type Description
CLASSIFICATION

Binary-coefficient least-squares classifier fit.

REGRESSION

Binary-coefficient least-squares regression fit.

FEATURE_SELECTION

Binary selection of a feature subset (delegated to the QMQ-09 Data layer).

MODEL_SELECTION

One-hot selection of one candidate model.

HYPERPARAMETER_OPTIMIZATION

One-hot choice per hyperparameter.

CLUSTERING

Assignment of records to k clusters (delegated to the QMQ-09 Data layer).

parse(value) classmethod

Coerce a name or member to a :class:MLProblemType.

MLRecord dataclass

One observation inside an :class:MLDataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
target float

Numeric target value (a class index for classification, a continuous response for regression).

0.0
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
MLValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

MLValidationError

Bases: MLError

Raised when an ML model or problem fails domain validation.

ModelSelectionObjective dataclass

Bases: MLObjective

Minimize the selected candidate's validation_loss + complexity_penalty.

The one-hot objective sum_c (loss_c + penalty_c) * s_c is translated as a Qubit MINIMIZE objective over the candidate variables. Candidate metrics are supplied by the caller; no training is performed.

ModelSelectionOneHotConstraint dataclass

Bases: MLConstraint

Exactly one candidate is selected (sum_c s_c = 1).

ModelSelectionSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot model-selection problem.

Attributes:

Name Type Description
selected_model_id str

Identifier of the selected candidate.

RegressionLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a regression fit.

Identical expansion to :class:ClassificationLossObjective; the targets are continuous response values instead of class labels.

RegressionSolution dataclass

Bases: MLBaseSolution

Solution of a regression (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

ClassicalSolverResult dataclass

Result of an exhaustive classical run.

Parameters:

Name Type Description Default
solver str

Solver identity ("classical/exhaustive").

'classical/exhaustive'
exhaustive bool

Always True (this is an exhaustive baseline).

True
assignment dict[str, int]

Chosen binary assignment (variable name -> 0/1).

dict()
energy float

QUBO energy of the chosen assignment (minimization form, penalties included).

0.0
objective_value float | None

Optional true objective value of the assignment.

None
feasible bool

Whether the chosen assignment satisfies the predicate.

True
num_evaluations int

Number of enumerated assignments (2^n).

0
num_feasible int

Number of assignments satisfying the predicate.

0
limit int

The max_variables limit that was enforced.

0
metadata dict[str, Any]

Free-form solver metadata.

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

ConstraintPenalizer

Converts supported constraints into exact QUBO penalty terms.

Parameters:

Name Type Description Default
penalty float | None

Positive penalty multiplier P. When None a default of 10.0 is used. The caller (typically the QUBO mapper) should scale P above the objective range so that violating a constraint can never be attractive.

None

penalize(constraint)

Return the QUBO penalty term expansion for a constraint.

Raises:

Type Description
UnsupportedConstraintError

For unsupported constraint types.

ExhaustiveLimitError

Bases: ValueError

Raised when exhaustive enumeration would exceed the configured limit.

ExhaustiveSolver

Deterministic exhaustive solver for small QUBOs.

Parameters:

Name Type Description Default
max_variables int

Upper bound on :attr:QUBOModel.num_variables. Enumeration of 2^n assignments is only attempted for n <= max_variables.

20

solve(qubo, *, is_feasible=None, objective_fn=None)

Enumerate all 2^n assignments and return the best feasible one.

The "best" assignment minimises the QUBO energy among feasible assignments. Assignment order is deterministic (Gray-code enumeration); ties keep the first-seen assignment.

Parameters:

Name Type Description Default
qubo QUBOModel

The model to solve.

required
is_feasible Callable[[dict[str, int]], bool] | None

Optional predicate deciding which assignments are feasible. When omitted, every assignment is feasible.

None
objective_fn Callable[[dict[str, int]], float] | None

Optional true-objective evaluator used only to populate :attr:ClassicalSolverResult.objective_value.

None

Raises:

Type Description
ExhaustiveLimitError

If qubo.num_variables > max_variables.

NoFeasibleSolutionError

If no assignment is feasible.

IsingModel dataclass

A canonical Ising/spin model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered spin variable names.

required
h dict[str, float]

Variable name -> linear field h_i.

dict()
couplings dict[tuple[str, str], float]

(i, j) with i < j -> coupling J_ij.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only).

0.0
name str

Model label.

'ising'
metadata dict[str, Any]

Free-form model metadata.

dict()

Raises:

Type Description
IsingError

If variable names are duplicated, a field/coupling references an unknown variable, or a self-coupling is given.

num_variables property

Number of spin variables.

num_terms property

Number of field + coupling terms.

add_field(name, value)

Add (or accumulate) a field h_i and return self.

add_coupling(left, right, value)

Add (or accumulate) a coupling J_ij and return self.

energy(assignment)

Compute the Ising energy of a spin assignment.

assignment may be a dict name -> -1/+1 or a sequence of spins in :attr:variables order.

Raises:

Type Description
IsingError

If an assignment is missing, unknown, or not -1/+1.

to_qubo()

Convert to an energy-equivalent :class:QUBOModel via s = 2x - 1.

from_qubo(qubo) classmethod

Convert a QUBO to an energy-equivalent :class:IsingModel.

Applies x = (s + 1) / 2: h_i = a_i/2 + sum_j(b_ij)/4 and J_ij = b_ij/4.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an IsingModel from :meth:to_dict output.

NoFeasibleSolutionError

Bases: ValueError

Raised when no assignment satisfies the feasibility predicate.

PenaltyTerm dataclass

One expanded QUBO penalty term for a constraint.

Parameters:

Name Type Description Default
constraint str

Name of the originating constraint.

required
operator str

Serialized operator ("==", "<=", ">=").

required
weight float

Penalty multiplier P.

required
linear dict[str, float]

Variable name -> linear coefficient.

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient.

dict()
constant float

Additive penalty constant.

0.0
slack_variables list[str]

Slack variables introduced for inequalities.

list()
expression str

Human-readable residual squared, e.g. "P = 10.0 * (2*x0 + 3*x1 - 5)^2".

''

to_dict()

Serialize to a JSON-safe dictionary.

QUBOModel dataclass

A canonical binary quadratic model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered variable names (one QUBO bit per variable).

required
linear dict[str, float]

Variable name -> linear coefficient (c_i).

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient (c_ij). Diagonal terms are rewritten into linear.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only; both constant and offset contribute to :meth:energy).

0.0
name str

Model label.

'qubo'
metadata dict[str, Any]

Free-form model metadata (e.g. penalty records).

dict()

Raises:

Type Description
QUBOError

If names are invalid/duplicated, a coefficient is not finite, a quadratic key is malformed (i == j or reversed hands accepted and canonicalised), or a quadratic references an unknown variable.

num_variables property

Number of QUBO variables (bits).

num_terms property

Number of linear + pairwise terms.

degree property

Polynomial degree (2 when pairwise terms exist, else 1).

add_linear(name, value)

Add (or accumulate) a linear coefficient and return self.

add_quadratic(left, right, value)

Add (or accumulate) a pairwise coefficient and return self.

Raises:

Type Description
QUBOError

If left == right (diagonal terms belong on linear for binary variables) or a variable is unknown.

add_constant(value)

Add to the constant term and return self.

energy(assignment)

Compute the QUBO energy of a binary assignment.

assignment may be a dict mapping variable name -> 0/1 or a sequence of bits in :attr:variables order.

Raises:

Type Description
QUBOError

If an assignment is missing, unknown, or not binary.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QUBOModel from :meth:to_dict output.

GateSpec dataclass

A single gate operation on named qubits.

Parameters:

Name Type Description Default
name str

Gate name ("h", "x", "cx", "rx", ...).

required
qubits tuple[int, ...]

Qubit indices the gate acts on (1 or 2 entries).

required
params tuple[float, ...]

Optional numeric rotation parameters ((theta,) for rx).

()

from_tuple(name, qubits, *params) classmethod

Build a GateSpec from positional parts.

to_dict()

Serialize to a JSON-safe dictionary.

QuantumProgram dataclass

A declarative quantum program for translation to MicroQuantum.

Parameters:

Name Type Description Default
num_qubits int

Fixed number of qubits.

required
operations list[GateSpec]

Ordered gate operations.

list()
name str

Optional program label (used for provenance).

'program'
metadata dict[str, Any]

Optional domain metadata attached to the program.

dict()

num_operations property

Number of gate operations in the program.

gate_names property

Ordered gate names, for quick inspection.

add(name, qubits, *params)

Append a gate operation and return self (fluent).

add_gate(spec)

Append a pre-built GateSpec and return self.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QuantumProgram from :meth:to_dict output.

bell_state() classmethod

Convenience constructor for a 2-qubit Bell state program.

AlgorithmInterpretation dataclass

Algorithm and runtime details of the executed run.

Parameters:

Name Type Description Default
algorithm str

Algorithm id (e.g. "qaoa", "exhaustive") or "".

''
backend str

Backend that executed the quantum leg or "".

''
optimizer str

Optimizer label used by the variational loop or "".

''
num_qubits int | None

Mapped qubit count or None.

None
circuit_depth int | None

Circuit depth or None.

None
num_gates int | None

Gate count or None.

None
shots int | None

Shot count or None.

None
microquantum_version str

MicroQuantum version string or "".

''
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

BenchmarkInterpretation dataclass

Interpreted benchmark outcome vs the classical baseline.

Parameters:

Name Type Description Default
benchmark_id str

Id of the benchmark (if any).

''
baseline str

Baseline label ("classical").

'classical'
winner str | None

QMQ-05 winner classification value or None.

None
objective_delta float | None

Normalized objective delta (strategy - baseline).

None
measured_basis list[str]

What the outcome was ranked on (e.g. ["objective"]).

list()
strategy_status str

Status of the benchmarked strategy leg.

''
baseline_status str

Status of the baseline leg.

''
outcome str

"better" / "worse" / "tie" / "not_comparable" for the benchmarked strategy.

''
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ExecutionInterpretation dataclass

Execution-level status and cost facts.

Parameters:

Name Type Description Default
executor str

Executor label (e.g. "classical/exhaustive") or "".

''
status str

Execution status ("executed" / "failed" / ...).

'executed'
error str

Recorded error message or "".

''
failure_category str | None

Coarse failure category when the run failed.

None
wall_clock_time float | None

Wall-clock time of the interpreted phase.

None
num_evaluations int | None

Number of objective evaluations.

None
iterations int | None

Variational iterations.

None
executions int

Number of executions.

0
retries int

Number of retries.

0
selected_leg str | None

Selected leg of a hybrid run ("classical" / "quantum") or None.

None
classical_status str | None

Status of the classical leg/baseline or None.

None
quantum_status str | None

Status of the quantum leg or None.

None
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FeasibilityInterpretation dataclass

Structured view of constraint satisfaction.

Parameters:

Name Type Description Default
status FeasibilityStatus

Feasibility status.

UNKNOWN
satisfied int

Number of satisfied constraints.

0
violated int

Number of violated constraints.

0
unknown int

Number of unevaluated constraints.

0
total int

Total number of assessed constraints.

0
violated_constraints list[str]

Names of violated constraints (when known).

list()
violation_magnitude float

Total numerical violation magnitude.

0.0
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FeasibilityStatus

Bases: Enum

Constraint-satisfaction status of a solution.

Attributes:

Name Type Description
FEASIBLE

No constraint is violated.

INFEASIBLE

At least one constraint is violated.

UNKNOWN

Constraint satisfaction could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:FeasibilityStatus.

Interpretation dataclass

A structured, data-derived explanation of a solution.

Parameters:

Name Type Description Default
summary str

One-line human-readable summary.

''
quality InterpretationQuality

Feasibility/evidence quality level.

UNKNOWN
confidence float | None

Optional numeric confidence in [0, 1].

None
details dict[str, Any]

Free-form facts (feasible, objective values, statuses).

dict()
metadata dict[str, Any]

Free-form metadata (e.g. strategy used).

dict()

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Interpretation from :meth:to_dict output.

InterpretationQuality

Bases: Enum

Overall confidence in a solution interpretation.

Attributes:

Name Type Description
HIGH

Fully evaluated and feasible.

MEDIUM

Partially evaluated (some constraints unknown).

LOW

Infeasible (one or more constraints violated).

UNKNOWN

Nothing could be evaluated.

InterpretationStatus

Bases: Enum

Outcome status of the interpreted run.

Attributes:

Name Type Description
EXECUTED

The run completed as planned.

FAILED

The run recorded a failure.

DEGRADED

The run completed, but only after a fallback (e.g. a quantum-capable strategy executed classically).

UNKNOWN

No execution status could be determined.

parse(value) classmethod

Coerce a label or member to an :class:InterpretationStatus.

Limitation dataclass

One honest caveat about what an interpretation does not establish.

Parameters:

Name Type Description Default
category str

Machine-readable category, e.g. "known_optimum_unavailable".

required
message str

Human-readable limitation statement.

required

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a limitation from :meth:to_dict output.

ObjectiveInterpretation dataclass

Structured view of the interpreted objective.

Parameters:

Name Type Description Default
sense str

Optimization sense ("minimize" / "maximize").

'minimize'
objective_value float | None

Recorded objective value of the returned solution.

None
energy float | None

Recorded QUBO/Ising energy (when reported).

None
known_optimum float | None

Known optimum supplied to the benchmark (or None).

None
optimality_gap float | None

Relative distance from the known optimum (None when no optimum is available).

None
approximation_ratio float | None

Approximation ratio vs the known optimum (None when not interpretable).

None
quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Evidential basis of the quality claim.

UNCERTAIN
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

Provenance dataclass

Where-and-how metadata attached to a domain result.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Computation strategy used.

None
formulation str

Formulation kind (e.g. "optimization").

''
algorithm str

Algorithm used (e.g. "vqe", "grover", "qaoa", "exhaustive") or "".

''
executor str

Executor identity (e.g. "classical/exhaustive", "microquantum/qaoa") or "".

''
backend str

Backend that executed the workflow or "".

''
execution_metadata dict[str, Any]

Metadata from the execution layer (experiment id, actual backend, shots, counts-derived summary).

dict()
sdk_version str

QuantsMind SDK version that produced the result.

_sdk_version()
created_at str

UTC ISO timestamp of record creation.

(lambda: isoformat())()
metadata dict[str, Any]

Free-form provenance metadata.

dict()

strategy_label property

Serialized strategy label (e.g. "hybrid").

from_execution(*, strategy=None, formulation='', algorithm='', executor='', backend='', execution=None, metadata=None) classmethod

Build provenance, deriving execution metadata from a result.

execution may be any object exposing experiment_id, program_name, backend_name, shots and provenance attributes (e.g. a :class:~quantsmind.quantum.circuit_result.QuantumResult), or a QMQ-02 executor result exposing solver/energy (e.g. :class:~quantsmind.quantum.optimization.classical.ClassicalSolverResult or :class:~quantsmind.quantum.integration.microquantum.QaoaExecutionResult).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Provenance from :meth:to_dict output.

ProvenanceOverview dataclass

Consolidated provenance view of an interpreted run.

Parameters:

Name Type Description Default
problem_name str

Name of the problem that was solved.

''
formulation str

Formulation kind ("optimization") or "".

''
strategy str | None

Strategy that produced the outcome or None.

None
algorithm str

Algorithm id or "".

''
executor str

Executor label or "".

''
backend str

Backend used or "".

''
microquantum_version str

MicroQuantum version string or "".

''
sdk_version str

QuantsMind SDK version or "".

''
benchmark_id str | None

Benchmark id (if any) or None.

None
baseline str

Classical baseline label or "".

''
created_at str

UTC ISO timestamp of the report.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

Qualification

Bases: Enum

Evidential basis behind an interpretation claim.

Attributes:

Name Type Description
MATHEMATICAL_PROOF

Optimality established by an exact method (e.g. exhaustive search over the full discrete space).

EMPIRICAL

Claim rests on recorded measurements.

HEURISTIC

Claim rests on a heuristic method; optimality is not established.

UNCERTAIN

Insufficient evidence for any stronger claim.

parse(value) classmethod

Coerce a label or member to a :class:Qualification.

ResultInterpretation dataclass

Complete structured interpretation of one execution / benchmark result.

All sections are always present when constructed by :class:ResultInterpreter (they may carry None / UNKNOWN values when information is missing). The flat view properties mirror selected machine-readable fields so downstream consumers do not need to descend into the sections.

Parameters:

Name Type Description Default
status InterpretationStatus

Run :class:InterpretationStatus.

UNKNOWN
summary str

Generated human-readable narrative (only supported claims).

''
solution_quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Overall evidential basis of the quality claim.

UNCERTAIN
feasibility FeasibilityInterpretation | None

Constraint satisfaction section.

None
objective ObjectiveInterpretation | None

Objective facts and quality section.

None
benchmark BenchmarkInterpretation | None

Benchmark outcome section (None without a benchmark).

None
strategy StrategyInterpretation | None

Requested/selected/actual strategy section.

None
algorithm AlgorithmInterpretation | None

Algorithm and runtime details.

None
execution ExecutionInterpretation | None

Execution status and cost facts.

None
limitations list[Limitation]

Applicable caveats (:class:Limitation list).

list()
provenance ProvenanceOverview | None

Consolidated provenance view.

None

winner property

Benchmark winner classification value (None without a benchmark).

objective_value property

Recorded objective value of the decoded solution.

optimality_gap property

Relative distance from the known optimum (None when unavailable).

approximation_ratio property

Approximation ratio vs the known optimum (None when unavailable).

requested_strategy property

Strategy the caller asked for.

selected_strategy property

Strategy actually selected for execution.

actual_executor property

Executor label that produced the outcome.

fallback_used property

Whether execution degraded to another strategy.

feasibility_status property

Feasibility status value (None when the section is absent).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ResultInterpreter

Builds :class:ResultInterpretation objects from reports and benchmarks.

The interpreter is stateless apart from its numerical tolerances; the same inputs always produce the same interpretation (deterministic).

interpret_report(report, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a solution report without benchmark evidence.

interpret_benchmark(benchmark, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a benchmark result (using its embedded report when present).

interpret(report=None, *, benchmark=None, gap_tolerance=None, near_optimal_tolerance=None)

Produce a full structured interpretation of a run.

Parameters:

Name Type Description Default
report SolutionReport | None

The workflow :class:SolutionReport (optional when full benchmark evidence exists, otherwise required for the solution-level facts).

None
benchmark BenchmarkResult | None

The QMQ-05 :class:BenchmarkResult (optional).

None
gap_tolerance float | None

Optimality distance considered exact (overrides the interpreter default).

None
near_optimal_tolerance float | None

Gap below which a non-optimal result is labelled :attr:SolutionQuality.NEAR_OPTIMAL.

None

Returns:

Name Type Description
A ResultInterpretation

class:ResultInterpretation over the available data.

summarize(report=None, *, benchmark=None)

Shortcut returning just the generated narrative of an interpretation.

SolutionInterpreter

Produces conservative, data-derived interpretations of solutions.

The interpreter derives its statements only from the solution itself (feasibility, objective values, constraint statuses, score) and the strategy that produced it. No domain meaning is invented.

interpret(solution, *, strategy=None)

Interpret a solution using only its own data.

Parameters:

Name Type Description Default
solution ProblemSolution

The domain solution to interpret.

required
strategy ComputationStrategy | str | None

Optional computation strategy used (recorded as metadata only).

None

Returns:

Name Type Description
An Interpretation

class:Interpretation constructed from solution facts.

__call__(solution, *, strategy=None)

Convenience alias for :meth:interpret.

SolutionQuality

Bases: Enum

Evidence-backed quality classification of a solution.

Attributes:

Name Type Description
OPTIMAL

Feasible and equal to the known optimum (within tolerance).

NEAR_OPTIMAL

Feasible and within the near-optimal tolerance of the known optimum.

FEASIBLE

Feasible, with no evidence basis for optimality (no known optimum, or a gap beyond the near-optimal tolerance).

INFEASIBLE

One or more constraints are violated.

UNKNOWN

Feasibility could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:SolutionQuality.

SolutionReport dataclass

Complete record of one workflow run for a domain problem.

Parameters:

Name Type Description Default
problem QuantumProblem | None

The problem that was solved.

None
formulation MathematicalModel | None

The formulation model built for the problem.

None
strategy ComputationStrategy | None

The strategy selected and used.

None
mapping MappingResult | None

The mapping record from program to runtime object.

None
execution Any | None

The execution result (QuantumResult or raw engine result).

None
solution ProblemSolution | None

The domain-level solution.

None
interpretation Interpretation | None

Data-derived interpretation of the solution.

None
provenance Provenance | None

Where-and-how metadata for the run.

None
classification ClassificationResult | None

QMQ-03 problem classification (optional).

None
recommendation AlgorithmRecommendation | None

QMQ-03 algorithm recommendation (optional).

None
plan ComputationPlan | None

QMQ-03 computation plan (optional).

None
classical_execution ClassicalExecutionResult | None

QMQ-04 classical leg result (classical/hybrid runs).

None
quantum_execution QuantumExecutionResult | None

QMQ-04 quantum leg result (quantum/hybrid runs).

None
comparison ExecutionComparison | None

QMQ-04 hybrid comparison + selection (hybrid runs).

None
selected_leg str | None

QMQ-04 selected leg ("classical"/"quantum").

None
result_interpretation ResultInterpretation | None

QMQ-06 structured interpretation (optional).

None
benchmark BenchmarkResult | None

QMQ-05 benchmark result this report belongs to (optional).

None
created_at str

UTC ISO timestamp of report creation.

(lambda: isoformat())()

to_dict()

Serialize the report to a JSON-safe dictionary.

StrategyInterpretation dataclass

Requested vs selected vs executed strategy.

Parameters:

Name Type Description Default
requested_strategy str | None

Strategy the caller asked for.

None
selected_strategy str | None

Strategy actually selected for execution.

None
actual_strategy str | None

Strategy that produced the outcome (may be a degraded fallback).

None
fallback_used bool

Whether execution degraded to another strategy.

False
reason str

Reason for the fallback (when used).

''
explanation str

Human-readable sentence.

''

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ComputationStrategy

Bases: Enum

How a domain problem should be computed.

Attributes:

Name Type Description
CLASSICAL

Classical computation on CPUs/GPUs.

QUANTUM

End-to-end quantum computation (MicroQuantum runtime).

HYBRID

Classical domain pre/post-processing with a quantum kernel.

QUANTUM_INSPIRED

Classical algorithms inspired by quantum mechanics.

AUTO

Deterministic rule-based selection (see :class:StrategySelector).

uses_quantum_runtime property

True for strategies that require MicroQuantum execution.

parse(value) classmethod

Coerce a name or member to a :class:ComputationStrategy.

StrategySelector

Selects a :class:ComputationStrategy for a domain problem.

Selection rules (QMQ-01, fully deterministic):

  1. An explicit preferred_strategy is honoured; if it requires a quantum runtime that is unavailable it is downgraded to CLASSICAL.
  2. If no quantum backend is available, the strategy is CLASSICAL.
  3. Otherwise a size-based heuristic applies:

  4. n <= quantum_attempt_threshold -> HYBRID (small problems can run a quantum kernel with classical pre/post-processing).

  5. quantum_attempt_threshold < n <= quantum_inspired_threshold -> QUANTUM_INSPIRED (too large for a variational circuit with a reasonable shot budget, but suitable for classical algorithms inspired by quantum mechanics).
  6. n > quantum_inspired_threshold -> CLASSICAL (domain pre-processing only).

A problem can override rule 3 by setting problem.metadata["quantum_suitable"] = False (then CLASSICAL is returned).

Parameters:

Name Type Description Default
quantum_attempt_threshold int

Problem size at or below which a quantum kernel is attempted.

25
quantum_inspired_threshold int

Problem size at or below which QUANTUM_INSPIRED is used.

500
quantum_enabled bool

Master switch allowing quantum-family strategies.

True

select(problem, *, backend_available=None, available_algorithms=None)

Choose a strategy deterministically.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
backend_available bool | None

If given, overrides the global MicroQuantum availability check.

None
available_algorithms set[str] | None

If given and empty, forces CLASSICAL.

None

select_reasoned(problem, *, backend_available=None, available_algorithms=None, classification=None, formulation=None, capabilities=None)

Select a strategy with a full, explainable rationale (QMQ-03 §7).

The decision is made by the same deterministic rules as :meth:select, but the AUTO path may additionally consider the problem class, formulation kind and capability flags when they are provided — instead of size alone. Without those signals the result is identical to :meth:select (backward compatible).

Returns:

Name Type Description
StrategyDecision StrategyDecision

The selected strategy plus reasons and signals.

explain(problem, *, backend_available=None, available_algorithms=None)

Return the selected strategy and a human-readable rationale.

Useful for logging and testing but never consumed by the workflow itself.

QuantumWorkflow

Pipelines a domain problem through formulation, strategy, mapping, execution and solution reporting.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem to process.

required
program Any | None

Optional :class:QuantumProgram attached for the QMQ-01 low-level quantum execution path. When provided, the quantum strategy runs the explicit program instead of the automatic QUBO/Ising path.

None
backend str | None

Backend name (e.g. "statevector") or an engine backend instance.

None
shots int

Number of shots per execution.

1024
seed int | None

Optional RNG seed for reproducibility.

None
name str

Workflow/experiment label.

'quantum_workflow'
selector StrategySelector | None

Optional :class:StrategySelector (defaults to a fresh rule-based selector).

None
mapper DomainMapper | None

Optional :class:DomainMapper (defaults to :class:QuantumCircuitMapper); only used for the explicit program path.

None
classical_executor ExhaustiveSolver | None

Optional :class:ExhaustiveSolver for the classical baseline (defaults to a fresh solver with max_variables=20).

None
num_layers int

QAOA layers for the automatic quantum path.

1
penalty float | None

Optional constraint penalty multiplier for the QUBO mapping.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (useful to bound runtime in tests/CI).

None
classifier ProblemClassifier | None

Optional :class:ProblemClassifier (QMQ-03).

None
algorithm_selector AlgorithmSelector | None

Optional :class:AlgorithmSelector (QMQ-03).

None
capabilities CapabilityModel | None

Optional :class:CapabilityModel snapshot (detected on demand when omitted).

None
requested_algorithm str | None

Optional explicit algorithm id honoured by the QMQ-03 recommender.

None
allow_algorithm_fallback bool

If True, an unavailable requested algorithm falls back to an executable replacement (recorded, never silent).

False
executor Executor | None

Optional QMQ-04 :class:Executor overriding the strategy-derived executor (used as-is by :meth:create_executor).

None
options ExecutionOptions | None

Optional QMQ-04 :class:ExecutionOptions; workflow-level arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults it can override.

None

execution_options()

Resolve execution options for the current decisions.

Workflow constructor arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults; an explicit :class:ExecutionOptions on the constructor overrides them.

create_executor()

Build (or reuse) the executor for the selected strategy (QMQ-04 §4).

The classical executor reuses the workflow's configured :class:ExhaustiveSolver; the quantum executor delegates to MicroQuantum's QAOA.

formulate()

Build (or reuse) a formulation for the problem.

classify()

Classify the problem (QMQ-03).

Returns:

Name Type Description
ClassificationResult ClassificationResult

Deterministic structural classification of

ClassificationResult

the problem.

select_strategy()

Select the computation strategy for the problem.

Uses the reasoned (QMQ-03) path once the problem has been classified; otherwise the legacy QMQ-01 selector is used so callers that never classify keep identical behaviour.

recommend()

Recommend an algorithm for the classified problem (QMQ-03).

Runs classification + strategy selection first, then asks the :class:AlgorithmSelector for a scored recommendation with an executable fallback chain.

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

The scored recommendation.

plan()

Build a declarative computation plan for the current decisions.

Returns:

Name Type Description
ComputationPlan ComputationPlan

The plan (QMQ-03, ready for QMQ-04).

map()

Map the problem to a computational representation.

Routing rules:

  • An attached :class:QuantumProgram uses the QMQ-01 circuit mapping (quantum strategies only).
  • Otherwise CLASSICAL uses QUBOMapper (problem -> QUBO).
  • QUANTUM/HYBRID additionally use IsingMapper (QUBO -> Ising). QUANTUM requires MicroQuantum; HYBRID degrades to the QUBO mapping when MicroQuantum is absent (the quantum leg is then recorded as unavailable during execution — a documented fallback, never a fabricated quantum result).

Raises:

Type Description
MicroQuantumUnavailableError

For a QUANTUM strategy when the optional dependency is missing (an ImportError-compatible subclass of :class:WorkflowError).

WorkflowError

For unsupported strategies.

execute()

Execute the mapped representation via the strategy-derived executor.

QMQ-04: the QMQ-03 computation plan is executed through the :class:Executor built by :meth:create_executor using :meth:execution_options:

  • CLASSICAL: exhaustive baseline over the QUBO.
  • QUANTUM: QAOA delegated to MicroQuantum (validated).
  • HYBRID: both legs run; an unavailable quantum leg falls back to the classical result and is recorded as skipped — never fabricated.
  • Explicit-program path: run through :class:QuantumExperiment.

Raises:

Type Description
WorkflowError

If mapping/planning/execution cannot proceed.

UnsupportedStrategyError

If the plan resolves to a strategy this layer cannot execute.

build_solution()

Derive a domain solution from the execution result.

Quantum-program executions decode the most probable measurement bitstring using problem.metadata["encoding"] (QMQ-01). QMQ-02 executions (classical baseline, QAOA) carry an explicit assignment and are used directly. Objectives and constraints support callable and symbolic string expressions.

interpret(solution)

Produce a data-derived interpretation of the solution.

build_provenance(execution=None)

Build provenance for the current run.

Hybrid executions record the selected leg as the provenance executor ("hybrid") and carry the explicit comparison in metadata.

run()

Run the full pipeline and return a :class:SolutionReport.

Pipeline (QMQ-03): formulate -> classify -> select strategy -> recommend algorithm -> build plan -> map -> execute.

WorkflowState

Bases: Enum

Lifecycle state of one :class:QuantumWorkflow run (QMQ-04 §3).

Transitions are forward-only and lenient: intermediate stages may be skipped (e.g. map() jumps straight to MAPPED), but a completed or failed workflow cannot be reused and no stage can move backwards.

microquantum_available()

Return True when the optional microquantum package is installed.

approximation_ratio(achieved, optimum, sense)

Approximation ratio against a known optimum, where mathematically appropriate (QMQ-05 §6).

Formula (documented):

  • MAXIMIZE: ratio = achieved / optimum
  • MINIMIZE: ratio = optimum / achieved

The ratio is only reported (≤1 when the result is suboptimal) for positive optima and non-negative meaningful denominators. Returns None whenever the ratio is not interpretable (zero optimum, missing values, conflicting signs) — no value is manufactured.

b1_knapsack()

3-var knapsack: maximize value under one capacity constraint.

Optimum: x0=1, x1=1, x2=0 -> objective 7 (classical, exact).

b2_linear_max()

3-var unconstrained maximize linear objective.

Optimum: all ones -> objective 12 (classical, exact).

b3_qubo_min()

2-var QUBO minimize: x0 + x1 - 2*x0*x1.

Optimum: x0=x1=1 -> objective 0 (a zero-optimum case exercising the optimality_gap/approximation_ratio division handling).

b4_maxcut_triangle()

Max-Cut on the triangle (QMQ-04 canonical example, reused unchanged).

Optimum cut: 2 (any single-edge separation is max for the triangle); a genuinely quantum-capable HYBRID run compares against the exact classical cut value.

b5_geq_max()

4-var maximize with a >= constraint.

Optimum: all ones -> objective 8 (constraint exactly relaxed, classical). Non-trivially constrained so the exhaustive baseline walks a larger space than the unconstrained members.

constraint_violations(problem, assignment)

Count and magnitude of constraint violations for an assignment.

Uses the existing domain :class:Constraint abstraction (QMQ-05 §12): a constraint is violated iff its :meth:Constraint.evaluate status is VIOLATED; the magnitude is the numeric excess over the RHS value (missing/unevaluable expressions contribute 0).

Returns (count, magnitude).

default_suite(*, shots=512, seed=7, max_variables=20)

Build the canonical QMQ-05 suite of five deterministic benchmarks.

Parameters:

Name Type Description Default
shots int

Quantum-leg shot count for HYBRID members.

512
seed int

Reproducibility seed for HYBRID members.

7
max_variables int

Classical baseline exhaustive limit.

20

default_suite_examples()

Return the members of :func:default_suite (convenience for tooling).

is_better(left, right, sense)

True when left strictly outperforms right under sense.

metrics_rank_key(metrics, sense)

Deterministic (feasibility class, violations, normalized score) key.

Higher tuple is better: feasible beats unknown beats infeasible; among infeasible results a lower violation magnitude beats a higher one (the magnitude is negated so fewer violations rank higher), then the normalized objective decides.

normalized_score(sense, objective_value, energy)

Return a higher-is-better scalar for ranking or None.

The domain objective is normalized by its sense; when the objective is unavailable, the QUBO/Ising energy is used and lower energy is always better (the QMQ-04 energy-direction fix, centralized here).

objective_sense(problem)

Return the primary objective sense of a problem.

The first objective is the scalar being optimised (matching the workflow and QMQ-04 executors); a problem without objectives defaults to MINIMIZE.

optimality_gap(achieved, optimum)

Relative distance from a known optimum (0.0 means exact).

Formula (QMQ-05 §11, documented):

  • optimum != 0: gap = |optimum - achieved| / |optimum|
  • optimum == 0: gap = |optimum - achieved| (absolute distance, avoiding division by zero).

The gap is always non-negative and sense-independent: a result that exactly matches the known optimum gives 0.0, any other result gives a positive distance (a result better than the recorded optimum still yields a positive gap — the discrepancy is surfaced, never hidden).

Returns None when either value is missing or non-finite.

sense_label(sense)

Serialized sense label ("minimize"/"maximize").

build_circuit(program)

Translate a :class:QuantumProgram into a MicroQuantum circuit.

validate_program(program)

Return a list of translation errors for a program (empty means valid).

to_microquantum_result(result)

Return the underlying MicroQuantum result from a QuantumResult.

all_examples()

Run every canonical example and return the produced artifacts.

assess_data_quality(dataset)

Assess dataset quality and return a deterministic report.

Missing values, invalid values (non-finite or outside the feature bounds when bounds are supplied) and duplicate rows are counted exactly. Duplicates are rows with identical values across the deterministic feature order; the first occurrence is kept and every later identical occurrence is counted.

clustering_example()

Example F — k=2 clustering of the canonical dataset.

Executed as a real quadratic binary QUBO (assignment equality constraints + optional cluster-count bounds). The expected optimum assigns {r0, r2} to cluster 0 and {r1, r3} to cluster 1 with a total within-cluster distance of approximately 1.2.

data_context_example()

The canonical QMQ-09 data context (Euclidean, no preferred strategy).

dataset_example()

The canonical QMQ-09 dataset: 4 records over 5 features.

euclidean_distance(left, right)

Return the Euclidean distance between two equal-length vectors.

feature_selection_example()

Example A — exact-2 feature selection (selection set {height, depth}).

grouped_feature_selection_example()

Example C — grouped feature selection with group cardinality.

Geometry group {height, width, depth} limited to <= 2, appearance group {brightness, texture} limited to <= 1, total cardinality <= 3. The optimal selection is {height, depth, texture} (utility 11).

pairwise_relationship(dataset, *, kind='distance', metric='euclidean', weights=None)

Build the deterministic pairwise relationship of dataset.

Parameters:

Name Type Description Default
dataset DataSet

The dataset to measure (must be structurally valid).

required
kind str

Relationship kind ("distance" or "similarity").

'distance'
metric str

One of "euclidean", "squared_euclidean" or "weighted_euclidean" (the latter uses weights or the dataset feature weights).

'euclidean'
weights dict[str, float] | None

Optional feature name -> weight map.

None

Returns:

Type Description
DataRelationship

A symmetric :class:DataRelationship.

quality_example()

Example E — deterministic data-quality report of the canonical dataset.

selection_cost_example()

Example B — cost-aware selection (utility minus cost, penalty 1.0).

serialization_example()

Example G — JSON-safe round trips of the canonical problems.

similarity_example()

Example D — pairwise Euclidean / similarity relationship of the dataset.

similarity_from_distance(distance, *, sigma=1.0)

Return the Gaussian similarity exp(-distance^2 / (2 sigma^2)).

Parameters:

Name Type Description Default
distance float

A non-negative distance.

required
sigma float

Positive kernel width.

1.0

Returns:

Type Description
float

A value in (0, 1]; identical vectors give 1.0.

squared_euclidean_distance(left, right)

Return the squared Euclidean distance between two vectors.

weighted_squared_euclidean_distance(left, right, weights)

Return the squared Euclidean distance with per-dimension weights.

assess_problem(problem, registry=None, *, strategy=None, capabilities=None)

Assess one domain problem through the QMQ-03 pipeline (no execution).

Parameters:

Name Type Description Default
problem Any

The domain problem to assess.

required
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the built-in domains.

None
strategy str | None

Optional requested strategy label (forwarded to :meth:StrategySelector.select_reasoned through the binding).

None
capabilities CapabilityModel | None

Capability snapshot; detected when omitted.

None

Raises:

Type Description
UnsupportedDomainError

When no registered binding supports the problem.

DomainValidationError

When the problem fails its validation.

domain_data_example()

Full domain pipeline on the Data feature-selection example (QMQ-11 §16 B).

domain_finance_example()

Full domain pipeline on the finance example problem (QMQ-11 §16 A).

The example problem is the deterministic financial formulation of the canonical QMQ-08 risk-adjusted portfolio (cardinality-only, binary), so its QUBO maps losslessly and the end-to-end solve is well-defined.

domain_ml_example()

Full domain pipeline on the ML classification example (QMQ-11 §16 C).

domain_pipeline_example()

Cross-domain example: Finance, Data and ML through one intelligence.

Returns a dict keyed by domain label with each problem's assessment, plan, solve, benchmark and interpretation artifacts.

available_algorithms()

Return the sorted list of canonical algorithm names QuantsMind can delegate.

resolve_algorithm(name)

Resolve an algorithm name to its MicroQuantum class (public API).

run_algorithm(name, **kwargs)

Instantiate and run a MicroQuantum algorithm by name.

The algorithm class is resolved from MicroQuantum's public API, then instantiated with kwargs and run via its public entry point (run, solve or compute_minimum_eigenvalue). The native MicroQuantum result object is returned.

compute_portfolio_metrics(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0)

Convenience wrapper around :meth:PortfolioMetrics.compute.

constraint_from_dict(data)

Rebuild a financial constraint from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

example_asset_universe()

Example 1 — a four-asset universe with supplied expected returns.

example_budget(capital=1.0, name='qmq07_budget')

Example 2 — a capital/budget with allocation bounds.

example_budget_portfolio()

Example D — continuous allocation under a budget with position limits.

example_combined_problem()

Example 6 — maximize return minus a risk penalty (mean-variance).

example_financial_problem()

The canonical QMQ-07 example problem (combined objective, binary).

example_group_constraints_portfolio()

Example E — binary selection with group allocation constraints.

example_maximize_return_portfolio()

Example A — maximize expected return under a cardinality bound.

example_minimize_risk_portfolio()

Example B — minimize portfolio variance under a cardinality bound.

example_portfolio_problem()

The canonical QMQ-08 example problem (risk-adjusted, binary).

example_portfolio_risk_matrix()

Risk matrix over the portfolio universe (same supplied data as QMQ-07).

example_portfolio_universe()

Universe A — two equity assets, one bond and one cash asset.

example_return_problem()

Example 4 — maximize expected return under a budget.

example_risk_adjusted_portfolio()

Example C — maximize risk-adjusted return (mean-variance utility).

example_risk_matrix()

Example 3 — a deterministic covariance/risk matrix.

example_risk_problem()

Example 5 — minimize portfolio variance under a budget.

expected_return_of(universe, weights)

Expected portfolio return sum(expected_return_i * w_i) over the universe.

Missing weights default to 0; identifiers outside the universe are ignored (unknown identifiers are a validation concern, not a metric).

objective_from_dict(data)

Rebuild a financial objective from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

portfolio_variance(risk, weights)

Portfolio variance w^T Cov w from a supplied risk matrix.

The matrix owns the deterministic asset order; entries for assets without a weight default to 0.

portfolio_volatility(risk, weights)

Portfolio volatility (standard deviation) sqrt(w^T Cov w).

Round-off may produce a value marginally below zero for an empty allocation; the reported volatility is clamped at 0.

risk_contributions(risk, weights)

Marginal variance contribution w_i * (Cov w)_i per asset identifier.

synthetic_asset(identifier, expected_return, volatility=None, *, symbol='', asset_class='equity', price=None)

Build one deterministic synthetic asset.

formulate(problem)

Select and return the appropriate formulation for a domain problem.

Uses deterministic, rule-based logic based on problem.metadata and problem contents. Returns the existing problem.formulation when already set.

model_from_dict(data)

Reconstruct a formulation model from its serialized kind.

ising_to_optimization_problem(ising, *, name=None)

Wrap an Ising model into a MicroQuantum OptimizationProblem.

ising_to_pauli_sum(ising)

Build the microquantum.PauliSum (Ising Hamiltonian) for a model.

Qubit i of the Pauli labels corresponds to the i-th variable in :attr:IsingModel.variables. The additive constant is not part of the Pauli sum (MicroQuantum's eigenvalue excludes it); it is carried by :meth:IsingModel.energy instead.

qaoa_available()

Return whether a QAOA-capable MicroQuantum is importable.

run_qaoa(ising, *, qubo=None, num_layers=1, shots=1024, seed=None, backend=None, name=None, optimizer=None)

Minimise an Ising model via MicroQuantum's public QAOA API.

The Ising model is wrapped as a MicroQuantum OptimizationProblem (cost Hamiltonian); QAOA.from_problem().solve() performs the computation, and the optimized ansatz is sampled on the chosen backend to recover a bitstring. Returns an honest record: MicroQuantum's raw eigenvalue plus the QUBO/Ising energies of the sampled assignment.

Parameters:

Name Type Description Default
ising IsingModel

The Ising model to minimise.

required
qubo QUBOModel | None

Optional QUBO model for reporting the sampled assignment's QUBO energy.

None
num_layers int

QAOA layers (p).

1
shots int

Shot count used for the final sampling.

1024
seed int | None

Optional RNG seed.

None
backend str | None

Backend name or engine backend instance.

None
name str | None

Problem name recorded in the result metadata.

None
optimizer Any | None

Optional MicroQuantum optimizer instance to use for the variational loop (overrides the engine default; tests pass a low-iteration one to keep the run fast).

None

Raises:

Type Description
QuantumIntegrationError

If QAOA is not available or the run fails.

ImportError

If MicroQuantum is not installed (with install hint).

ml_all_examples()

Run every canonical example and return the produced artifacts.

ml_classification_example()

Example A — binary-coefficient least-squares classification.

The optimum activates all three features (f0, f1, f2) with a residual sum of squares of exactly 3.0.

ml_clustering_example()

Example F — delegated QMQ-09 k=2 clustering.

Uses the classic QMQ-09 geometry: clusters {r0, r2} and {r1, r3} with a total within-cluster distance of approximately 8.2156.

ml_dataset_example()

The canonical QMQ-10 dataset: 4 records over 3 features (f0..f2).

ml_feature_selection_example()

Example C — delegated QMQ-09 feature selection.

Utilities {f0: 3, f1: 5, f2: 2} with unit costs and a maximum of two features; the optimum selection is {f0, f1} with utility 8.0.

ml_hyperparameter_example()

Example E — one-hot per-parameter hyperparameter choice.

learning_rate gains (0.8, 1.5, 1.2) and depth gains (0.9, 1.8, 1.4); the optimum total gain is 1.5 + 1.8 = 3.3.

ml_model_selection_example()

Example D — one-hot model selection.

Candidate objectives validation_loss + complexity_penalty: M1 3.4, M2 2.9, M3 3.1, M4 2.8, so the optimum selects M4 with objective 2.8.

ml_regression_example()

Example B — regression variant of the same least-squares objective.

coerce_expression(value)

Coerce a number, string or Expression into an Expression.

Raises:

Type Description
ExpressionError

If value is a callable or an unsupported type. Callables cannot be introspected into monomials, so automatic QUBO/penalty formulation requires symbolic strings or nodes.

parse_expression(text)

Parse a safe arithmetic expression string into an Expression tree.

Supported grammar: numbers, identifiers, + - * ( ), unary minus and integer powers via ** or ^. No eval() is used anywhere.

Raises:

Type Description
ExpressionParseError

If the text is not a valid expression.

qubo_from_expression(expression, variables, *, name='qubo')

Build a QUBO from a symbolic expression over binary variables.

Linear monomials become linear terms, degree-two monomials become pairwise terms and the constant monomial becomes the constant term. Products that collapse to the same variable (x^2) are reduced via binary idempotence to linear terms. Terms of degree greater than two are rejected explicitly.

Raises:

Type Description
QUBOError

If the expression references an unknown variable or contains a term of degree greater than two.

benchmark

QMQ-05: benchmarking & classical comparison.

Public surface:

  • :class:Benchmark — a serializable benchmark definition (problem + strategy + baseline + known optimum).
  • :class:BenchmarkSuite / :func:default_suite — the canonical five deterministic benchmark problems.
  • :class:BenchmarkRunner — executes a benchmark against a classical exhaustive baseline (reusing QMQ-02/04) and reports honest results.
  • :class:BenchmarkMetrics — measured quality / performance / resources.
  • :class:BenchmarkComparison / :class:BenchmarkWinner — deterministic strategy-vs-baseline classification (feasibility class first, then normalized objective; a completion alone never claims advantage).
  • :class:BenchmarkResult / :class:BenchmarkRunSummary — serializable reports, repeated-run aggregates (§14) and the solution-report reference (composition, §17).

BaselineConfig dataclass

Configuration of the classical baseline (QMQ-05 §4/§8).

The baseline reuses the QMQ-02/04 exact exhaustive solver — no second classical solver exists. kind is fixed to "classical" until the SDK adds another baseline; only that kind is honoured.

Benchmark dataclass

Definition of one benchmark (QMQ-05 §4).

A benchmark is a reusable, serializable recipe: the problem to solve, the strategy to run (defaulting to the problem's preferred strategy), optional algorithm/execution options, the classical baseline configuration, an optional known optimum, and free-form metadata.

resolved_strategy property

Strategy of the benchmark (its own, else the problem's preferred).

strategy_label property

Serialized strategy label of :attr:resolved_strategy.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Benchmark from :meth:to_dict output.

BenchmarkComparison dataclass

Benchmark strategy outcome vs the classical baseline (QMQ-05 §9/§12/§13).

Fields

strategy: Strategy label that was benchmarked. baseline: Baseline label ("classical"). sense: Sense used for ranking ("minimize"/"maximize"). winner: Result classification. objective_delta: Normalized objective delta (strategy - baseline), positive means the strategy outcome is better. strategy_status: "executed" / "failed" / "skipped". baseline_status: Same for the baseline. selected_reason: Human-readable justification. metadata: Free-form (e.g. the QMQ-04 hybrid leg comparison dict).

build(*, strategy, strategy_metrics, baseline_metrics, sense=ObjectiveSense.MINIMIZE, strategy_status='executed', baseline_status='executed', metadata=None) classmethod

Classify a strategy outcome against the classical baseline.

Deterministic policy (QMQ-05 §12/§13):

  1. feasible beats unknown beats infeasible;
  2. both feasible (or both unknown): better normalized objective wins (per sense; energy fallback, lower always better);
  3. both infeasible: fewer constraint violations wins, then objective;
  4. exact equalities are a TIE;
  5. a missing strategy/baseline outcome, a disabled baseline, or a missing objective/energy produces NO_COMPARABLE_RESULT.

A strictly better strategy outcome is classified on the strategy (classical -> CLASSICAL_WIN, quantum -> QUANTUM_WIN, hybrid -> HYBRID_WIN); a worse one is CLASSICAL_WIN.

build_none(*, strategy, sense, strategy_metrics, strategy_status, baseline_status, reason, metadata) classmethod

Build a NO_COMPARABLE_RESULT comparison.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

BenchmarkMetrics dataclass

Measured quality / performance / resource metrics (QMQ-05 §6/§7).

Missing information is None (or 0 for counts) — nothing is invented beyond what the execution layer actually reports.

from_execution(problem, execution, *, sense, reference_optimum=None, wall_clock_time=None, options=None, seed=None, backend='', optimizer='', microquantum_version='', num_qubits=None, status='executed', executions=1, retries=0) classmethod

Build metrics from a normalized QMQ-04 execution result.

execution may be a :class:ClassicalExecutionResult, :class:QuantumExecutionResult, or any leg exposing assignment/objective_value/energy/feasible. reference_optimum is the known optimum (or the baseline optimum) used for the gap/ratio; None leaves them unknown.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

BenchmarkResult dataclass

Serializable report of one benchmark run (QMQ-05 §16).

The in-memory object keeps a reference to the underlying :class:SolutionReport (composition, QMQ-05 §17); serialization carries only lightweight reference metadata — the full solution report is not duplicated inside the benchmark report.

to_dict()

Serialize to a JSON-safe dictionary (report kept as a reference).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

The :class:SolutionReport reference is intentionally not rebuilt (composition reference); all measured fields round-trip exactly.

BenchmarkRunSummary dataclass

Aggregates of repeated benchmark runs (QMQ-05 §14).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a summary from :meth:to_dict output.

BenchmarkSuite dataclass

A named collection of benchmarks for reproducible evaluation (QMQ-05 §18).

benchmarks is keyed by benchmark_id so members are addressable and serializable. The canonical suite is produced by :func:quantsmind.quantum.benchmark.suite.default_suite.

ids property

Benchmark ids in registration order.

add(benchmark)

Register a benchmark (duplicate ids are rejected).

get(benchmark_id)

Return a benchmark by id.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a suite from :meth:to_dict output.

BenchmarkWinner

Bases: Enum

Classification of a benchmark run vs its classical baseline (QMQ-05 §13).

  • CLASSICAL_WIN — the classical baseline produced the better result.
  • QUANTUM_WIN — a quantum strategy produced the better result.
  • HYBRID_WIN — a hybrid strategy (its selected leg) produced the better result.
  • TIE — baseline and strategy tied after normalization.
  • NO_COMPARABLE_RESULT — no fair comparison was possible (the strategy leg did not execute, the baseline is disabled, or no comparable objective/energy existed).

These describe measured outcomes only; no "quantum advantage" claim is ever derived from a classification.

parse(value) classmethod

Coerce a label or member to a :class:BenchmarkWinner.

BenchmarkRunner

Runs benchmarks and produces serializable :class:BenchmarkResult reports.

A runner holds no per-run state; it can be reused across benchmarks and suites. runs > 1 repeats a benchmark and aggregates the repetitions into a :class:BenchmarkRunSummary (QMQ-05 §14).

run(benchmark, *, runs=1, raise_on_error=False)

Run a benchmark once or several times.

Parameters:

Name Type Description Default
benchmark Benchmark

The benchmark definition to execute.

required
runs int

Number of repetitions (1 returns a single-run result).

1
raise_on_error bool

If True, a failing strategy run raises instead of being recorded as a failed run (used in tests/CI).

False

approximation_ratio(achieved, optimum, sense)

Approximation ratio against a known optimum, where mathematically appropriate (QMQ-05 §6).

Formula (documented):

  • MAXIMIZE: ratio = achieved / optimum
  • MINIMIZE: ratio = optimum / achieved

The ratio is only reported (≤1 when the result is suboptimal) for positive optima and non-negative meaningful denominators. Returns None whenever the ratio is not interpretable (zero optimum, missing values, conflicting signs) — no value is manufactured.

constraint_violations(problem, assignment)

Count and magnitude of constraint violations for an assignment.

Uses the existing domain :class:Constraint abstraction (QMQ-05 §12): a constraint is violated iff its :meth:Constraint.evaluate status is VIOLATED; the magnitude is the numeric excess over the RHS value (missing/unevaluable expressions contribute 0).

Returns (count, magnitude).

is_better(left, right, sense)

True when left strictly outperforms right under sense.

normalized_score(sense, objective_value, energy)

Return a higher-is-better scalar for ranking or None.

The domain objective is normalized by its sense; when the objective is unavailable, the QUBO/Ising energy is used and lower energy is always better (the QMQ-04 energy-direction fix, centralized here).

objective_sense(problem)

Return the primary objective sense of a problem.

The first objective is the scalar being optimised (matching the workflow and QMQ-04 executors); a problem without objectives defaults to MINIMIZE.

optimality_gap(achieved, optimum)

Relative distance from a known optimum (0.0 means exact).

Formula (QMQ-05 §11, documented):

  • optimum != 0: gap = |optimum - achieved| / |optimum|
  • optimum == 0: gap = |optimum - achieved| (absolute distance, avoiding division by zero).

The gap is always non-negative and sense-independent: a result that exactly matches the known optimum gives 0.0, any other result gives a positive distance (a result better than the recorded optimum still yields a positive gap — the discrepancy is surfaced, never hidden).

Returns None when either value is missing or non-finite.

sense_label(sense)

Serialized sense label ("minimize"/"maximize").

metrics_rank_key(metrics, sense)

Deterministic (feasibility class, violations, normalized score) key.

Higher tuple is better: feasible beats unknown beats infeasible; among infeasible results a lower violation magnitude beats a higher one (the magnitude is negated so fewer violations rank higher), then the normalized objective decides.

b1_knapsack()

3-var knapsack: maximize value under one capacity constraint.

Optimum: x0=1, x1=1, x2=0 -> objective 7 (classical, exact).

b2_linear_max()

3-var unconstrained maximize linear objective.

Optimum: all ones -> objective 12 (classical, exact).

b3_qubo_min()

2-var QUBO minimize: x0 + x1 - 2*x0*x1.

Optimum: x0=x1=1 -> objective 0 (a zero-optimum case exercising the optimality_gap/approximation_ratio division handling).

b4_maxcut_triangle()

Max-Cut on the triangle (QMQ-04 canonical example, reused unchanged).

Optimum cut: 2 (any single-edge separation is max for the triangle); a genuinely quantum-capable HYBRID run compares against the exact classical cut value.

b5_geq_max()

4-var maximize with a >= constraint.

Optimum: all ones -> objective 8 (constraint exactly relaxed, classical). Non-trivially constrained so the exhaustive baseline walks a larger space than the unconstrained members.

default_suite(*, shots=512, seed=7, max_variables=20)

Build the canonical QMQ-05 suite of five deterministic benchmarks.

Parameters:

Name Type Description Default
shots int

Quantum-leg shot count for HYBRID members.

512
seed int

Reproducibility seed for HYBRID members.

7
max_variables int

Classical baseline exhaustive limit.

20

default_suite_examples()

Return the members of :func:default_suite (convenience for tooling).

metrics

Pure QMQ-05 comparison and metric math.

All sense/energy normalization of the benchmark layer is centralized here (QMQ-05 §10):

  • QUBO/Ising energy is always compared as "lower is better" — this is the QMQ-04 energy-direction fix, kept as the single reference.
  • Domain objectives follow the problem's own MINIMIZE / MAXIMIZE sense.

The module imports nothing from :mod:quantsmind.quantum.benchmark.models, so it stays circular-import free and reusable by any future consumer.

objective_sense(problem)

Return the primary objective sense of a problem.

The first objective is the scalar being optimised (matching the workflow and QMQ-04 executors); a problem without objectives defaults to MINIMIZE.

sense_label(sense)

Serialized sense label ("minimize"/"maximize").

is_better(left, right, sense)

True when left strictly outperforms right under sense.

normalized_score(sense, objective_value, energy)

Return a higher-is-better scalar for ranking or None.

The domain objective is normalized by its sense; when the objective is unavailable, the QUBO/Ising energy is used and lower energy is always better (the QMQ-04 energy-direction fix, centralized here).

optimality_gap(achieved, optimum)

Relative distance from a known optimum (0.0 means exact).

Formula (QMQ-05 §11, documented):

  • optimum != 0: gap = |optimum - achieved| / |optimum|
  • optimum == 0: gap = |optimum - achieved| (absolute distance, avoiding division by zero).

The gap is always non-negative and sense-independent: a result that exactly matches the known optimum gives 0.0, any other result gives a positive distance (a result better than the recorded optimum still yields a positive gap — the discrepancy is surfaced, never hidden).

Returns None when either value is missing or non-finite.

approximation_ratio(achieved, optimum, sense)

Approximation ratio against a known optimum, where mathematically appropriate (QMQ-05 §6).

Formula (documented):

  • MAXIMIZE: ratio = achieved / optimum
  • MINIMIZE: ratio = optimum / achieved

The ratio is only reported (≤1 when the result is suboptimal) for positive optima and non-negative meaningful denominators. Returns None whenever the ratio is not interpretable (zero optimum, missing values, conflicting signs) — no value is manufactured.

constraint_violations(problem, assignment)

Count and magnitude of constraint violations for an assignment.

Uses the existing domain :class:Constraint abstraction (QMQ-05 §12): a constraint is violated iff its :meth:Constraint.evaluate status is VIOLATED; the magnitude is the numeric excess over the RHS value (missing/unevaluable expressions contribute 0).

Returns (count, magnitude).

models

QMQ-05 benchmark models: definition, metrics, comparison, results.

The models are generic over the existing QMQ-01..04 pipeline: a :class:Benchmark wraps a :class:~quantsmind.quantum.core.problem.QuantumProblem plus strategy/algorithm/execution configuration; :class:BenchmarkMetrics describe a measured execution; :class:BenchmarkComparison classifies the benchmark result against the classical baseline; :class:BenchmarkResult is the serializable report. All sense/ranking logic delegates to :mod:quantsmind.quantum.benchmark.metrics (no duplicated sign handling, QMQ-05 §10).

BenchmarkWinner

Bases: Enum

Classification of a benchmark run vs its classical baseline (QMQ-05 §13).

  • CLASSICAL_WIN — the classical baseline produced the better result.
  • QUANTUM_WIN — a quantum strategy produced the better result.
  • HYBRID_WIN — a hybrid strategy (its selected leg) produced the better result.
  • TIE — baseline and strategy tied after normalization.
  • NO_COMPARABLE_RESULT — no fair comparison was possible (the strategy leg did not execute, the baseline is disabled, or no comparable objective/energy existed).

These describe measured outcomes only; no "quantum advantage" claim is ever derived from a classification.

parse(value) classmethod

Coerce a label or member to a :class:BenchmarkWinner.

BaselineConfig dataclass

Configuration of the classical baseline (QMQ-05 §4/§8).

The baseline reuses the QMQ-02/04 exact exhaustive solver — no second classical solver exists. kind is fixed to "classical" until the SDK adds another baseline; only that kind is honoured.

Benchmark dataclass

Definition of one benchmark (QMQ-05 §4).

A benchmark is a reusable, serializable recipe: the problem to solve, the strategy to run (defaulting to the problem's preferred strategy), optional algorithm/execution options, the classical baseline configuration, an optional known optimum, and free-form metadata.

resolved_strategy property

Strategy of the benchmark (its own, else the problem's preferred).

strategy_label property

Serialized strategy label of :attr:resolved_strategy.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Benchmark from :meth:to_dict output.

BenchmarkMetrics dataclass

Measured quality / performance / resource metrics (QMQ-05 §6/§7).

Missing information is None (or 0 for counts) — nothing is invented beyond what the execution layer actually reports.

from_execution(problem, execution, *, sense, reference_optimum=None, wall_clock_time=None, options=None, seed=None, backend='', optimizer='', microquantum_version='', num_qubits=None, status='executed', executions=1, retries=0) classmethod

Build metrics from a normalized QMQ-04 execution result.

execution may be a :class:ClassicalExecutionResult, :class:QuantumExecutionResult, or any leg exposing assignment/objective_value/energy/feasible. reference_optimum is the known optimum (or the baseline optimum) used for the gap/ratio; None leaves them unknown.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

BenchmarkComparison dataclass

Benchmark strategy outcome vs the classical baseline (QMQ-05 §9/§12/§13).

Fields

strategy: Strategy label that was benchmarked. baseline: Baseline label ("classical"). sense: Sense used for ranking ("minimize"/"maximize"). winner: Result classification. objective_delta: Normalized objective delta (strategy - baseline), positive means the strategy outcome is better. strategy_status: "executed" / "failed" / "skipped". baseline_status: Same for the baseline. selected_reason: Human-readable justification. metadata: Free-form (e.g. the QMQ-04 hybrid leg comparison dict).

build(*, strategy, strategy_metrics, baseline_metrics, sense=ObjectiveSense.MINIMIZE, strategy_status='executed', baseline_status='executed', metadata=None) classmethod

Classify a strategy outcome against the classical baseline.

Deterministic policy (QMQ-05 §12/§13):

  1. feasible beats unknown beats infeasible;
  2. both feasible (or both unknown): better normalized objective wins (per sense; energy fallback, lower always better);
  3. both infeasible: fewer constraint violations wins, then objective;
  4. exact equalities are a TIE;
  5. a missing strategy/baseline outcome, a disabled baseline, or a missing objective/energy produces NO_COMPARABLE_RESULT.

A strictly better strategy outcome is classified on the strategy (classical -> CLASSICAL_WIN, quantum -> QUANTUM_WIN, hybrid -> HYBRID_WIN); a worse one is CLASSICAL_WIN.

build_none(*, strategy, sense, strategy_metrics, strategy_status, baseline_status, reason, metadata) classmethod

Build a NO_COMPARABLE_RESULT comparison.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

BenchmarkRunSummary dataclass

Aggregates of repeated benchmark runs (QMQ-05 §14).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a summary from :meth:to_dict output.

BenchmarkResult dataclass

Serializable report of one benchmark run (QMQ-05 §16).

The in-memory object keeps a reference to the underlying :class:SolutionReport (composition, QMQ-05 §17); serialization carries only lightweight reference metadata — the full solution report is not duplicated inside the benchmark report.

to_dict()

Serialize to a JSON-safe dictionary (report kept as a reference).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

The :class:SolutionReport reference is intentionally not rebuilt (composition reference); all measured fields round-trip exactly.

BenchmarkSuite dataclass

A named collection of benchmarks for reproducible evaluation (QMQ-05 §18).

benchmarks is keyed by benchmark_id so members are addressable and serializable. The canonical suite is produced by :func:quantsmind.quantum.benchmark.suite.default_suite.

ids property

Benchmark ids in registration order.

add(benchmark)

Register a benchmark (duplicate ids are rejected).

get(benchmark_id)

Return a benchmark by id.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a suite from :meth:to_dict output.

metrics_rank_key(metrics, sense)

Deterministic (feasibility class, violations, normalized score) key.

Higher tuple is better: feasible beats unknown beats infeasible; among infeasible results a lower violation magnitude beats a higher one (the magnitude is negated so fewer violations rank higher), then the normalized objective decides.

runner

Benchmark runner: executes a :class:Benchmark against its classical baseline.

The runner is deliberately thin and honest (QMQ-05 §19/§20):

  • The benchmark strategy runs through the existing :class:~quantsmind.quantum.workflow.workflow.QuantumWorkflow pipeline (formulate -> classify -> recommend -> plan -> map -> execute).
  • The classical baseline is a separate CLASSICAL-preference workflow run over the same problem, reusing the QMQ-02/04 exhaustive solver (no second classical solver, no duplicated execution engine).
  • Strategy forcing never touches ExecutionOptions.strategy (that only feeds context/provenance, not dispatch): the problem is cloned with preferred_strategy set, which the QMQ-03 reasoned selector honours.
  • A quantum leg that cannot run degrades honestly (recorded) or records a failed run with the typed error — a completion alone never becomes a "quantum advantage" claim (QMQ-05 §13).
BenchmarkRunner

Runs benchmarks and produces serializable :class:BenchmarkResult reports.

A runner holds no per-run state; it can be reused across benchmarks and suites. runs > 1 repeats a benchmark and aggregates the repetitions into a :class:BenchmarkRunSummary (QMQ-05 §14).

run(benchmark, *, runs=1, raise_on_error=False)

Run a benchmark once or several times.

Parameters:

Name Type Description Default
benchmark Benchmark

The benchmark definition to execute.

required
runs int

Number of repetitions (1 returns a single-run result).

1
raise_on_error bool

If True, a failing strategy run raises instead of being recorded as a failed run (used in tests/CI).

False

suite

Canonical QMQ-05 benchmark suite: five small, deterministic problems.

The suite is deliberately small and exact (QMQ-05 §18):

  • every benchmark is solvable exhaustively in milliseconds, so a classical baseline of known optimum can be computed and cross-checked;
  • the variety covers linear and QUBO objectives, bound/inequality and equality-free constraints, both senses, and classical vs quantum-capable strategies;
  • known_optimum values are stated explicitly and independently of the run (they are verified by tests, never derived from the benchmark itself).

No Finance, no sub-question novelty: the members reuse the QMQ-02/04 problem patterns exactly.

b1_knapsack()

3-var knapsack: maximize value under one capacity constraint.

Optimum: x0=1, x1=1, x2=0 -> objective 7 (classical, exact).

b2_linear_max()

3-var unconstrained maximize linear objective.

Optimum: all ones -> objective 12 (classical, exact).

b3_qubo_min()

2-var QUBO minimize: x0 + x1 - 2*x0*x1.

Optimum: x0=x1=1 -> objective 0 (a zero-optimum case exercising the optimality_gap/approximation_ratio division handling).

b4_maxcut_triangle()

Max-Cut on the triangle (QMQ-04 canonical example, reused unchanged).

Optimum cut: 2 (any single-edge separation is max for the triangle); a genuinely quantum-capable HYBRID run compares against the exact classical cut value.

b5_geq_max()

4-var maximize with a >= constraint.

Optimum: all ones -> objective 8 (constraint exactly relaxed, classical). Non-trivially constrained so the exhaustive baseline walks a larger space than the unconstrained members.

default_suite(*, shots=512, seed=7, max_variables=20)

Build the canonical QMQ-05 suite of five deterministic benchmarks.

Parameters:

Name Type Description Default
shots int

Quantum-leg shot count for HYBRID members.

512
seed int

Reproducibility seed for HYBRID members.

7
max_variables int

Classical baseline exhaustive limit.

20
default_suite_examples()

Return the members of :func:default_suite (convenience for tooling).

bridge

Bridge between QuantsMind domain descriptions and MicroQuantum.

The bridge is the only place where QuantsMind constructs MicroQuantum objects. It translates a :class:~quantsmind.quantum.program.QuantumProgram into a microquantum.core.circuit.QuantumCircuit using MicroQuantum's public Operator factory API and QuantumCircuit.append.

It does not reimplement gates, circuits, states, measurement, simulation, transpilation, algorithms or providers.

UnknownGateError

Bases: ValueError

Raised when a program references a gate MicroQuantum cannot build.

GateParamError

Bases: ValueError

Raised when a gate receives an unexpected number of parameters.

validate_program(program)

Return a list of translation errors for a program (empty means valid).

build_circuit(program)

Translate a :class:QuantumProgram into a MicroQuantum circuit.

circuit_result

QuantsMind-facing quantum result enrichment.

QuantumResult wraps a MicroQuantum BackendResult and adds QuantsMind-specific context: experiment identity, domain metadata and provenance. The MicroQuantum result remains directly accessible via primitives.native — QuantsMind does not re-implement Quantum result semantics.

QuantumResult dataclass

Enriched result of a QuantsMind quantum experiment.

Parameters:

Name Type Description Default
native Any

The underlying MicroQuantum BackendResult.

required
experiment_id str

QuantsMind experiment identity.

''
program_name str

Name of the originating QuantumProgram.

''
domain_metadata dict[str, Any]

Domain metadata attached by the caller.

dict()
provenance dict[str, Any]

Execution provenance details.

dict()
created_at str

UTC ISO timestamp when this enrichment was created.

(lambda: isoformat())()
counts property

Measurement counts from the backend result.

statevector property

State vector from the backend result (when provided).

samples property

Raw samples from the backend result (when provided).

shots property

Number of shots executed.

backend_name property

Name of the backend that produced the result.

num_qubits property

Number of qubits in the executed circuit.

success property

Whether the backend reported success.

from_backend_result(result, *, experiment_id='', program_name='', domain_metadata=None, provenance=None) classmethod

Wrap a MicroQuantum BackendResult with QuantsMind context.

to_dict()

Serialize enrichment and underlying result to a JSON-safe dict.

to_microquantum_result(result)

Return the underlying MicroQuantum result from a QuantumResult.

core

Core domain problem model of QuantsMind Quantum.

The core layer defines the vocabulary of a domain problem: variables, objectives, constraints, domain context, the problem itself and domain solutions. It contains no execution logic — that lives in the workflow layer and in MicroQuantum.

Constraint dataclass

A constraint of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
expression Callable[[dict[str, Any]], float] | str | None

Callable(assignments) -> float, a symbolic string, or None.

None
operator ConstraintOperator

Comparison operator (<=, >=, ==).

LE
value float

RHS constant the expression is compared against.

0.0
priority ConstraintPriority

HARD or SOFT classification.

HARD
penalty float

Optional penalty weight applied when a SOFT constraint is violated (used by later formulation phases).

0.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the penalty is negative.

le(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a <= constraint.

ge(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a >= constraint.

eq(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create an == constraint.

compare(lhs)

Compare an evaluated expression against the constraint value.

evaluate(assignments)

Evaluate the constraint against variable assignments.

Constraints without an expression report :data:ConstraintStatus.UNKNOWN. Symbolic string (and expression-node) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild a Constraint from :meth:to_dict output.

ConstraintOperator

Bases: Enum

Relational operator of a constraint.

Attributes:

Name Type Description
LE

expression <= value

GE

expression >= value

EQ

expression == value

parse(value) classmethod

Coerce a symbol ("<=", ">=", "==") to an operator.

ConstraintPriority

Bases: Enum

Hard/soft classification of a constraint.

Attributes:

Name Type Description
HARD

Must be satisfied for a solution to be feasible.

SOFT

Desirable; violations may be traded via penalty.

parse(value) classmethod

Coerce "hard"/"soft" (or a member) to a priority.

ConstraintStatus

Bases: Enum

Evaluation status of a constraint against an assignment.

Attributes:

Name Type Description
SATISFIED

The constraint holds for the evaluated assignments.

VIOLATED

The constraint does not hold.

UNKNOWN

The constraint could not be evaluated (no expression).

DomainContext dataclass

Context in which a quantum domain problem exists.

Parameters:

Name Type Description Default
domain str

Top-level domain (e.g. "finance", "fraud", "energy").

required
subdomain str

Optional subdomain (e.g. "portfolio").

''
use_case str

Optional business/scientific use case.

''
context_metadata dict[str, Any]

Domain-specific business/scientific metadata.

dict()
units list[str]

Applicable measurement units (e.g. ["USD", "days"]).

list()
metadata dict[str, Any]

Free-form custom metadata.

dict()

Raises:

Type Description
ValueError

If domain is empty.

qualified()

Return "domain" or "domain/subdomain".

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DomainContext from :meth:to_dict output.

Objective dataclass

A scalar objective of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
sense ObjectiveSense

MINIMIZE or MAXIMIZE.

required
expression Expression

Callable(assignments) -> float, a symbolic string, or None.

None
weight float

Non-negative scaling weight used when objectives are combined.

1.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the weight is negative.

minimize(name, expression=None, *, weight=1.0) classmethod

Create a MINIMIZE objective.

maximize(name, expression=None, *, weight=1.0) classmethod

Create a MAXIMIZE objective.

evaluate(assignments)

Evaluate the objective against variable assignments.

Callable expressions are evaluated directly. Symbolic string (and :class:~quantsmind.quantum.optimization.expression.Expression) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

describe()

Return a human-readable description, e.g. "minimize cost".

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild an Objective from :meth:to_dict output.

ObjectiveSense

Bases: Enum

Optimisation sense of an objective.

Attributes:

Name Type Description
MINIMIZE

Prefer lower objective values (e.g. cost, risk, latency).

MAXIMIZE

Prefer higher objective values (e.g. return, throughput).

parse(value) classmethod

Coerce "min"/"max" (or a member) to :class:ObjectiveSense.

QuantumProblem dataclass

A domain problem that a QuantsMind Quantum workflow can process.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
description str

Optional human-readable description.

''
domain DomainContext | str | None

Domain context, or a plain domain string coerced to one.

None
variables list[Variable]

Decision variables of the problem.

list()
objectives list[Objective]

Objectives to optimise.

list()
constraints list[Constraint]

Feasibility constraints.

list()
metadata dict[str, Any]

Free-form metadata (used by formulation detection, e.g. {"model_kind": "graph"} or {"encoding": {...}}).

dict()
formulation Any

Optional formulation model attached to the problem.

None
preferred_strategy Any

Optional preferred computation strategy (a :class:ComputationStrategy or its name).

None
provenance dict[str, Any]

Optional record of how the problem was assembled.

dict()

Raises:

Type Description
ValueError

If the name is empty or names repeat within a category.

variable_names property

Names of all variables.

objective_names property

Names of all objectives.

constraint_names property

Names of all constraints.

size property

Number of decision variables (the problem's effective size).

add_variable(variable)

Add a variable (duplicate names are rejected).

add_objective(objective)

Add an objective (duplicate names are rejected).

add_constraint(constraint)

Add a constraint (duplicate names are rejected).

variable(name)

Return the variable with the given name.

objective(name)

Return the objective with the given name.

constraint(name)

Return the constraint with the given name.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QuantumProblem from :meth:to_dict output.

ProblemSolution dataclass

A domain-level solution to a :class:QuantumProblem.

Parameters:

Name Type Description Default
problem_name str

Name of the problem this solution satisfies.

''
assignments dict[str, Any]

Variable name -> assigned value.

dict()
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, ConstraintStatus]

Constraint name -> evaluation status.

dict()
score float | None

Optional combined, sense-aware score (higher is better).

None
feasible bool

Whether all constraints are satisfied (none violated).

False
metadata dict[str, Any]

Free-form solution metadata (backend, shots, ...).

dict()
from_names(problem_name, variable_names, objective_names, constraint_names) classmethod

Build an empty solution skeleton matching a problem's structure.

evaluate(problem)

Populate objective values and constraint status from assignments.

Only callable expressions participate (symbolic strings raise by design until QMQ-02 formulation support lands). Feasibility is recomputed from the resulting statuses.

is_feasible()

Return True when no constraint is violated (unknowns are benign).

compute_score(problem)

Weighted, sense-aware objective score (higher is better).

Maximizing objectives contribute weight * value; minimizing objectives contribute -weight * value. Returns None when no objective could be evaluated.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ProblemSolution from :meth:to_dict output.

Variable dataclass

A decision variable of a quantum domain problem.

Parameters:

Name Type Description Default
name str

Unique variable name within the problem.

required
type VariableType

Variable category (binary/integer/continuous/categorical).

CONTINUOUS
lower_bound int | float | None

Inclusive numeric lower bound for non-categorical types.

None
upper_bound int | float | None

Inclusive numeric upper bound for non-categorical types.

None
domain str

Optional namespace the variable belongs to (e.g. "asset").

''
description str

Optional human-readable explanation.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If bounds are inconsistent with the variable type.

binary(name, *, domain='', description='') classmethod

Create a 0/1 decision variable.

integer(name, lower_bound, upper_bound, *, domain='', description='') classmethod

Create an integer variable with inclusive bounds.

continuous(name, lower_bound=None, upper_bound=None, *, domain='', description='') classmethod

Create a real-valued variable with optional inclusive bounds.

categorical(name, *, domain='', description='') classmethod

Create a categorical variable (no numeric bounds).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Variable from :meth:to_dict output.

VariableType

Bases: Enum

Type of a decision variable.

Attributes:

Name Type Description
BINARY

0/1 decision variable.

INTEGER

Discrete integer variable (bounded).

CONTINUOUS

Real-valued variable.

CATEGORICAL

Discrete label variable with no numeric bounds.

parse(value) classmethod

Coerce a name or member to a :class:VariableType (e.g. "binary").

constraint

Constraints of quantum domain problems.

A constraint restricts the feasible assignments of a :class:QuantumProblem. QMQ-01 keeps the representation extensible (<=, >=, ==, hard/soft classification, optional penalty) but does not build a symbolic mathematics engine; that arrives with the formulation capabilities of QMQ-02.

ConstraintOperator

Bases: Enum

Relational operator of a constraint.

Attributes:

Name Type Description
LE

expression <= value

GE

expression >= value

EQ

expression == value

parse(value) classmethod

Coerce a symbol ("<=", ">=", "==") to an operator.

ConstraintPriority

Bases: Enum

Hard/soft classification of a constraint.

Attributes:

Name Type Description
HARD

Must be satisfied for a solution to be feasible.

SOFT

Desirable; violations may be traded via penalty.

parse(value) classmethod

Coerce "hard"/"soft" (or a member) to a priority.

ConstraintStatus

Bases: Enum

Evaluation status of a constraint against an assignment.

Attributes:

Name Type Description
SATISFIED

The constraint holds for the evaluated assignments.

VIOLATED

The constraint does not hold.

UNKNOWN

The constraint could not be evaluated (no expression).

Constraint dataclass

A constraint of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
expression Callable[[dict[str, Any]], float] | str | None

Callable(assignments) -> float, a symbolic string, or None.

None
operator ConstraintOperator

Comparison operator (<=, >=, ==).

LE
value float

RHS constant the expression is compared against.

0.0
priority ConstraintPriority

HARD or SOFT classification.

HARD
penalty float

Optional penalty weight applied when a SOFT constraint is violated (used by later formulation phases).

0.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the penalty is negative.

le(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a <= constraint.

ge(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create a >= constraint.

eq(name, expression=None, value=0.0, *, priority=ConstraintPriority.HARD, penalty=0.0) classmethod

Create an == constraint.

compare(lhs)

Compare an evaluated expression against the constraint value.

evaluate(assignments)

Evaluate the constraint against variable assignments.

Constraints without an expression report :data:ConstraintStatus.UNKNOWN. Symbolic string (and expression-node) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild a Constraint from :meth:to_dict output.

domain_context

Domain context for quantum domain problems.

A :class:DomainContext describes the environment a problem lives in (finance, fraud, manufacturing, energy, ...). QMQ-01 provides the foundation only; concrete domain modules extend it later.

DomainContext dataclass

Context in which a quantum domain problem exists.

Parameters:

Name Type Description Default
domain str

Top-level domain (e.g. "finance", "fraud", "energy").

required
subdomain str

Optional subdomain (e.g. "portfolio").

''
use_case str

Optional business/scientific use case.

''
context_metadata dict[str, Any]

Domain-specific business/scientific metadata.

dict()
units list[str]

Applicable measurement units (e.g. ["USD", "days"]).

list()
metadata dict[str, Any]

Free-form custom metadata.

dict()

Raises:

Type Description
ValueError

If domain is empty.

qualified()

Return "domain" or "domain/subdomain".

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DomainContext from :meth:to_dict output.

objective

Objectives of quantum domain problems.

An objective describes what a workflow should optimise (minimize cost, maximize return, ...). It carries enough information to participate in formulation and strategy selection: a sense, an optional expression, and a weight used when objectives are combined.

ObjectiveSense

Bases: Enum

Optimisation sense of an objective.

Attributes:

Name Type Description
MINIMIZE

Prefer lower objective values (e.g. cost, risk, latency).

MAXIMIZE

Prefer higher objective values (e.g. return, throughput).

parse(value) classmethod

Coerce "min"/"max" (or a member) to :class:ObjectiveSense.

Objective dataclass

A scalar objective of a :class:QuantumProblem.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
sense ObjectiveSense

MINIMIZE or MAXIMIZE.

required
expression Expression

Callable(assignments) -> float, a symbolic string, or None.

None
weight float

Non-negative scaling weight used when objectives are combined.

1.0
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If the name is empty or the weight is negative.

minimize(name, expression=None, *, weight=1.0) classmethod

Create a MINIMIZE objective.

maximize(name, expression=None, *, weight=1.0) classmethod

Create a MAXIMIZE objective.

evaluate(assignments)

Evaluate the objective against variable assignments.

Callable expressions are evaluated directly. Symbolic string (and :class:~quantsmind.quantum.optimization.expression.Expression) expressions are parsed and evaluated by the QMQ-02 expression model without eval().

describe()

Return a human-readable description, e.g. "minimize cost".

to_dict()

Serialize to a JSON-safe dictionary.

Callable expressions cannot be serialized and are stored as None.

from_dict(data) classmethod

Rebuild an Objective from :meth:to_dict output.

problem

The central domain problem model of QuantsMind Quantum.

A :class:QuantumProblem bundles identity, description, domain context, variables, objectives, constraints, metadata, an optional formulation, a preferred computation strategy and provenance. It is the input object that flows through formulation, strategy selection, mapping, execution and solution reporting.

QuantumProblem dataclass

A domain problem that a QuantsMind Quantum workflow can process.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
description str

Optional human-readable description.

''
domain DomainContext | str | None

Domain context, or a plain domain string coerced to one.

None
variables list[Variable]

Decision variables of the problem.

list()
objectives list[Objective]

Objectives to optimise.

list()
constraints list[Constraint]

Feasibility constraints.

list()
metadata dict[str, Any]

Free-form metadata (used by formulation detection, e.g. {"model_kind": "graph"} or {"encoding": {...}}).

dict()
formulation Any

Optional formulation model attached to the problem.

None
preferred_strategy Any

Optional preferred computation strategy (a :class:ComputationStrategy or its name).

None
provenance dict[str, Any]

Optional record of how the problem was assembled.

dict()

Raises:

Type Description
ValueError

If the name is empty or names repeat within a category.

variable_names property

Names of all variables.

objective_names property

Names of all objectives.

constraint_names property

Names of all constraints.

size property

Number of decision variables (the problem's effective size).

add_variable(variable)

Add a variable (duplicate names are rejected).

add_objective(objective)

Add an objective (duplicate names are rejected).

add_constraint(constraint)

Add a constraint (duplicate names are rejected).

variable(name)

Return the variable with the given name.

objective(name)

Return the objective with the given name.

constraint(name)

Return the constraint with the given name.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QuantumProblem from :meth:to_dict output.

solution

Solutions produced for quantum domain problems.

A :class:ProblemSolution is a domain solution: it carries variable assignments, objective values, constraint status, a score and feasibility. It is deliberately disconnected from any raw MicroQuantum circuit result — those remain accessible through the execution layer.

ProblemSolution dataclass

A domain-level solution to a :class:QuantumProblem.

Parameters:

Name Type Description Default
problem_name str

Name of the problem this solution satisfies.

''
assignments dict[str, Any]

Variable name -> assigned value.

dict()
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, ConstraintStatus]

Constraint name -> evaluation status.

dict()
score float | None

Optional combined, sense-aware score (higher is better).

None
feasible bool

Whether all constraints are satisfied (none violated).

False
metadata dict[str, Any]

Free-form solution metadata (backend, shots, ...).

dict()
from_names(problem_name, variable_names, objective_names, constraint_names) classmethod

Build an empty solution skeleton matching a problem's structure.

evaluate(problem)

Populate objective values and constraint status from assignments.

Only callable expressions participate (symbolic strings raise by design until QMQ-02 formulation support lands). Feasibility is recomputed from the resulting statuses.

is_feasible()

Return True when no constraint is violated (unknowns are benign).

compute_score(problem)

Weighted, sense-aware objective score (higher is better).

Maximizing objectives contribute weight * value; minimizing objectives contribute -weight * value. Returns None when no objective could be evaluated.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ProblemSolution from :meth:to_dict output.

variable

Domain problem variables for QuantsMind Quantum.

Variables are the decision quantities of a :class:QuantumProblem. They carry a type, optional bounds and domain metadata that later formulation phases (QMQ-02 onward) translate into QUBO variables, Ising spins, circuit qubits or classical decision variables.

VariableType

Bases: Enum

Type of a decision variable.

Attributes:

Name Type Description
BINARY

0/1 decision variable.

INTEGER

Discrete integer variable (bounded).

CONTINUOUS

Real-valued variable.

CATEGORICAL

Discrete label variable with no numeric bounds.

parse(value) classmethod

Coerce a name or member to a :class:VariableType (e.g. "binary").

Variable dataclass

A decision variable of a quantum domain problem.

Parameters:

Name Type Description Default
name str

Unique variable name within the problem.

required
type VariableType

Variable category (binary/integer/continuous/categorical).

CONTINUOUS
lower_bound int | float | None

Inclusive numeric lower bound for non-categorical types.

None
upper_bound int | float | None

Inclusive numeric upper bound for non-categorical types.

None
domain str

Optional namespace the variable belongs to (e.g. "asset").

''
description str

Optional human-readable explanation.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
ValueError

If bounds are inconsistent with the variable type.

binary(name, *, domain='', description='') classmethod

Create a 0/1 decision variable.

integer(name, lower_bound, upper_bound, *, domain='', description='') classmethod

Create an integer variable with inclusive bounds.

continuous(name, lower_bound=None, upper_bound=None, *, domain='', description='') classmethod

Create a real-valued variable with optional inclusive bounds.

categorical(name, *, domain='', description='') classmethod

Create a categorical variable (no numeric bounds).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Variable from :meth:to_dict output.

data

Data Intelligence domain layer of QuantsMind Quantum (QMQ-09).

The Data layer models data-intelligence optimization problems as validated, deterministic objects — features, records, datasets, relationships, data quality, and the feature-selection / clustering problem families — and converts them into the existing QMQ mathematical/optimization infrastructure (QMQ-02 formulation, QUBO mapping, workflow, execution, benchmark, interpretation). It works entirely from supplied/synthetic data: no live data ingestion, no ML framework, no connectors, no cloud, no scraping.

QMQ-09 scope:

  • observations/features (DataFeature, DataRecord, DataSet, FeatureVector),
  • distance & similarity primitives and pairwise relationships,
  • deterministic data-quality reports,
  • feature-selection objectives/constraints and clustering as a real quadratic binary QUBO (assignment equality constraints),
  • the DataProblem domain representation, DataFormulationAdapter, DataMapper, DataMetrics, DataSolution and DataOptimizer,
  • canonical examples A–G and JSON-safe serialization.

Importing this package never requires microquantum.

AssignmentConstraint dataclass

Bases: DataConstraint

Every record is assigned to exactly one cluster (sum_c z_i_c = 1).

ClusterCountConstraint dataclass

Bases: DataConstraint

Bound the number of records assigned to every cluster.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_records float

Minimum number of records per cluster (>= 0).

1.0
max_records float | None

Maximum number of records per cluster (None = unbounded).

None
description str

Free-form description.

''

DataConstraint dataclass

Base class of all data constraints.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

FeatureCountConstraint dataclass

Bases: DataConstraint

Limit the total number of selected features.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_features float

Minimum number of selected features (>= 0).

1.0
max_features float | None

Maximum number of selected features (None = unbounded).

None
description str

Free-form description.

''

FeatureGroupConstraint dataclass

Bases: DataConstraint

Limit the number of selected features inside one feature group.

Parameters:

Name Type Description Default
name str

Constraint name.

required
group str

Free-form group label (metadata only).

''
members list[str]

Feature names of the group.

list()
lower float

Minimum number of selected members within the group.

0.0
upper float | None

Maximum number of selected members within the group (None = unbounded).

None
description str

Free-form description.

''

DataContext dataclass

Data-domain context of a Data problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "feature_selection", "clustering", "analysis").

''
subdomain str

Domain subdomain (e.g. "tabular").

''
distance_metric str

One of :data:DISTANCE_METRICS used for pairwise relationships, similarity and clustering distance objectives.

'euclidean'
feature_weights dict[str, float]

Optional per-feature weights for the weighted Euclidean distance (feature name -> non-negative weight).

dict()
similarity_sigma float

Kernel width of the Gaussian similarity transform.

1.0
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

DataError

Bases: ValueError

Base error of the QuantsMind Quantum Data Intelligence layer.

DataValidationError

Bases: DataError

Raised when a Data model or problem fails domain validation.

DataFormulationAdapter

Converts data problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention for feature selection and the z{record}_{cluster} convention for clustering, objectives keep their senses, and every data constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a data problem (empty = valid).

raise_if_invalid(problem)

Raise :class:DataValidationError when the problem is invalid.

Raises:

Type Description
DataValidationError

If the problem fails validation.

data_metadata(problem) staticmethod

JSON-safe Data provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a data problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem DataProblem

The validated data problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
DataValidationError

If the data problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a data problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

cluster_variable_index(problem, record_index, cluster) classmethod

Return the flat QMQ index of the z{record}_{cluster} variable.

DataMapper dataclass

Maps a validated Data problem to a deterministic variable mapping.

Mirrors the :class:FinanceAssetMapper pattern: validates, then provides :meth:map (which returns a :class:DataMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

DataMapping dataclass

Deterministic mapping between Data variables and QMQ indices.

Created by :meth:DataMapper.map from a validated :class:DataProblem.

variable_names property

QMQ variable names in deterministic order.

feature_variable(feature_name)

Return the QMQ variable name for feature_name.

feature_index(feature_name)

Return the deterministic index of feature_name.

feature(variable_name)

Return the decoded feature for variable_name (or None).

cluster_variable(record_id, cluster_index)

Return the QMQ variable name for record_id and cluster_index.

cluster(record_index, cluster_index)

Return the decoded cluster assignment for the variable at the given indices.

cluster_of(assignments, record_id)

Return the cluster assigned to record_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

DecodedClusterAssignment dataclass

One decoded cluster assignment decision.

Attributes:

Name Type Description
record_id str

Domain record identifier.

record_index int

Deterministic record index.

cluster_index int

Deterministic cluster index.

variable_name str

QMQ variable name (z{record}_{cluster}).

value float

Raw assignment value (0.0 or 1.0).

DecodedDataFeature dataclass

One decoded feature-selection decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (x<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DataMetrics dataclass

Deterministic outcome metrics of a Data solve.

Attributes:

Name Type Description
problem_type str

Data problem family ("feature_selection" or "clustering").

selected_feature_count int

Number of selected features (FS).

selected_utility float

Total utility of the selected features (FS).

selection_cost float

Total cost of the selected features (FS).

net_objective float

Primary objective value (utility - penalty*cost for FS, total within-cluster distance for clustering).

cluster_count int

Number of non-empty clusters (clustering).

total_within_cluster_distance float | None

Total within-cluster pairwise distance (clustering).

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

DataFeature dataclass

One numeric feature/dimension of a :class:DataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
lower_bound float | None

Optional inclusive lower bound for valid values.

None
upper_bound float | None

Optional inclusive upper bound for valid values.

None
weight float

Optional non-negative weight (used by weighted distances and data quality).

1.0
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
allows(value)

Return whether value respects the optional feature bounds.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

DataRecord dataclass

One observation inside a :class:DataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
DataValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

DataSet dataclass

Ordered collection of features and records.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time, so partial data can be inspected through :func:quantsmind.quantum.data.quality.assess_data_quality.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every Data problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[DataFeature]

Ordered feature list.

list()
records list[DataRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:DataFeature with name.

record(record_id)

Return the :class:DataRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
DataValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:DataValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

FeatureVector dataclass

Lightweight immutable numeric feature vector (in feature order).

Parameters:

Name Type Description Default
values tuple[float, ...]

Numeric values in feature order.

required
normalization dict[str, Any]

Free-form normalization metadata (JSON-safe).

dict()
dimension property

Number of numeric dimensions.

to_list()

Return the values as a plain list.

from_sequence(values, *, normalization=None) classmethod

Build a vector from any sequence of finite numbers.

from_record(record, features) classmethod

Build a vector from a record in deterministic feature order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a vector from :meth:to_dict output.

ClusteringDistanceObjective dataclass

Bases: DataObjective

Minimize the total within-cluster pairwise distance.

The quadratic objective sum_cluster sum_{i<j} distance(i, j) * z_i_c * z_j_c runs over the pairwise relationships of the problem's dataset (supplied explicitly as problem.pairwise or computed from the Data context distance metric).

Parameters:

Name Type Description Default
name str

Objective name.

required
description str

Free-form description.

''

DataObjective dataclass

Base class of all data objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

Data-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

FeatureSelectionObjective dataclass

Bases: DataObjective

Combined feature-selection objective utility - penalty * cost.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
costs dict[str, float]

Feature name -> non-negative cost.

dict()
penalty float

Non-negative penalty applied to the total selection cost.

1.0
description str

Free-form description.

''

FeatureUtilityObjective dataclass

Bases: DataObjective

Maximize the sum of selected-feature utilities.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
description str

Free-form description.

''

SelectionCostObjective dataclass

Bases: DataObjective

Minimize the sum of selected-feature costs.

Parameters:

Name Type Description Default
name str

Objective name.

required
costs dict[str, float]

Feature name -> non-negative cost.

dict()
description str

Free-form description.

''

DataOptimizationConfiguration dataclass

Execution/optimization configuration of a Data problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
DataValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

DataOptimizer

Solves and benchmarks :class:DataProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Data adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the Data layer.

solve(problem, *, strategy=None, config=None)

Solve a Data problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.data.solution.DataSolution with data metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
DataValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a Data problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem DataProblem

The Data problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config DataOptimizationConfiguration | None

Optional execution/optimization configuration.

None
mapping(problem)

Return the deterministic Data variable mapping of a problem.

DataProblem dataclass

Domain problem of the Data Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset DataSet

The ordered dataset the problem operates on.

required
problem_type DataProblemType

Family (:attr:DataProblemType.FEATURE_SELECTION or :attr:DataProblemType.CLUSTERING).

FEATURE_SELECTION
objectives list[DataObjective]

Ordered list of data objectives (names must be unique).

list()
constraints list[DataConstraint]

Ordered list of data constraints (names must be unique).

list()
context DataContext | None

Optional Data context (distance metric / strategy intent).

None
k int | None

Number of clusters (clustering problems only).

None
pairwise DataRelationship | None

Optional precomputed pairwise relationship (clustering only; recomputed deterministically when None).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
DataValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a clustering/feature selection configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

feature_variables()

Return the binary feature variables x0 .. x{n-1} in feature order.

cluster_variables()

Return the binary assignment variables in record-major order.

decision_variables()

Return the deterministic decision-variable list for this problem.

Feature selection yields one binary variable per feature in dataset order. Clustering yields one binary variable per (record, cluster) pair in record-major order so that record = z` record index blocks are contiguous.

clustering_distance_matrix()

Return the pairwise distance relationship used by clustering.

Uses :attr:pairwise when supplied (after validating the record alignment) and otherwise recomputes the deterministic distance relationship from the Data context distance metric.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:DataValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

DataProblemType

Bases: Enum

Supported data intelligence problem families.

Attributes:

Name Type Description
FEATURE_SELECTION

Binary selection of a subset of features.

CLUSTERING

Assignment of records to k clusters.

parse(value) classmethod

Coerce a name or member to a :class:DataProblemType.

DataQualityReport dataclass

Deterministic quality assessment of one dataset.

Parameters:

Name Type Description Default
valid bool

Whether the dataset is structurally valid (non-empty, no missing/invalid/duplicate entries, feature-consistent records).

False
record_count int

Number of records.

0
feature_count int

Number of features.

0
missing_count int

Number of missing (absent) feature values.

0
invalid_count int

Number of non-finite or out-of-bounds values.

0
duplicate_count int

Number of records identical to an earlier record.

0
feature_consistency bool

Whether every record carries exactly the dataset feature set.

False
issues list[str]

Deterministic, human-readable issue list.

list()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a report from :meth:to_dict output.

DataRelationship dataclass

Pairwise relationship matrix over ordered record identifiers.

Parameters:

Name Type Description Default
record_order list[str]

Ordered record identifiers.

required
kind str

One of :data:RELATIONSHIP_KINDS.

required
values list[list[float]]

Square symmetric matrix in record_order; row/column index is the record index. Mirrored for bit-for-bit symmetry.

required
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
size property

Number of records.

__len__()

Number of records.

row(record_id)

Return the row of record_id.

record_index(record_id)

Return the deterministic index of record_id.

value(record_a, record_b)

Return the pairwise value between two records.

validate_against(record_ids)

Raise when the relationship does not cover exactly record_ids.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a relationship from :meth:to_dict output.

DataOptimizationResult dataclass

Result of a Data solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

DataSolution dataclass

The domain result of solving a Data optimization problem.

Decision fields are derived from the deterministic Data mapping, so they always reflect the feature/record order of the underlying dataset. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating data problem.

''
problem_type str

Data problem family.

''
selected_features list[str]

Selected feature names in feature order (FS).

list()
selected_utility float

Total utility of the selected features (FS).

0.0
selection_cost float

Total cost of the selected features (FS).

0.0
cluster_assignments dict[str, int]

Record id -> cluster id (clustering).

dict()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether no constraint was violated.

False
metrics DataMetrics

Aggregated data metrics.

DataMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark features selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
cluster_count property

Number of non-empty clusters used by the solution.

total_within_cluster_distance property

Total within-cluster pairwise distance (clustering).

selected()

Return the selected features in feature order (alias).

assigned_clusters()

Return the record id -> cluster id assignments (alias).

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a data solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic Data mapping, computes data metrics from the dataset and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

constraint_from_dict(data)

Rebuild any supported Data constraint from :meth:to_dict output.

all_examples()

Run every canonical example and return the produced artifacts.

clustering_example()

Example F — k=2 clustering of the canonical dataset.

Executed as a real quadratic binary QUBO (assignment equality constraints + optional cluster-count bounds). The expected optimum assigns {r0, r2} to cluster 0 and {r1, r3} to cluster 1 with a total within-cluster distance of approximately 1.2.

data_context_example()

The canonical QMQ-09 data context (Euclidean, no preferred strategy).

dataset_example()

The canonical QMQ-09 dataset: 4 records over 5 features.

feature_selection_example()

Example A — exact-2 feature selection (selection set {height, depth}).

grouped_feature_selection_example()

Example C — grouped feature selection with group cardinality.

Geometry group {height, width, depth} limited to <= 2, appearance group {brightness, texture} limited to <= 1, total cardinality <= 3. The optimal selection is {height, depth, texture} (utility 11).

quality_example()

Example E — deterministic data-quality report of the canonical dataset.

selection_cost_example()

Example B — cost-aware selection (utility minus cost, penalty 1.0).

serialization_example()

Example G — JSON-safe round trips of the canonical problems.

similarity_example()

Example D — pairwise Euclidean / similarity relationship of the dataset.

euclidean_distance(left, right)

Return the Euclidean distance between two equal-length vectors.

similarity_from_distance(distance, *, sigma=1.0)

Return the Gaussian similarity exp(-distance^2 / (2 sigma^2)).

Parameters:

Name Type Description Default
distance float

A non-negative distance.

required
sigma float

Positive kernel width.

1.0

Returns:

Type Description
float

A value in (0, 1]; identical vectors give 1.0.

squared_euclidean_distance(left, right)

Return the squared Euclidean distance between two vectors.

weighted_squared_euclidean_distance(left, right, weights)

Return the squared Euclidean distance with per-dimension weights.

objective_from_dict(data)

Rebuild any supported Data objective from :meth:to_dict output.

assess_data_quality(dataset)

Assess dataset quality and return a deterministic report.

Missing values, invalid values (non-finite or outside the feature bounds when bounds are supplied) and duplicate rows are counted exactly. Duplicates are rows with identical values across the deterministic feature order; the first occurrence is kept and every later identical occurrence is counted.

pairwise_relationship(dataset, *, kind='distance', metric='euclidean', weights=None)

Build the deterministic pairwise relationship of dataset.

Parameters:

Name Type Description Default
dataset DataSet

The dataset to measure (must be structurally valid).

required
kind str

Relationship kind ("distance" or "similarity").

'distance'
metric str

One of "euclidean", "squared_euclidean" or "weighted_euclidean" (the latter uses weights or the dataset feature weights).

'euclidean'
weights dict[str, float] | None

Optional feature name -> weight map.

None

Returns:

Type Description
DataRelationship

A symmetric :class:DataRelationship.

constraints

Data-domain constraints of the QMQ-09 Data Intelligence layer.

Constraints translate the domain feature-selection / clustering semantics into QMQ-01 :class:Constraint instances with symbolic expressions over the deterministic Data variable naming conventions.

Supported families:

  • :class:FeatureCountConstraint — total number of selected features in [min_features, max_features],
  • :class:FeatureGroupConstraint — per-group selection limits,
  • :class:AssignmentConstraint — every record is assigned to exactly one cluster (sum_cluster z_i_c = 1),
  • :class:ClusterCountConstraint — per-cluster record-count bounds.
DataConstraint dataclass

Base class of all data constraints.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

FeatureCountConstraint dataclass

Bases: DataConstraint

Limit the total number of selected features.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_features float

Minimum number of selected features (>= 0).

1.0
max_features float | None

Maximum number of selected features (None = unbounded).

None
description str

Free-form description.

''
FeatureGroupConstraint dataclass

Bases: DataConstraint

Limit the number of selected features inside one feature group.

Parameters:

Name Type Description Default
name str

Constraint name.

required
group str

Free-form group label (metadata only).

''
members list[str]

Feature names of the group.

list()
lower float

Minimum number of selected members within the group.

0.0
upper float | None

Maximum number of selected members within the group (None = unbounded).

None
description str

Free-form description.

''
AssignmentConstraint dataclass

Bases: DataConstraint

Every record is assigned to exactly one cluster (sum_c z_i_c = 1).

ClusterCountConstraint dataclass

Bases: DataConstraint

Bound the number of records assigned to every cluster.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_records float

Minimum number of records per cluster (>= 0).

1.0
max_records float | None

Maximum number of records per cluster (None = unbounded).

None
description str

Free-form description.

''
constraint_from_dict(data)

Rebuild any supported Data constraint from :meth:to_dict output.

expression_string_for(expression)

Return the symbolic expression string verbatim (transparent helper).

context

QMQ-09 data context and domain-context mapping.

:class:DataContext captures the domain intent behind a Data problem (purpose, subdomain, the distance metric and feature weights used for similarity, and an optional preferred computation strategy). It maps onto the QMQ-01 :class:DomainContext used by the formulation and workflow layers through :meth:DataContext.to_domain_context.

DataContext dataclass

Data-domain context of a Data problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "feature_selection", "clustering", "analysis").

''
subdomain str

Domain subdomain (e.g. "tabular").

''
distance_metric str

One of :data:DISTANCE_METRICS used for pairwise relationships, similarity and clustering distance objectives.

'euclidean'
feature_weights dict[str, float]

Optional per-feature weights for the weighted Euclidean distance (feature name -> non-negative weight).

dict()
similarity_sigma float

Kernel width of the Gaussian similarity transform.

1.0
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

errors

Error taxonomy of the QuantsMind Quantum Data Intelligence layer.

QMQ-09 errors subclass :class:ValueError so that existing generic except ValueError handling in the workflow and formulation layers keeps working. :class:DataValidationError is the structured validation error raised by the Data models and the formulation adapter.

DataError

Bases: ValueError

Base error of the QuantsMind Quantum Data Intelligence layer.

DataValidationError

Bases: DataError

Raised when a Data model or problem fails domain validation.

examples

Canonical QMQ-09 Data Intelligence examples.

Every example is built exclusively from supplied, deterministic data and never requires microquantum at import time. Examples A–G:

A. :func:feature_selection_example — height/depth selected (utility 9, exact-2 constraint), B. :func:selection_cost_example — cost-aware selection, C. :func:grouped_feature_selection_example — geometry/appearance groups, D. :func:similarity_example — similarity / relationship matrix, E. :func:quality_example — deterministic data-quality report, F. :func:clustering_example — k=2 clustering (real quadratic binary QUBO), clusters {r0, r2} and {r1, r3}, G. :func:serialization_example — JSON-safe round trip.

dataset_example()

The canonical QMQ-09 dataset: 4 records over 5 features.

data_context_example()

The canonical QMQ-09 data context (Euclidean, no preferred strategy).

feature_selection_example()

Example A — exact-2 feature selection (selection set {height, depth}).

selection_cost_example()

Example B — cost-aware selection (utility minus cost, penalty 1.0).

grouped_feature_selection_example()

Example C — grouped feature selection with group cardinality.

Geometry group {height, width, depth} limited to <= 2, appearance group {brightness, texture} limited to <= 1, total cardinality <= 3. The optimal selection is {height, depth, texture} (utility 11).

similarity_example()

Example D — pairwise Euclidean / similarity relationship of the dataset.

quality_example()

Example E — deterministic data-quality report of the canonical dataset.

clustering_example()

Example F — k=2 clustering of the canonical dataset.

Executed as a real quadratic binary QUBO (assignment equality constraints + optional cluster-count bounds). The expected optimum assigns {r0, r2} to cluster 0 and {r1, r3} to cluster 1 with a total within-cluster distance of approximately 1.2.

serialization_example()

Example G — JSON-safe round trips of the canonical problems.

all_examples()

Run every canonical example and return the produced artifacts.

formulation

Data -> QMQ formulation adapter.

:class:DataFormulationAdapter converts a validated :class:~quantsmind.quantum.data.problem.DataProblem into the existing QMQ pipeline: a :class:QuantumProblem (consumed unchanged by the existing :func:~quantsmind.quantum.formulation.formulate and QUBO mapper). It preserves objective senses, the deterministic variable naming conventions, constraint bounds, feature/record orderings and JSON-safe Data provenance metadata. No Data-specific QUBO exists — the existing QMQ-02 representations are reused end-to-end.

DataFormulationAdapter

Converts data problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention for feature selection and the z{record}_{cluster} convention for clustering, objectives keep their senses, and every data constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a data problem (empty = valid).

raise_if_invalid(problem)

Raise :class:DataValidationError when the problem is invalid.

Raises:

Type Description
DataValidationError

If the problem fails validation.

data_metadata(problem) staticmethod

JSON-safe Data provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a data problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem DataProblem

The validated data problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
DataValidationError

If the data problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a data problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

cluster_variable_index(problem, record_index, cluster) classmethod

Return the flat QMQ index of the z{record}_{cluster} variable.

mapping

QMQ-09 data-domain mappings.

The mapper translates the domain Data variable naming conventions (x<i> for feature selection, z{record}_{cluster} for clustering) into a deterministic :class:DataMapping that decodes QMQ assignments back into domain-readable decisions (selected features and cluster assignments).

The mapper handles:

  • x<i> feature-selection variables (binary, [0, 1]),
  • z{record}_{cluster} clustering assignment variables (binary, record-major),
  • automatic slack-value tolerance when decoding (selected_threshold applies to binary feature variables; cluster variables use a >= 0.5 rule),
  • deterministic ordering and index mapping.
DecodedDataFeature dataclass

One decoded feature-selection decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (x<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedClusterAssignment dataclass

One decoded cluster assignment decision.

Attributes:

Name Type Description
record_id str

Domain record identifier.

record_index int

Deterministic record index.

cluster_index int

Deterministic cluster index.

variable_name str

QMQ variable name (z{record}_{cluster}).

value float

Raw assignment value (0.0 or 1.0).

DataMapping dataclass

Deterministic mapping between Data variables and QMQ indices.

Created by :meth:DataMapper.map from a validated :class:DataProblem.

variable_names property

QMQ variable names in deterministic order.

feature_variable(feature_name)

Return the QMQ variable name for feature_name.

feature_index(feature_name)

Return the deterministic index of feature_name.

feature(variable_name)

Return the decoded feature for variable_name (or None).

cluster_variable(record_id, cluster_index)

Return the QMQ variable name for record_id and cluster_index.

cluster(record_index, cluster_index)

Return the decoded cluster assignment for the variable at the given indices.

cluster_of(assignments, record_id)

Return the cluster assigned to record_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

DataMapper dataclass

Maps a validated Data problem to a deterministic variable mapping.

Mirrors the :class:FinanceAssetMapper pattern: validates, then provides :meth:map (which returns a :class:DataMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

metrics

Data-metrics computation of the QMQ-09 Data Intelligence layer.

:class:DataMetrics summarises the domain outcome of a Data solve: selected features and their utility/cost, cluster structure and the total within-cluster distance, plus the existing QMQ-05 constraint-violation counts. Computations are deterministic and reuse the QMQ-05 :func:constraint_violations helper (never recomputed ad hoc).

DataMetrics dataclass

Deterministic outcome metrics of a Data solve.

Attributes:

Name Type Description
problem_type str

Data problem family ("feature_selection" or "clustering").

selected_feature_count int

Number of selected features (FS).

selected_utility float

Total utility of the selected features (FS).

selection_cost float

Total cost of the selected features (FS).

net_objective float

Primary objective value (utility - penalty*cost for FS, total within-cluster distance for clustering).

cluster_count int

Number of non-empty clusters (clustering).

total_within_cluster_distance float | None

Total within-cluster pairwise distance (clustering).

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

models

Core QMQ-09 data-domain models.

The module owns the observation, feature and dataset vocabulary consumed by every other Data layer component:

  • :class:DataFeature describes one dimension (name, optional bounds and a non-negative weight),
  • :class:DataRecord holds one observation (identifier + per-feature values),
  • :class:FeatureVector is a lightweight immutable numeric vector used by distances and data quality,
  • :class:DataSet is the ordered, deterministic collection that every Data problem is built from.

All models are JSON-safe through :meth:to_dict/:meth:from_dict and are deterministic: feature and record ordering is preserved and validated at construction time.

DataFeature dataclass

One numeric feature/dimension of a :class:DataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
lower_bound float | None

Optional inclusive lower bound for valid values.

None
upper_bound float | None

Optional inclusive upper bound for valid values.

None
weight float

Optional non-negative weight (used by weighted distances and data quality).

1.0
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
allows(value)

Return whether value respects the optional feature bounds.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

DataRecord dataclass

One observation inside a :class:DataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
DataValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

FeatureVector dataclass

Lightweight immutable numeric feature vector (in feature order).

Parameters:

Name Type Description Default
values tuple[float, ...]

Numeric values in feature order.

required
normalization dict[str, Any]

Free-form normalization metadata (JSON-safe).

dict()
dimension property

Number of numeric dimensions.

to_list()

Return the values as a plain list.

from_sequence(values, *, normalization=None) classmethod

Build a vector from any sequence of finite numbers.

from_record(record, features) classmethod

Build a vector from a record in deterministic feature order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a vector from :meth:to_dict output.

DataSet dataclass

Ordered collection of features and records.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time, so partial data can be inspected through :func:quantsmind.quantum.data.quality.assess_data_quality.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every Data problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[DataFeature]

Ordered feature list.

list()
records list[DataRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:DataFeature with name.

record(record_id)

Return the :class:DataRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
DataValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:DataValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

numerics

Numeric distance and similarity primitives of the Data Intelligence layer.

All functions accept any finite numeric sequence (list[float] or :class:FeatureVector.to_list) and are deterministic and strict about dimension mismatches and non-finite inputs.

euclidean_distance(left, right)

Return the Euclidean distance between two equal-length vectors.

squared_euclidean_distance(left, right)

Return the squared Euclidean distance between two vectors.

weighted_squared_euclidean_distance(left, right, weights)

Return the squared Euclidean distance with per-dimension weights.

pairwise_distance_matrix(vectors, *, metric='euclidean', weights=None)

Return the symmetric pairwise distance matrix for vectors.

Internal batch helper (deliberately outside __all__ so the frozen API manifest is unchanged): coerces and validates each vector once instead of once per pair, evaluates the upper triangle only, and mirrors it, so results are symmetric by construction.

Parameters:

Name Type Description Default
vectors Sequence[Sequence[float]]

The vectors to compare (non-empty, uniform length).

required
metric str

One of "euclidean", "squared_euclidean" or "weighted_euclidean" (requires weights).

'euclidean'
weights Sequence[float] | None

Per-dimension non-negative weights for weighted_euclidean.

None

Raises:

Type Description
DataValidationError

For empty input, ragged vectors, non-finite values, negative weights, or an unknown metric — the same errors the per-pair functions raise.

similarity_from_distance(distance, *, sigma=1.0)

Return the Gaussian similarity exp(-distance^2 / (2 sigma^2)).

Parameters:

Name Type Description Default
distance float

A non-negative distance.

required
sigma float

Positive kernel width.

1.0

Returns:

Type Description
float

A value in (0, 1]; identical vectors give 1.0.

objectives

Data-domain objectives of the QMQ-09 Data Intelligence layer.

Objectives operate on the domain variable names generated by the deterministic Data naming conventions (:mod:quantsmind.quantum.data._expr) and are translated into :class:quantsmind.quantum.core.objective.Objective instances (MAXIMIZE / MINIMIZE Qubit) at formulation time.

Supported objective families:

  • :class:FeatureUtilityObjective — maximize feature utility (sum_i utilities[i] * x_i),
  • :class:SelectionCostObjective — minimize selection cost (sum_i costs[i] * x_i),
  • :class:FeatureSelectionObjective — combined utility-minus-cost (sum_u - penalty * sum_c),
  • :class:ClusteringDistanceObjective — minimize total within-cluster pairwise distance (sum_c sum_{i<j} distance[i][j] * z_i_c * z_j_c).

Every objective serializes through :meth:to_dict/:meth:from_dict and validates against a concrete :class:DataProblem (passed positionally so validation sees the dataset / problem type / k).

DataObjective dataclass

Base class of all data objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

Data-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

FeatureUtilityObjective dataclass

Bases: DataObjective

Maximize the sum of selected-feature utilities.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
description str

Free-form description.

''
SelectionCostObjective dataclass

Bases: DataObjective

Minimize the sum of selected-feature costs.

Parameters:

Name Type Description Default
name str

Objective name.

required
costs dict[str, float]

Feature name -> non-negative cost.

dict()
description str

Free-form description.

''
FeatureSelectionObjective dataclass

Bases: DataObjective

Combined feature-selection objective utility - penalty * cost.

Parameters:

Name Type Description Default
name str

Objective name.

required
utilities dict[str, float]

Feature name -> non-negative utility.

dict()
costs dict[str, float]

Feature name -> non-negative cost.

dict()
penalty float

Non-negative penalty applied to the total selection cost.

1.0
description str

Free-form description.

''
ClusteringDistanceObjective dataclass

Bases: DataObjective

Minimize the total within-cluster pairwise distance.

The quadratic objective sum_cluster sum_{i<j} distance(i, j) * z_i_c * z_j_c runs over the pairwise relationships of the problem's dataset (supplied explicitly as problem.pairwise or computed from the Data context distance metric).

Parameters:

Name Type Description Default
name str

Objective name.

required
description str

Free-form description.

''
objective_from_dict(data)

Rebuild any supported Data objective from :meth:to_dict output.

optimizer

Optimization entry point of the QMQ-09 Data Intelligence layer.

:class:DataOptimizationConfiguration carries execution/optimization settings and :class:DataOptimizer solves or benchmarks :class:~quantsmind.quantum.data.problem.DataProblem instances through the existing QMQ-03..05 pipeline — the classical exhaustive baseline (QMQ-05) and the workflow (QMQ-04). No second solver or algorithm exists for the Data layer; clustering is executed as a real quadratic binary problem through the existing QUBO formulation.

DataOptimizationConfiguration dataclass

Execution/optimization configuration of a Data problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
DataValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

DataOptimizer

Solves and benchmarks :class:DataProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Data adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the Data layer.

solve(problem, *, strategy=None, config=None)

Solve a Data problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.data.solution.DataSolution with data metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
DataValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a Data problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem DataProblem

The Data problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config DataOptimizationConfiguration | None

Optional execution/optimization configuration.

None
mapping(problem)

Return the deterministic Data variable mapping of a problem.

problem

Data problem representation of the QMQ-09 Data Intelligence layer.

:class:DataProblem is the domain problem: an ordered :class:DataSet, a :class:DataProblemType, optional objectives, optional constraints, the Data context and the clustering hyper-parameters. The deterministic :meth:DataProblem.decision_variables mapping (feature selection -> x<i>, clustering -> z{record}_{cluster}) is the single contract shared by the formulation adapter, the mapper, execution and result layers.

DataProblemType

Bases: Enum

Supported data intelligence problem families.

Attributes:

Name Type Description
FEATURE_SELECTION

Binary selection of a subset of features.

CLUSTERING

Assignment of records to k clusters.

parse(value) classmethod

Coerce a name or member to a :class:DataProblemType.

DataProblem dataclass

Domain problem of the Data Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset DataSet

The ordered dataset the problem operates on.

required
problem_type DataProblemType

Family (:attr:DataProblemType.FEATURE_SELECTION or :attr:DataProblemType.CLUSTERING).

FEATURE_SELECTION
objectives list[DataObjective]

Ordered list of data objectives (names must be unique).

list()
constraints list[DataConstraint]

Ordered list of data constraints (names must be unique).

list()
context DataContext | None

Optional Data context (distance metric / strategy intent).

None
k int | None

Number of clusters (clustering problems only).

None
pairwise DataRelationship | None

Optional precomputed pairwise relationship (clustering only; recomputed deterministically when None).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
DataValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a clustering/feature selection configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

feature_variables()

Return the binary feature variables x0 .. x{n-1} in feature order.

cluster_variables()

Return the binary assignment variables in record-major order.

decision_variables()

Return the deterministic decision-variable list for this problem.

Feature selection yields one binary variable per feature in dataset order. Clustering yields one binary variable per (record, cluster) pair in record-major order so that record = z` record index blocks are contiguous.

clustering_distance_matrix()

Return the pairwise distance relationship used by clustering.

Uses :attr:pairwise when supplied (after validating the record alignment) and otherwise recomputes the deterministic distance relationship from the Data context distance metric.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:DataValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

quality

Deterministic data-quality assessment of the Data Intelligence layer.

:func:assess_data_quality produces a :class:DataQualityReport with exact counts for missing values, invalid (non-finite / out-of-bounds) values, duplicate rows and feature-consistency across records. The report is JSON-safe and deterministic.

DataQualityReport dataclass

Deterministic quality assessment of one dataset.

Parameters:

Name Type Description Default
valid bool

Whether the dataset is structurally valid (non-empty, no missing/invalid/duplicate entries, feature-consistent records).

False
record_count int

Number of records.

0
feature_count int

Number of features.

0
missing_count int

Number of missing (absent) feature values.

0
invalid_count int

Number of non-finite or out-of-bounds values.

0
duplicate_count int

Number of records identical to an earlier record.

0
feature_consistency bool

Whether every record carries exactly the dataset feature set.

False
issues list[str]

Deterministic, human-readable issue list.

list()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a report from :meth:to_dict output.

assess_data_quality(dataset)

Assess dataset quality and return a deterministic report.

Missing values, invalid values (non-finite or outside the feature bounds when bounds are supplied) and duplicate rows are counted exactly. Duplicates are rows with identical values across the deterministic feature order; the first occurrence is kept and every later identical occurrence is counted.

relationship

Pairwise relationship matrix of the Data Intelligence layer.

:class:DataRelationship is a deterministic, symmetric pairwise matrix over the ordered record identifiers (distance, similarity, adjacency or affinity). :func:pairwise_relationship builds the canonical distance/similarity relationship of a :class:DataSet from the Data context distance metric.

DataRelationship dataclass

Pairwise relationship matrix over ordered record identifiers.

Parameters:

Name Type Description Default
record_order list[str]

Ordered record identifiers.

required
kind str

One of :data:RELATIONSHIP_KINDS.

required
values list[list[float]]

Square symmetric matrix in record_order; row/column index is the record index. Mirrored for bit-for-bit symmetry.

required
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
size property

Number of records.

__len__()

Number of records.

row(record_id)

Return the row of record_id.

record_index(record_id)

Return the deterministic index of record_id.

value(record_a, record_b)

Return the pairwise value between two records.

validate_against(record_ids)

Raise when the relationship does not cover exactly record_ids.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a relationship from :meth:to_dict output.

pairwise_relationship(dataset, *, kind='distance', metric='euclidean', weights=None)

Build the deterministic pairwise relationship of dataset.

Parameters:

Name Type Description Default
dataset DataSet

The dataset to measure (must be structurally valid).

required
kind str

Relationship kind ("distance" or "similarity").

'distance'
metric str

One of "euclidean", "squared_euclidean" or "weighted_euclidean" (the latter uses weights or the dataset feature weights).

'euclidean'
weights dict[str, float] | None

Optional feature name -> weight map.

None

Returns:

Type Description
DataRelationship

A symmetric :class:DataRelationship.

similarity_from_sigma(distance)

Legacy-free Gaussian similarity with the default kernel width.

solution

Solutions and results of the QMQ-09 Data Intelligence layer.

:class:DataSolution is the domain result of a Data solve: selected features with utility/cost, cluster assignments, metric aggregation and the execution facts. It is built from a QMQ :class:~quantsmind.quantum.result.result.SolutionReport via :meth:DataSolution.from_report, reusing the existing QMQ-05 constraint evaluation and QMQ-06 interpretation infrastructure. The benchmark is optional and delegated to QMQ-05; interpretation to QMQ-06.

DataSolution dataclass

The domain result of solving a Data optimization problem.

Decision fields are derived from the deterministic Data mapping, so they always reflect the feature/record order of the underlying dataset. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating data problem.

''
problem_type str

Data problem family.

''
selected_features list[str]

Selected feature names in feature order (FS).

list()
selected_utility float

Total utility of the selected features (FS).

0.0
selection_cost float

Total cost of the selected features (FS).

0.0
cluster_assignments dict[str, int]

Record id -> cluster id (clustering).

dict()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether no constraint was violated.

False
metrics DataMetrics

Aggregated data metrics.

DataMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark features selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
cluster_count property

Number of non-empty clusters used by the solution.

total_within_cluster_distance property

Total within-cluster pairwise distance (clustering).

selected()

Return the selected features in feature order (alias).

assigned_clusters()

Return the record id -> cluster id assignments (alias).

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a data solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic Data mapping, computes data metrics from the dataset and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

DataOptimizationResult dataclass

Result of a Data solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

domain

QMQ-11 — Advanced Quantum & Domain Intelligence.

This subpackage is the cross-domain intelligence layer on top of the existing QMQ-03..06 pipeline. It enables:

  • explicit, registered domain dispatch (Finance, Portfolio, Data, ML) through :class:~quantsmind.quantum.domain.registry.DomainRegistry;
  • inspectable assessment (:class:~quantsmind.quantum.domain.assessment .ProblemAssessment) and planning (:class:~quantsmind.quantum.domain.plan.ExecutionPlan) that reuse the QMQ-03 classification, formulation, strategy and algorithm engines;
  • honest quantum suitability assessment (:class:~quantsmind.quantum.domain.suitability .QuantumSuitabilityAssessor) that never claims quantum execution without a real runtime;
  • domain-agnostic solve/benchmark (:class:~quantsmind.quantum.domain.intelligence.DomainIntelligence) through the per-domain optimizers (QMQ-04..06).

No quantum engine, QUBO mapper or interpreter is duplicated here — every execution reuses the existing pipeline.

ProblemAssessment dataclass

Full, inspectable assessment of one domain problem (QMQ-11 §7).

Parameters:

Name Type Description Default
problem_name str

Name of the assessed problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the assessed problem.

''
classification ClassificationResult | None

QMQ-03 classification decision.

None
formulation FormulationRecommendation | None

QMQ-03 formulation-kind recommendation.

None
strategy_decision StrategyDecision | None

QMQ-03 strategy decision (with rationale).

None
algorithm_recommendation Any | None

QMQ-03 algorithm recommendation (with executable fallbacks).

None
capabilities CapabilityModel | None

Capability snapshot the decisions used.

None
suitability SuitabilityAssessment | None

:class:SuitabilityAssessment of the plan.

None
computation_plan ComputationPlan | None

The QMQ-03 :class:ComputationPlan built.

None
reasons list[str]

Rolled-up human-readable justification.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
domain_label property

Serialized domain label (e.g. "ml").

strategy_label property

Serialized selected strategy label.

algorithm property

Selected primary algorithm id ("" when none).

formulation_kind property

Recommended formulation kind (e.g. "qubo").

suitability_label property

Serialized suitability label ("" when unassessed).

is_implementable property

True when a computation plan was built (ready to run).

summary()

One-line human summary of the assessment.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

DomainDispatchError

Bases: DomainError

Raised when a problem cannot be dispatched to a registered domain.

DomainError

Bases: ValueError

Base error of the quantum domain intelligence layer.

DomainValidationError

Bases: DomainError

Raised when a domain problem fails its own validation rules.

UnsupportedDomainError

Bases: DomainDispatchError

Raised when no registered domain binding matches a problem.

DomainIntelligence

Cross-domain assessment, planning, solving and benchmarking.

Parameters:

Name Type Description Default
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the four built-in domains.

None
assessor QuantumSuitabilityAssessor | None

:class:QuantumSuitabilityAssessor; defaulted when omitted.

None
interpreter Any | None

Interpreter used by :meth:interpret; defaulted lazily.

None
assess(problem, *, strategy=None, capabilities=None)

Assess a domain problem (classify/formulate/strategy/algorithm/ suitability) without executing anything.

plan(problem, *, strategy=None, capabilities=None)

Build an inspectable :class:ExecutionPlan for a problem.

The plan can be inspected before any execution happens; no quantum work is performed by planning itself.

solve(problem, *, strategy=None, config=None)

Solve a domain problem through its registered optimizer.

The result is wrapped in a :class:DomainRunResult with the honest strategy/algorithm/backend/execution-mode facts and the QMQ-06 interpretation.

Raises:

Type Description
UnsupportedDomainError

When no domain binding matches.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a domain problem against the classical baseline (QMQ-05).

interpret(result)

Return the QMQ-06 interpretation carried by a run result.

Returns:

Name Type Description
The Any

class:ResultInterpretation (QMQ-06) of the run, or raises

Any

class:DomainDispatchError when no interpretation exists.

solve_and_interpret(problem, *, strategy=None, config=None)

Solve and attach the interpretation in a single call.

The interpretation is already carried by the wrapped result from QMQ-06; this method only validates that it is present.

supported_domains()

Serialized labels of the registered domains.

is_supported(problem)

True when a domain binding matches the problem.

ExecutionPlan dataclass

Domain-aware, inspectable execution plan (QMQ-11 §7).

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan (classification, formulation, strategy, algorithm, mapping, executor, fallbacks).

required
domain DomainKind

The dispatched :class:DomainKind.

required
problem_type str

Class name of the source domain problem.

required
strategy_requested str

Explicit strategy the caller requested ("" for automatic).

required
suitability SuitabilityAssessment

Suitability assessment of the plan.

required
classification str

Serialized classification label.

''
formulation_kind str

Serialized formulation kind.

''
reasons list[str]

Rolled-up reasons from the plan and suitability.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
summary()

One-line human summary of the plan.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

DomainBinding dataclass

Explicit binding between a domain and its execution capabilities.

Parameters:

Name Type Description Default
kind DomainKind

The registered :class:DomainKind.

required
label str

Human-readable sub-label of the binding.

required
problem_types tuple[type, ...]

isinstance-matchable problem types this binding owns.

required
validate Callable[[Any], list[str]]

Callable(problem) -> list[str] of validation issues.

required
raise_if_invalid Callable[[Any], None]

Callable(problem) -> None raising the domain's validation error.

required
to_quantum_problem Callable[..., QuantumProblem]

Callable(problem, *, preferred_strategy=None) -> :class:QuantumProblem. Reuses the existing per-domain formulation adapter.

required
solve Callable[..., Any]

Callable(problem, *, strategy=None, config=None, seed=None) through the per-domain optimizer.

required
benchmark Callable[..., Any]

Callable(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None, seed=None).

required
description str

Human-readable description of the binding.

''
metadata dict[str, Any]

Free-form metadata (module path, rule path, ...).

dict()
accepts(problem)

True when this binding owns the given problem instance.

DomainKind

Bases: Enum

Registered quantum-enabled domains (QMQ-11).

parse(value) classmethod

Coerce a label or member to a :class:DomainKind.

DomainRegistry

Registered dispatch table for supported domains (QMQ-11 §10).

The registry is extensible through :meth:register: an external domain supplies its own :class:DomainBinding (wrapping any problem types, formulation adapters and optimizers) and becomes dispatachable by the shared :class:~quantsmind.quantum.domain.intelligence.DomainIntelligence layer without changing core code.

register(binding)

Register a :class:DomainBinding (explicit dispatch entry).

register_defaults()

Register the four built-in domain bindings.

The bindings live in :mod:quantsmind.quantum.domain.adapters and wrap the existing per-domain formulation adapters and optimizers. Registration order is stable: finance, portfolio, data, ml.

resolve(problem)

Return the :class:DomainBinding owning problem.

Raises:

Type Description
UnsupportedDomainError

When no binding accepts the problem.

resolve_kind(kind)

Return the binding registered for a :class:DomainKind.

kind_of(problem)

Return the :class:DomainKind of a problem instance.

is_registered(problem)

True when a binding accepts the problem.

domains()

Registered :class:DomainKind values in registration order.

bindings()

Registered bindings (copy) in registration order.

DomainRunResult dataclass

Honest, provenance-rich result of a domain solve or benchmark.

Parameters:

Name Type Description Default
problem_name str

Name of the solved problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the source domain problem.

''
strategy_requested str

Strategy the caller requested ("" = auto).

''
strategy_selected str

Strategy selected by QMQ-03 for execution.

''
strategy_executed str

Strategy that actually produced the outcome (may differ from selected after a fallback/degradation).

''
algorithm str

Algorithm id that ran ("" when classical).

''
backend str

Backend that executed the quantum leg ("" otherwise).

''
execution_mode str

"quantum" / "classical" / "classical" "quantum-inspired".

'classical'
fallback_used bool

True when the executed path differed from the requested/selected path (honest degradation).

False
feasible bool | None

Feasibility of the produced solution or None.

None
objective_value float | None

Leading objective value or None.

None
limitations list[str]

Honest list of what did NOT happen (e.g. quantum runtime missing).

list()
interpretation Any | None

QMQ-06 structured interpretation (optional).

None
report Any | None

The QMQ-04 :class:SolutionReport (in-memory reference).

None
benchmark Any | None

QMQ-05 :class:BenchmarkResult (in-memory reference).

None
domain_result Any | None

The per-domain result object (in-memory reference).

None
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
interpretation_status()

Serialized QMQ-06 interpretation status ("" when absent).

to_dict()

Serialize to a JSON-safe dictionary (reports as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report, domain_result) are not rebuilt; measured facts round-trip exactly.

QuantumSuitability

Bases: Enum

Suitability of a problem for the quantum path (QMQ-11 §5).

parse(value) classmethod

Coerce a label or member to a :class:QuantumSuitability.

QuantumSuitabilityAssessor

Deterministic, evidence-backed suitability assessment (QMQ-11 §5).

Rules (in evaluation order):

  1. No usable plan -> UNKNOWN.
  2. Not QUBO-amenable (plan.formulation != "qubo") -> UNSUITABLE.
  3. Quantum algorithm selected AND runtime + algorithm available -> SUITABLE.
  4. Quantum path exists (quantum/classical-hybrid strategy or quantum algorithm) but is not executable here -> CONDITIONALLY_SUITABLE with the missing prerequisites listed as limitations.
  5. Otherwise (AUTO selected CLASSICAL for a QUBO-amenable problem) -> CONDITIONALLY_SUITABLE with the size policy stated.
assess(*, plan, capabilities=None, problem_name=None)

Assess a :class:ComputationPlan against an environment snapshot.

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan to assess.

required
capabilities CapabilityModel | None

Capability snapshot; re-detected when omitted.

None
problem_name str | None

Optional override of the assessed problem name.

None

Returns:

Name Type Description
SuitabilityAssessment SuitabilityAssessment

Level, reasons, limitations and evidence.

assess_unknown(*, problem_name)

Return an UNKNOWN assessment when no plan could be built.

SuitabilityAssessment dataclass

Evidence-backed suitability of one problem (QMQ-11 §5).

Parameters:

Name Type Description Default
problem_name str

Names the assessed problem.

required
suitability QuantumSuitability

The assigned :class:QuantumSuitability level.

required
reason str

Human-readable justification of the assignment.

required
signals dict[str, Any]

Structural signals driving the decision (strategy, algorithm, formulation, capability flags, ...).

dict()
evidence dict[str, Any]

Exact facts that produced the decision.

dict()
limitations list[str]

Honest list of conditions that are NOT satisfied.

list()
quantum_available bool

Whether a quantum execution runtime was available (MicroQuantum installed and enabled).

False
algorithm_available bool

Whether the selected quantum algorithm was executable in this environment.

False
formulation_amenable bool

Whether a QUBO formulation path exists.

False
provenance dict[str, Any]

Where-and-how metadata for the assessment.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()
label property

Serialized suitability label (e.g. "suitable").

is_suitable property

True for SUITABLE or CONDITIONALLY_SUITABLE.

is_suitable answers "is there a viable quantum path for this problem" — never "quantum was executed". Use :attr:quantum_available / :attr:algorithm_available for the execution readiness facts.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

assess_problem(problem, registry=None, *, strategy=None, capabilities=None)

Assess one domain problem through the QMQ-03 pipeline (no execution).

Parameters:

Name Type Description Default
problem Any

The domain problem to assess.

required
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the built-in domains.

None
strategy str | None

Optional requested strategy label (forwarded to :meth:StrategySelector.select_reasoned through the binding).

None
capabilities CapabilityModel | None

Capability snapshot; detected when omitted.

None

Raises:

Type Description
UnsupportedDomainError

When no registered binding supports the problem.

DomainValidationError

When the problem fails its validation.

domain_data_example()

Full domain pipeline on the Data feature-selection example (QMQ-11 §16 B).

domain_finance_example()

Full domain pipeline on the finance example problem (QMQ-11 §16 A).

The example problem is the deterministic financial formulation of the canonical QMQ-08 risk-adjusted portfolio (cardinality-only, binary), so its QUBO maps losslessly and the end-to-end solve is well-defined.

domain_ml_example()

Full domain pipeline on the ML classification example (QMQ-11 §16 C).

domain_pipeline_example()

Cross-domain example: Finance, Data and ML through one intelligence.

Returns a dict keyed by domain label with each problem's assessment, plan, solve, benchmark and interpretation artifacts.

adapters

Built-in domain bindings (QMQ-11 §10).

Each binding ties one domain to its existing formulation adapter and optimizer through a common :class:DomainBinding surface. The bindings are imported and registered by :class:DomainRegistry on construction; new domains build their own bindings with the same public API and register them through :meth:DomainRegistry.register — no core change required.

finance_binding()

Binding for :class:~quantsmind.quantum.finance.models.FinancialProblem through the Finance adapter and optimizer (QMQ-11 Example A).

portfolio_binding()

Binding for :class:~quantsmind.quantum.finance.portfolio .PortfolioOptimizationProblem (QMQ-08).

data_binding()

Binding for :class:~quantsmind.quantum.data.problem.DataProblem (QMQ-09).

ml_binding()

Binding for :class:~quantsmind.quantum.ml.problem.MLProblem (QMQ-10).

default_bindings()

The four built-in domain bindings in dispatch priority order.

assessment

Cross-domain problem assessment (QMQ-11 §4, §7).

:func:assess_problem walks one domain problem through the registered binding and the existing QMQ-03 intelligence pipeline — classify, formulate, choose strategy, recommend algorithm, build the computation plan, assess suitability — and returns a :class:ProblemAssessment that is fully inspectable and serializable. No execution happens during assessment.

ProblemAssessment dataclass

Full, inspectable assessment of one domain problem (QMQ-11 §7).

Parameters:

Name Type Description Default
problem_name str

Name of the assessed problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the assessed problem.

''
classification ClassificationResult | None

QMQ-03 classification decision.

None
formulation FormulationRecommendation | None

QMQ-03 formulation-kind recommendation.

None
strategy_decision StrategyDecision | None

QMQ-03 strategy decision (with rationale).

None
algorithm_recommendation Any | None

QMQ-03 algorithm recommendation (with executable fallbacks).

None
capabilities CapabilityModel | None

Capability snapshot the decisions used.

None
suitability SuitabilityAssessment | None

:class:SuitabilityAssessment of the plan.

None
computation_plan ComputationPlan | None

The QMQ-03 :class:ComputationPlan built.

None
reasons list[str]

Rolled-up human-readable justification.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
domain_label property

Serialized domain label (e.g. "ml").

strategy_label property

Serialized selected strategy label.

algorithm property

Selected primary algorithm id ("" when none).

formulation_kind property

Recommended formulation kind (e.g. "qubo").

suitability_label property

Serialized suitability label ("" when unassessed).

is_implementable property

True when a computation plan was built (ready to run).

summary()

One-line human summary of the assessment.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

assess_problem(problem, registry=None, *, strategy=None, capabilities=None)

Assess one domain problem through the QMQ-03 pipeline (no execution).

Parameters:

Name Type Description Default
problem Any

The domain problem to assess.

required
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the built-in domains.

None
strategy str | None

Optional requested strategy label (forwarded to :meth:StrategySelector.select_reasoned through the binding).

None
capabilities CapabilityModel | None

Capability snapshot; detected when omitted.

None

Raises:

Type Description
UnsupportedDomainError

When no registered binding supports the problem.

DomainValidationError

When the problem fails its validation.

errors

Domain intelligence error hierarchy (QMQ-11).

Cross-domain problems are validated, assessed, planned and dispatched through the registered domain bindings. Errors raised while doing so form a small, backend-agnostic hierarchy derived from :class:ValueError.

DomainError

Bases: ValueError

Base error of the quantum domain intelligence layer.

DomainValidationError

Bases: DomainError

Raised when a domain problem fails its own validation rules.

DomainDispatchError

Bases: DomainError

Raised when a problem cannot be dispatched to a registered domain.

UnsupportedDomainError

Bases: DomainDispatchError

Raised when no registered domain binding matches a problem.

examples

End-to-end domain intelligence examples (QMQ-11 §16).

These examples reuse the existing per-domain example problems and run them through :class:DomainIntelligence: assessment (QMQ-03) and planning inspect the recommended quantum path (automatic strategy — the honest quantum-suitability of each problem is recorded), while solve/benchmark execute on an explicit classical strategy so they are deterministic and fast.

domain_finance_example()

Full domain pipeline on the finance example problem (QMQ-11 §16 A).

The example problem is the deterministic financial formulation of the canonical QMQ-08 risk-adjusted portfolio (cardinality-only, binary), so its QUBO maps losslessly and the end-to-end solve is well-defined.

domain_data_example()

Full domain pipeline on the Data feature-selection example (QMQ-11 §16 B).

domain_ml_example()

Full domain pipeline on the ML classification example (QMQ-11 §16 C).

domain_pipeline_example()

Cross-domain example: Finance, Data and ML through one intelligence.

Returns a dict keyed by domain label with each problem's assessment, plan, solve, benchmark and interpretation artifacts.

intelligence

Domain intelligence orchestrator (QMQ-11 §9).

:class:DomainIntelligence is the public, domain-agnostic entry point. It dispatches a problem to its registered :class:DomainBinding, then walks it through the existing QMQ-03 pipeline (assess) or executes it through the per-domain optimizer (solve / benchmark). All decisions and execution facts are inspectable and serializable.

DomainIntelligence

Cross-domain assessment, planning, solving and benchmarking.

Parameters:

Name Type Description Default
registry DomainRegistry | None

Dispatch registry; defaults to a fresh :class:DomainRegistry with the four built-in domains.

None
assessor QuantumSuitabilityAssessor | None

:class:QuantumSuitabilityAssessor; defaulted when omitted.

None
interpreter Any | None

Interpreter used by :meth:interpret; defaulted lazily.

None
assess(problem, *, strategy=None, capabilities=None)

Assess a domain problem (classify/formulate/strategy/algorithm/ suitability) without executing anything.

plan(problem, *, strategy=None, capabilities=None)

Build an inspectable :class:ExecutionPlan for a problem.

The plan can be inspected before any execution happens; no quantum work is performed by planning itself.

solve(problem, *, strategy=None, config=None)

Solve a domain problem through its registered optimizer.

The result is wrapped in a :class:DomainRunResult with the honest strategy/algorithm/backend/execution-mode facts and the QMQ-06 interpretation.

Raises:

Type Description
UnsupportedDomainError

When no domain binding matches.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a domain problem against the classical baseline (QMQ-05).

interpret(result)

Return the QMQ-06 interpretation carried by a run result.

Returns:

Name Type Description
The Any

class:ResultInterpretation (QMQ-06) of the run, or raises

Any

class:DomainDispatchError when no interpretation exists.

solve_and_interpret(problem, *, strategy=None, config=None)

Solve and attach the interpretation in a single call.

The interpretation is already carried by the wrapped result from QMQ-06; this method only validates that it is present.

supported_domains()

Serialized labels of the registered domains.

is_supported(problem)

True when a domain binding matches the problem.

plan

Inspectable, domain-aware execution plan (QMQ-11 §7).

:mod:quantsmind.quantum.domain.plan wraps a :class:ComputationPlan with the domain dimension (:class:DomainKind) and the full :class:SuitabilityAssessment, so the caller can inspect what will run, why it was selected, and whether the quantum path is available in this environment, before any execution happens.

ExecutionPlan dataclass

Domain-aware, inspectable execution plan (QMQ-11 §7).

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan (classification, formulation, strategy, algorithm, mapping, executor, fallbacks).

required
domain DomainKind

The dispatched :class:DomainKind.

required
problem_type str

Class name of the source domain problem.

required
strategy_requested str

Explicit strategy the caller requested ("" for automatic).

required
suitability SuitabilityAssessment

Suitability assessment of the plan.

required
classification str

Serialized classification label.

''
formulation_kind str

Serialized formulation kind.

''
reasons list[str]

Rolled-up reasons from the plan and suitability.

list()
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
summary()

One-line human summary of the plan.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

registry

Explicit, registered cross-domain dispatch (QMQ-11 §10).

A :class:DomainRegistry maps each supported domain to an explicit :class:DomainBinding. The built-in registry pre-registers the Finance, Portfolio, Data and ML domains; new domains register themselves through the same public API — there is no central if/elif monolith.

Each binding exposes four capabilities that the domain intelligence layer reuses:

  • validate / raise_if_invalid — domain validation.
  • to_quantum_problem — formulate the domain problem into the existing QMQ pipeline.
  • solve / benchmark — execute the existing QMQ-03..06 pipeline through the per-domain optimizer.
DomainKind

Bases: Enum

Registered quantum-enabled domains (QMQ-11).

parse(value) classmethod

Coerce a label or member to a :class:DomainKind.

DomainBinding dataclass

Explicit binding between a domain and its execution capabilities.

Parameters:

Name Type Description Default
kind DomainKind

The registered :class:DomainKind.

required
label str

Human-readable sub-label of the binding.

required
problem_types tuple[type, ...]

isinstance-matchable problem types this binding owns.

required
validate Callable[[Any], list[str]]

Callable(problem) -> list[str] of validation issues.

required
raise_if_invalid Callable[[Any], None]

Callable(problem) -> None raising the domain's validation error.

required
to_quantum_problem Callable[..., QuantumProblem]

Callable(problem, *, preferred_strategy=None) -> :class:QuantumProblem. Reuses the existing per-domain formulation adapter.

required
solve Callable[..., Any]

Callable(problem, *, strategy=None, config=None, seed=None) through the per-domain optimizer.

required
benchmark Callable[..., Any]

Callable(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None, seed=None).

required
description str

Human-readable description of the binding.

''
metadata dict[str, Any]

Free-form metadata (module path, rule path, ...).

dict()
accepts(problem)

True when this binding owns the given problem instance.

DomainRegistry

Registered dispatch table for supported domains (QMQ-11 §10).

The registry is extensible through :meth:register: an external domain supplies its own :class:DomainBinding (wrapping any problem types, formulation adapters and optimizers) and becomes dispatachable by the shared :class:~quantsmind.quantum.domain.intelligence.DomainIntelligence layer without changing core code.

register(binding)

Register a :class:DomainBinding (explicit dispatch entry).

register_defaults()

Register the four built-in domain bindings.

The bindings live in :mod:quantsmind.quantum.domain.adapters and wrap the existing per-domain formulation adapters and optimizers. Registration order is stable: finance, portfolio, data, ml.

resolve(problem)

Return the :class:DomainBinding owning problem.

Raises:

Type Description
UnsupportedDomainError

When no binding accepts the problem.

resolve_kind(kind)

Return the binding registered for a :class:DomainKind.

kind_of(problem)

Return the :class:DomainKind of a problem instance.

is_registered(problem)

True when a binding accepts the problem.

domains()

Registered :class:DomainKind values in registration order.

bindings()

Registered bindings (copy) in registration order.

result

Domain-level run result (QMQ-11 §8).

:class:DomainRunResult bundles a domain solve/benchmark outcome with the honest execution facts: the requested strategy, the strategy that was actually selected and executed, the algorithm, the backend, the execution mode (classical / quantum), whether a fallback was used, and the QMQ-06 interpretation (which records DEGRADED when a quantum-capable strategy had to execute classically).

Composition references (report, domain_result) are kept in memory and serialized only as lightweight references, mirroring QMQ-05.

DomainRunResult dataclass

Honest, provenance-rich result of a domain solve or benchmark.

Parameters:

Name Type Description Default
problem_name str

Name of the solved problem.

required
domain DomainKind | None

The dispatched :class:DomainKind.

None
problem_type str

Class name of the source domain problem.

''
strategy_requested str

Strategy the caller requested ("" = auto).

''
strategy_selected str

Strategy selected by QMQ-03 for execution.

''
strategy_executed str

Strategy that actually produced the outcome (may differ from selected after a fallback/degradation).

''
algorithm str

Algorithm id that ran ("" when classical).

''
backend str

Backend that executed the quantum leg ("" otherwise).

''
execution_mode str

"quantum" / "classical" / "classical" "quantum-inspired".

'classical'
fallback_used bool

True when the executed path differed from the requested/selected path (honest degradation).

False
feasible bool | None

Feasibility of the produced solution or None.

None
objective_value float | None

Leading objective value or None.

None
limitations list[str]

Honest list of what did NOT happen (e.g. quantum runtime missing).

list()
interpretation Any | None

QMQ-06 structured interpretation (optional).

None
report Any | None

The QMQ-04 :class:SolutionReport (in-memory reference).

None
benchmark Any | None

QMQ-05 :class:BenchmarkResult (in-memory reference).

None
domain_result Any | None

The per-domain result object (in-memory reference).

None
provenance dict[str, Any]

Where-and-how metadata.

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
interpretation_status()

Serialized QMQ-06 interpretation status ("" when absent).

to_dict()

Serialize to a JSON-safe dictionary (reports as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report, domain_result) are not rebuilt; measured facts round-trip exactly.

result_from_domain_result(domain_result, problem, binding, *, kind, strategy_requested, provenance=None, metadata=None)

Wrap a per-domain optimizer result into a :class:DomainRunResult.

Parameters:

Name Type Description Default
domain_result Any

Finance/Portfolio/Data/ML optimizer result.

required
problem Any

The solved domain problem.

required
binding DomainBinding | None

The dispatched :class:DomainBinding (for the domain).

required
kind str

"solve" or "benchmark".

required
strategy_requested str | None

Explicit requested strategy (None = auto).

required
provenance dict[str, Any] | None

Optional provenance to attach.

None
metadata dict[str, Any] | None

Optional free-form metadata.

None

The wrapper reads the honest execution facts from the underlying :class:SolutionReport and the QMQ-06 :class:ResultInterpretation, so it never invents a quantum claim.

suitability

Quantum suitability assessment (QMQ-11 §5).

:Sclass:QuantumSuitabilityAssessor decides, deterministically and with full evidence, whether a problem can or should run on the quantum path. The assessment never claims quantum advantage or quantum execution: it only records whether a QUBO path exists, whether a quantum algorithm was selected, whether the runtime + algorithm are available, and why.

Suitability levels:

  • SUITABLE — the problem is QUBO-amenable, a quantum algorithm was selected, and the environment can execute it.
  • CONDITIONALLY_SUITABLE — a quantum path exists but cannot run here (missing runtime/algorithm), or was intentionally not selected (AUTO size policy).
  • UNSUITABLE — no usable quantum path exists for the problem.
  • UNKNOWN — no plan was available to assess.
QuantumSuitability

Bases: Enum

Suitability of a problem for the quantum path (QMQ-11 §5).

parse(value) classmethod

Coerce a label or member to a :class:QuantumSuitability.

SuitabilityAssessment dataclass

Evidence-backed suitability of one problem (QMQ-11 §5).

Parameters:

Name Type Description Default
problem_name str

Names the assessed problem.

required
suitability QuantumSuitability

The assigned :class:QuantumSuitability level.

required
reason str

Human-readable justification of the assignment.

required
signals dict[str, Any]

Structural signals driving the decision (strategy, algorithm, formulation, capability flags, ...).

dict()
evidence dict[str, Any]

Exact facts that produced the decision.

dict()
limitations list[str]

Honest list of conditions that are NOT satisfied.

list()
quantum_available bool

Whether a quantum execution runtime was available (MicroQuantum installed and enabled).

False
algorithm_available bool

Whether the selected quantum algorithm was executable in this environment.

False
formulation_amenable bool

Whether a QUBO formulation path exists.

False
provenance dict[str, Any]

Where-and-how metadata for the assessment.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()
label property

Serialized suitability label (e.g. "suitable").

is_suitable property

True for SUITABLE or CONDITIONALLY_SUITABLE.

is_suitable answers "is there a viable quantum path for this problem" — never "quantum was executed". Use :attr:quantum_available / :attr:algorithm_available for the execution readiness facts.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an assessment from :meth:to_dict output.

QuantumSuitabilityAssessor

Deterministic, evidence-backed suitability assessment (QMQ-11 §5).

Rules (in evaluation order):

  1. No usable plan -> UNKNOWN.
  2. Not QUBO-amenable (plan.formulation != "qubo") -> UNSUITABLE.
  3. Quantum algorithm selected AND runtime + algorithm available -> SUITABLE.
  4. Quantum path exists (quantum/classical-hybrid strategy or quantum algorithm) but is not executable here -> CONDITIONALLY_SUITABLE with the missing prerequisites listed as limitations.
  5. Otherwise (AUTO selected CLASSICAL for a QUBO-amenable problem) -> CONDITIONALLY_SUITABLE with the size policy stated.
assess(*, plan, capabilities=None, problem_name=None)

Assess a :class:ComputationPlan against an environment snapshot.

Parameters:

Name Type Description Default
plan ComputationPlan

The QMQ-03 :class:ComputationPlan to assess.

required
capabilities CapabilityModel | None

Capability snapshot; re-detected when omitted.

None
problem_name str | None

Optional override of the assessed problem name.

None

Returns:

Name Type Description
SuitabilityAssessment SuitabilityAssessment

Level, reasons, limitations and evidence.

assess_unknown(*, problem_name)

Return an UNKNOWN assessment when no plan could be built.

execution

Execution layer of QuantsMind Quantum (QMQ-04).

Classical, quantum and hybrid executors turn a :class:ExecutorContext (problem + computation plan + mapped payloads + options) into normalized, comparable execution results with an explicit failure taxonomy.

ClassicalExecutionResult dataclass

Normalized classical execution result.

Leg identity is "classical"; :attr:executor/:attr:solver keep the legacy label "classical/exhaustive" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_solver(result, *, objective_value, feasible, options) classmethod

Normalize an :class:ClassicalSolverResult into an execution result.

ClassicalExecutor

Bases: Executor

Exact-solution classical leg of an execution.

Parameters:

Name Type Description Default
solver ExhaustiveSolver | None

Optional :class:ExhaustiveSolver override (workflows reuse their configured classical executor solver here).

None

ExecutionComparison dataclass

Explicit comparison of the legs of a hybrid execution.

Parameters:

Name Type Description Default
entries list[ExecutionComparisonEntry]

Comparison entries, one per leg.

list()
winner str | None

Leg id that won selection ("classical" / "quantum" / None when nothing executed).

None
selected_reason str

Human-readable justification for the winner.

''
tie_break str

Tie-break rule description when selection needed one.

''
sense str

Objective sense used for ranking ("minimize"/"maximize").

'minimize'
metadata dict[str, Any]

Free-form metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

build(entries, *, sense=ObjectiveSense.MINIMIZE) classmethod

Rank executed legs and pick a deterministic winner.

Ranking (QMQ-04 §11): 1. feasible beats infeasible, 2. better objective per the problem's sense (fallback: QUBO energy, lower is better), 3. ties are broken deterministically in favour of the classical exact baseline.

No quantum-advantage/speedup claim is ever derived from this ranking.

ExecutionComparisonEntry dataclass

One leg of a hybrid execution, ready for comparison.

Parameters:

Name Type Description Default
leg str

"classical" or "quantum".

required
algorithm str

Algorithm id that produced the result.

''
executor str

Executor label (e.g. "classical/exhaustive").

''
status str

"executed" / "skipped" / "failed".

_EXECUTED
objective_value float | None

Domain objective value of the returned assignment.

None
energy float | None

QUBO energy of the returned assignment (minimization form).

None
feasible bool | None

Whether the assignment satisfies the domain constraints.

None
message str

Free-form note (skip/failure reason, ...).

''
metadata dict[str, Any]

Free-form metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an entry from :meth:to_dict output.

from_execution(*, leg, execution, status=_EXECUTED, message='', metadata=None) classmethod

Build an entry from a normalized execution result.

ClassicalExecutionError

Bases: ExecutionError

The classical baseline could not execute the plan.

ExecutionError

Bases: ValueError

Base class for execution-layer failures.

HybridExecutionError

Bases: ExecutionError

A hybrid execution failed because no leg produced a result.

InvalidExecutionOptionError

Bases: ExecutionError

An execution option is invalid for the requested strategy.

InvalidQuantumResultError

Bases: ExecutionError

A decoded quantum result failed validation (variables/values/energy).

MicroQuantumUnavailableError

Bases: ImportError, WorkflowError

MicroQuantum is not importable but a quantum strategy needed it.

Subclasses both :class:ImportError (so except ImportError catches it at the engine boundary) and :class:WorkflowError (so workflow-level callers keep their existing behaviour).

QuantumExecutionError

Bases: ExecutionError

A quantum execution failed while delegating to MicroQuantum.

UnsupportedStrategyError

Bases: ExecutionError

The requested strategy/executor combination is not supported.

WorkflowError

Bases: ValueError

Raised when a workflow step cannot proceed.

Kept in this module (rather than the workflow package) so dependency errors can subclass it without creating an import cycle.

Executor

Bases: ABC

Common interface for classical / quantum / hybrid executors.

Subclasses identify themselves through :attr:name and :attr:executor_id and declare which strategies they implement in :attr:strategies. Execution is prepare -> execute -> validate; each step may raise the typed :mod:quantsmind.quantum.execution.errors.

is_available(capabilities=None)

Whether this executor can currently execute (default: True).

prepare(context)

Validate inputs and fail fast before any real work.

execute(context) abstractmethod

Run the planned computation and return a normalized result.

validate(result, context)

Validate and normalize an execution result (default: passthrough).

ExecutorContext dataclass

Everything one executor needs to run one plan.

Parameters:

Name Type Description Default
problem Any

The domain problem being executed.

required
plan Any

The QMQ-03 computation plan (the plan drives execution).

required
formulation Any | None

Formulation produced for the problem (optional).

None
qubo Any | None

Mapped QUBO model (used by the classical leg).

None
ising Any | None

Mapped Ising model (used by the quantum leg).

None
options ExecutionOptions

Execution configuration for this run.

ExecutionOptions()
metadata dict[str, Any]

Free-form contextual metadata.

dict()
strategy property

Strategy resolving options override, then the plan, then None.

algorithm property

Algorithm resolving options override, then the plan.

HybridExecutionResult dataclass

Composite result of a hybrid execution.

Parameters:

Name Type Description Default
classical ClassicalExecutionResult | None

Classical leg result (or None when skipped/failed).

None
quantum QuantumExecutionResult | None

Quantum leg result (or None when skipped/failed).

None
comparison ExecutionComparison | None

Explicit comparison + deterministic selection.

None
selected str | None

Selected leg id ("classical" / "quantum").

None
selected_assignment dict[str, int]

Assignment chosen by selection.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()
assignment property

Selected assignment (existing build_solution compatibility).

quantum_unavailable property

True when the quantum leg produced no execution result.

solver property

Selected leg's executor label (provenance compatibility).

energy property

Selected leg's QUBO energy (provenance compatibility).

shots property

Selected leg's shot count.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

HybridExecutor

Bases: Executor

Runs the classical baseline and the QAOA leg, then selects a winner.

Parameters:

Name Type Description Default
classical_executor ClassicalExecutor | None

Optional :class:ClassicalExecutor override.

None
quantum_executor QuantumExecutor | None

Optional :class:QuantumExecutor override.

None

ExecutionOptions dataclass

Controlled execution configuration for one workflow run.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Strategy to execute. None defers to the :class:ComputationPlan (QMQ-03 decision).

None
algorithm str | None

Optional algorithm override (echoed into metadata; the plan's recommended algorithm drives execution unless requested_algorithm is set on the workflow).

None
shots int

Shot count for the quantum leg.

1024
seed int | None

Optional RNG seed for reproducible quantum sampling.

None
backend str | None

Backend name (e.g. "statevector") or instance.

None
num_layers int

QAOA layers (p) for the quantum leg.

1
penalty float | None

Optional QUBO constraint penalty multiplier.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (delegated unchanged).

None
optimization_level int

0..3 optimization hint; recorded in metadata (the QAOA path does not consume it).

0
run_classical_baseline bool | None

For HYBRID, whether to run the classical baseline. None means automatic (always run).

None
allow_fallback bool

Whether an unavailable requested algorithm may fall back to an executable replacement (never silent).

False
metadata dict[str, Any]

Free-form execution metadata.

dict()
resolved_strategy property

Strategy parsed to a :class:ComputationStrategy (or None).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild options from :meth:to_dict output.

QuantumExecutionResult dataclass

Validated, normalized quantum execution result.

Leg identity is "quantum"; :attr:executor/:attr:solver keep the legacy label "microquantum/qaoa" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_qaoa(result, *, objective_value, feasible, options) classmethod

Normalize a validated :class:QaoaExecutionResult.

QuantumExecutor

Bases: Executor

QAOA quantum leg of an execution (delegates unchanged to MicroQuantum).

validate(result, context)

Validate a QaoaExecutionResult before it becomes a leg of the run.

Checks (QMQ-04 §9): decoded variable names against the mapped QUBO (slack variables included), binary values, re-computed QUBO energy consistency, domain objective/feasibility. The raw MicroQuantum metadata stays intact.

classical

Classical executor on top of the exact exhaustive baseline (QMQ-04 §6).

This wraps :class:~quantsmind.quantum.optimization.classical.ExhaustiveSolver behind the common :class:Executor interface. The solver is reused unchanged — no second classical path is added.

ClassicalExecutionResult dataclass

Normalized classical execution result.

Leg identity is "classical"; :attr:executor/:attr:solver keep the legacy label "classical/exhaustive" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_solver(result, *, objective_value, feasible, options) classmethod

Normalize an :class:ClassicalSolverResult into an execution result.

ClassicalExecutor

Bases: Executor

Exact-solution classical leg of an execution.

Parameters:

Name Type Description Default
solver ExhaustiveSolver | None

Optional :class:ExhaustiveSolver override (workflows reuse their configured classical executor solver here).

None

comparison

Classical/quantum comparison for hybrid execution (QMQ-04 §10/§11).

:class:ExecutionComparison is the explicit comparison artifact of a hybrid run: one entry per executed/skipped/failed leg plus a deterministic winner and the reasons that produced it. No advantage, speedup or superiority claim is ever fabricated here — only the recorded objective value, energy, feasibility and status of each leg are compared.

ExecutionComparisonEntry dataclass

One leg of a hybrid execution, ready for comparison.

Parameters:

Name Type Description Default
leg str

"classical" or "quantum".

required
algorithm str

Algorithm id that produced the result.

''
executor str

Executor label (e.g. "classical/exhaustive").

''
status str

"executed" / "skipped" / "failed".

_EXECUTED
objective_value float | None

Domain objective value of the returned assignment.

None
energy float | None

QUBO energy of the returned assignment (minimization form).

None
feasible bool | None

Whether the assignment satisfies the domain constraints.

None
message str

Free-form note (skip/failure reason, ...).

''
metadata dict[str, Any]

Free-form metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an entry from :meth:to_dict output.

from_execution(*, leg, execution, status=_EXECUTED, message='', metadata=None) classmethod

Build an entry from a normalized execution result.

ExecutionComparison dataclass

Explicit comparison of the legs of a hybrid execution.

Parameters:

Name Type Description Default
entries list[ExecutionComparisonEntry]

Comparison entries, one per leg.

list()
winner str | None

Leg id that won selection ("classical" / "quantum" / None when nothing executed).

None
selected_reason str

Human-readable justification for the winner.

''
tie_break str

Tie-break rule description when selection needed one.

''
sense str

Objective sense used for ranking ("minimize"/"maximize").

'minimize'
metadata dict[str, Any]

Free-form metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a comparison from :meth:to_dict output.

build(entries, *, sense=ObjectiveSense.MINIMIZE) classmethod

Rank executed legs and pick a deterministic winner.

Ranking (QMQ-04 §11): 1. feasible beats infeasible, 2. better objective per the problem's sense (fallback: QUBO energy, lower is better), 3. ties are broken deterministically in favour of the classical exact baseline.

No quantum-advantage/speedup claim is ever derived from this ranking.

errors

Typed execution errors for QuantsMind Quantum (QMQ-04).

The failure taxonomy is explicit: callers can distinguish a missing MicroQuantum dependency from a failed quantum run, a bad decoded result, an unsupported strategy, or a classical execution failure — without swallowing any of them.

ExecutionError

Bases: ValueError

Base class for execution-layer failures.

WorkflowError

Bases: ValueError

Raised when a workflow step cannot proceed.

Kept in this module (rather than the workflow package) so dependency errors can subclass it without creating an import cycle.

MicroQuantumUnavailableError

Bases: ImportError, WorkflowError

MicroQuantum is not importable but a quantum strategy needed it.

Subclasses both :class:ImportError (so except ImportError catches it at the engine boundary) and :class:WorkflowError (so workflow-level callers keep their existing behaviour).

ClassicalExecutionError

Bases: ExecutionError

The classical baseline could not execute the plan.

QuantumExecutionError

Bases: ExecutionError

A quantum execution failed while delegating to MicroQuantum.

HybridExecutionError

Bases: ExecutionError

A hybrid execution failed because no leg produced a result.

InvalidQuantumResultError

Bases: ExecutionError

A decoded quantum result failed validation (variables/values/energy).

UnsupportedStrategyError

Bases: ExecutionError

The requested strategy/executor combination is not supported.

InvalidExecutionOptionError

Bases: ExecutionError

An execution option is invalid for the requested strategy.

evaluation

Evaluation helpers shared by every QMQ-04 executor.

These are the single source of truth for turning a candidate assignment into feasibility/objective facts, so the classical and quantum legs (and their validation) cannot disagree about a problem's semantics.

feasibility_predicate(problem)

Return a predicate marking an assignment feasible iff no constraint is violated (unknowns are benign).

is_feasible_assignment(problem, assignment)

Evaluate domain feasibility of a candidate assignment.

objective_evaluator(problem)

Return an evaluator for the first objective (0.0 when absent).

This mirrors the workflow baseline: only the first objective participates in scalar comparisons; all objectives are reported separately.

objective_values(problem, assignment)

Evaluate every objective for an assignment (only evaluable ones).

objective_value(problem, assignment)

Scalar objective value of the first objective (or None).

executor

Executor abstraction for QuantsMind Quantum (QMQ-04 §2).

An :class:Executor turns a :class:ExecutorContext (problem + computation plan + mapped payloads + options) into a normalized execution result through a predictable, common interface:

prepare() -> execute() -> validate()

ExecutionOptions dataclass

Controlled execution configuration for one workflow run.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Strategy to execute. None defers to the :class:ComputationPlan (QMQ-03 decision).

None
algorithm str | None

Optional algorithm override (echoed into metadata; the plan's recommended algorithm drives execution unless requested_algorithm is set on the workflow).

None
shots int

Shot count for the quantum leg.

1024
seed int | None

Optional RNG seed for reproducible quantum sampling.

None
backend str | None

Backend name (e.g. "statevector") or instance.

None
num_layers int

QAOA layers (p) for the quantum leg.

1
penalty float | None

Optional QUBO constraint penalty multiplier.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (delegated unchanged).

None
optimization_level int

0..3 optimization hint; recorded in metadata (the QAOA path does not consume it).

0
run_classical_baseline bool | None

For HYBRID, whether to run the classical baseline. None means automatic (always run).

None
allow_fallback bool

Whether an unavailable requested algorithm may fall back to an executable replacement (never silent).

False
metadata dict[str, Any]

Free-form execution metadata.

dict()
resolved_strategy property

Strategy parsed to a :class:ComputationStrategy (or None).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild options from :meth:to_dict output.

ExecutorContext dataclass

Everything one executor needs to run one plan.

Parameters:

Name Type Description Default
problem Any

The domain problem being executed.

required
plan Any

The QMQ-03 computation plan (the plan drives execution).

required
formulation Any | None

Formulation produced for the problem (optional).

None
qubo Any | None

Mapped QUBO model (used by the classical leg).

None
ising Any | None

Mapped Ising model (used by the quantum leg).

None
options ExecutionOptions

Execution configuration for this run.

ExecutionOptions()
metadata dict[str, Any]

Free-form contextual metadata.

dict()
strategy property

Strategy resolving options override, then the plan, then None.

algorithm property

Algorithm resolving options override, then the plan.

Executor

Bases: ABC

Common interface for classical / quantum / hybrid executors.

Subclasses identify themselves through :attr:name and :attr:executor_id and declare which strategies they implement in :attr:strategies. Execution is prepare -> execute -> validate; each step may raise the typed :mod:quantsmind.quantum.execution.errors.

is_available(capabilities=None)

Whether this executor can currently execute (default: True).

prepare(context)

Validate inputs and fail fast before any real work.

execute(context) abstractmethod

Run the planned computation and return a normalized result.

validate(result, context)

Validate and normalize an execution result (default: passthrough).

hybrid

Hybrid executor: real classical + real quantum legs, honest comparison.

QMQ-04 §10-§12: a hybrid run performs both computations. The quantum leg that cannot run (MicroQuantum absent or broken) is recorded as skipped/failed — never invented. The comparison then picks the deterministic winner; when only one leg executed, that leg wins by default and the reason says so explicitly.

HybridExecutionResult dataclass

Composite result of a hybrid execution.

Parameters:

Name Type Description Default
classical ClassicalExecutionResult | None

Classical leg result (or None when skipped/failed).

None
quantum QuantumExecutionResult | None

Quantum leg result (or None when skipped/failed).

None
comparison ExecutionComparison | None

Explicit comparison + deterministic selection.

None
selected str | None

Selected leg id ("classical" / "quantum").

None
selected_assignment dict[str, int]

Assignment chosen by selection.

dict()
metadata dict[str, Any]

Free-form metadata.

dict()
assignment property

Selected assignment (existing build_solution compatibility).

quantum_unavailable property

True when the quantum leg produced no execution result.

solver property

Selected leg's executor label (provenance compatibility).

energy property

Selected leg's QUBO energy (provenance compatibility).

shots property

Selected leg's shot count.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

HybridExecutor

Bases: Executor

Runs the classical baseline and the QAOA leg, then selects a winner.

Parameters:

Name Type Description Default
classical_executor ClassicalExecutor | None

Optional :class:ClassicalExecutor override.

None
quantum_executor QuantumExecutor | None

Optional :class:QuantumExecutor override.

None

options

Controlled execution configuration (QMQ-04 §14).

:class:ExecutionOptions is the single, traceable configuration object an execution consumes. Quantum-specific options (shots, seed, backend, layers, optimizer) are delegated straight to MicroQuantum's public QAOA API; there is no second complete execution-configuration model here.

ExecutionOptions dataclass

Controlled execution configuration for one workflow run.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Strategy to execute. None defers to the :class:ComputationPlan (QMQ-03 decision).

None
algorithm str | None

Optional algorithm override (echoed into metadata; the plan's recommended algorithm drives execution unless requested_algorithm is set on the workflow).

None
shots int

Shot count for the quantum leg.

1024
seed int | None

Optional RNG seed for reproducible quantum sampling.

None
backend str | None

Backend name (e.g. "statevector") or instance.

None
num_layers int

QAOA layers (p) for the quantum leg.

1
penalty float | None

Optional QUBO constraint penalty multiplier.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (delegated unchanged).

None
optimization_level int

0..3 optimization hint; recorded in metadata (the QAOA path does not consume it).

0
run_classical_baseline bool | None

For HYBRID, whether to run the classical baseline. None means automatic (always run).

None
allow_fallback bool

Whether an unavailable requested algorithm may fall back to an executable replacement (never silent).

False
metadata dict[str, Any]

Free-form execution metadata.

dict()
resolved_strategy property

Strategy parsed to a :class:ComputationStrategy (or None).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild options from :meth:to_dict output.

quantum

Quantum executor delegating to MicroQuantum's public QAOA (QMQ-04 §7/§9).

The quantum leg is a thin, validated wrapper over :func:~quantsmind.quantum.integration.microquantum.run_qaoa — the engine keeps its single QAOA implementation; this layer adds plan-driven options, MicroQuantum-availability handling and explicit result validation (§9).

QuantumExecutionResult dataclass

Validated, normalized quantum execution result.

Leg identity is "quantum"; :attr:executor/:attr:solver keep the legacy label "microquantum/qaoa" so provenance serialization does not change.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

from_qaoa(result, *, objective_value, feasible, options) classmethod

Normalize a validated :class:QaoaExecutionResult.

QuantumExecutor

Bases: Executor

QAOA quantum leg of an execution (delegates unchanged to MicroQuantum).

validate(result, context)

Validate a QaoaExecutionResult before it becomes a leg of the run.

Checks (QMQ-04 §9): decoded variable names against the mapped QUBO (slack variables included), binary values, re-computed QUBO energy consistency, domain objective/feasibility. The raw MicroQuantum metadata stays intact.

experiment

Quantum experiment orchestration for QuantsMind.

A :class:QuantumExperiment is a domain orchestration wrapper: it takes a :class:~quantsmind.quantum.program.QuantumProgram (or a built MicroQuantum circuit), executes it through MicroQuantum's public runtime and wraps the result in a :class:~quantsmind.quantum.circuit_result.QuantumResult.

Quantum computation is always delegated to MicroQuantum. This module contains no quantum algorithm, gate, circuit or simulator logic.

QuantumExperiment

Domain-level quantum experiment that delegates execution to MicroQuantum.

Parameters:

Name Type Description Default
program ProgramOrCircuit

A QuantsMind QuantumProgram, or an already-built MicroQuantum QuantumCircuit.

required
backend str | None

Backend name (e.g. "statevector") or a MicroQuantum Backend instance. None uses MicroQuantum's default.

None
shots int

Number of shots per execution.

1024
seed int | None

Optional RNG seed for reproducibility.

None
name str

Experiment label.

'quantum_experiment'
experiment_id str | None

Optional explicit identity (generated otherwise).

None
domain_metadata dict[str, Any] | None

Domain metadata attached to the result.

None
optimization_level int

MicroQuantum optimization level (0-3).

0
options dict[str, Any] | None

Extra MicroQuantum runtime options.

None
name property

Experiment label.

experiment_id property

Unique experiment identity.

run()

Execute the experiment through MicroQuantum and enrich the result.

available_algorithms()

Return the sorted list of canonical algorithm names QuantsMind can delegate.

resolve_algorithm(name)

Resolve an algorithm name to its MicroQuantum class (public API).

run_algorithm(name, **kwargs)

Instantiate and run a MicroQuantum algorithm by name.

The algorithm class is resolved from MicroQuantum's public API, then instantiated with kwargs and run via its public entry point (run, solve or compute_minimum_eigenvalue). The native MicroQuantum result object is returned.

finance

Finance domain layer of QuantsMind Quantum (QMQ-07 / QMQ-08).

The Finance layer models financial optimization problems as validated, domain-neutral-but-finance-specific objects and converts them into the existing QMQ mathematical/optimization infrastructure (QMQ-02 formulation, QUBO mapping, workflow, execution, benchmark, interpretation). It works entirely from supplied/synthetic data — no live market data, no trading execution, no quantum algorithms.

QMQ-07 ships the Finance foundation (models, weights, context, risk, budget, objectives, constraints, formulation and mapping). QMQ-08 builds the portfolio optimization layer on top of it: a :class:PortfolioOptimizationProblem, portfolio metrics, portfolio solution and result models, and a :class:PortfolioOptimizer that runs the existing QMQ pipeline (binary selection supported; continuous allocation is validated/formulated but the current binary-only QUBO pipeline surfaces honest errors rather than silently approximating; integer allocation raises validation errors).

This is computational Finance domain infrastructure. It is not investment advice and does not provide live financial-data or trading services.

Importing this package never requires microquantum.

Budget dataclass

Validated capital / budget representation.

Parameters:

Name Type Description Default
total float

Total available budget (allocation units).

required
currency str

Optional currency code (metadata only).

''
min_allocation float | None

Optional minimum aggregate allocation.

None
max_allocation float | None

Optional maximum aggregate allocation.

None

Raises:

Type Description
FinanceValidationError

If totals are invalid or bounds inconsistent.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Budget from :meth:to_dict output.

BudgetConstraint dataclass

Bases: FinancialConstraint

Budget limit: sum(cost_i * x_i) <= total.

Without costs the aggregate allocation is bounded: sum(x_i) <= total. costs maps asset identifier -> cost per unit of allocation; missing assets use a unit cost of 1.

CardinalityConstraint dataclass

Bases: FinancialConstraint

Bounded cardinality / aggregate allocation: min <= sum(x_i) <= max.

Under a binary allocation the sum is the number of selected assets (a cardinality bound); under a continuous allocation it bounds the aggregate allocation. Bounds are real values; whole-valued bounds additionally participate in a cardinality sanity check against the universe size.

FinancialConstraint dataclass

Base class of financial constraints.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets)

Return validation issues against an asset universe (empty = valid).

to_quantum_constraints(assets)

Materialize into existing QMQ constraints.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

GroupAllocationConstraint dataclass

Bases: FinancialConstraint

Group allocation limits: lower <= sum_{i in group} x_i <= upper.

A group is an :attr:~quantsmind.quantum.finance.models.Asset.asset_class value (e.g. "equity").

PositionLimitConstraint dataclass

Bases: FinancialConstraint

Position limits on specific assets: lower <= x_i <= upper.

WeightBoundsConstraint dataclass

Bases: FinancialConstraint

Per-asset allocation bounds: lower_i <= x_i <= upper_i.

FinancialContext dataclass

Financial metadata and model configuration.

Parameters:

Name Type Description Default
currency str

Optional currency code (metadata only; no conversion).

''
subdomain str

Finance subdomain (e.g. "portfolio").

''
investment_horizon str

Optional horizon label (e.g. "1Y").

''
risk_free_rate float | None

Optional risk-free rate used by risk-adjusted models.

None
transaction_cost_rate float

Assumed proportional transaction-cost rate.

0.0
assumptions dict[str, Any]

Named model assumptions (JSON-safe values).

dict()
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If a numeric field is invalid.

to_domain_context()

Derive the generic QMQ :class:DomainContext for this finance.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialContext from :meth:to_dict output.

FinanceError

Bases: ValueError

Base error of the QuantsMind Quantum Finance domain layer.

FinanceValidationError

Bases: FinanceError

Raised when a Finance model or problem fails domain validation.

FinanceFormulationAdapter

Converts financial problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention in universe order, objectives keep their senses, and every financial constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a financial problem (empty = valid).

raise_if_invalid(problem)

Raise :class:FinanceValidationError when the problem is invalid.

Raises:

Type Description
FinanceValidationError

If the problem fails validation.

finance_metadata(problem) staticmethod

JSON-safe Finance provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a financial problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem FinancialProblem

The validated financial problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
FinanceValidationError

If the financial problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a financial problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

AssetMapping dataclass

The deterministic asset <-> variable <-> index mapping of a problem.

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
asset_order list[str]

Ordered asset identifiers (universe order).

required
allocation_kind AllocationKind

Allocation representation of the problem.

required
symbols dict[str, str]

Optional asset identifier -> symbol lookup.

dict()
variable_names property

Decision-variable names in asset order (x0, x1, ...).

index(identifier)

Return the variable index of an asset identifier.

variable(identifier)

Return the decision-variable name of an asset identifier.

asset(variable_name)

Return the asset identifier for a decision-variable name.

Raises:

Type Description
KeyError

If the variable name is outside the mapping.

decode_assignments(assignments, *, selected_threshold=0.5)

Decode an assignment back into ordered asset decisions.

Keys may be decision-variable names (x0) or asset identifiers; unknown keys (e.g. QUBO slack variables) are ignored. selected is value > selected_threshold.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetMapping from :meth:to_dict output.

DecodedAsset dataclass

A decoded asset decision from an assignment.

Parameters:

Name Type Description Default
asset_id str

The asset identifier.

required
index int

Deterministic variable index of the asset.

required
variable_name str

The decision-variable name (x<i>).

required
symbol str

Optional asset symbol.

''
value float

The assigned value in the solution.

0.0
selected bool

Whether the value exceeds the selection threshold.

False
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DecodedAsset from :meth:to_dict output.

FinanceAssetMapper

Builds the deterministic :class:AssetMapping of a financial problem.

map(problem)

Return the asset -> variable mapping of a financial problem.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

Asset dataclass

Bases: FinancialInstrument

An instrument extended with optimization-relevant financial data.

Parameters:

Name Type Description Default
expected_return float

Supplied expected return (may be negative).

0.0
price float | None

Optional unit price/value (must be positive when set).

None
volatility float | None

Optional annualized volatility (>= 0 when set).

None
asset_class str

Optional group label (e.g. "equity", "bond"), used by :class:~quantsmind.quantum.finance.constraints .GroupAllocationConstraint.

''

Raises:

Type Description
FinanceValidationError

If a numeric field is not finite or violates its documented domain.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Asset from :meth:to_dict output.

AssetUniverse dataclass

An ordered, validated collection of financial assets.

Deterministic ordering is preserved from construction (insertion order) because QUBO variable mapping depends on deterministic variable indices. Duplicate identifiers are rejected.

Parameters:

Name Type Description Default
assets list[Asset]

Ordered list of assets.

required
name str

Optional universe name (may be empty).

''

Raises:

Type Description
FinanceValidationError

If an identifier is empty or repeated.

has(identifier)

Return whether an asset identifier is in the universe.

asset(identifier)

Return the asset with the given identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

index_of(identifier)

Return the deterministic index of an asset identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

identifier_order()

Return the deterministic ordered asset identifiers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetUniverse from :meth:to_dict output.

FinancialInstrument dataclass

Identity of a financial instrument.

Parameters:

Name Type Description Default
identifier str

Unique, non-empty instrument identifier (e.g. "USD").

required
symbol str

Optional ticker/symbol; defaults to the identifier.

''
name str

Optional human-readable name; defaults to the identifier.

''
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the identifier is empty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialInstrument from :meth:to_dict output.

FinancialProblem dataclass

A complete financial optimization problem definition.

Connects an :class:AssetUniverse, optional :class:FinancialContext and :class:RiskMatrix, financial objectives, financial constraints and an :class:AllocationKind. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints.

list()
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
allocation_kind AllocationKind

How the allocation is represented (continuous / binary / integer).

CONTINUOUS
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the name is empty or objective/constraint names repeat.

size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables following the x<i> convention.

One variable per asset in universe order. continuous yields long-only [0, inf) weights, binary yields 0/1 selection. integer is intentionally not defined here: the portfolio representation is a QMQ-08 decision.

validate()

Return a list of human-actionable validation issues.

An empty list means the problem is a valid input to the formulation adapter. Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_budget_constraint(budget, name='budget')

Convenience: append a budget constraint derived from a :class:Budget.

The aggregate allocation is bounded by budget.total; when min_allocation / max_allocation are set they bound the sum as well (as minimum/maximum aggregate allocation constraints).

constraint_exists(name)

Return whether a constraint with the given name already exists.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialProblem from :meth:to_dict output.

ExpectedReturnObjective dataclass

Bases: FinancialObjective

Maximize expected return: maximize sum(expected_return_i * x_i).

FinancialObjective dataclass

Base class of financial objectives.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets, risk)

Return validation issues against an asset universe (empty = valid).

to_quantum_objective(assets, context=None, risk=None)

Materialize into an existing QMQ objective.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output (name + description).

Subclasses with extra fields override from_dict.

RiskAdjustedObjective dataclass

Bases: FinancialObjective

Maximize risk-adjusted return: maximize return - lambda * risk.

A mean-variance utility objective combining the expected-return terms with a risk penalty scaled by risk_aversion >= 0. A zero aversion degenerates to the pure expected-return objective.

RiskObjective dataclass

Bases: FinancialObjective

Minimize total variance: minimize w^T Cov w.

Requires a positive-semidefinite :class:RiskMatrix aligned with the asset universe.

FinanceOptimizationResult

Result of a Finance solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

FinanceOptimizer

Solves and benchmarks :class:~quantsmind.quantum.finance.models .FinancialProblem instances (QMQ-11 §16).

A thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for finance problems.

solve(problem, *, strategy=None, config=None)

Solve a FinancialProblem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:FinancialSolution with asset decisions, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a FinancialProblem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem Any

The financial problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config OptimizationConfiguration | None

Optional execution/optimization configuration.

None

FinancialSolution dataclass

Deterministic decoded solution of a FinancialProblem (QMQ-11).

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
allocation_kind str

Allocation representation of the problem.

'binary'
assets list[DecodedAsset]

Ordered asset decisions.

list()
objective_value float | None

Leading objective value of the solution.

None
objective_values dict[str, float]

Objective name -> value snapshot.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether the solution satisfies all constraints.

False
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver/executor label.

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

0
num_variables int

Number of decision variables after formulation.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark assets selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
selected_assets()

Selected asset identifiers in universe order.

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a financial solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07) and reuses the existing constraint-evaluation infrastructure for feasibility and constraint status.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

OptimizationConfiguration dataclass

Execution/optimization configuration of a portfolio problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
FinanceValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

PortfolioAssetMapper

Deterministic asset <-> variable mapping for portfolios.

Reuses the QMQ-07 solution decoding: an assignment is decoded back into ordered asset decisions, QUBO slack/aux variables are ignored, and selected follows value > selected_threshold.

mapping(portfolio)

Return the asset -> variable :class:AssetMapping of a portfolio.

decode(portfolio, assignments, *, selected_threshold=0.5)

Decode an assignment into ordered asset decisions (:class:DecodedAsset).

variable(portfolio, identifier)

Return the decision-variable name of an asset identifier.

asset(portfolio, variable_name)

Return the asset identifier for a decision-variable name.

PortfolioFormulationAdapter

Portfolio -> QMQ conversion adapter.

Delegates structural conversion to the QMQ-07 :class:FinanceFormulationAdapter and injects portfolio provenance metadata (domain_sublayer="portfolio", the configuration dict, the budget). Reuses the existing QMQ-02 formulation — there is no second portfolio QUBO/Ising representation.

validate(portfolio)

Return the validation issues of a portfolio (empty = valid).

raise_if_invalid(portfolio)

Raise :class:FinanceValidationError when the portfolio is invalid.

Raises:

Type Description
FinanceValidationError

If the portfolio fails validation.

to_quantum_problem(portfolio, *, preferred_strategy=None)

Convert a portfolio into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The validated portfolio problem.

required
preferred_strategy Any

Optional preferred computation strategy; when None the portfolio's optimization configuration decides.

None
formulate(portfolio)

Return the existing QMQ formulation of a portfolio.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

PortfolioOptimizationProblem dataclass

A complete portfolio optimization problem definition.

Connects an :class:AssetUniverse, financial objectives/constraints, an optional :class:Budget, optional :class:~quantsmind.quantum.finance.context.FinancialContext and :class:~quantsmind.quantum.finance.risk.RiskMatrix, an allocation representation and an :class:OptimizationConfiguration. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints (budget/weight/cardinality/ position/group). A :class:Budget additionally materializes its constraints during formulation.

list()
allocation_kind AllocationKind

binary (supported) or continuous (validated/formulated; execution honestly surfaces the binary pipeline limit). integer raises :class:FinanceValidationError.

BINARY
budget Budget | None

Optional budget whose constraints are materialized on formulation.

None
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
optimization_config OptimizationConfiguration

Execution/optimization configuration.

OptimizationConfiguration()
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()
size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables in universe order.

binary yields 0/1 selection variables; continuous yields long-only [0, inf) weight variables. integer raises :class:FinanceValidationError — QMQ-08 does not represent integer quantities (honest: nothing is silently approximated).

Raises:

Type Description
FinanceValidationError

If the allocation kind is integer.

to_financial_problem()

Materialize the portfolio as a QMQ-07 :class:FinancialProblem.

Explicit constraints keep their declaration order; a :class:Budget appends its aggregate-allocation constraints (named budget / budget_min_allocation / budget_max_allocation / budget_allocation) after them.

Raises:

Type Description
FinanceValidationError

If a budget-derived name collides with an explicit constraint name.

to_quantum_problem(*, preferred_strategy=None)

Convert the portfolio into a QMQ :class:QuantumProblem.

Delegates to :class:PortfolioFormulationAdapter.

formulate()

Return the existing QMQ formulation of the portfolio.

validate()

Return a list of human-actionable validation issues.

Validation is performed before any formulation: on the portfolio structure, the derived QMQ-07 :class:FinancialProblem (universe, objectives, risk alignment, per-constraint) and portfolio-level feasibility (e.g. a minimum aggregate allocation above the available capital). Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio problem from :meth:to_dict output.

PortfolioOptimizer

Solves and benchmarks :class:PortfolioOptimizationProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for portfolios.

solve(portfolio, *, strategy=None)

Solve a portfolio problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the optimization configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.finance.portfolio_solution .PortfolioSolution with portfolio metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Reasons

FinanceValidationError: If the portfolio is invalid. MappingError: For a continuous allocation, because the current QUBO pipeline is binary-only (honest failure — no silent approximation). UnsupportedStrategyError: For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(portfolio, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False)

Benchmark a portfolio against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The portfolio problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the optimization configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False

PortfolioMetrics dataclass

Measured metrics of a portfolio selection (QMQ-08).

expected_return / variance / volatility are None whenever the underlying data (e.g. a risk matrix) was not supplied; counts default to 0. Nothing is invented beyond the supplied financial data.

Parameters:

Name Type Description Default
expected_return float | None

Expected portfolio return (supplied returns only).

None
variance float | None

w^T Cov w over the supplied risk matrix.

None
volatility float | None

Square root of the (clamped) variance.

None
selected_count int

Number of assets selected (weight > threshold).

0
allocation_sum float

Sum of all weights in universe order.

0.0
constraint_violations int

Number of violated constraints.

0
constraint_violation_magnitude float

Total excess magnitude of violations.

0.0
compute(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute portfolio metrics from supplied allocations.

Parameters:

Name Type Description Default
universe AssetUniverse

The asset universe (owns the deterministic order).

required
weights Mapping[str, float]

Asset identifier -> weight mapping.

required
risk RiskMatrix | None

Optional risk matrix for variance/volatility.

None
selected_threshold float

Weight strictly above this counts as selected.

0.5
violation_count int

Number of violated constraints (from the existing constraint evaluation infrastructure; 0 when unused).

0
violation_magnitude float

Total excess magnitude (0.0 when unused).

0.0
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild :class:PortfolioMetrics from :meth:to_dict output.

PortfolioComponent dataclass

One asset decision inside a :class:PortfolioSolution.

Parameters:

Name Type Description Default
asset_id str

Asset identifier.

required
symbol str

Asset symbol.

required
index int

Deterministic variable index in universe order.

required
variable_name str

Decision-variable name (x<i>).

required
weight float

Assigned value of the asset in the solution.

required
selected bool

Whether the value exceeds the selection threshold.

required
expected_return float

Supplied expected return of the asset.

required
expected_contribution float

weight * expected_return.

required
risk_contribution float | None

Marginal variance contribution when a risk matrix was supplied (None otherwise).

None
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a component from :meth:to_dict output.

PortfolioOptimizationResult dataclass

Result of a portfolio solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

PortfolioSolution dataclass

The domain result of solving a portfolio optimization problem.

Components are ordered by the deterministic universe order. weights() maps every asset identifier (in that order) to its weight. Constraint compliance comes from the existing QMQ constraint-evaluation infrastructure (QMQ-05 metric helpers), never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating portfolio problem.

''
allocation_kind AllocationKind

Allocation representation that was solved.

BINARY
components list[PortfolioComponent]

Ordered per-asset decisions.

list()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> "satisfied"/"violated"/....

dict()
feasible bool

Whether no constraint was violated.

False
metrics PortfolioMetrics

Measured portfolio metrics.

PortfolioMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
optimization_level int

Execution optimization hint.

0
selection_threshold float

Threshold used to mark components selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
weights()

Deterministic asset identifier -> weight mapping (universe order).

selected_assets()

Selected asset identifiers in universe order.

from_report(portfolio, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a portfolio solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07), computes portfolio metrics from supplied data and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio solution from :meth:to_dict output.

RiskMatrix dataclass

A covariance/risk matrix over a deterministic asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Ordered asset identifiers the matrix rows/columns map to.

required
matrix list[list[float]]

Covariance matrix (n x n); must be square, finite, and symmetric within :data:_SYMMETRY_TOLERANCE (values are normalized to exact symmetry).

required
volatilities list[float | None] | None

Optional per-asset volatility (standard deviation), aligned with asset_order.

None

Raises:

Type Description
FinanceValidationError

On structural or numerical invalidity, or a confirmed non-PSD matrix (only when the PSD check is conclusive).

Attributes:

Name Type Description
psd_validated bool

Whether the positive-semidefinite check was conclusive.

psd bool

Whether the matrix is positive semidefinite (False when the check was inconclusive).

require_psd()

Raise when the matrix is not confirmed positive semidefinite.

Raises:

Type Description
FinanceError

If the matrix fails the PSD requirement (including an inconclusive check, which is reported rather than assumed).

index(identifier)

Return the row/column index of an asset identifier.

covariance(left, right)

Return the covariance entry between two assets.

variance(identifier)

Return the variance (diagonal entry) of an asset.

correlation()

Return the correlation matrix derived from this covariance matrix.

Raises:

Type Description
FinanceError

If volatilities are missing or contain zeros.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a RiskMatrix from :meth:to_dict output.

Allocation dataclass

A validated asset -> weight allocation over a fixed asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Deterministic order of asset identifiers (must match the asset universe ordering that formulation relies on).

required
weights dict[str, float]

Asset identifier -> weight value. Only identifiers present in asset_order are allowed; missing entries default to 0.

dict()
kind AllocationKind

Reported allocation representation.

CONTINUOUS

Raises:

Type Description
FinanceValidationError

If an identifier is unknown, repeated, or a weight is not finite.

weight(identifier)

Return the weight of an asset (0 when unset).

total()

Return the sum of all weights in asset_order.

from_universe(universe, weights, *, kind=AllocationKind.CONTINUOUS) classmethod

Build an allocation aligned with an asset universe order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Allocation from :meth:to_dict output.

AllocationKind

Bases: Enum

Representation of an allocation decision.

Attributes:

Name Type Description
CONTINUOUS

Real-valued weights (e.g. fractions of capital).

BINARY

0/1 selection of whether an asset is held.

INTEGER

Integer quantities (e.g. number of units).

parse(value) classmethod

Coerce a name or member to an :class:AllocationKind.

constraint_from_dict(data)

Rebuild a financial constraint from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

example_asset_universe()

Example 1 — a four-asset universe with supplied expected returns.

example_budget(capital=1.0, name='qmq07_budget')

Example 2 — a capital/budget with allocation bounds.

example_combined_problem()

Example 6 — maximize return minus a risk penalty (mean-variance).

example_financial_problem()

The canonical QMQ-07 example problem (combined objective, binary).

example_return_problem()

Example 4 — maximize expected return under a budget.

example_risk_matrix()

Example 3 — a deterministic covariance/risk matrix.

example_risk_problem()

Example 5 — minimize portfolio variance under a budget.

synthetic_asset(identifier, expected_return, volatility=None, *, symbol='', asset_class='equity', price=None)

Build one deterministic synthetic asset.

objective_from_dict(data)

Rebuild a financial objective from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

example_budget_portfolio()

Example D — continuous allocation under a budget with position limits.

example_group_constraints_portfolio()

Example E — binary selection with group allocation constraints.

example_maximize_return_portfolio()

Example A — maximize expected return under a cardinality bound.

example_minimize_risk_portfolio()

Example B — minimize portfolio variance under a cardinality bound.

example_portfolio_problem()

The canonical QMQ-08 example problem (risk-adjusted, binary).

example_portfolio_risk_matrix()

Risk matrix over the portfolio universe (same supplied data as QMQ-07).

example_portfolio_universe()

Universe A — two equity assets, one bond and one cash asset.

example_risk_adjusted_portfolio()

Example C — maximize risk-adjusted return (mean-variance utility).

compute_portfolio_metrics(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0)

Convenience wrapper around :meth:PortfolioMetrics.compute.

expected_return_of(universe, weights)

Expected portfolio return sum(expected_return_i * w_i) over the universe.

Missing weights default to 0; identifiers outside the universe are ignored (unknown identifiers are a validation concern, not a metric).

portfolio_variance(risk, weights)

Portfolio variance w^T Cov w from a supplied risk matrix.

The matrix owns the deterministic asset order; entries for assets without a weight default to 0.

portfolio_volatility(risk, weights)

Portfolio volatility (standard deviation) sqrt(w^T Cov w).

Round-off may produce a value marginally below zero for an empty allocation; the reported volatility is clamped at 0.

risk_contributions(risk, weights)

Marginal variance contribution w_i * (Cov w)_i per asset identifier.

budget

Capital / budget representation of the Finance domain layer.

A :class:Budget captures the available capital in nullable currency metadata plus optional minimum/maximum aggregate-allocation constraints. It is a domain concept only — currency conversion and live FX are out of scope.

Budget dataclass

Validated capital / budget representation.

Parameters:

Name Type Description Default
total float

Total available budget (allocation units).

required
currency str

Optional currency code (metadata only).

''
min_allocation float | None

Optional minimum aggregate allocation.

None
max_allocation float | None

Optional maximum aggregate allocation.

None

Raises:

Type Description
FinanceValidationError

If totals are invalid or bounds inconsistent.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Budget from :meth:to_dict output.

constraints

Financial constraints of the Finance domain layer.

Each :class:FinancialConstraint is a validated, serializable domain constraint that materializes into the existing QMQ :class:~quantsmind.quantum.core.constraint.Constraint objects used by the formulation layer. Every constraint carries an identifier, a description, validation, a documented mathematical meaning and serialization.

FinancialConstraint dataclass

Base class of financial constraints.

Parameters:

Name Type Description Default
name str

Unique constraint name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets)

Return validation issues against an asset universe (empty = valid).

to_quantum_constraints(assets)

Materialize into existing QMQ constraints.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

BudgetConstraint dataclass

Bases: FinancialConstraint

Budget limit: sum(cost_i * x_i) <= total.

Without costs the aggregate allocation is bounded: sum(x_i) <= total. costs maps asset identifier -> cost per unit of allocation; missing assets use a unit cost of 1.

WeightBoundsConstraint dataclass

Bases: FinancialConstraint

Per-asset allocation bounds: lower_i <= x_i <= upper_i.

CardinalityConstraint dataclass

Bases: FinancialConstraint

Bounded cardinality / aggregate allocation: min <= sum(x_i) <= max.

Under a binary allocation the sum is the number of selected assets (a cardinality bound); under a continuous allocation it bounds the aggregate allocation. Bounds are real values; whole-valued bounds additionally participate in a cardinality sanity check against the universe size.

PositionLimitConstraint dataclass

Bases: FinancialConstraint

Position limits on specific assets: lower <= x_i <= upper.

GroupAllocationConstraint dataclass

Bases: FinancialConstraint

Group allocation limits: lower <= sum_{i in group} x_i <= upper.

A group is an :attr:~quantsmind.quantum.finance.models.Asset.asset_class value (e.g. "equity").

constraint_from_dict(data)

Rebuild a financial constraint from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

context

Financial problem context of the Finance domain layer.

A :class:FinancialContext is the metadata/model configuration of a financial problem: currency, horizon, assumptions and model settings. It is not an external data-ingestion framework — QMQ-07 works entirely from supplied data.

FinancialContext dataclass

Financial metadata and model configuration.

Parameters:

Name Type Description Default
currency str

Optional currency code (metadata only; no conversion).

''
subdomain str

Finance subdomain (e.g. "portfolio").

''
investment_horizon str

Optional horizon label (e.g. "1Y").

''
risk_free_rate float | None

Optional risk-free rate used by risk-adjusted models.

None
transaction_cost_rate float

Assumed proportional transaction-cost rate.

0.0
assumptions dict[str, Any]

Named model assumptions (JSON-safe values).

dict()
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If a numeric field is invalid.

to_domain_context()

Derive the generic QMQ :class:DomainContext for this finance.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialContext from :meth:to_dict output.

errors

Error taxonomy of the QuantsMind Quantum Finance domain layer.

QMQ-07 errors subclass :class:ValueError so that existing generic except ValueError handling in the workflow and formulation layers keeps working. :class:FinanceValidationError is the structured validation error raised by the Finance models and the formulation adapter.

FinanceError

Bases: ValueError

Base error of the QuantsMind Quantum Finance domain layer.

FinanceValidationError

Bases: FinanceError

Raised when a Finance model or problem fails domain validation.

examples

Canonical synthetic Finance examples (QMQ-07 §23).

Every example is deterministic, tiny and built entirely from supplied data. They are synthetic examples, not market recommendations, and not investment advice.

synthetic_asset(identifier, expected_return, volatility=None, *, symbol='', asset_class='equity', price=None)

Build one deterministic synthetic asset.

example_asset_universe()

Example 1 — a four-asset universe with supplied expected returns.

example_budget(capital=1.0, name='qmq07_budget')

Example 2 — a capital/budget with allocation bounds.

example_risk_matrix()

Example 3 — a deterministic covariance/risk matrix.

example_return_problem()

Example 4 — maximize expected return under a budget.

example_risk_problem()

Example 5 — minimize portfolio variance under a budget.

example_combined_problem()

Example 6 — maximize return minus a risk penalty (mean-variance).

example_financial_problem()

The canonical QMQ-07 example problem (combined objective, binary).

formulation

Finance -> QMQ formulation adapter.

:class:FinanceFormulationAdapter converts a validated :class:~quantsmind.quantum.finance.models.FinancialProblem into the existing QMQ pipeline: a :class:QuantumProblem (which the existing :func:~quantsmind.quantum.formulation.formulate and QUBO mapper consume unchanged). It preserves objective senses, variables, constraints, coefficients, the deterministic asset ordering and Finance provenance metadata. No Finance-specific QUBO exists — the existing QMQ-02 representations are reused.

FinanceFormulationAdapter

Converts financial problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the x<i> convention in universe order, objectives keep their senses, and every financial constraint materializes into QMQ constraints.

validate(problem)

Return the validation issues of a financial problem (empty = valid).

raise_if_invalid(problem)

Raise :class:FinanceValidationError when the problem is invalid.

Raises:

Type Description
FinanceValidationError

If the problem fails validation.

finance_metadata(problem) staticmethod

JSON-safe Finance provenance metadata for the quantum problem.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert a financial problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem FinancialProblem

The validated financial problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
FinanceValidationError

If the financial problem is invalid.

formulate(problem)

Return the existing QMQ formulation of a financial problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

mapping

Deterministic asset <-> variable mapping and solution decoding.

QMQ-07 establishes the canonical mapping::

asset identifier <-> decision variable (``x<i>``) <-> variable index

and the generic infrastructure to decode a future optimization result back into financial asset decisions. QMQ-08 builds the actual portfolio workflow on top of this.

DecodedAsset dataclass

A decoded asset decision from an assignment.

Parameters:

Name Type Description Default
asset_id str

The asset identifier.

required
index int

Deterministic variable index of the asset.

required
variable_name str

The decision-variable name (x<i>).

required
symbol str

Optional asset symbol.

''
value float

The assigned value in the solution.

0.0
selected bool

Whether the value exceeds the selection threshold.

False
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a DecodedAsset from :meth:to_dict output.

AssetMapping dataclass

The deterministic asset <-> variable <-> index mapping of a problem.

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
asset_order list[str]

Ordered asset identifiers (universe order).

required
allocation_kind AllocationKind

Allocation representation of the problem.

required
symbols dict[str, str]

Optional asset identifier -> symbol lookup.

dict()
variable_names property

Decision-variable names in asset order (x0, x1, ...).

index(identifier)

Return the variable index of an asset identifier.

variable(identifier)

Return the decision-variable name of an asset identifier.

asset(variable_name)

Return the asset identifier for a decision-variable name.

Raises:

Type Description
KeyError

If the variable name is outside the mapping.

decode_assignments(assignments, *, selected_threshold=0.5)

Decode an assignment back into ordered asset decisions.

Keys may be decision-variable names (x0) or asset identifiers; unknown keys (e.g. QUBO slack variables) are ignored. selected is value > selected_threshold.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetMapping from :meth:to_dict output.

FinanceAssetMapper

Builds the deterministic :class:AssetMapping of a financial problem.

map(problem)

Return the asset -> variable mapping of a financial problem.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

models

Core financial models of the Finance domain layer.

This module owns the strongly typed, validated financial domain objects: :class:FinancialInstrument, :class:Asset, :class:AssetUniverse and the :class:FinancialProblem that connects universe, context, objectives, constraints and risk information. Building these objects never invokes a quantum engine.

FinancialInstrument dataclass

Identity of a financial instrument.

Parameters:

Name Type Description Default
identifier str

Unique, non-empty instrument identifier (e.g. "USD").

required
symbol str

Optional ticker/symbol; defaults to the identifier.

''
name str

Optional human-readable name; defaults to the identifier.

''
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the identifier is empty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialInstrument from :meth:to_dict output.

Asset dataclass

Bases: FinancialInstrument

An instrument extended with optimization-relevant financial data.

Parameters:

Name Type Description Default
expected_return float

Supplied expected return (may be negative).

0.0
price float | None

Optional unit price/value (must be positive when set).

None
volatility float | None

Optional annualized volatility (>= 0 when set).

None
asset_class str

Optional group label (e.g. "equity", "bond"), used by :class:~quantsmind.quantum.finance.constraints .GroupAllocationConstraint.

''

Raises:

Type Description
FinanceValidationError

If a numeric field is not finite or violates its documented domain.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Asset from :meth:to_dict output.

AssetUniverse dataclass

An ordered, validated collection of financial assets.

Deterministic ordering is preserved from construction (insertion order) because QUBO variable mapping depends on deterministic variable indices. Duplicate identifiers are rejected.

Parameters:

Name Type Description Default
assets list[Asset]

Ordered list of assets.

required
name str

Optional universe name (may be empty).

''

Raises:

Type Description
FinanceValidationError

If an identifier is empty or repeated.

has(identifier)

Return whether an asset identifier is in the universe.

asset(identifier)

Return the asset with the given identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

index_of(identifier)

Return the deterministic index of an asset identifier.

Raises:

Type Description
KeyError

If the identifier is not in the universe.

identifier_order()

Return the deterministic ordered asset identifiers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an AssetUniverse from :meth:to_dict output.

FinancialProblem dataclass

A complete financial optimization problem definition.

Connects an :class:AssetUniverse, optional :class:FinancialContext and :class:RiskMatrix, financial objectives, financial constraints and an :class:AllocationKind. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints.

list()
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
allocation_kind AllocationKind

How the allocation is represented (continuous / binary / integer).

CONTINUOUS
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()

Raises:

Type Description
FinanceValidationError

If the name is empty or objective/constraint names repeat.

size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables following the x<i> convention.

One variable per asset in universe order. continuous yields long-only [0, inf) weights, binary yields 0/1 selection. integer is intentionally not defined here: the portfolio representation is a QMQ-08 decision.

validate()

Return a list of human-actionable validation issues.

An empty list means the problem is a valid input to the formulation adapter. Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_budget_constraint(budget, name='budget')

Convenience: append a budget constraint derived from a :class:Budget.

The aggregate allocation is bounded by budget.total; when min_allocation / max_allocation are set they bound the sum as well (as minimum/maximum aggregate allocation constraints).

constraint_exists(name)

Return whether a constraint with the given name already exists.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a FinancialProblem from :meth:to_dict output.

objectives

Financial objectives of the Finance domain layer.

Each :class:FinancialObjective is a validated, serializable domain objective that materializes into the existing QMQ :class:~quantsmind.quantum.core.objective.Objective (reusing the existing :class:~quantsmind.quantum.core.objective.ObjectiveSense) with a symbolic expression understood by the QMQ-02 formulation layer.

FinancialObjective dataclass

Base class of financial objectives.

Parameters:

Name Type Description Default
name str

Unique objective name.

required
description str

Optional human-readable description.

''

Raises:

Type Description
FinanceValidationError

If the name is empty.

validate(assets, risk)

Return validation issues against an asset universe (empty = valid).

to_quantum_objective(assets, context=None, risk=None)

Materialize into an existing QMQ objective.

Raises:

Type Description
NotImplementedError

On the base class.

to_dict()

Serialize to a JSON-safe dictionary (kind included).

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output (name + description).

Subclasses with extra fields override from_dict.

ExpectedReturnObjective dataclass

Bases: FinancialObjective

Maximize expected return: maximize sum(expected_return_i * x_i).

RiskObjective dataclass

Bases: FinancialObjective

Minimize total variance: minimize w^T Cov w.

Requires a positive-semidefinite :class:RiskMatrix aligned with the asset universe.

RiskAdjustedObjective dataclass

Bases: FinancialObjective

Maximize risk-adjusted return: maximize return - lambda * risk.

A mean-variance utility objective combining the expected-return terms with a risk penalty scaled by risk_aversion >= 0. A zero aversion degenerates to the pure expected-return objective.

objective_from_dict(data)

Rebuild a financial objective from its serialized kind.

Raises:

Type Description
FinanceValidationError

If the kind is unknown.

optimizer

Finance solve & benchmark pipeline (QMQ-11 §16, Example A).

:class:FinanceOptimizer gives FinancialProblem instances the same thin, workflow-backed pipeline that the Data, ML and Portfolio domains already have: formulation through the Finance adapter (QMQ-07), QUBO mapping (QMQ-02), workflow execution (QMQ-04) with the classical exhaustive baseline, benchmarking (QMQ-05) and interpretation (QMQ-06). No second quantum algorithm or solver exists for finance problems.

FinancialSolution dataclass

Deterministic decoded solution of a FinancialProblem (QMQ-11).

Parameters:

Name Type Description Default
problem_name str

Name of the originating financial problem.

required
allocation_kind str

Allocation representation of the problem.

'binary'
assets list[DecodedAsset]

Ordered asset decisions.

list()
objective_value float | None

Leading objective value of the solution.

None
objective_values dict[str, float]

Objective name -> value snapshot.

dict()
constraint_status dict[str, str]

Constraint name -> status label.

dict()
feasible bool

Whether the solution satisfies all constraints.

False
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver/executor label.

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

0
num_variables int

Number of decision variables after formulation.

0
num_constraints int

Number of constraints after formulation.

0
selection_threshold float

Threshold used to mark assets selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
selected_assets()

Selected asset identifiers in universe order.

from_report(problem, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a financial solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07) and reuses the existing constraint-evaluation infrastructure for feasibility and constraint status.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a solution from :meth:to_dict output.

FinanceOptimizationResult

Result of a Finance solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

FinanceOptimizer

Solves and benchmarks :class:~quantsmind.quantum.finance.models .FinancialProblem instances (QMQ-11 §16).

A thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for finance problems.

solve(problem, *, strategy=None, config=None)

Solve a FinancialProblem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:FinancialSolution with asset decisions, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
FinanceValidationError

If the problem is invalid.

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark a FinancialProblem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem Any

The financial problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config OptimizationConfiguration | None

Optional execution/optimization configuration.

None

portfolio

Portfolio optimization layer of QuantsMind Quantum (QMQ-08).

:class:PortfolioOptimizationProblem is the strongly typed portfolio definition (universe, objectives, constraints, budget, allocation kind, optimization configuration). :class:PortfolioFormulationAdapter converts it to the existing QMQ pipeline through the QMQ-07 Finance adapter — no second QUBO/Ising representation exists. :class:PortfolioAssetMapper reuses the QMQ-07 asset mapping, and :class:PortfolioOptimizer runs the existing QMQ-03..06 workflow/benchmark/interpretation pipeline.

Allocation representations:

  • binary — 0/1 asset selection; fully supported through the QUBO path.
  • continuous — real-valued long-only weights; validated and formulated, but the current QUBO pipeline is binary-only, so execution surfaces the honest :class:MappingError instead of silently approximating.
  • integer — intentionally not represented (QMQ-07 deferred decision); validation raises the existing :class:FinanceValidationError.

This layer works entirely from supplied data. It is not investment advice. Importing this module never requires microquantum.

OptimizationConfiguration dataclass

Execution/optimization configuration of a portfolio problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
FinanceValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

PortfolioOptimizationProblem dataclass

A complete portfolio optimization problem definition.

Connects an :class:AssetUniverse, financial objectives/constraints, an optional :class:Budget, optional :class:~quantsmind.quantum.finance.context.FinancialContext and :class:~quantsmind.quantum.finance.risk.RiskMatrix, an allocation representation and an :class:OptimizationConfiguration. Construction never invokes a quantum engine.

Parameters:

Name Type Description Default
name str

Unique problem name.

required
universe AssetUniverse

The available financial assets.

required
objectives list[FinancialObjective]

Financial objectives (at least one).

list()
constraints list[FinancialConstraint]

Financial constraints (budget/weight/cardinality/ position/group). A :class:Budget additionally materializes its constraints during formulation.

list()
allocation_kind AllocationKind

binary (supported) or continuous (validated/formulated; execution honestly surfaces the binary pipeline limit). integer raises :class:FinanceValidationError.

BINARY
budget Budget | None

Optional budget whose constraints are materialized on formulation.

None
context FinancialContext | None

Optional financial metadata/configuration.

None
risk RiskMatrix | None

Optional covariance/risk matrix over the universe.

None
optimization_config OptimizationConfiguration

Execution/optimization configuration.

OptimizationConfiguration()
description str

Optional description.

''
metadata dict[str, Any]

Free-form metadata.

dict()
size property

Number of assets (one decision variable per asset).

decision_variables property

Deterministic decision variables in universe order.

binary yields 0/1 selection variables; continuous yields long-only [0, inf) weight variables. integer raises :class:FinanceValidationError — QMQ-08 does not represent integer quantities (honest: nothing is silently approximated).

Raises:

Type Description
FinanceValidationError

If the allocation kind is integer.

to_financial_problem()

Materialize the portfolio as a QMQ-07 :class:FinancialProblem.

Explicit constraints keep their declaration order; a :class:Budget appends its aggregate-allocation constraints (named budget / budget_min_allocation / budget_max_allocation / budget_allocation) after them.

Raises:

Type Description
FinanceValidationError

If a budget-derived name collides with an explicit constraint name.

to_quantum_problem(*, preferred_strategy=None)

Convert the portfolio into a QMQ :class:QuantumProblem.

Delegates to :class:PortfolioFormulationAdapter.

formulate()

Return the existing QMQ formulation of the portfolio.

validate()

Return a list of human-actionable validation issues.

Validation is performed before any formulation: on the portfolio structure, the derived QMQ-07 :class:FinancialProblem (universe, objectives, risk alignment, per-constraint) and portfolio-level feasibility (e.g. a minimum aggregate allocation above the available capital). Validation never raises; use :meth:raise_if_invalid.

raise_if_invalid()

Raise :class:FinanceValidationError listing all issues.

Raises:

Type Description
FinanceValidationError

If :meth:validate returns any issue.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio problem from :meth:to_dict output.

PortfolioFormulationAdapter

Portfolio -> QMQ conversion adapter.

Delegates structural conversion to the QMQ-07 :class:FinanceFormulationAdapter and injects portfolio provenance metadata (domain_sublayer="portfolio", the configuration dict, the budget). Reuses the existing QMQ-02 formulation — there is no second portfolio QUBO/Ising representation.

validate(portfolio)

Return the validation issues of a portfolio (empty = valid).

raise_if_invalid(portfolio)

Raise :class:FinanceValidationError when the portfolio is invalid.

Raises:

Type Description
FinanceValidationError

If the portfolio fails validation.

to_quantum_problem(portfolio, *, preferred_strategy=None)

Convert a portfolio into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The validated portfolio problem.

required
preferred_strategy Any

Optional preferred computation strategy; when None the portfolio's optimization configuration decides.

None
formulate(portfolio)

Return the existing QMQ formulation of a portfolio.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

PortfolioAssetMapper

Deterministic asset <-> variable mapping for portfolios.

Reuses the QMQ-07 solution decoding: an assignment is decoded back into ordered asset decisions, QUBO slack/aux variables are ignored, and selected follows value > selected_threshold.

mapping(portfolio)

Return the asset -> variable :class:AssetMapping of a portfolio.

decode(portfolio, assignments, *, selected_threshold=0.5)

Decode an assignment into ordered asset decisions (:class:DecodedAsset).

variable(portfolio, identifier)

Return the decision-variable name of an asset identifier.

asset(portfolio, variable_name)

Return the asset identifier for a decision-variable name.

PortfolioOptimizer

Solves and benchmarks :class:PortfolioOptimizationProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the Finance adapter, workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for portfolios.

solve(portfolio, *, strategy=None)

Solve a portfolio problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the optimization configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into a :class:~quantsmind.quantum.finance.portfolio_solution .PortfolioSolution with portfolio metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Reasons

FinanceValidationError: If the portfolio is invalid. MappingError: For a continuous allocation, because the current QUBO pipeline is binary-only (honest failure — no silent approximation). UnsupportedStrategyError: For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(portfolio, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False)

Benchmark a portfolio against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
portfolio PortfolioOptimizationProblem

The portfolio problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the optimization configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False

portfolio_examples

Canonical synthetic portfolio examples (QMQ-08 §21).

Each example builds a deterministic, tiny :class:PortfolioOptimizationProblem entirely from supplied data — no market data, no estimation. They are synthetic examples, not market recommendations, and not investment advice.

example_portfolio_universe()

Universe A — two equity assets, one bond and one cash asset.

example_portfolio_risk_matrix()

Risk matrix over the portfolio universe (same supplied data as QMQ-07).

example_maximize_return_portfolio()

Example A — maximize expected return under a cardinality bound.

example_minimize_risk_portfolio()

Example B — minimize portfolio variance under a cardinality bound.

example_risk_adjusted_portfolio()

Example C — maximize risk-adjusted return (mean-variance utility).

example_budget_portfolio()

Example D — continuous allocation under a budget with position limits.

example_group_constraints_portfolio()

Example E — binary selection with group allocation constraints.

example_portfolio_problem()

The canonical QMQ-08 example problem (risk-adjusted, binary).

portfolio_metrics

Portfolio metrics of the QMQ-08 portfolio layer.

Metrics are computed entirely from supplied financial data (expected returns and an optional :class:~quantsmind.quantum.finance.risk.RiskMatrix) — no statistical estimation, no market data.

PortfolioMetrics dataclass

Measured metrics of a portfolio selection (QMQ-08).

expected_return / variance / volatility are None whenever the underlying data (e.g. a risk matrix) was not supplied; counts default to 0. Nothing is invented beyond the supplied financial data.

Parameters:

Name Type Description Default
expected_return float | None

Expected portfolio return (supplied returns only).

None
variance float | None

w^T Cov w over the supplied risk matrix.

None
volatility float | None

Square root of the (clamped) variance.

None
selected_count int

Number of assets selected (weight > threshold).

0
allocation_sum float

Sum of all weights in universe order.

0.0
constraint_violations int

Number of violated constraints.

0
constraint_violation_magnitude float

Total excess magnitude of violations.

0.0
compute(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute portfolio metrics from supplied allocations.

Parameters:

Name Type Description Default
universe AssetUniverse

The asset universe (owns the deterministic order).

required
weights Mapping[str, float]

Asset identifier -> weight mapping.

required
risk RiskMatrix | None

Optional risk matrix for variance/volatility.

None
selected_threshold float

Weight strictly above this counts as selected.

0.5
violation_count int

Number of violated constraints (from the existing constraint evaluation infrastructure; 0 when unused).

0
violation_magnitude float

Total excess magnitude (0.0 when unused).

0.0
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild :class:PortfolioMetrics from :meth:to_dict output.

expected_return_of(universe, weights)

Expected portfolio return sum(expected_return_i * w_i) over the universe.

Missing weights default to 0; identifiers outside the universe are ignored (unknown identifiers are a validation concern, not a metric).

portfolio_variance(risk, weights)

Portfolio variance w^T Cov w from a supplied risk matrix.

The matrix owns the deterministic asset order; entries for assets without a weight default to 0.

portfolio_volatility(risk, weights)

Portfolio volatility (standard deviation) sqrt(w^T Cov w).

Round-off may produce a value marginally below zero for an empty allocation; the reported volatility is clamped at 0.

risk_contributions(risk, weights)

Marginal variance contribution w_i * (Cov w)_i per asset identifier.

compute_portfolio_metrics(universe, weights, risk=None, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0)

Convenience wrapper around :meth:PortfolioMetrics.compute.

portfolio_solution

Portfolio results of the QMQ-08 portfolio layer.

:class:PortfolioComponent describes one asset decision, :class:PortfolioSolution is the domain result of a portfolio solve and :class:PortfolioOptimizationResult bundles the solution with the optional QMQ-05 benchmark result and QMQ-06 interpretation.

PortfolioComponent dataclass

One asset decision inside a :class:PortfolioSolution.

Parameters:

Name Type Description Default
asset_id str

Asset identifier.

required
symbol str

Asset symbol.

required
index int

Deterministic variable index in universe order.

required
variable_name str

Decision-variable name (x<i>).

required
weight float

Assigned value of the asset in the solution.

required
selected bool

Whether the value exceeds the selection threshold.

required
expected_return float

Supplied expected return of the asset.

required
expected_contribution float

weight * expected_return.

required
risk_contribution float | None

Marginal variance contribution when a risk matrix was supplied (None otherwise).

None
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a component from :meth:to_dict output.

PortfolioSolution dataclass

The domain result of solving a portfolio optimization problem.

Components are ordered by the deterministic universe order. weights() maps every asset identifier (in that order) to its weight. Constraint compliance comes from the existing QMQ constraint-evaluation infrastructure (QMQ-05 metric helpers), never recomputed ad hoc.

Parameters:

Name Type Description Default
problem_name str

Name of the originating portfolio problem.

''
allocation_kind AllocationKind

Allocation representation that was solved.

BINARY
components list[PortfolioComponent]

Ordered per-asset decisions.

list()
objective_value float | None

Value of the first objective (the primary one).

None
objective_values dict[str, float]

Objective name -> evaluated value.

dict()
constraint_status dict[str, str]

Constraint name -> "satisfied"/"violated"/....

dict()
feasible bool

Whether no constraint was violated.

False
metrics PortfolioMetrics

Measured portfolio metrics.

PortfolioMetrics()
energy float | None

QUBO energy reported by the execution (when available).

None
solver str

Solver label (e.g. "classical/exhaustive").

''
strategy str

Selected computation strategy (lower-case label).

''
algorithm str

Executed algorithm (e.g. "exhaustive").

''
backend str

Backend label.

''
seed int | None

Execution seed.

None
shots int

Shot count.

1024
num_variables int

Number of decision variables.

0
num_constraints int

Number of constraints after formulation.

0
optimization_level int

Execution optimization hint.

0
selection_threshold float

Threshold used to mark components selected.

0.5
execution_time float | None

Wall time of the solve in seconds.

None
provenance dict[str, Any]

JSON-safe provenance metadata of the run.

dict()
metadata dict[str, Any]

Free-form result metadata.

dict()
weights()

Deterministic asset identifier -> weight mapping (universe order).

selected_assets()

Selected asset identifiers in universe order.

from_report(portfolio, report, *, execution_time=None, selection_threshold=0.5) classmethod

Build a portfolio solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic asset mapping (QMQ-07), computes portfolio metrics from supplied data and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a portfolio solution from :meth:to_dict output.

PortfolioOptimizationResult dataclass

Result of a portfolio solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult).

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

risk

Risk representation of the Finance domain layer.

:class:RiskMatrix is a validated covariance/risk matrix over a deterministic asset order. QMQ-07 validates structure (dimensions, finite entries, symmetry, positive semidefiniteness) but deliberately does not implement statistical estimation — supplied data only.

RiskMatrix dataclass

A covariance/risk matrix over a deterministic asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Ordered asset identifiers the matrix rows/columns map to.

required
matrix list[list[float]]

Covariance matrix (n x n); must be square, finite, and symmetric within :data:_SYMMETRY_TOLERANCE (values are normalized to exact symmetry).

required
volatilities list[float | None] | None

Optional per-asset volatility (standard deviation), aligned with asset_order.

None

Raises:

Type Description
FinanceValidationError

On structural or numerical invalidity, or a confirmed non-PSD matrix (only when the PSD check is conclusive).

Attributes:

Name Type Description
psd_validated bool

Whether the positive-semidefinite check was conclusive.

psd bool

Whether the matrix is positive semidefinite (False when the check was inconclusive).

require_psd()

Raise when the matrix is not confirmed positive semidefinite.

Raises:

Type Description
FinanceError

If the matrix fails the PSD requirement (including an inconclusive check, which is reported rather than assumed).

index(identifier)

Return the row/column index of an asset identifier.

covariance(left, right)

Return the covariance entry between two assets.

variance(identifier)

Return the variance (diagonal entry) of an asset.

correlation()

Return the correlation matrix derived from this covariance matrix.

Raises:

Type Description
FinanceError

If volatilities are missing or contain zeros.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a RiskMatrix from :meth:to_dict output.

weights

Allocation-weight representation of the Finance domain layer.

QMQ-07 introduces the domain concepts required to express allocation weights and cleanly distinguishes the three representations QMQ-08 will pick between for the portfolio model: continuous weights, binary selection and integer quantities. QMQ-07 ships the concepts; QMQ-08 decides the specific portfolio representation.

AllocationKind

Bases: Enum

Representation of an allocation decision.

Attributes:

Name Type Description
CONTINUOUS

Real-valued weights (e.g. fractions of capital).

BINARY

0/1 selection of whether an asset is held.

INTEGER

Integer quantities (e.g. number of units).

parse(value) classmethod

Coerce a name or member to an :class:AllocationKind.

Allocation dataclass

A validated asset -> weight allocation over a fixed asset order.

Parameters:

Name Type Description Default
asset_order list[str]

Deterministic order of asset identifiers (must match the asset universe ordering that formulation relies on).

required
weights dict[str, float]

Asset identifier -> weight value. Only identifiers present in asset_order are allowed; missing entries default to 0.

dict()
kind AllocationKind

Reported allocation representation.

CONTINUOUS

Raises:

Type Description
FinanceValidationError

If an identifier is unknown, repeated, or a weight is not finite.

weight(identifier)

Return the weight of an asset (0 when unset).

total()

Return the sum of all weights in asset_order.

from_universe(universe, weights, *, kind=AllocationKind.CONTINUOUS) classmethod

Build an allocation aligned with an asset universe order.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Allocation from :meth:to_dict output.

formulation

Formulation layer of QuantsMind Quantum.

The formulation layer translates a domain problem into a structured mathematical representation. Each model type extends :class:MathematicalModel with family-specific detail.

GraphModel dataclass

Bases: MathematicalModel

Structural formulation of a graph problem.

Parameters:

Name Type Description Default
nodes list[str]

Names/labels of graph nodes.

list()
edges list[tuple[str, str]]

Undirected edge pairs (source, target).

list()
n_nodes property

Number of graph nodes.

n_edges property

Number of graph edges.

from_problem(problem) classmethod

Snapshot a graph problem (nodes/edges from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a GraphModel from :meth:to_dict output.

MathematicalModel dataclass

A structural formulation of a domain problem.

Parameters:

Name Type Description Default
name str

Formulation name.

'model'
problem_name str

Name of the originating problem.

''
variables list[str]

Names of the participating variables.

list()
objectives list[str]

Names of the participating objectives.

list()
constraints list[str]

Names of the participating constraints.

list()
metadata dict[str, Any]

Formulation metadata (copied from the problem).

dict()

Attributes:

Name Type Description
kind str

Machine-readable formulation family, overridden by subclasses.

n_variables property

Number of participating variables.

n_objectives property

Number of participating objectives.

n_constraints property

Number of participating constraints.

from_problem(problem) classmethod

Snapshot a domain problem into a mathematical model.

Constructs a concrete instance of cls so subclasses reading extra state after a super().from_problem call are always operating on their own type.

describe()

Return a one-line description of the formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a MathematicalModel from :meth:to_dict output.

Subclasses reuse this constructor because their extra fields have defaults; any subclass-specific keys are re-collected by their own overridden from_dict.

MLModel dataclass

Bases: MathematicalModel

Structural formulation of a machine learning problem.

Parameters:

Name Type Description Default
features list[str]

Feature names/schema.

list()
target str

Target column name.

''
task str

Learning task (e.g. "classification", "regression").

''
from_problem(problem) classmethod

Snapshot an ML problem (schema from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an MLModel from :meth:to_dict output.

OptimizationModel dataclass

Bases: MathematicalModel

Structural formulation of an optimization problem.

Parameters:

Name Type Description Default
objective_senses dict[str, str]

Objective name -> "minimize"/"maximize".

dict()
variable_bounds dict[str, list[Any]]

Variable name -> [lower_bound, upper_bound].

dict()
constant_term float

Additive constant of the (single) objective.

0.0
problem_ref QuantumProblem | None

Reference to the originating problem (not serialized).

None
from_problem(problem) classmethod

Snapshot an optimization problem including senses and bounds.

objective_value(assignment)

Evaluate the first objective against an assignment (or None).

Raises:

Type Description
ValueError

If the model has no source problem reference.

constraint_values(assignment)

Evaluate every constraint expression against an assignment.

Returns a mapping of constraint name -> numeric left-hand side (None when the constraint has no expression).

is_feasible(assignment)

Return whether the assignment satisfies every constraint.

to_dict()

Serialize to a JSON-safe dictionary (problem reference excluded).

from_dict(data) classmethod

Rebuild an OptimizationModel from :meth:to_dict output.

SimulationModel dataclass

Bases: MathematicalModel

Structural formulation of a simulation problem.

Parameters:

Name Type Description Default
time_steps int

Number of discrete evolution steps.

0
dynamics str

Description of the evolution law (e.g. "hamiltonian", "reaction-diffusion").

''
n_steps property

Number of evolution steps.

from_problem(problem) classmethod

Snapshot a simulation problem (solver config from metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a SimulationModel from :meth:to_dict output.

StatisticalModel dataclass

Bases: MathematicalModel

Structural formulation of a statistical problem.

Parameters:

Name Type Description Default
distribution str

Target distribution or family (e.g. "gaussian").

''
assumptions list[str]

Statistical assumptions (e.g. ["iid", "normal"]).

list()
from_problem(problem) classmethod

Snapshot a statistical problem (config from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a StatisticalModel from :meth:to_dict output.

formulate(problem)

Select and return the appropriate formulation for a domain problem.

Uses deterministic, rule-based logic based on problem.metadata and problem contents. Returns the existing problem.formulation when already set.

model_from_dict(data)

Reconstruct a formulation model from its serialized kind.

graph_model

Graph formulation of quantum domain problems.

A :class:GraphModel extends :class:MathematicalModel with graph structure (nodes and edges) for problems such as maximum independent set, graph coloring, community detection or network optimization.

GraphModel dataclass

Bases: MathematicalModel

Structural formulation of a graph problem.

Parameters:

Name Type Description Default
nodes list[str]

Names/labels of graph nodes.

list()
edges list[tuple[str, str]]

Undirected edge pairs (source, target).

list()
n_nodes property

Number of graph nodes.

n_edges property

Number of graph edges.

from_problem(problem) classmethod

Snapshot a graph problem (nodes/edges from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a GraphModel from :meth:to_dict output.

mathematical_model

Mathematical formulation foundation for quantum domain problems.

A :class:MathematicalModel sits between a :class:~quantsmind.quantum.core.problem.QuantumProblem and computational execution. It records which variables, objectives and constraints participate, and which family the problem belongs to (optimization, graph, ML, simulation or statistical). Concrete computational representations (QUBO, Ising, Hamiltonians, circuits) are layered on top in QMQ-02.

MathematicalModel dataclass

A structural formulation of a domain problem.

Parameters:

Name Type Description Default
name str

Formulation name.

'model'
problem_name str

Name of the originating problem.

''
variables list[str]

Names of the participating variables.

list()
objectives list[str]

Names of the participating objectives.

list()
constraints list[str]

Names of the participating constraints.

list()
metadata dict[str, Any]

Formulation metadata (copied from the problem).

dict()

Attributes:

Name Type Description
kind str

Machine-readable formulation family, overridden by subclasses.

n_variables property

Number of participating variables.

n_objectives property

Number of participating objectives.

n_constraints property

Number of participating constraints.

from_problem(problem) classmethod

Snapshot a domain problem into a mathematical model.

Constructs a concrete instance of cls so subclasses reading extra state after a super().from_problem call are always operating on their own type.

describe()

Return a one-line description of the formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a MathematicalModel from :meth:to_dict output.

Subclasses reuse this constructor because their extra fields have defaults; any subclass-specific keys are re-collected by their own overridden from_dict.

ml_model

Machine learning formulation of quantum domain problems.

An :class:MLModel extends :class:MathematicalModel with a feature/ target schema so QMQ-02 can reason about quantum machine-learning workflows (quantum kernels, variational classifiers) from a domain problem.

MLModel dataclass

Bases: MathematicalModel

Structural formulation of a machine learning problem.

Parameters:

Name Type Description Default
features list[str]

Feature names/schema.

list()
target str

Target column name.

''
task str

Learning task (e.g. "classification", "regression").

''
from_problem(problem) classmethod

Snapshot an ML problem (schema from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an MLModel from :meth:to_dict output.

optimization_model

Optimization formulation of quantum domain problems.

An :class:OptimizationModel is a :class:MathematicalModel specialised for optimization problems: it snapshots objective senses, variable bounds and a constant term from the originating problem, and keeps a reference to that problem so QMQ-02 evaluation methods (:meth:objective_value, :meth:constraint_values, :meth:is_feasible) can operate on real expressions.

The problem reference is not serialized: rebuilding a model from :meth:from_dict yields a structural snapshot in which the evaluation methods raise a :class:ValueError explaining that the model must be built from a problem first.

OptimizationModel dataclass

Bases: MathematicalModel

Structural formulation of an optimization problem.

Parameters:

Name Type Description Default
objective_senses dict[str, str]

Objective name -> "minimize"/"maximize".

dict()
variable_bounds dict[str, list[Any]]

Variable name -> [lower_bound, upper_bound].

dict()
constant_term float

Additive constant of the (single) objective.

0.0
problem_ref QuantumProblem | None

Reference to the originating problem (not serialized).

None
from_problem(problem) classmethod

Snapshot an optimization problem including senses and bounds.

objective_value(assignment)

Evaluate the first objective against an assignment (or None).

Raises:

Type Description
ValueError

If the model has no source problem reference.

constraint_values(assignment)

Evaluate every constraint expression against an assignment.

Returns a mapping of constraint name -> numeric left-hand side (None when the constraint has no expression).

is_feasible(assignment)

Return whether the assignment satisfies every constraint.

to_dict()

Serialize to a JSON-safe dictionary (problem reference excluded).

from_dict(data) classmethod

Rebuild an OptimizationModel from :meth:to_dict output.

simulation_model

Simulation formulation of quantum domain problems.

A :class:SimulationModel extends :class:MathematicalModel with time-step/dynamics structure for simulating the evolution of a system over time (physical, chemical, biological or market dynamics).

SimulationModel dataclass

Bases: MathematicalModel

Structural formulation of a simulation problem.

Parameters:

Name Type Description Default
time_steps int

Number of discrete evolution steps.

0
dynamics str

Description of the evolution law (e.g. "hamiltonian", "reaction-diffusion").

''
n_steps property

Number of evolution steps.

from_problem(problem) classmethod

Snapshot a simulation problem (solver config from metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a SimulationModel from :meth:to_dict output.

statistical_model

Statistical formulation of quantum domain problems.

A :class:StatisticalModel extends :class:MathematicalModel with distribution and assumption structure for problems where the goal is statistical inference, hypothesis testing or data modelling (e.g. quantum-enhanced estimation, Monte Carlo methods).

StatisticalModel dataclass

Bases: MathematicalModel

Structural formulation of a statistical problem.

Parameters:

Name Type Description Default
distribution str

Target distribution or family (e.g. "gaussian").

''
assumptions list[str]

Statistical assumptions (e.g. ["iid", "normal"]).

list()
from_problem(problem) classmethod

Snapshot a statistical problem (config from problem metadata).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a StatisticalModel from :meth:to_dict output.

integration

Integration layer of QuantsMind Quantum.

Wraps the MicroQuantum runtime behind a stable facade so the domain, formulation, strategy, mapping, workflow and result layers never import microquantum directly.

microquantum_available()

Return True when the optional microquantum package is installed.

require_microquantum()

Import and return the microquantum module, with a clear error.

resolve_backend(backend)

Resolve a backend name or instance into a MicroQuantum Backend.

None is passed through so MicroQuantum picks its default. A string is looked up on MicroQuantum's local provider. Anything else is assumed to already be a MicroQuantum Backend instance.

microquantum

MicroQuantum integration facade.

Keeps the only microquantum-importing seams behind clearly marked helpers. Nothing else in quantsmind.quantum should import microquantum directly; the runtime availability checks and the lazy import live in :mod:quantsmind.quantum._mq and are re-exported here for the domain layer.

Importing this module (or any of quantsmind.quantum) never requires microquantum to be installed.

QMQ-02 adds the QUBO/Ising -> MicroQuantum delegation: an :class:~quantsmind.quantum.optimization.ising.IsingModel becomes a microquantum.PauliSum (the Ising Hamiltonian) and an OptimizationProblem, which is then minimised with MicroQuantum's QAOA via its public API. No circuits, gates, states, simulators, QAOA implementations or runtimes are duplicated here.

QuantumIntegrationError

Bases: RuntimeError

Raised when a MicroQuantum delegation fails or is unavailable.

QaoaExecutionResult dataclass

Record of a QUBO/Ising run delegated to MicroQuantum's QAOA.

Parameters:

Name Type Description Default
solver str

Solver identity ("microquantum/qaoa").

'microquantum/qaoa'
algorithm str

Algorithm used ("qaoa").

'qaoa'
backend str

Backend that executed the run.

''
num_layers int

Number of QAOA layers used.

1
bitstring str

Most-frequent measured bitstring.

''
assignment dict[str, int]

QUBO variable name -> 0/1 decoded from the bitstring.

dict()
energy float | None

QUBO energy of the assignment (minimization form, penalties included) when a QUBO was supplied.

None
ising_energy float | None

Ising energy of the assignment (carries the constant).

None
mq_eigenvalue float | None

Raw eigenvalue returned by MicroQuantum (Ising energy without the additive constant).

None
converged bool

Whether MicroQuantum's optimizer reported convergence.

False
iterations int

Optimizer iterations reported by MicroQuantum.

0
shots int

Shot count used for the final sampling.

0
seed int | None

Seed used.

None
metadata dict[str, Any]

Free-form execution metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

microquantum_available()

Return True when the optional microquantum package is installed.

require_microquantum()

Import and return the microquantum module, with a clear error.

resolve_backend(backend)

Resolve a backend name or instance into a MicroQuantum Backend.

None is passed through so MicroQuantum picks its default. A string is looked up on MicroQuantum's local provider. Anything else is assumed to already be a MicroQuantum Backend instance.

ising_to_pauli_sum(ising)

Build the microquantum.PauliSum (Ising Hamiltonian) for a model.

Qubit i of the Pauli labels corresponds to the i-th variable in :attr:IsingModel.variables. The additive constant is not part of the Pauli sum (MicroQuantum's eigenvalue excludes it); it is carried by :meth:IsingModel.energy instead.

ising_to_optimization_problem(ising, *, name=None)

Wrap an Ising model into a MicroQuantum OptimizationProblem.

qaoa_available()

Return whether a QAOA-capable MicroQuantum is importable.

run_qaoa(ising, *, qubo=None, num_layers=1, shots=1024, seed=None, backend=None, name=None, optimizer=None)

Minimise an Ising model via MicroQuantum's public QAOA API.

The Ising model is wrapped as a MicroQuantum OptimizationProblem (cost Hamiltonian); QAOA.from_problem().solve() performs the computation, and the optimized ansatz is sampled on the chosen backend to recover a bitstring. Returns an honest record: MicroQuantum's raw eigenvalue plus the QUBO/Ising energies of the sampled assignment.

Parameters:

Name Type Description Default
ising IsingModel

The Ising model to minimise.

required
qubo QUBOModel | None

Optional QUBO model for reporting the sampled assignment's QUBO energy.

None
num_layers int

QAOA layers (p).

1
shots int

Shot count used for the final sampling.

1024
seed int | None

Optional RNG seed.

None
backend str | None

Backend name or engine backend instance.

None
name str | None

Problem name recorded in the result metadata.

None
optimizer Any | None

Optional MicroQuantum optimizer instance to use for the variational loop (overrides the engine default; tests pass a low-iteration one to keep the run fast).

None

Raises:

Type Description
QuantumIntegrationError

If QAOA is not available or the run fails.

ImportError

If MicroQuantum is not installed (with install hint).

intelligence

QMQ-03 — Algorithm & Computational Strategy Intelligence.

This subpackage implements the "intelligence" layer of QuantsMind Quantum: it answers what the problem is, how it should be formulated, which strategy fits, which algorithm to recommend, and how the whole thing will run. It owns no circuit, gate, state or simulator — those all live in MicroQuantum (or in the QMQ-02 classical baseline).

Pipeline (QMQ-03 §14):

problem -> classify -> suggest formulation -> choose strategy
         -> recommend algorithm -> build computation plan

Public entry points:

  • :class:~quantsmind.quantum.intelligence.classification.ProblemClassifier
  • :class:~quantsmind.quantum.intelligence.recommender.FormulationRecommender
  • :class:~quantsmind.quantum.intelligence.recommender.AlgorithmSelector
  • :class:~quantsmind.quantum.intelligence.registry.AlgorithmRegistry
  • :class:~quantsmind.quantum.intelligence.capabilities.CapabilityModel
  • :class:~quantsmind.quantum.intelligence.plan.ComputationPlan

None of these modules import microquantum at import time; capability detection is lazy and graceful (QMQ-03 §11, §15).

AlgorithmAvailability dataclass

Three-level availability of one algorithm.

Parameters:

Name Type Description Default
algorithm str

Canonical algorithm id.

required
architecture_supported bool

QuantsMind Quantum has a descriptor for it.

required
available_in_microquantum bool

The installed MicroQuantum exposes it.

required
currently_executable bool

It can run in this environment right now.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

AlgorithmCategory

Bases: Enum

High-level family an algorithm belongs to.

parse(value) classmethod

Coerce a label or member to an :class:AlgorithmCategory.

AlgorithmDescriptor dataclass

Structural description of an algorithm known to QuantsMind Quantum.

Parameters:

Name Type Description Default
name str

Canonical id (e.g. "qaoa").

required
label str

Human-readable label (e.g. "QAOA").

required
category AlgorithmCategory

High-level algorithm family.

required
description str

What the algorithm does.

required
problem_classes tuple[str, ...]

Problem-class labels the algorithm suits.

()
formulations tuple[str, ...]

Formulation kinds the algorithm consumes.

()
strategies tuple[ComputationStrategy, ...]

Strategies the algorithm participates in.

()
execution_modes tuple[str, ...]

How the algorithm is executed (e.g. "vqe_loop").

()
microquantum_identifier str | None

Public MicroQuantum class name, or None for non-quantum algorithms (e.g. the classical baseline).

None
required_capabilities tuple[str, ...]

Capability names that must be available for the algorithm to run (e.g. "qaoa_available").

()
min_variables int | None

Minimum useful problem size (inclusive).

None
max_variables int | None

Maximum useful problem size (inclusive).

None
metadata dict[str, Any]

Free-form metadata.

dict()
category_label property

Serialized category label (e.g. "optimization").

matches(*, problem_class=None, formulation=None, strategy=None)

Return whether this descriptor is applicable to the given signals.

Only constraints that are provided are checked; unknown signals are not grounds for exclusion.

availability(capabilities)

Compute executive availability against a :class:CapabilityModel.

Classical algorithms are executable when their (classical) capabilities are met; quantum algorithms require the corresponding MicroQuantum probe to have succeeded.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a descriptor from :meth:to_dict output.

AlgorithmRecommendation dataclass

A scored, rule-based algorithm recommendation.

Parameters:

Name Type Description Default
algorithm str | None

Recommended canonical algorithm id, or None when no executable algorithm fits.

required
suitability_score float

Rule-based heuristic score in [0, 1]. This is not ML confidence; it reflects how well deterministic rules match this problem, formulation and strategy.

required
reason str

Human-readable, signal-based explanation.

required
required_capabilities list[str]

Capabilities the recommendation needs.

list()
expected_input_representation str

What the algorithm is handed (e.g. "IsingModel -> microquantum.OptimizationProblem").

''
execution_mode str

How the algorithm runs (e.g. "vqe_loop").

''
fallbacks list[AlgorithmRecommendation]

Executable fallback recommendations (never the only path when a primary is unavailable).

list()
capabilities dict[str, bool]

Snapshot of the capability flags considered.

dict()
user_requested bool

True when the algorithm was explicitly requested.

False
metadata dict[str, Any]

Free-form metadata (e.g. requested_algorithm when a fallback was applied).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a recommendation from :meth:to_dict output.

CapabilityModel dataclass

Snapshot of what the current environment can execute.

Parameters:

Name Type Description Default
microquantum_installed bool

The optional microquantum package is importable.

False
quantum_enabled bool

Master switch for quantum-family execution.

True
simulator_available bool

A local simulator backend is exposed by MicroQuantum.

False
backend_available bool

A backend can be resolved for execution.

False
qml_available bool

MicroQuantum exposes a quantum machine-learning class.

False
quantum_execution_enabled bool

MicroQuantum can actually be executed (installed and enabled).

False
classical_baseline_available bool

The QMQ-02 classical exhaustive baseline exists (always true).

True
algorithm_available dict[str, bool]

Algorithm id -> probe result.

dict()
metadata dict[str, Any]

Free-form detection metadata.

dict()
detect(*, quantum_enabled=True, backend_available=None) classmethod

Probe the environment using public APIs only.

Parameters:

Name Type Description Default
quantum_enabled bool

Whether quantum execution is enabled by policy.

True
backend_available bool | None

Explicit backend signal; None falls back to local-simulator availability.

None
is_available(capability)

Return whether a named capability holds.

Accepts canonical aliases: "qaoa_available", "qaoa", "microquantum", or any attribute of this model.

executable_algorithms()

Sorted ids of algorithms currently executable in this environment.

required_caps_met(required_capabilities)

True when every required capability is available.

capability_flags()

All boolean capability flags as a flat dictionary.

Algorithm probes are also included as "<id>_available" keys.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a CapabilityModel from :meth:to_dict output.

ClassificationResult dataclass

Result of a deterministic problem classification.

Parameters:

Name Type Description Default
problem_name str

Name of the classified problem.

required
problem_class ProblemClass

The assigned :class:ProblemClass.

required
reason str

Human-readable explanation of the assignment.

required
signals dict[str, Any]

Structural signals used by the classifier (variable types, formulation kind, counts, ...).

dict()
metadata dict[str, Any]

Free-form classification metadata (e.g. the rule path).

dict()
label property

Serialized label of the problem class (e.g. "binary_optimization").

is_optimization property

True for the optimization family of classes.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ClassificationResult from :meth:to_dict output.

ProblemClass

Bases: Enum

Machine-readable problem category (QMQ-03).

Labels are snake_case so they survive JSON round trips.

parse(value) classmethod

Coerce a snake_case label or member to a :class:ProblemClass.

known_labels() classmethod

All serialized labels of the supported problem classes.

ProblemClassifier

Deterministic structural problem classifier (QMQ-03).

Parameters:

Name Type Description Default
default_class ProblemClass | str

Class assigned when no signal is available.

UNKNOWN
classify(problem, formulation=None)

Classify a domain problem using structural rules only.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand otherwise).

None

Returns:

Name Type Description
ClassificationResult ClassificationResult

The assigned class and its rationale.

ComputationPlan dataclass

Declarative execution plan for one problem (QMQ-03 §13).

Parameters:

Name Type Description Default
problem_name str

Name of the domain problem.

required
problem_class str

Classification label (e.g. "binary_optimization").

required
formulation str

Formulation kind to execute (e.g. "qubo").

required
strategy ComputationStrategy

Chosen :class:ComputationStrategy.

required
algorithm str | None

Recommended primary algorithm id, or None.

required
recommendation AlgorithmRecommendation

The full algorithm recommendation object.

required
mapping str

Mapping label needed for the chosen algorithm (e.g. "qubo" / "ising" / "none").

'none'
executor str

Executor that will run the plan (e.g. "microquantum/qaoa" / "classical/exhaustive").

''
fallbacks list[str]

Executable fallback algorithm ids in preference order.

list()
capabilities dict[str, bool]

Capability snapshot justifying the recommendation.

dict()
classification ClassificationResult | None

The classification decision used.

None
formulation_recommendation FormulationRecommendation | None

The formulation recommendation used.

None
strategy_decision StrategyDecision | None

The strategy decision used.

None
reason str

Standing human-readable justification.

''
provenance dict[str, Any]

Emergent provenance notes (module, rule path).

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
strategy_label property

Serialized strategy label (e.g. "hybrid").

is_quantum()

True when the plan executes a quantum algorithm.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

AlgorithmSelectionError

Bases: ValueError

Raised when no rule can select an algorithm for the inputs.

AlgorithmSelector

Deterministic rule-based algorithm selector (QMQ-03 §8–§10).

Parameters:

Name Type Description Default
registry AlgorithmRegistry | None

Algorithm registry (defaults to the standard catalog).

None
select(problem, formulation=None, strategy=None, classification=None, capabilities=None, requested_algorithm=None, *, allow_fallback=False)

Select an algorithm, or raise when no rule applies.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

The chosen formulation (defaults to the problem's).

None
strategy ComputationStrategy | str | None

The chosen :class:ComputationStrategy.

None
classification ClassificationResult | ProblemClass | None

Classification result; re-classified if omitted.

None
capabilities CapabilityModel | None

Capability snapshot; auto-detected if omitted.

None
requested_algorithm str | None

Optional explicit algorithm id.

None
allow_fallback bool

If True and the requested algorithm is not executable, an executable replacement is selected and recorded. A requested algorithm is never silently replaced: the fallback is always marked in metadata.

False

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

A scored recommendation with an

AlgorithmRecommendation

executable fallback chain.

Raises:

Type Description
AlgorithmSelectionError

When the request is impossible (unknown requested algorithm, or - without allow_fallback - an unavailable requested algorithm).

FormulationAlternative dataclass

One alternative formulation the recommender may offer.

Parameters:

Name Type Description Default
kind str

Formulation kind label (e.g. "ising", "qubo").

required
reason str

Why this alternative exists and when it should be preferred.

required
appropriateness float

0.0–1.0 rule-based fit for this problem.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommendation dataclass

Recommended formulation for a problem.

Parameters:

Name Type Description Default
problem_name str

Classified problem name.

required
classification str

Label of the problem class driving the decision.

required
primary str

Recommended formulation kind (e.g. "qubo").

required
alternatives list[FormulationAlternative]

Additional executables, with reasons.

list()
reason str

Human-readable explanation of the primary choice.

''
metadata dict[str, Any]

Free-form metadata (rule path, forced flag, ...).

dict()
is_qubo property

True when the primary recommendation is a QUBO formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommender

Rule-based formulation-kind recommender (QMQ-03 §6).

The evaluator is purely structural: it reads the problem class and the current formulation, never the mathematical content.

Parameters:

Name Type Description Default
registries AlgorithmRegistry | None

Bundled, unused (kept for extensibility); pass the algorithm registry when available.

None
recommend(problem, formulation=None, strategy=None, classification=None, *, force_qubo=False)

Recommend a formulation kind for problem.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand).

None
strategy ComputationStrategy | None

Optional strategy; informs which formulations can be consumed.

None
classification ClassificationResult | ProblemClass | None

Classification result (or just a class) to avoid re-classification.

None
force_qubo bool

When True, QUBO is recommended even for non-binary problems (recorded in metadata; the caller decides whether the problem is actually quantizable).

False

Returns:

Name Type Description
FormulationRecommendation FormulationRecommendation

The recommended primary kind and

FormulationRecommendation

alternatives.

AlgorithmRegistry

Registry of algorithm descriptors.

Implements registration, lookup, search and availability queries. The default catalog is loaded on construction and can be replaced or extended.

register(descriptor)

Register descriptor; raise on a duplicate or empty id.

unregister(name)

Remove name; raise :class:UnknownAlgorithmError.

get(name)

Return the descriptor for name or raise UnknownAlgorithmError.

find(*, problem_class=None, formulation=None, category=None, strategy=None)

Return descriptors matching the given signals (sorted by name).

registered()

All registered descriptors sorted by name.

available(capabilities)

Executive availability for every registered algorithm.

executable_algorithms(capabilities)

Sorted ids currently executable against capabilities.

to_dict()

Serialize the registry (descriptors + version).

from_dict(data) classmethod

Rebuild a registry from :meth:to_dict output.

Only the serialized descriptors are registered (the default catalog is not preloaded).

DuplicateAlgorithmError

Bases: ValueError

Raised when registering an id that already exists.

UnknownAlgorithmError

Bases: KeyError

Raised when an algorithm id is not registered.

algorithms

QMQ-03 algorithm domain model.

An :class:AlgorithmDescriptor is a description of an algorithm that QuantsMind Quantum knows how to talk about. Describing an algorithm does not mean QuantsMind implements it: computation is always delegated to MicroQuantum (or to the QMQ-02 classical baseline). The descriptor records which problem classes, formulations and strategies an algorithm suits, and what capability the environment must provide for it to be executable.

:class:AlgorithmAvailability keeps the three-level availability contract explicit:

  • architecture_supported — QuantsMind Quantum has a descriptor for it.
  • available_in_microquantum — the installed MicroQuantum exposes it.
  • currently_executable — it can run in this environment right now.

An :class:AlgorithmRecommendation is a scored, rule-based suggestion (never a measured confidence) together with executable fallbacks.

AlgorithmCategory

Bases: Enum

High-level family an algorithm belongs to.

parse(value) classmethod

Coerce a label or member to an :class:AlgorithmCategory.

AlgorithmDescriptor dataclass

Structural description of an algorithm known to QuantsMind Quantum.

Parameters:

Name Type Description Default
name str

Canonical id (e.g. "qaoa").

required
label str

Human-readable label (e.g. "QAOA").

required
category AlgorithmCategory

High-level algorithm family.

required
description str

What the algorithm does.

required
problem_classes tuple[str, ...]

Problem-class labels the algorithm suits.

()
formulations tuple[str, ...]

Formulation kinds the algorithm consumes.

()
strategies tuple[ComputationStrategy, ...]

Strategies the algorithm participates in.

()
execution_modes tuple[str, ...]

How the algorithm is executed (e.g. "vqe_loop").

()
microquantum_identifier str | None

Public MicroQuantum class name, or None for non-quantum algorithms (e.g. the classical baseline).

None
required_capabilities tuple[str, ...]

Capability names that must be available for the algorithm to run (e.g. "qaoa_available").

()
min_variables int | None

Minimum useful problem size (inclusive).

None
max_variables int | None

Maximum useful problem size (inclusive).

None
metadata dict[str, Any]

Free-form metadata.

dict()
category_label property

Serialized category label (e.g. "optimization").

matches(*, problem_class=None, formulation=None, strategy=None)

Return whether this descriptor is applicable to the given signals.

Only constraints that are provided are checked; unknown signals are not grounds for exclusion.

availability(capabilities)

Compute executive availability against a :class:CapabilityModel.

Classical algorithms are executable when their (classical) capabilities are met; quantum algorithms require the corresponding MicroQuantum probe to have succeeded.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a descriptor from :meth:to_dict output.

AlgorithmAvailability dataclass

Three-level availability of one algorithm.

Parameters:

Name Type Description Default
algorithm str

Canonical algorithm id.

required
architecture_supported bool

QuantsMind Quantum has a descriptor for it.

required
available_in_microquantum bool

The installed MicroQuantum exposes it.

required
currently_executable bool

It can run in this environment right now.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

AlgorithmRecommendation dataclass

A scored, rule-based algorithm recommendation.

Parameters:

Name Type Description Default
algorithm str | None

Recommended canonical algorithm id, or None when no executable algorithm fits.

required
suitability_score float

Rule-based heuristic score in [0, 1]. This is not ML confidence; it reflects how well deterministic rules match this problem, formulation and strategy.

required
reason str

Human-readable, signal-based explanation.

required
required_capabilities list[str]

Capabilities the recommendation needs.

list()
expected_input_representation str

What the algorithm is handed (e.g. "IsingModel -> microquantum.OptimizationProblem").

''
execution_mode str

How the algorithm runs (e.g. "vqe_loop").

''
fallbacks list[AlgorithmRecommendation]

Executable fallback recommendations (never the only path when a primary is unavailable).

list()
capabilities dict[str, bool]

Snapshot of the capability flags considered.

dict()
user_requested bool

True when the algorithm was explicitly requested.

False
metadata dict[str, Any]

Free-form metadata (e.g. requested_algorithm when a fallback was applied).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a recommendation from :meth:to_dict output.

capabilities

QMQ-03 capability detection layer.

A :class:CapabilityModel answers what can actually run in this environment. It always distinguishes:

  • Whether MicroQuantum is installed.
  • Which MicroQuantum algorithms the installed version exposes (public API probes only — never private internals, never source copies).
  • Whether classical baselines are available (always, in QuantsMind Quantum).

Nothing in this module imports microquantum at import time; probes are lazy and graceful, so classical-only environments remain fully functional.

CapabilityModel dataclass

Snapshot of what the current environment can execute.

Parameters:

Name Type Description Default
microquantum_installed bool

The optional microquantum package is importable.

False
quantum_enabled bool

Master switch for quantum-family execution.

True
simulator_available bool

A local simulator backend is exposed by MicroQuantum.

False
backend_available bool

A backend can be resolved for execution.

False
qml_available bool

MicroQuantum exposes a quantum machine-learning class.

False
quantum_execution_enabled bool

MicroQuantum can actually be executed (installed and enabled).

False
classical_baseline_available bool

The QMQ-02 classical exhaustive baseline exists (always true).

True
algorithm_available dict[str, bool]

Algorithm id -> probe result.

dict()
metadata dict[str, Any]

Free-form detection metadata.

dict()
detect(*, quantum_enabled=True, backend_available=None) classmethod

Probe the environment using public APIs only.

Parameters:

Name Type Description Default
quantum_enabled bool

Whether quantum execution is enabled by policy.

True
backend_available bool | None

Explicit backend signal; None falls back to local-simulator availability.

None
is_available(capability)

Return whether a named capability holds.

Accepts canonical aliases: "qaoa_available", "qaoa", "microquantum", or any attribute of this model.

executable_algorithms()

Sorted ids of algorithms currently executable in this environment.

required_caps_met(required_capabilities)

True when every required capability is available.

capability_flags()

All boolean capability flags as a flat dictionary.

Algorithm probes are also included as "<id>_available" keys.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a CapabilityModel from :meth:to_dict output.

classification

QMQ-03 deterministic problem classification.

The classifier decides what kind of problem a :class:~quantsmind.quantum.core.problem.QuantumProblem is (binary_optimization, graph_optimization, simulation, ...). It is synthetic and rule based, never an AI/LLM model: every decision is derived from structural signals (variable types, formulation kind, explicit metadata) and is fully deterministic and explainable.

Rules are ordered by specificity:

  1. An explicit problem.metadata["problem_class"] override wins.
  2. Otherwise the formulation kind drives the decision (graph -> graph_optimization, ml -> machine_learning, ...).
  3. optimization formulations are refined by the variable types (all binary -> binary_optimization, any continuous -> continuous_optimization, any integer -> integer_optimization, otherwise constraint_optimization).

The classifier is extensible: subclasses can override :meth:_classify or custom rules can be layered in front of :meth:classify.

ProblemClass

Bases: Enum

Machine-readable problem category (QMQ-03).

Labels are snake_case so they survive JSON round trips.

parse(value) classmethod

Coerce a snake_case label or member to a :class:ProblemClass.

known_labels() classmethod

All serialized labels of the supported problem classes.

ClassificationResult dataclass

Result of a deterministic problem classification.

Parameters:

Name Type Description Default
problem_name str

Name of the classified problem.

required
problem_class ProblemClass

The assigned :class:ProblemClass.

required
reason str

Human-readable explanation of the assignment.

required
signals dict[str, Any]

Structural signals used by the classifier (variable types, formulation kind, counts, ...).

dict()
metadata dict[str, Any]

Free-form classification metadata (e.g. the rule path).

dict()
label property

Serialized label of the problem class (e.g. "binary_optimization").

is_optimization property

True for the optimization family of classes.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a ClassificationResult from :meth:to_dict output.

ProblemClassifier

Deterministic structural problem classifier (QMQ-03).

Parameters:

Name Type Description Default
default_class ProblemClass | str

Class assigned when no signal is available.

UNKNOWN
classify(problem, formulation=None)

Classify a domain problem using structural rules only.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand otherwise).

None

Returns:

Name Type Description
ClassificationResult ClassificationResult

The assigned class and its rationale.

plan

QMQ-03 declarative computation plan.

A :class:ComputationPlan records, for one domain problem, every decision the intelligence layer made: classification, formulation, strategy, algorithm recommendation (with fallbacks), mapping, executor and the capability snapshot that justified them. It is declarative and serializable, ready for QMQ-04 to execute without re-deriving any decision.

ComputationPlan dataclass

Declarative execution plan for one problem (QMQ-03 §13).

Parameters:

Name Type Description Default
problem_name str

Name of the domain problem.

required
problem_class str

Classification label (e.g. "binary_optimization").

required
formulation str

Formulation kind to execute (e.g. "qubo").

required
strategy ComputationStrategy

Chosen :class:ComputationStrategy.

required
algorithm str | None

Recommended primary algorithm id, or None.

required
recommendation AlgorithmRecommendation

The full algorithm recommendation object.

required
mapping str

Mapping label needed for the chosen algorithm (e.g. "qubo" / "ising" / "none").

'none'
executor str

Executor that will run the plan (e.g. "microquantum/qaoa" / "classical/exhaustive").

''
fallbacks list[str]

Executable fallback algorithm ids in preference order.

list()
capabilities dict[str, bool]

Capability snapshot justifying the recommendation.

dict()
classification ClassificationResult | None

The classification decision used.

None
formulation_recommendation FormulationRecommendation | None

The formulation recommendation used.

None
strategy_decision StrategyDecision | None

The strategy decision used.

None
reason str

Standing human-readable justification.

''
provenance dict[str, Any]

Emergent provenance notes (module, rule path).

dict()
created_at str

ISO-8601 creation timestamp.

_utc_now()
metadata dict[str, Any]

Free-form metadata.

dict()
strategy_label property

Serialized strategy label (e.g. "hybrid").

is_quantum()

True when the plan executes a quantum algorithm.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a plan from :meth:to_dict output.

recommender

QMQ-03 formulation recommendation and rule-based algorithm selection.

Two responsibilities live here:

  • :class:FormulationRecommender — decides which formulation kind a problem should use. It deliberately does not force everything into QUBO (QMQ-03 §6): QUBO is recommended only for binary problems, Ising is offered as an alternative, graph/simulation/ML/statistical problems keep their native formulations.

  • :class:AlgorithmSelector — turns a classified problem, an accepted formulation and a strategy into an :class:AlgorithmRecommendation using deterministic rule-based heuristics. Scores are documented suitability scores, not ML confidence, and the selector never presents an unavailable algorithm as the only path: an executable fallback is always attached when a quantum recommendation cannot run.

FormulationAlternative dataclass

One alternative formulation the recommender may offer.

Parameters:

Name Type Description Default
kind str

Formulation kind label (e.g. "ising", "qubo").

required
reason str

Why this alternative exists and when it should be preferred.

required
appropriateness float

0.0–1.0 rule-based fit for this problem.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommendation dataclass

Recommended formulation for a problem.

Parameters:

Name Type Description Default
problem_name str

Classified problem name.

required
classification str

Label of the problem class driving the decision.

required
primary str

Recommended formulation kind (e.g. "qubo").

required
alternatives list[FormulationAlternative]

Additional executables, with reasons.

list()
reason str

Human-readable explanation of the primary choice.

''
metadata dict[str, Any]

Free-form metadata (rule path, forced flag, ...).

dict()
is_qubo property

True when the primary recommendation is a QUBO formulation.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FormulationRecommender

Rule-based formulation-kind recommender (QMQ-03 §6).

The evaluator is purely structural: it reads the problem class and the current formulation, never the mathematical content.

Parameters:

Name Type Description Default
registries AlgorithmRegistry | None

Bundled, unused (kept for extensibility); pass the algorithm registry when available.

None
recommend(problem, formulation=None, strategy=None, classification=None, *, force_qubo=False)

Recommend a formulation kind for problem.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

Optional prebuilt formulation (built on demand).

None
strategy ComputationStrategy | None

Optional strategy; informs which formulations can be consumed.

None
classification ClassificationResult | ProblemClass | None

Classification result (or just a class) to avoid re-classification.

None
force_qubo bool

When True, QUBO is recommended even for non-binary problems (recorded in metadata; the caller decides whether the problem is actually quantizable).

False

Returns:

Name Type Description
FormulationRecommendation FormulationRecommendation

The recommended primary kind and

FormulationRecommendation

alternatives.

AlgorithmSelectionError

Bases: ValueError

Raised when no rule can select an algorithm for the inputs.

AlgorithmSelector

Deterministic rule-based algorithm selector (QMQ-03 §8–§10).

Parameters:

Name Type Description Default
registry AlgorithmRegistry | None

Algorithm registry (defaults to the standard catalog).

None
select(problem, formulation=None, strategy=None, classification=None, capabilities=None, requested_algorithm=None, *, allow_fallback=False)

Select an algorithm, or raise when no rule applies.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem.

required
formulation MathematicalModel | None

The chosen formulation (defaults to the problem's).

None
strategy ComputationStrategy | str | None

The chosen :class:ComputationStrategy.

None
classification ClassificationResult | ProblemClass | None

Classification result; re-classified if omitted.

None
capabilities CapabilityModel | None

Capability snapshot; auto-detected if omitted.

None
requested_algorithm str | None

Optional explicit algorithm id.

None
allow_fallback bool

If True and the requested algorithm is not executable, an executable replacement is selected and recorded. A requested algorithm is never silently replaced: the fallback is always marked in metadata.

False

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

A scored recommendation with an

AlgorithmRecommendation

executable fallback chain.

Raises:

Type Description
AlgorithmSelectionError

When the request is impossible (unknown requested algorithm, or - without allow_fallback - an unavailable requested algorithm).

registry

QMQ-03 algorithm registry.

The registry is the single source of truth for which algorithms QuantsMind Quantum knows about. It is a plain, extensible catalog — not a giant conditional. Registration is explicit, and the default catalog ships the QMQ-03 algorithm set.

Availability is never inferred here: a registered algorithm is known to the architecture; whether it can run is decided by the capability layer at selection time.

AlgorithmAvailability dataclass

Three-level availability of one algorithm.

Parameters:

Name Type Description Default
algorithm str

Canonical algorithm id.

required
architecture_supported bool

QuantsMind Quantum has a descriptor for it.

required
available_in_microquantum bool

The installed MicroQuantum exposes it.

required
currently_executable bool

It can run in this environment right now.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

UnknownAlgorithmError

Bases: KeyError

Raised when an algorithm id is not registered.

DuplicateAlgorithmError

Bases: ValueError

Raised when registering an id that already exists.

AlgorithmRegistry

Registry of algorithm descriptors.

Implements registration, lookup, search and availability queries. The default catalog is loaded on construction and can be replaced or extended.

register(descriptor)

Register descriptor; raise on a duplicate or empty id.

unregister(name)

Remove name; raise :class:UnknownAlgorithmError.

get(name)

Return the descriptor for name or raise UnknownAlgorithmError.

find(*, problem_class=None, formulation=None, category=None, strategy=None)

Return descriptors matching the given signals (sorted by name).

registered()

All registered descriptors sorted by name.

available(capabilities)

Executive availability for every registered algorithm.

executable_algorithms(capabilities)

Sorted ids currently executable against capabilities.

to_dict()

Serialize the registry (descriptors + version).

from_dict(data) classmethod

Rebuild a registry from :meth:to_dict output.

Only the serialized descriptors are registered (the default catalog is not preloaded).

mapping

Mapping layer of QuantsMind Quantum.

Maps domain/computational descriptions into runtime representations. QMQ-01 ships the quantum-circuit mapping. QMQ-02 adds the automatic problem -> optimization -> QUBO -> Ising pipeline:

  • :class:ProblemMapper problem -> :class:OptimizationModel
  • :class:QUBOMapper problem -> :class:QUBOModel (with penalties)
  • :class:IsingMapper QUBO -> :class:IsingModel
  • :class:QuantumCircuitMapper program -> MicroQuantum circuit (QMQ-01)

IsingMapper

Maps a :class:QUBOModel to an energy-equivalent :class:IsingModel.

map(qubo, *, strategy=ComputationStrategy.HYBRID)

Record the QUBO -> Ising conversion.

The built :class:~quantsmind.quantum.optimization.ising.IsingModel is attached as the mapping payload; MicroQuantum conversion is deferred to the integration layer.

Raises:

Type Description
MappingError

If qubo is not a :class:QUBOModel.

DomainMapper

Bases: ABC

Maps a computational description into a runtime representation.

Subclasses implement one directed mapping. map() validates the input and records the mapping steps; build() materializes the runtime object (a MicroQuantum circuit, a QUBO, ...).

map(program, *, strategy) abstractmethod

Validate the input and record the mapping steps.

build(result) abstractmethod

Materialize the mapped computational representation.

MappingError

Bases: ValueError

Raised when a domain description cannot be mapped to a computation.

MappingResult dataclass

Record of a domain -> computation mapping.

Parameters:

Name Type Description Default
mapper str

Name of the mapper that produced the record.

required
strategy ComputationStrategy

Strategy the mapping was produced for.

required
source str

A short description of the input representation.

required
target str

A short description of the output representation.

required
steps list[str]

Human-readable mapping steps taken.

list()
metadata dict[str, Any]

Free-form mapping metadata.

dict()
payload Any

Optional non-serializable mapped object.

None
to_dict()

Serialize to a JSON-safe dictionary (payload excluded).

QuantumCircuitMapper

Bases: DomainMapper

Real mapping: declarative :class:QuantumProgram -> MicroQuantum circuit.

Validation is performed via :func:validate_program; the actual MicroQuantum circuit is built lazily by :func:build_circuit when :meth:build is called.

Raises:

Type Description
MappingError

If the program is invalid or the strategy is incompatible with quantum execution.

map(program, *, strategy=ComputationStrategy.HYBRID)

Validate the program and record the mapping steps.

Parameters:

Name Type Description Default
program Any

A :class:~quantsmind.quantum.program.QuantumProgram.

required
strategy ComputationStrategy

The chosen computation strategy.

HYBRID

Raises:

Type Description
MappingError

If the strategy is incompatible with quantum execution or the program is not translatable.

build(result)

Materialize the MicroQuantum circuit.

Delegates to :func:quantsmind.quantum.bridge.build_circuit, which in turn calls MicroQuantum's public Operator factories.

ProblemMapper

Maps a :class:QuantumProblem to an :class:OptimizationModel.

map(problem)

Return the optimization formulation of a problem.

Raises:

Type Description
MappingError

If the problem has no optimization formulation (no objective / unsupported model kind).

QUBOMapper

Maps a binary :class:QuantumProblem to a :class:QUBOModel.

The objective expression (symbolic string or expression node) becomes the quadratic polynomial; a MAXIMIZE objective is negated so the QUBO is always a minimization; supported constraints are folded in as exact penalty terms. The mapping record keeps the original sense and the penalty detail so reports can restore objective and feasibility.

map(problem, *, strategy=ComputationStrategy.HYBRID, penalty=None)

Build the QUBO model and record the mapping.

Raises:

Type Description
MappingError

If the problem cannot be mapped (no objective, non-binary variables, non-symbolic objective, non-quadratic terms, or an unsupported constraint).

ising

QUBO -> Ising -> quantum-representation mapping (QMQ-02).

:class:IsingMapper converts an energy-equivalent :class:~quantsmind.quantum.optimization.qubo.QUBOModel into an :class:~quantsmind.quantum.optimization.ising.IsingModel (x = (s+1)/2) so the domain problem can be handed to a quantum engine. The mapper itself stays engine-agnostic and serializable; building MicroQuantum objects from the Ising model happens in the integration layer.

IsingMapper

Maps a :class:QUBOModel to an energy-equivalent :class:IsingModel.

map(qubo, *, strategy=ComputationStrategy.HYBRID)

Record the QUBO -> Ising conversion.

The built :class:~quantsmind.quantum.optimization.ising.IsingModel is attached as the mapping payload; MicroQuantum conversion is deferred to the integration layer.

Raises:

Type Description
MappingError

If qubo is not a :class:QUBOModel.

mapper

Domain-to-computation mapping foundation.

A mapping takes a :class:~quantsmind.quantum.program.QuantumProgram (a computational representation of a domain problem) and produces a :class:MappingResult describing the mapping steps. Building the actual runtime object is deferred to :meth:DomainMapper.build.

QMQ-01 ships one real mapping: :class:QuantumCircuitMapper -> MicroQuantum circuit (via the bridge). QMQ-02 adds QUBO / Ising / Hamiltonian / classical mappings.

MappingError

Bases: ValueError

Raised when a domain description cannot be mapped to a computation.

MappingResult dataclass

Record of a domain -> computation mapping.

Parameters:

Name Type Description Default
mapper str

Name of the mapper that produced the record.

required
strategy ComputationStrategy

Strategy the mapping was produced for.

required
source str

A short description of the input representation.

required
target str

A short description of the output representation.

required
steps list[str]

Human-readable mapping steps taken.

list()
metadata dict[str, Any]

Free-form mapping metadata.

dict()
payload Any

Optional non-serializable mapped object.

None
to_dict()

Serialize to a JSON-safe dictionary (payload excluded).

DomainMapper

Bases: ABC

Maps a computational description into a runtime representation.

Subclasses implement one directed mapping. map() validates the input and records the mapping steps; build() materializes the runtime object (a MicroQuantum circuit, a QUBO, ...).

map(program, *, strategy) abstractmethod

Validate the input and record the mapping steps.

build(result) abstractmethod

Materialize the mapped computational representation.

QuantumCircuitMapper

Bases: DomainMapper

Real mapping: declarative :class:QuantumProgram -> MicroQuantum circuit.

Validation is performed via :func:validate_program; the actual MicroQuantum circuit is built lazily by :func:build_circuit when :meth:build is called.

Raises:

Type Description
MappingError

If the program is invalid or the strategy is incompatible with quantum execution.

map(program, *, strategy=ComputationStrategy.HYBRID)

Validate the program and record the mapping steps.

Parameters:

Name Type Description Default
program Any

A :class:~quantsmind.quantum.program.QuantumProgram.

required
strategy ComputationStrategy

The chosen computation strategy.

HYBRID

Raises:

Type Description
MappingError

If the strategy is incompatible with quantum execution or the program is not translatable.

build(result)

Materialize the MicroQuantum circuit.

Delegates to :func:quantsmind.quantum.bridge.build_circuit, which in turn calls MicroQuantum's public Operator factories.

qubo

Automatic problem -> optimization -> QUBO mapping (QMQ-02).

The QMQ-01 foundation left this stage as NotImplementedError. QMQ-02 implements it for the supported binary-optimization path::

QuantumProblem
    -> OptimizationModel      (ProblemMapper)
    -> QUBOModel              (QUBOMapper, incl. constraint penalties)

Unsupported problems fail loudly with :class:MappingError — never with a fake or empty mapping.

ProblemMapper

Maps a :class:QuantumProblem to an :class:OptimizationModel.

map(problem)

Return the optimization formulation of a problem.

Raises:

Type Description
MappingError

If the problem has no optimization formulation (no objective / unsupported model kind).

QUBOMapper

Maps a binary :class:QuantumProblem to a :class:QUBOModel.

The objective expression (symbolic string or expression node) becomes the quadratic polynomial; a MAXIMIZE objective is negated so the QUBO is always a minimization; supported constraints are folded in as exact penalty terms. The mapping record keeps the original sense and the penalty detail so reports can restore objective and feasibility.

map(problem, *, strategy=ComputationStrategy.HYBRID, penalty=None)

Build the QUBO model and record the mapping.

Raises:

Type Description
MappingError

If the problem cannot be mapped (no objective, non-binary variables, non-symbolic objective, non-quadratic terms, or an unsupported constraint).

ml

QMQ-10 AI/ML Intelligence Foundation domain layer.

The ML layer turns small/structured ML selection problems (classification, regression, feature selection, model selection, hyperparameter optimization, clustering) into real QMQ problems solved by the existing QMQ-02..06 pipeline through the QUBO formulation.

Design pillars (QMQ-10):

  • Reuse, not rewrite — no second QUBO/Ising/solver/workflow/benchmark/ interpreter is introduced; the ML layer only adds domain objects, objectives, constraints, a formulation adapter, a deterministic mapping, solutions, metrics, and a thin optimizer over the existing pipeline.
  • Delegation — feature selection and clustering are delegated to the complete QMQ-09 Data layer (source_domain="data" provenance).
  • Honest quantum semantics — fitting is a well-posed quadratic binary problem; failure on a quantum runtime is reported honestly through the existing degradation rules.
  • No ML dependencies — only the Python standard library is imported.

Examples and fixtures are deterministic and never import microquantum.

HyperparameterOnePerParameterConstraint dataclass

Bases: MLConstraint

Exactly one choice per hyperparameter (sum_c h_{p,c} = 1 per p).

MLAssignmentConstraint dataclass

Bases: MLConstraint

Delegated: every record assigned to exactly one cluster.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLClusterCountConstraint dataclass

Bases: MLConstraint

Delegated: bound per-cluster record counts.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLCoefficientCountConstraint dataclass

Bases: MLConstraint

Bound the total number of selected fitting coefficients.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_coefficients float

Minimum number of non-zero coefficients (>= 0).

1.0
max_coefficients float | None

Maximum number of non-zero coefficients (None = unbounded).

None
description str

Free-form description.

''

MLConstraint dataclass

Base class of all ML constraints.

domain property

ML-domain label of this constraint.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_data_constraint(problem=None)

Translate into a QMQ-09 data constraint (delegated constraints only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

MLFeatureCountConstraint dataclass

Bases: MLConstraint

Bound the number of selected features (delegated to QMQ-09).

Converted into a Data FeatureCountConstraint at formulation time.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

ModelSelectionOneHotConstraint dataclass

Bases: MLConstraint

Exactly one candidate is selected (sum_c s_c = 1).

MLContext dataclass

ML-domain context of an ML problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "classification", "model_selection", "hyperparameter_optimization").

''
subdomain str

Domain subdomain (e.g. "tabular").

'tabular'
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

MLError

Bases: ValueError

Base error of the QuantsMind Quantum AI/ML Intelligence layer.

MLValidationError

Bases: MLError

Raised when an ML model or problem fails domain validation.

MLFormulationAdapter

Converts ML problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the w<i> (fitting), s<c> (model selection) and h{p}_{c} (hyperparameter) conventions, objectives keep their senses, and every ML constraint materializes into QMQ constraints. Feature selection and clustering delegate to the QMQ-09 Data layer.

validate(problem)

Return the validation issues of an ML problem (empty = valid).

raise_if_invalid(problem)

Raise :class:MLValidationError when the problem is invalid.

Raises:

Type Description
MLValidationError

If the problem fails validation.

is_delegated(problem)

Return whether the problem is delegated to the QMQ-09 Data layer.

ml_metadata(problem)

JSON-safe ML provenance metadata for the quantum problem.

to_data_problem(problem)

Build the delegated QMQ-09 DataProblem of an ML problem.

Feature selection converts MLFeatureSelectionObjective and MLFeatureCountConstraint into their Data equivalents; clustering converts the ML clustering objective/constraints (with default assignment semantics when absent).

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem (feature selection or clustering).

required

Raises:

Type Description
MLValidationError

If the problem is not a delegated family or cannot be expressed by the Data layer.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert an ML problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
MLValidationError

If the ML problem is invalid.

formulate(problem)

Return the existing QMQ formulation of an ML problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

DecodedHyperparameterChoice dataclass

One decoded hyperparameter-choice decision.

Attributes:

Name Type Description
parameter_name str

Domain hyperparameter name.

param_index int

Deterministic parameter index.

choice_index int

Deterministic choice index.

choice_value Any

The concrete choice value (JSON-safe).

variable_name str

QMQ variable name (h{p}_{c}).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedMLCoefficient dataclass

One decoded fitting-coefficient decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (w<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedModelSelection dataclass

One decoded model-selection decision.

Attributes:

Name Type Description
model_id str

Domain candidate identifier.

index int

Deterministic candidate index.

variable_name str

QMQ variable name (s<c>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

MLMapper dataclass

Maps a validated ML problem to a deterministic variable mapping.

Mirrors the :class:DataMapper pattern: validates, then provides :meth:map (which returns an :class:MLMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

Raises:

Type Description
MLValidationError

If the problem is delegated to the QMQ-09 Data layer (use the Data mapper on the delegated problem).

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

MLMapping dataclass

Deterministic mapping between ML variables and QMQ indices.

Created by :meth:MLMapper.map from a validated :class:MLProblem.

variable_names property

QMQ variable names in deterministic order.

coefficient(feature_name)

Return the decoded coefficient for feature_name (or None).

candidate(model_id)

Return the decoded model selection for model_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

MLMetrics dataclass

Deterministic outcome metrics of an ML solve.

Attributes:

Name Type Description
problem_type str

ML problem family ("classification", "regression", "model_selection" or "hyperparameter_optimization").

ssr float | None

Sum of squared residuals of the fitted linear model (fitting).

mse float | None

Mean squared error (ssr / num_records, fitting).

selected_feature_count int

Number of selected coefficients (fitting).

selected_model_id str

Selected candidate identifier (model selection).

selected_loss float | None

Validation loss of the selected candidate.

selected_penalty float | None

Complexity penalty of the selected candidate.

total_gain float | None

Total gain of the selected hyperparameter configuration.

objective_value float | None

Primary objective value decoded from the assignment.

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

MLDataSet dataclass

Ordered collection of :class:MLFeature and :class:MLRecord.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every ML problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[MLFeature]

Ordered feature list.

list()
records list[MLRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:MLFeature with name.

record(record_id)

Return the :class:MLRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

targets()

Return target values in deterministic record order.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
MLValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:MLValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

MLFeature dataclass

One numeric feature/dimension of an :class:MLDataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

MLHyperparameter dataclass

One hyperparameter with a deterministic finite choice space.

Parameters:

Name Type Description Default
name str

Unique hyperparameter name.

required
choices list[MLHyperparameterChoice]

Ordered choice list (at least one).

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
choice_count property

Number of choices.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a hyperparameter from :meth:to_dict output.

MLHyperparameterChoice dataclass

One choice of an :class:MLHyperparameter.

Parameters:

Name Type Description Default
value Any

The concrete choice value (free-form but JSON-safe, e.g. a float / string / int). Used only for reporting.

None
gain float

Caller-supplied non-negative gain of this choice. The hyperparameter objective maximizes the total gain of the chosen configuration.

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a choice from :meth:to_dict output.

MLModelCandidate dataclass

One model-selection candidate with caller-supplied validation scores.

Parameters:

Name Type Description Default
model_id str

Unique candidate identifier.

required
validation_loss float

Caller-supplied candidate validation loss (must be finite and non-negative).

0.0
complexity_penalty float

Caller-supplied complexity penalty (must be finite and non-negative).

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
objective()

Return validation_loss + complexity_penalty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a candidate from :meth:to_dict output.

MLRecord dataclass

One observation inside an :class:MLDataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
target float

Numeric target value (a class index for classification, a continuous response for regression).

0.0
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
MLValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

ClassificationLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a least-squares fit.

The objective fits y_i ~= sum_f w_f * x_if with binary coefficients selected to minimize :math:SSR = sum_i (y_i - sum_f w_f x_if)^2. Expanding the square turns the problem into a real quadratic binary QUBO whose linear coefficients are sum_i x_if^2 - 2 sum_i y_i x_if and whose pairwise coefficients are 2 sum_i x_if x_ig (diagonal terms fold into the linear part because w_f^2 = w_f). No training is performed; the targets are the supplied numeric class labels.

HyperparameterObjective dataclass

Bases: MLObjective

Maximize the total gain of the selected hyperparameter choices.

The one-hot objective sum_{p,c} gain_{p,c} * h_{p,c} is translated as a Qubit MAXIMIZE objective over the per-parameter choice variables. The search space is deterministic and finite (supplied choices only); no search heuristic is involved.

MLClusteringDistanceObjective dataclass

Bases: MLObjective

Delegated clustering distance objective (QMQ-09 Data layer).

Converted into the Data ClusteringDistanceObjective at formulation time; clustering runs as a real quadratic binary QUBO.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

MLFeatureSelectionObjective dataclass

Bases: MLObjective

Combined utility-minus-cost objective for delegated feature selection.

Delegated to the QMQ-09 Data layer: converted into a Data FeatureSelectionObjective (utility minus penalty * cost) at formulation time.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

MLObjective dataclass

Base class of all ML objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

ML-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_data_objective(problem=None)

Translate into a QMQ-09 data objective (delegated objectives only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

ModelSelectionObjective dataclass

Bases: MLObjective

Minimize the selected candidate's validation_loss + complexity_penalty.

The one-hot objective sum_c (loss_c + penalty_c) * s_c is translated as a Qubit MINIMIZE objective over the candidate variables. Candidate metrics are supplied by the caller; no training is performed.

RegressionLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a regression fit.

Identical expansion to :class:ClassificationLossObjective; the targets are continuous response values instead of class labels.

MLOptimizationConfiguration dataclass

Execution/optimization configuration of an ML problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
MLValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

MLOptimizer

Solves and benchmarks :class:MLProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the ML adapter (delegating feature selection and clustering to the QMQ-09 Data adapter), workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the ML layer.

solve(problem, *, strategy=None, config=None)

Solve an ML problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into an ML domain solution with ML metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
MLValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark an ML problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem MLProblem

The ML problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config MLOptimizationConfiguration | None

Optional execution/optimization configuration.

None
mapping(problem)

Return the deterministic ML variable mapping of a problem.

MLProblem dataclass

Domain problem of the AI/ML Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset MLDataSet | None

The ordered ML dataset (required for classification, regression, feature selection and clustering; optional for model selection and hyperparameter optimization).

None
problem_type MLProblemType

Family (:class:MLProblemType).

CLASSIFICATION
objectives list[MLObjective]

Ordered list of ML objectives (names must be unique).

list()
constraints list[MLConstraint]

Ordered list of ML constraints (names must be unique).

list()
context MLContext | None

Optional ML context (purpose / strategy intent).

None
candidates list[MLModelCandidate]

Ordered model-selection candidates (model selection only).

list()
hyperparameters list[MLHyperparameter]

Ordered hyperparameter space (hyperparameter optimization only).

list()
k int | None

Number of clusters (clustering only).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
MLValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a dataset/candidate/parameters configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

hyperparameter_choice_counts property

Return per-hyperparameter choice counts in deterministic order.

feature_variables()

Return the binary coefficient variables w0 .. w{n-1} in feature order.

selection_variables()

Return the one-hot model-selection variables s0 .. s{n-1}.

hyperparameter_variables()

Return the one-hot hyperparameter choice variables (parameter-major).

decision_variables()

Return the deterministic decision-variable list for this problem.

Fitting problems yield one binary variable per feature, model selection one binary variable per candidate and hyperparameter problems one binary variable per (parameter, choice) pair in parameter-major order. Feature-selection and clustering problems are delegated to the QMQ-09 Data layer and expose no ML variables here.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:MLValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

MLProblemType

Bases: Enum

Supported AI/ML problem families.

Attributes:

Name Type Description
CLASSIFICATION

Binary-coefficient least-squares classifier fit.

REGRESSION

Binary-coefficient least-squares regression fit.

FEATURE_SELECTION

Binary selection of a feature subset (delegated to the QMQ-09 Data layer).

MODEL_SELECTION

One-hot selection of one candidate model.

HYPERPARAMETER_OPTIMIZATION

One-hot choice per hyperparameter.

CLUSTERING

Assignment of records to k clusters (delegated to the QMQ-09 Data layer).

parse(value) classmethod

Coerce a name or member to a :class:MLProblemType.

ClassificationSolution dataclass

Bases: MLBaseSolution

Solution of a classification (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

HyperparameterSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot hyperparameter optimization problem.

Attributes:

Name Type Description
selected_choices dict[str, Any]

Hyperparameter name -> selected choice value.

MLBaseSolution dataclass

Common domain fields of every ML solution.

Decision fields are derived from the deterministic ML mapping, so they always reflect the feature/candidate/hyperparameter order of the problem. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

MLFeatureSelectionSolution dataclass

Bases: MLBaseSolution

Wrapper solution of a delegated feature-selection problem (QMQ-09).

Attributes:

Name Type Description
selected_features list[str]

Selected feature names in feature order.

selected_utility float

Total utility of the selected features.

selection_cost float

Total cost of the selected features.

from_data_solution(problem, solution) classmethod

Build the ML wrapper from a delegated QMQ-09 DataSolution.

MLOptimizationResult dataclass

Result of an ML solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult). The solution is an ML domain solution or, for delegated clustering, the QMQ-09 DataSolution.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

ModelSelectionSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot model-selection problem.

Attributes:

Name Type Description
selected_model_id str

Identifier of the selected candidate.

RegressionSolution dataclass

Bases: MLBaseSolution

Solution of a regression (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

ml_all_examples()

Run every canonical example and return the produced artifacts.

ml_classification_example()

Example A — binary-coefficient least-squares classification.

The optimum activates all three features (f0, f1, f2) with a residual sum of squares of exactly 3.0.

ml_clustering_example()

Example F — delegated QMQ-09 k=2 clustering.

Uses the classic QMQ-09 geometry: clusters {r0, r2} and {r1, r3} with a total within-cluster distance of approximately 8.2156.

ml_dataset_example()

The canonical QMQ-10 dataset: 4 records over 3 features (f0..f2).

ml_feature_selection_example()

Example C — delegated QMQ-09 feature selection.

Utilities {f0: 3, f1: 5, f2: 2} with unit costs and a maximum of two features; the optimum selection is {f0, f1} with utility 8.0.

ml_hyperparameter_example()

Example E — one-hot per-parameter hyperparameter choice.

learning_rate gains (0.8, 1.5, 1.2) and depth gains (0.9, 1.8, 1.4); the optimum total gain is 1.5 + 1.8 = 3.3.

ml_model_selection_example()

Example D — one-hot model selection.

Candidate objectives validation_loss + complexity_penalty: M1 3.4, M2 2.9, M3 3.1, M4 2.8, so the optimum selects M4 with objective 2.8.

ml_regression_example()

Example B — regression variant of the same least-squares objective.

constraints

ML-domain constraints of the QMQ-10 AI/ML Intelligence layer.

Constraints translate the domain fitting, model-selection and hyperparameter-selection semantics into QMQ-01 :class:Constraint instances with symbolic expressions over the deterministic ML variable naming conventions.

Supported families:

  • :class:MLCoefficientCountConstraint — bound the number of non-zero fitting coefficients (classification / regression),
  • :class:ModelSelectionOneHotConstraint — exactly one candidate is selected (equality sum = 1),
  • :class:HyperparameterOnePerParameterConstraint — exactly one choice is selected per hyperparameter,
  • :class:MLFeatureCountConstraint — bound the number of selected features (delegated to QMQ-09 Data layer),
  • :class:MLAssignmentConstraint — every record is assigned to exactly one cluster (delegated to QMQ-09 Data layer),
  • :class:MLClusterCountConstraint — bound per-cluster record counts (delegated to QMQ-09 Data layer).
MLConstraint dataclass

Base class of all ML constraints.

domain property

ML-domain label of this constraint.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_constraints(problem)

Translate into QMQ core :class:Constraint instances.

to_data_constraint(problem=None)

Translate into a QMQ-09 data constraint (delegated constraints only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a constraint from :meth:to_dict output.

MLCoefficientCountConstraint dataclass

Bases: MLConstraint

Bound the total number of selected fitting coefficients.

Parameters:

Name Type Description Default
name str

Constraint name.

required
min_coefficients float

Minimum number of non-zero coefficients (>= 0).

1.0
max_coefficients float | None

Maximum number of non-zero coefficients (None = unbounded).

None
description str

Free-form description.

''
ModelSelectionOneHotConstraint dataclass

Bases: MLConstraint

Exactly one candidate is selected (sum_c s_c = 1).

HyperparameterOnePerParameterConstraint dataclass

Bases: MLConstraint

Exactly one choice per hyperparameter (sum_c h_{p,c} = 1 per p).

MLFeatureCountConstraint dataclass

Bases: MLConstraint

Bound the number of selected features (delegated to QMQ-09).

Converted into a Data FeatureCountConstraint at formulation time.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLAssignmentConstraint dataclass

Bases: MLConstraint

Delegated: every record assigned to exactly one cluster.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

MLClusterCountConstraint dataclass

Bases: MLConstraint

Delegated: bound per-cluster record counts.

to_data_constraint(problem=None)

Return the equivalent QMQ-09 Data constraint.

constraint_from_dict(data)

Rebuild any supported ML constraint from :meth:to_dict output.

context

QMQ-10 ML context and domain-context mapping.

:class:MLContext captures the domain intent behind an ML problem (purpose, subdomain, an optional preferred computation strategy and modelling assumptions). It maps onto the QMQ-01 :class:DomainContext used by the formulation and workflow layers through :meth:MLContext.to_domain_context.

MLContext dataclass

ML-domain context of an ML problem.

Parameters:

Name Type Description Default
purpose str

Free-form purpose label (e.g. "classification", "model_selection", "hyperparameter_optimization").

''
subdomain str

Domain subdomain (e.g. "tabular").

'tabular'
preferred_strategy str

Optional preferred computation strategy label; validated against the existing strategy vocabulary when not empty.

''
assumptions dict[str, Any]

Free-form modelling assumptions (JSON-safe).

dict()
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_domain_context()

Return the QMQ-01 domain context used by the formulation layers.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a context from :meth:to_dict output.

errors

Error taxonomy of the QuantsMind Quantum AI/ML Intelligence layer.

QMQ-10 errors subclass :class:ValueError so that existing generic except ValueError handling in the workflow and formulation layers keeps working. :class:MLValidationError is the structured validation error raised by the ML models and the formulation adapter.

MLError

Bases: ValueError

Base error of the QuantsMind Quantum AI/ML Intelligence layer.

MLValidationError

Bases: MLError

Raised when an ML model or problem fails domain validation.

examples

Canonical QMQ-10 AI/ML Intelligence examples.

Every example is built exclusively from supplied, deterministic data and never requires microquantum at import time. Examples A–F:

A. :func:ml_classification_example — binary-coefficient least-squares classification (known optimum SSR 3.0, all three features active), B. :func:ml_regression_example — regression variant of the same dataset (same optimum 3.0), C. :func:ml_feature_selection_example — delegated QMQ-09 selection (optimum {f0, f1}, utility 8.0), D. :func:ml_model_selection_example — one-hot model selection (optimum candidate M4, objective 2.8), E. :func:ml_hyperparameter_example — one-hot hyperparameter choice (optimum total gain 3.3), F. :func:ml_clustering_example — delegated QMQ-09 k=2 clustering of the classic geometry (clusters {r0, r2} and {r1, r3}).

ml_dataset_example()

The canonical QMQ-10 dataset: 4 records over 3 features (f0..f2).

ml_classification_example()

Example A — binary-coefficient least-squares classification.

The optimum activates all three features (f0, f1, f2) with a residual sum of squares of exactly 3.0.

ml_regression_example()

Example B — regression variant of the same least-squares objective.

ml_feature_selection_example()

Example C — delegated QMQ-09 feature selection.

Utilities {f0: 3, f1: 5, f2: 2} with unit costs and a maximum of two features; the optimum selection is {f0, f1} with utility 8.0.

ml_model_selection_example()

Example D — one-hot model selection.

Candidate objectives validation_loss + complexity_penalty: M1 3.4, M2 2.9, M3 3.1, M4 2.8, so the optimum selects M4 with objective 2.8.

ml_hyperparameter_example()

Example E — one-hot per-parameter hyperparameter choice.

learning_rate gains (0.8, 1.5, 1.2) and depth gains (0.9, 1.8, 1.4); the optimum total gain is 1.5 + 1.8 = 3.3.

ml_clustering_example()

Example F — delegated QMQ-09 k=2 clustering.

Uses the classic QMQ-09 geometry: clusters {r0, r2} and {r1, r3} with a total within-cluster distance of approximately 8.2156.

ml_all_examples()

Run every canonical example and return the produced artifacts.

formulation

ML -> QMQ formulation adapter.

:class:MLFormulationAdapter converts a validated :class:~quantsmind.quantum.ml.problem.MLProblem into the existing QMQ pipeline: a :class:QuantumProblem (consumed unchanged by the existing :func:~quantsmind.quantum.formulation.formulate and QUBO mapper). It preserves objective senses, the deterministic variable naming conventions, constraint bounds, feature/record orderings and JSON-safe ML provenance metadata.

Feature-selection and clustering problems are delegated to the QMQ-09 Data layer: the adapter constructs a DataProblem from the same ML dataset and runs it through DataFormulationAdapter, so the quantum formulation, QUBO mapping and solution decoding of the Data layer are reused end-to-end (provenance records source_domain="data").

MLFormulationAdapter

Converts ML problems into the existing QMQ formulation.

The conversion is deterministic: decision variables follow the w<i> (fitting), s<c> (model selection) and h{p}_{c} (hyperparameter) conventions, objectives keep their senses, and every ML constraint materializes into QMQ constraints. Feature selection and clustering delegate to the QMQ-09 Data layer.

validate(problem)

Return the validation issues of an ML problem (empty = valid).

raise_if_invalid(problem)

Raise :class:MLValidationError when the problem is invalid.

Raises:

Type Description
MLValidationError

If the problem fails validation.

is_delegated(problem)

Return whether the problem is delegated to the QMQ-09 Data layer.

ml_metadata(problem)

JSON-safe ML provenance metadata for the quantum problem.

to_data_problem(problem)

Build the delegated QMQ-09 DataProblem of an ML problem.

Feature selection converts MLFeatureSelectionObjective and MLFeatureCountConstraint into their Data equivalents; clustering converts the ML clustering objective/constraints (with default assignment semantics when absent).

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem (feature selection or clustering).

required

Raises:

Type Description
MLValidationError

If the problem is not a delegated family or cannot be expressed by the Data layer.

to_quantum_problem(problem, *, preferred_strategy=None)

Convert an ML problem into a QMQ :class:QuantumProblem.

Parameters:

Name Type Description Default
problem MLProblem

The validated ML problem.

required
preferred_strategy Any

Optional preferred computation strategy.

None

Raises:

Type Description
MLValidationError

If the ML problem is invalid.

formulate(problem)

Return the existing QMQ formulation of an ML problem.

Delegates to the existing :func:quantsmind.quantum.formulation .formulate, producing an :class:OptimizationModel (or another :class:MathematicalModel selected by the existing rules).

mapping

QMQ-10 ML-domain mappings.

The mapper translates the domain ML variable naming conventions (w<i> for fitting coefficients, s<c> for model selection, h{p}_{c} for hyperparameter choices) into a deterministic :class:MLMapping that decodes QMQ assignments back into domain-readable decisions.

Feature-selection and clustering problems are delegated: their mapping and decoding are performed by the QMQ-09 Data mapper on the delegated DataProblem.

DecodedMLCoefficient dataclass

One decoded fitting-coefficient decision.

Attributes:

Name Type Description
feature_name str

Domain feature name.

index int

Deterministic feature index.

variable_name str

QMQ variable name (w<i>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedModelSelection dataclass

One decoded model-selection decision.

Attributes:

Name Type Description
model_id str

Domain candidate identifier.

index int

Deterministic candidate index.

variable_name str

QMQ variable name (s<c>).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

DecodedHyperparameterChoice dataclass

One decoded hyperparameter-choice decision.

Attributes:

Name Type Description
parameter_name str

Domain hyperparameter name.

param_index int

Deterministic parameter index.

choice_index int

Deterministic choice index.

choice_value Any

The concrete choice value (JSON-safe).

variable_name str

QMQ variable name (h{p}_{c}).

value float

Raw assignment value (0.0 or 1.0).

selected bool

Whether the value exceeds the selection threshold.

MLMapping dataclass

Deterministic mapping between ML variables and QMQ indices.

Created by :meth:MLMapper.map from a validated :class:MLProblem.

variable_names property

QMQ variable names in deterministic order.

coefficient(feature_name)

Return the decoded coefficient for feature_name (or None).

candidate(model_id)

Return the decoded model selection for model_id (or None).

decode_assignments(assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

MLMapper dataclass

Maps a validated ML problem to a deterministic variable mapping.

Mirrors the :class:DataMapper pattern: validates, then provides :meth:map (which returns an :class:MLMapping) and :meth:decode_assignments (which directly returns decoded decisions).

map(problem)

Return the deterministic variable mapping of problem.

Raises:

Type Description
MLValidationError

If the problem is delegated to the QMQ-09 Data layer (use the Data mapper on the delegated problem).

decode_assignments(problem, assignments, *, selected_threshold=0.5)

Decode raw QMQ assignments into domain-readable decisions.

metrics

ML-metrics computation of the QMQ-10 AI/ML Intelligence layer.

:class:MLMetrics summarises the domain outcome of an ML solve: the sum of squared residuals of a fitting problem, the selected model's scores, the total gain of the selected hyperparameter configuration and the existing QMQ-05 constraint-violation counts. Computations are deterministic and reuse the QMQ-05 :func:constraint_violations accounting at the solution construction site (never recomputed ad hoc here).

MLMetrics dataclass

Deterministic outcome metrics of an ML solve.

Attributes:

Name Type Description
problem_type str

ML problem family ("classification", "regression", "model_selection" or "hyperparameter_optimization").

ssr float | None

Sum of squared residuals of the fitted linear model (fitting).

mse float | None

Mean squared error (ssr / num_records, fitting).

selected_feature_count int

Number of selected coefficients (fitting).

selected_model_id str

Selected candidate identifier (model selection).

selected_loss float | None

Validation loss of the selected candidate.

selected_penalty float | None

Complexity penalty of the selected candidate.

total_gain float | None

Total gain of the selected hyperparameter configuration.

objective_value float | None

Primary objective value decoded from the assignment.

constraint_violations int

Number of violated QMQ constraints.

constraint_violation_magnitude float

Aggregate violation magnitude.

metadata dict[str, Any]

Free-form metadata (JSON-safe).

compute(problem, assignments, *, selected_threshold=0.5, violation_count=0, violation_magnitude=0.0) classmethod

Compute deterministic metrics from raw QMQ assignments.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild metrics from :meth:to_dict output.

models

Core QMQ-10 AI/ML domain models.

The module owns the small/structured ML vocabulary consumed by every other ML layer component:

  • :class:MLFeature describes one numeric dimension of the ML dataset,
  • :class:MLRecord holds one observation (identifier + per-feature values + a numeric target),
  • :class:MLDataSet is the ordered, deterministic collection that the fitting, feature-selection and clustering problems are built from,
  • :class:MLModelCandidate carries caller-supplied validation loss and complexity penalty of one model-selection candidate,
  • :class:MLHyperparameter / :class:MLHyperparameterChoice carry the deterministic finite hyperparameter space with per-choice gains.

All models are JSON-safe through :meth:to_dict/:meth:from_dict and are deterministic: feature and record ordering is preserved and validated at construction time. Nothing here performs training, inference or hyperparameter search — the data is supplied, the search is the quantum optimization built by the formulation layer.

MLFeature dataclass

One numeric feature/dimension of an :class:MLDataSet.

Parameters:

Name Type Description Default
name str

Unique feature identifier.

required
kind str

Free-form feature kind (e.g. "numeric").

'numeric'
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a feature from :meth:to_dict output.

MLRecord dataclass

One observation inside an :class:MLDataSet.

Parameters:

Name Type Description Default
record_id str

Unique record identifier.

required
values dict[str, float]

Feature name -> value mapping.

dict()
target float

Numeric target value (a class index for classification, a continuous response for regression).

0.0
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
value(feature_name)

Return the value of feature_name (raises on unknown keys).

as_feature_vector(features)

Return values in deterministic features order.

Raises:

Type Description
MLValidationError

If a feature is missing from the record.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a record from :meth:to_dict output.

MLDataSet dataclass

Ordered collection of :class:MLFeature and :class:MLRecord.

Construction enforces unique feature names and unique record identifiers. Structural issues (missing/unknown/non-finite values, empty memberships) are reported by :meth:validate / :meth:raise_if_invalid without ever being raised at construction time.

Deterministic orderings exposed here (feature_names, record_ids, :meth:matrix) are the ordering contract for every ML problem.

Parameters:

Name Type Description Default
name str

Dataset identifier.

required
features list[MLFeature]

Ordered feature list.

list()
records list[MLRecord]

Ordered record list.

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
shape property

Return (feature_count, record_count).

feature_names property

Return feature names in deterministic order.

record_ids property

Return record identifiers in deterministic order.

__len__()

Number of records.

__iter__()

Iterate over records in deterministic order.

feature(name)

Return the :class:MLFeature with name.

record(record_id)

Return the :class:MLRecord with record_id.

index_of(record_id)

Return the deterministic record index of record_id.

targets()

Return target values in deterministic record order.

matrix()

Return rows (record order) of feature values (feature order).

Raises:

Type Description
MLValidationError

When a record is missing a feature (call :meth:raise_if_invalid first for friendly issues).

validate()

Return deterministic structural issues of the dataset.

Never raises; :meth:raise_if_invalid raises on a non-empty result.

raise_if_invalid()

Raise :class:MLValidationError with all structural issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a dataset from :meth:to_dict output.

MLModelCandidate dataclass

One model-selection candidate with caller-supplied validation scores.

Parameters:

Name Type Description Default
model_id str

Unique candidate identifier.

required
validation_loss float

Caller-supplied candidate validation loss (must be finite and non-negative).

0.0
complexity_penalty float

Caller-supplied complexity penalty (must be finite and non-negative).

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
objective()

Return validation_loss + complexity_penalty.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a candidate from :meth:to_dict output.

MLHyperparameterChoice dataclass

One choice of an :class:MLHyperparameter.

Parameters:

Name Type Description Default
value Any

The concrete choice value (free-form but JSON-safe, e.g. a float / string / int). Used only for reporting.

None
gain float

Caller-supplied non-negative gain of this choice. The hyperparameter objective maximizes the total gain of the chosen configuration.

0.0
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a choice from :meth:to_dict output.

MLHyperparameter dataclass

One hyperparameter with a deterministic finite choice space.

Parameters:

Name Type Description Default
name str

Unique hyperparameter name.

required
choices list[MLHyperparameterChoice]

Ordered choice list (at least one).

list()
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()
choice_count property

Number of choices.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a hyperparameter from :meth:to_dict output.

objectives

ML-domain objectives of the QMQ-10 AI/ML Intelligence layer.

Objectives operate on the domain variable names generated by the deterministic ML naming conventions (:mod:quantsmind.quantum.ml._expr) and are translated into :class:quantsmind.quantum.core.objective.Objective instances (MAXIMIZE / MINIMIZE Qubit) at formulation time.

Supported objective families:

  • :class:ClassificationLossObjective — minimize the sum of squared residuals of a binary-coefficient linear classifier fit,
  • :class:RegressionLossObjective — minimize the sum of squared residuals of a binary-coefficient linear regression fit (identical expansion; the two families differ in the target semantics: class indices vs continuous response),
  • :class:ModelSelectionObjective — minimize validation_loss + complexity_penalty of the selected candidate (one-hot),
  • :class:HyperparameterObjective — maximize the total gain of the selected choices (one-hot per hyperparameter),
  • :class:MLFeatureSelectionObjective / :class:MLClusteringDistanceObjective — delegated to the QMQ-09 Data layer at formulation time.

Every objective serializes through :meth:to_dict/:meth:from_dict and validates against a concrete :class:MLProblem (passed positionally so validation sees the dataset / problem type / candidates / k).

MLObjective dataclass

Base class of all ML objectives.

Subclasses override :attr:kind, :meth:validate and :meth:to_quantum_objective.

domain property

ML-domain label of this objective.

validate(problem)

Return deterministic validation issues for problem.

to_quantum_objective(problem)

Translate into the QMQ core :class:Objective (Qubit MAX/MIN).

to_data_objective(problem=None)

Translate into a QMQ-09 data objective (delegated objectives only).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an objective from :meth:to_dict output.

ClassificationLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a least-squares fit.

The objective fits y_i ~= sum_f w_f * x_if with binary coefficients selected to minimize :math:SSR = sum_i (y_i - sum_f w_f x_if)^2. Expanding the square turns the problem into a real quadratic binary QUBO whose linear coefficients are sum_i x_if^2 - 2 sum_i y_i x_if and whose pairwise coefficients are 2 sum_i x_if x_ig (diagonal terms fold into the linear part because w_f^2 = w_f). No training is performed; the targets are the supplied numeric class labels.

RegressionLossObjective dataclass

Bases: MLObjective

Minimize the sum of squared residuals of a regression fit.

Identical expansion to :class:ClassificationLossObjective; the targets are continuous response values instead of class labels.

ModelSelectionObjective dataclass

Bases: MLObjective

Minimize the selected candidate's validation_loss + complexity_penalty.

The one-hot objective sum_c (loss_c + penalty_c) * s_c is translated as a Qubit MINIMIZE objective over the candidate variables. Candidate metrics are supplied by the caller; no training is performed.

HyperparameterObjective dataclass

Bases: MLObjective

Maximize the total gain of the selected hyperparameter choices.

The one-hot objective sum_{p,c} gain_{p,c} * h_{p,c} is translated as a Qubit MAXIMIZE objective over the per-parameter choice variables. The search space is deterministic and finite (supplied choices only); no search heuristic is involved.

MLFeatureSelectionObjective dataclass

Bases: MLObjective

Combined utility-minus-cost objective for delegated feature selection.

Delegated to the QMQ-09 Data layer: converted into a Data FeatureSelectionObjective (utility minus penalty * cost) at formulation time.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

MLClusteringDistanceObjective dataclass

Bases: MLObjective

Delegated clustering distance objective (QMQ-09 Data layer).

Converted into the Data ClusteringDistanceObjective at formulation time; clustering runs as a real quadratic binary QUBO.

to_data_objective(problem=None)

Return the equivalent QMQ-09 Data objective.

objective_from_dict(data)

Rebuild any supported ML objective from :meth:to_dict output.

optimizer

Optimization entry point of the QMQ-10 AI/ML Intelligence layer.

:class:MLOptimizationConfiguration carries execution/optimization settings and :class:MLOptimizer solves or benchmarks :class:~quantsmind.quantum.ml.problem.MLProblem instances through the existing QMQ-03..05 pipeline — the classical exhaustive baseline (QMQ-05) and the workflow (QMQ-04). Feature-selection and clustering problems are delegated to the QMQ-09 :class:DataOptimizer end-to-end; the remaining families run as real quadratic binary problems through the existing QUBO formulation, QUBO mapping, workflow execution and interpretation. No second solver or algorithm exists for the ML layer.

MLOptimizationConfiguration dataclass

Execution/optimization configuration of an ML problem.

Parameters:

Name Type Description Default
preferred_strategy str | None

Preferred computation strategy (""/None means automatic). An explicit quantum-runtime strategy is honoured by the existing QMQ-03 selector with honest degradation when no quantum runtime is available.

None
algorithm str

Optional requested algorithm id (forwarded to the QMQ-03 recommender).

''
shots int

Shot count for quantum/hybrid legs.

1024
seed int | None

Optional RNG seed for reproducible runs.

None
solver_max_variables int

Variable cap of the classical exhaustive baseline (reused for state spaces of the workflow).

20
optimization_level int

0..3 optimization hint (recorded in metadata).

0
metadata dict[str, Any]

Free-form configuration metadata.

dict()

Raises:

Type Description
MLValidationError

If configuration values are invalid or an unknown strategy is requested.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a configuration from :meth:to_dict output.

MLOptimizer

Solves and benchmarks :class:MLProblem instances.

The optimizer is a thin wrapper over the existing QMQ-03..06 pipeline: formulation through the ML adapter (delegating feature selection and clustering to the QMQ-09 Data adapter), workflow execution (QMQ-04) with the classical exhaustive baseline, and interpretation (QMQ-06). No second quantum algorithm or solver exists for the ML layer.

solve(problem, *, strategy=None, config=None)

Solve an ML problem through the existing workflow pipeline.

The chosen strategy (explicit argument, else the configuration's preferred strategy, else the QMQ-03 automatic rule) is executed and the result is decoded into an ML domain solution with ML metrics, a QMQ-06 interpretation, and the underlying :class:SolutionReport.

Raises:

Type Description
MLValidationError

If the problem is invalid.

UnsupportedStrategyError

For a strategy the pipeline cannot execute (e.g. QUANTUM_INSPIRED).

benchmark(problem, *, strategy=None, known_optimum=None, runs=1, raise_on_error=False, config=None)

Benchmark an ML problem against the classical baseline (QMQ-05).

The baseline reuses the existing exhaustive solver. A failing strategy run is recorded as failed (honest) unless raise_on_error is set.

Parameters:

Name Type Description Default
problem MLProblem

The ML problem to benchmark.

required
strategy str | None

Strategy label to benchmark; defaults to the configuration's preferred strategy, else "classical".

None
known_optimum float | None

Optional known objective optimum for gap/ratio.

None
runs int

Number of repetitions (1 = single run).

1
raise_on_error bool

If True, raise instead of recording failures.

False
config MLOptimizationConfiguration | None

Optional execution/optimization configuration.

None
mapping(problem)

Return the deterministic ML variable mapping of a problem.

problem

ML problem representation of the QMQ-10 AI/ML Intelligence layer.

:class:MLProblem is the domain problem: an ordered :class:MLDataSet (fitting / feature selection / clustering families), optional objectives, optional constraints, the ML context, the model-selection candidates, the hyperparameter space and the clustering k. The deterministic :meth:MLProblem.decision_variables mapping (coefficients -> w<i>, model selection -> s<c>, hyperparameters -> h{p}_{c}) is the single contract shared by the formulation adapter, the mapper, execution and result layers. Feature selection and clustering are delegated to the QMQ-09 Data layer through a DataProblem built from the same dataset.

MLProblemType

Bases: Enum

Supported AI/ML problem families.

Attributes:

Name Type Description
CLASSIFICATION

Binary-coefficient least-squares classifier fit.

REGRESSION

Binary-coefficient least-squares regression fit.

FEATURE_SELECTION

Binary selection of a feature subset (delegated to the QMQ-09 Data layer).

MODEL_SELECTION

One-hot selection of one candidate model.

HYPERPARAMETER_OPTIMIZATION

One-hot choice per hyperparameter.

CLUSTERING

Assignment of records to k clusters (delegated to the QMQ-09 Data layer).

parse(value) classmethod

Coerce a name or member to a :class:MLProblemType.

MLProblem dataclass

Domain problem of the AI/ML Intelligence layer.

Parameters:

Name Type Description Default
name str

Problem identifier.

required
dataset MLDataSet | None

The ordered ML dataset (required for classification, regression, feature selection and clustering; optional for model selection and hyperparameter optimization).

None
problem_type MLProblemType

Family (:class:MLProblemType).

CLASSIFICATION
objectives list[MLObjective]

Ordered list of ML objectives (names must be unique).

list()
constraints list[MLConstraint]

Ordered list of ML constraints (names must be unique).

list()
context MLContext | None

Optional ML context (purpose / strategy intent).

None
candidates list[MLModelCandidate]

Ordered model-selection candidates (model selection only).

list()
hyperparameters list[MLHyperparameter]

Ordered hyperparameter space (hyperparameter optimization only).

list()
k int | None

Number of clusters (clustering only).

None
description str

Free-form description.

''
metadata dict[str, Any]

Free-form metadata (JSON-safe).

dict()

Raises:

Type Description
MLValidationError

On duplicate objective/constraint names, invalid problem-type hyper-parameters or a dataset/candidate/parameters configuration mix-up.

num_features property

Number of features of the underlying dataset.

num_records property

Number of records of the underlying dataset.

size property

Number of decision variables.

hyperparameter_choice_counts property

Return per-hyperparameter choice counts in deterministic order.

feature_variables()

Return the binary coefficient variables w0 .. w{n-1} in feature order.

selection_variables()

Return the one-hot model-selection variables s0 .. s{n-1}.

hyperparameter_variables()

Return the one-hot hyperparameter choice variables (parameter-major).

decision_variables()

Return the deterministic decision-variable list for this problem.

Fitting problems yield one binary variable per feature, model selection one binary variable per candidate and hyperparameter problems one binary variable per (parameter, choice) pair in parameter-major order. Feature-selection and clustering problems are delegated to the QMQ-09 Data layer and expose no ML variables here.

validate()

Return deterministic validation issues (never raises).

raise_if_invalid()

Raise :class:MLValidationError with all validation issues.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a problem from :meth:to_dict output.

solution

Solutions and results of the QMQ-10 AI/ML Intelligence layer.

Domain result classes translate a QMQ :class:~quantsmind.quantum.result.result.SolutionReport into readable ML decisions: fitted coefficients and predictions (classification/regression), the selected candidate, the selected hyperparameter configuration, or the delegated feature-selection selection set. They reuse the existing QMQ-05 constraint evaluation and QMQ-06 interpretation infrastructure. For delegated families (feature selection / clustering) the solution is either the QMQ-09 :class:DataSolution or the ML wrapper :class:MLFeatureSelectionSolution.

MLBaseSolution dataclass

Common domain fields of every ML solution.

Decision fields are derived from the deterministic ML mapping, so they always reflect the feature/candidate/hyperparameter order of the problem. Constraint compliance comes from the existing QMQ-05 metric helpers, never recomputed ad hoc.

ClassificationSolution dataclass

Bases: MLBaseSolution

Solution of a classification (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

RegressionSolution dataclass

Bases: MLBaseSolution

Solution of a regression (least-squares) problem.

Attributes:

Name Type Description
coefficients dict[str, float]

Feature name -> fitting coefficient (0.0 / 1.0).

predictions list[float]

Fitted response per record in record order.

selected_features property

Return the features with an active coefficient in feature order.

MLFeatureSelectionSolution dataclass

Bases: MLBaseSolution

Wrapper solution of a delegated feature-selection problem (QMQ-09).

Attributes:

Name Type Description
selected_features list[str]

Selected feature names in feature order.

selected_utility float

Total utility of the selected features.

selection_cost float

Total cost of the selected features.

from_data_solution(problem, solution) classmethod

Build the ML wrapper from a delegated QMQ-09 DataSolution.

ModelSelectionSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot model-selection problem.

Attributes:

Name Type Description
selected_model_id str

Identifier of the selected candidate.

HyperparameterSolution dataclass

Bases: MLBaseSolution

Solution of a one-hot hyperparameter optimization problem.

Attributes:

Name Type Description
selected_choices dict[str, Any]

Hyperparameter name -> selected choice value.

MLOptimizationResult dataclass

Result of an ML solve or benchmark.

report and benchmark are kept as in-memory composition references; serialization carries lightweight references (mirroring QMQ-05 :class:BenchmarkResult). The solution is an ML domain solution or, for delegated clustering, the QMQ-09 DataSolution.

to_dict()

Serialize to a JSON-safe dictionary (reports kept as references).

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

Composition references (report) are intentionally not rebuilt; the measured fields round-trip exactly.

ml_solution_from_report(problem, report, *, execution_time=None, selected_threshold=0.5)

Build the ML domain solution from a workflow :class:SolutionReport.

Decodes the decision-variable assignment through the deterministic ML mapping, computes ML metrics from the dataset and reuses the existing constraint-evaluation infrastructure for feasibility, constraint status and violation magnitude. Delegated families are not handled here (the optimizer uses the QMQ-09 data solution).

optimization

QMQ-02 optimization representations (expression, QUBO, Ising, baseline).

The optimization package provides the computational representations that the QMQ-01 domain foundation plugs into::

QuantumProblem
    -> OptimizationModel
    -> QUBOModel          (binary quadratic minimization)
    -> IsingModel         (spin form, energy-equivalent to the QUBO)
    -> quantum program / MicroQuantum
and, independently::

QUBOModel -> ExhaustiveSolver (classical baseline)

Nothing in this package imports microquantum; engine access stays in the integration layer.

ClassicalSolverResult dataclass

Result of an exhaustive classical run.

Parameters:

Name Type Description Default
solver str

Solver identity ("classical/exhaustive").

'classical/exhaustive'
exhaustive bool

Always True (this is an exhaustive baseline).

True
assignment dict[str, int]

Chosen binary assignment (variable name -> 0/1).

dict()
energy float

QUBO energy of the chosen assignment (minimization form, penalties included).

0.0
objective_value float | None

Optional true objective value of the assignment.

None
feasible bool

Whether the chosen assignment satisfies the predicate.

True
num_evaluations int

Number of enumerated assignments (2^n).

0
num_feasible int

Number of assignments satisfying the predicate.

0
limit int

The max_variables limit that was enforced.

0
metadata dict[str, Any]

Free-form solver metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

ExhaustiveLimitError

Bases: ValueError

Raised when exhaustive enumeration would exceed the configured limit.

ExhaustiveSolver

Deterministic exhaustive solver for small QUBOs.

Parameters:

Name Type Description Default
max_variables int

Upper bound on :attr:QUBOModel.num_variables. Enumeration of 2^n assignments is only attempted for n <= max_variables.

20
solve(qubo, *, is_feasible=None, objective_fn=None)

Enumerate all 2^n assignments and return the best feasible one.

The "best" assignment minimises the QUBO energy among feasible assignments. Assignment order is deterministic (Gray-code enumeration); ties keep the first-seen assignment.

Parameters:

Name Type Description Default
qubo QUBOModel

The model to solve.

required
is_feasible Callable[[dict[str, int]], bool] | None

Optional predicate deciding which assignments are feasible. When omitted, every assignment is feasible.

None
objective_fn Callable[[dict[str, int]], float] | None

Optional true-objective evaluator used only to populate :attr:ClassicalSolverResult.objective_value.

None

Raises:

Type Description
ExhaustiveLimitError

If qubo.num_variables > max_variables.

NoFeasibleSolutionError

If no assignment is feasible.

NoFeasibleSolutionError

Bases: ValueError

Raised when no assignment satisfies the feasibility predicate.

Constant dataclass

Bases: Expression

A literal numeric constant.

Expression dataclass

Base class of the symbolic expression tree.

Subclasses are immutable. Operator overloads construct new nodes, so 2 * x + 1 written against the returned Expression objects stays symbolic and never evaluates eagerly.

variables property

Variable names referenced by this expression (order of appearance).

evaluate(assignments)

Numerically evaluate the expression against variable assignments.

expand()

Expand into a canonical monomial map.

Keys are single variable names (linear) or tuples of variable names (products, duplicates preserved, sorted). The constant term is keyed by the empty tuple ().

ExpressionError

Bases: ValueError

Base error for symbolic expression problems.

ExpressionParseError

Bases: ExpressionError

Raised when an expression string cannot be parsed.

Product dataclass

Bases: Expression

A product of expressions.

Scale dataclass

Bases: Expression

A scalar multiple of an expression.

Sum dataclass

Bases: Expression

A sum of expressions (nested sums are flattened).

VariableExpression dataclass

Bases: Expression

A reference to a decision variable.

IsingError

Bases: ValueError

Raised when an Ising model is malformed or an operation is invalid.

IsingModel dataclass

A canonical Ising/spin model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered spin variable names.

required
h dict[str, float]

Variable name -> linear field h_i.

dict()
couplings dict[tuple[str, str], float]

(i, j) with i < j -> coupling J_ij.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only).

0.0
name str

Model label.

'ising'
metadata dict[str, Any]

Free-form model metadata.

dict()

Raises:

Type Description
IsingError

If variable names are duplicated, a field/coupling references an unknown variable, or a self-coupling is given.

num_variables property

Number of spin variables.

num_terms property

Number of field + coupling terms.

add_field(name, value)

Add (or accumulate) a field h_i and return self.

add_coupling(left, right, value)

Add (or accumulate) a coupling J_ij and return self.

energy(assignment)

Compute the Ising energy of a spin assignment.

assignment may be a dict name -> -1/+1 or a sequence of spins in :attr:variables order.

Raises:

Type Description
IsingError

If an assignment is missing, unknown, or not -1/+1.

to_qubo()

Convert to an energy-equivalent :class:QUBOModel via s = 2x - 1.

from_qubo(qubo) classmethod

Convert a QUBO to an energy-equivalent :class:IsingModel.

Applies x = (s + 1) / 2: h_i = a_i/2 + sum_j(b_ij)/4 and J_ij = b_ij/4.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an IsingModel from :meth:to_dict output.

ConstraintPenalizer

Converts supported constraints into exact QUBO penalty terms.

Parameters:

Name Type Description Default
penalty float | None

Positive penalty multiplier P. When None a default of 10.0 is used. The caller (typically the QUBO mapper) should scale P above the objective range so that violating a constraint can never be attractive.

None
penalize(constraint)

Return the QUBO penalty term expansion for a constraint.

Raises:

Type Description
UnsupportedConstraintError

For unsupported constraint types.

PenaltyTerm dataclass

One expanded QUBO penalty term for a constraint.

Parameters:

Name Type Description Default
constraint str

Name of the originating constraint.

required
operator str

Serialized operator ("==", "<=", ">=").

required
weight float

Penalty multiplier P.

required
linear dict[str, float]

Variable name -> linear coefficient.

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient.

dict()
constant float

Additive penalty constant.

0.0
slack_variables list[str]

Slack variables introduced for inequalities.

list()
expression str

Human-readable residual squared, e.g. "P = 10.0 * (2*x0 + 3*x1 - 5)^2".

''
to_dict()

Serialize to a JSON-safe dictionary.

UnsupportedConstraintError

Bases: ValueError

Raised when a constraint cannot be turned into a QUBO penalty.

QUBOError

Bases: ValueError

Raised when a QUBO is malformed or an operation is invalid.

QUBOModel dataclass

A canonical binary quadratic model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered variable names (one QUBO bit per variable).

required
linear dict[str, float]

Variable name -> linear coefficient (c_i).

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient (c_ij). Diagonal terms are rewritten into linear.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only; both constant and offset contribute to :meth:energy).

0.0
name str

Model label.

'qubo'
metadata dict[str, Any]

Free-form model metadata (e.g. penalty records).

dict()

Raises:

Type Description
QUBOError

If names are invalid/duplicated, a coefficient is not finite, a quadratic key is malformed (i == j or reversed hands accepted and canonicalised), or a quadratic references an unknown variable.

num_variables property

Number of QUBO variables (bits).

num_terms property

Number of linear + pairwise terms.

degree property

Polynomial degree (2 when pairwise terms exist, else 1).

add_linear(name, value)

Add (or accumulate) a linear coefficient and return self.

add_quadratic(left, right, value)

Add (or accumulate) a pairwise coefficient and return self.

Raises:

Type Description
QUBOError

If left == right (diagonal terms belong on linear for binary variables) or a variable is unknown.

add_constant(value)

Add to the constant term and return self.

energy(assignment)

Compute the QUBO energy of a binary assignment.

assignment may be a dict mapping variable name -> 0/1 or a sequence of bits in :attr:variables order.

Raises:

Type Description
QUBOError

If an assignment is missing, unknown, or not binary.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QUBOModel from :meth:to_dict output.

coerce_expression(value)

Coerce a number, string or Expression into an Expression.

Raises:

Type Description
ExpressionError

If value is a callable or an unsupported type. Callables cannot be introspected into monomials, so automatic QUBO/penalty formulation requires symbolic strings or nodes.

const(value)

Build a :class:Constant from a numeric value.

evaluate_expression(value, assignments)

Evaluate a number, string, Expression or callable.

Callables are called directly (this is the only path that executes user code); everything else goes through the safe symbolic evaluator.

parse_expression(text)

Parse a safe arithmetic expression string into an Expression tree.

Supported grammar: numbers, identifiers, + - * ( ), unary minus and integer powers via ** or ^. No eval() is used anywhere.

Raises:

Type Description
ExpressionParseError

If the text is not a valid expression.

var(name)

Build a :class:VariableExpression for name.

qubo_from_expression(expression, variables, *, name='qubo')

Build a QUBO from a symbolic expression over binary variables.

Linear monomials become linear terms, degree-two monomials become pairwise terms and the constant monomial becomes the constant term. Products that collapse to the same variable (x^2) are reduced via binary idempotence to linear terms. Terms of degree greater than two are rejected explicitly.

Raises:

Type Description
QUBOError

If the expression references an unknown variable or contains a term of degree greater than two.

classical

Deterministic classical baseline: exhaustive QUBO solving.

QuantsMind Quantum must eventually compare classical, quantum, hybrid and quantum-inspired execution paths. :class:ExhaustiveSolver is the QMQ-02 classical baseline: it enumerates every binary assignment of a small :class:~quantsmind.quantum.optimization.qubo.QUBOModel, computes the exact energy, honors an optional feasibility predicate, and returns the best feasible solution.

This is intentionally not a scalable optimizer. The enumeration space is 2^n and is bounded by :attr:ExhaustiveSolver.max_variables; exceeding the bound raises :class:ExhaustiveLimitError instead of accidentally running forever. The result identifies itself as classical/exhaustive so downstream reports never mistake it for a quantum or hybrid execution.

ExhaustiveLimitError

Bases: ValueError

Raised when exhaustive enumeration would exceed the configured limit.

NoFeasibleSolutionError

Bases: ValueError

Raised when no assignment satisfies the feasibility predicate.

ClassicalSolverResult dataclass

Result of an exhaustive classical run.

Parameters:

Name Type Description Default
solver str

Solver identity ("classical/exhaustive").

'classical/exhaustive'
exhaustive bool

Always True (this is an exhaustive baseline).

True
assignment dict[str, int]

Chosen binary assignment (variable name -> 0/1).

dict()
energy float

QUBO energy of the chosen assignment (minimization form, penalties included).

0.0
objective_value float | None

Optional true objective value of the assignment.

None
feasible bool

Whether the chosen assignment satisfies the predicate.

True
num_evaluations int

Number of enumerated assignments (2^n).

0
num_feasible int

Number of assignments satisfying the predicate.

0
limit int

The max_variables limit that was enforced.

0
metadata dict[str, Any]

Free-form solver metadata.

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a result from :meth:to_dict output.

ExhaustiveSolver

Deterministic exhaustive solver for small QUBOs.

Parameters:

Name Type Description Default
max_variables int

Upper bound on :attr:QUBOModel.num_variables. Enumeration of 2^n assignments is only attempted for n <= max_variables.

20
solve(qubo, *, is_feasible=None, objective_fn=None)

Enumerate all 2^n assignments and return the best feasible one.

The "best" assignment minimises the QUBO energy among feasible assignments. Assignment order is deterministic (Gray-code enumeration); ties keep the first-seen assignment.

Parameters:

Name Type Description Default
qubo QUBOModel

The model to solve.

required
is_feasible Callable[[dict[str, int]], bool] | None

Optional predicate deciding which assignments are feasible. When omitted, every assignment is feasible.

None
objective_fn Callable[[dict[str, int]], float] | None

Optional true-objective evaluator used only to populate :attr:ClassicalSolverResult.objective_value.

None

Raises:

Type Description
ExhaustiveLimitError

If qubo.num_variables > max_variables.

NoFeasibleSolutionError

If no assignment is feasible.

expression

Lightweight, safe symbolic expressions for QUBO/Ising formulation.

QMQ-02 introduces a small expression model sufficient to represent and evaluate the quadratic polynomials used by objectives, constraints, penalties and QUBO/Ising forms. It supports constants, variables, addition, subtraction, multiplication and integer powers.

This is deliberately not a symbolic algebra system: there is no simplification engine, no differentiation and no transcendental functions. The value is reliable representation and evaluation without eval().

The canonical expansion :meth:Expression.expand reduces an expression to a dict of monomials ((variable, ...) -> coefficient) with sorted keys and a constant entry in the empty tuple. A product of two occurrences of x produces the monomial ("x", "x") so binary idempotence (x^2 = x) can be applied by a later QUBO phase — it is not applied here.

ExpressionError

Bases: ValueError

Base error for symbolic expression problems.

ExpressionParseError

Bases: ExpressionError

Raised when an expression string cannot be parsed.

Expression dataclass

Base class of the symbolic expression tree.

Subclasses are immutable. Operator overloads construct new nodes, so 2 * x + 1 written against the returned Expression objects stays symbolic and never evaluates eagerly.

variables property

Variable names referenced by this expression (order of appearance).

evaluate(assignments)

Numerically evaluate the expression against variable assignments.

expand()

Expand into a canonical monomial map.

Keys are single variable names (linear) or tuples of variable names (products, duplicates preserved, sorted). The constant term is keyed by the empty tuple ().

Constant dataclass

Bases: Expression

A literal numeric constant.

VariableExpression dataclass

Bases: Expression

A reference to a decision variable.

Scale dataclass

Bases: Expression

A scalar multiple of an expression.

Sum dataclass

Bases: Expression

A sum of expressions (nested sums are flattened).

Product dataclass

Bases: Expression

A product of expressions.

var(name)

Build a :class:VariableExpression for name.

const(value)

Build a :class:Constant from a numeric value.

coefficient(value, expression)

Build a scalar multiple value * expression.

coerce_expression(value)

Coerce a number, string or Expression into an Expression.

Raises:

Type Description
ExpressionError

If value is a callable or an unsupported type. Callables cannot be introspected into monomials, so automatic QUBO/penalty formulation requires symbolic strings or nodes.

parse_expression(text)

Parse a safe arithmetic expression string into an Expression tree.

Supported grammar: numbers, identifiers, + - * ( ), unary minus and integer powers via ** or ^. No eval() is used anywhere.

Raises:

Type Description
ExpressionParseError

If the text is not a valid expression.

evaluate_expression(value, assignments)

Evaluate a number, string, Expression or callable.

Callables are called directly (this is the only path that executes user code); everything else goes through the safe symbolic evaluator.

ising

Spin (Ising) models and QUBO <-> Ising conversion.

An :class:IsingModel represents the minimization over spins s_i in {-1, +1} of::

minimize  sum(h_i * s_i) + sum(J_ij * s_i * s_j) + constant + offset

Conversion uses the standard mapping x = (s + 1) / 2 (equivalently s = 2x - 1). The two representations are energy equivalent: for the same assignment E_qubo(x) == E_ising(s(x)) with no energy drift, because all constant contributions are carried exactly through the conversion. The ::ref:tests <QMIO> verify this numerically over small exhaustive spaces.

IsingError

Bases: ValueError

Raised when an Ising model is malformed or an operation is invalid.

IsingModel dataclass

A canonical Ising/spin model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered spin variable names.

required
h dict[str, float]

Variable name -> linear field h_i.

dict()
couplings dict[tuple[str, str], float]

(i, j) with i < j -> coupling J_ij.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only).

0.0
name str

Model label.

'ising'
metadata dict[str, Any]

Free-form model metadata.

dict()

Raises:

Type Description
IsingError

If variable names are duplicated, a field/coupling references an unknown variable, or a self-coupling is given.

num_variables property

Number of spin variables.

num_terms property

Number of field + coupling terms.

add_field(name, value)

Add (or accumulate) a field h_i and return self.

add_coupling(left, right, value)

Add (or accumulate) a coupling J_ij and return self.

energy(assignment)

Compute the Ising energy of a spin assignment.

assignment may be a dict name -> -1/+1 or a sequence of spins in :attr:variables order.

Raises:

Type Description
IsingError

If an assignment is missing, unknown, or not -1/+1.

to_qubo()

Convert to an energy-equivalent :class:QUBOModel via s = 2x - 1.

from_qubo(qubo) classmethod

Convert a QUBO to an energy-equivalent :class:IsingModel.

Applies x = (s + 1) / 2: h_i = a_i/2 + sum_j(b_ij)/4 and J_ij = b_ij/4.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an IsingModel from :meth:to_dict output.

penalties

Constraint -> QUBO penalty transformation (QMQ-02).

Supported constraint classes (over binary variables x_i in {0,1}):

  • equality sum(c_i * x_i) + c0 == value -> P * (lhs - value)^2
  • inequality sum(c_i * x_i) + c0 <= value -> equality with slack bits P * (sum(c_i*x_i) + sum(2^j * s_j) - (value - c0))^2 where the slack bits cover every achievable deficit. This requires integer coefficients (the deficits are integers); non-integer inequalities are rejected explicitly because a penalty would be mathematically incorrect.
  • greater-or-equal is reduced to a <= constraint by negating all coefficients and the right-hand side (the reduced form may again require integer coefficients).

Unsupported constraint types (callable expressions, unknown operators, quantities of degree > 1, or unsatisfiable inequalities) fail with :class:UnsupportedConstraintError — never with a silent, wrong mapping.

UnsupportedConstraintError

Bases: ValueError

Raised when a constraint cannot be turned into a QUBO penalty.

PenaltyTerm dataclass

One expanded QUBO penalty term for a constraint.

Parameters:

Name Type Description Default
constraint str

Name of the originating constraint.

required
operator str

Serialized operator ("==", "<=", ">=").

required
weight float

Penalty multiplier P.

required
linear dict[str, float]

Variable name -> linear coefficient.

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient.

dict()
constant float

Additive penalty constant.

0.0
slack_variables list[str]

Slack variables introduced for inequalities.

list()
expression str

Human-readable residual squared, e.g. "P = 10.0 * (2*x0 + 3*x1 - 5)^2".

''
to_dict()

Serialize to a JSON-safe dictionary.

ConstraintPenalizer

Converts supported constraints into exact QUBO penalty terms.

Parameters:

Name Type Description Default
penalty float | None

Positive penalty multiplier P. When None a default of 10.0 is used. The caller (typically the QUBO mapper) should scale P above the objective range so that violating a constraint can never be attractive.

None
penalize(constraint)

Return the QUBO penalty term expansion for a constraint.

Raises:

Type Description
UnsupportedConstraintError

For unsupported constraint types.

qubo

Binary quadratic programming (QUBO) models.

A :class:QUBOModel represents the minimization problem::

minimize  x^T Q x + linear . x + constant + offset
x in {0, 1}^n

using named variables, linear coefficients, pairwise (quadratic) coefficients and an additive constant. Pairwise terms are canonicalised to i < j so every model has a single deterministic representation. For binary variables the identity x_i^2 = x_i is applied eagerly when a diagonal term is supplied, and supplying a diagonal term via the quadratic interface is rejected rather than silently miscounted.

QUBOError

Bases: ValueError

Raised when a QUBO is malformed or an operation is invalid.

QUBOModel dataclass

A canonical binary quadratic model to be minimised.

Parameters:

Name Type Description Default
variables list[str]

Ordered variable names (one QUBO bit per variable).

required
linear dict[str, float]

Variable name -> linear coefficient (c_i).

dict()
quadratic dict[tuple[str, str], float]

(i, j) with i < j -> pairwise coefficient (c_ij). Diagonal terms are rewritten into linear.

dict()
constant float

Additive constant term.

0.0
offset float

Additional additive shift (bookkeeping only; both constant and offset contribute to :meth:energy).

0.0
name str

Model label.

'qubo'
metadata dict[str, Any]

Free-form model metadata (e.g. penalty records).

dict()

Raises:

Type Description
QUBOError

If names are invalid/duplicated, a coefficient is not finite, a quadratic key is malformed (i == j or reversed hands accepted and canonicalised), or a quadratic references an unknown variable.

num_variables property

Number of QUBO variables (bits).

num_terms property

Number of linear + pairwise terms.

degree property

Polynomial degree (2 when pairwise terms exist, else 1).

add_linear(name, value)

Add (or accumulate) a linear coefficient and return self.

add_quadratic(left, right, value)

Add (or accumulate) a pairwise coefficient and return self.

Raises:

Type Description
QUBOError

If left == right (diagonal terms belong on linear for binary variables) or a variable is unknown.

add_constant(value)

Add to the constant term and return self.

energy(assignment)

Compute the QUBO energy of a binary assignment.

assignment may be a dict mapping variable name -> 0/1 or a sequence of bits in :attr:variables order.

Raises:

Type Description
QUBOError

If an assignment is missing, unknown, or not binary.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QUBOModel from :meth:to_dict output.

qubo_from_expression(expression, variables, *, name='qubo')

Build a QUBO from a symbolic expression over binary variables.

Linear monomials become linear terms, degree-two monomials become pairwise terms and the constant monomial becomes the constant term. Products that collapse to the same variable (x^2) are reduced via binary idempotence to linear terms. Terms of degree greater than two are rejected explicitly.

Raises:

Type Description
QUBOError

If the expression references an unknown variable or contains a term of degree greater than two.

program

Declarative, vendor-neutral quantum programs.

QuantumProgram is the QuantsMind-facing description of a quantum program: an ordered list of :class:GateSpec operations on a fixed number of qubits. It deliberately contains no execution logic — it is a translation input. The actual circuit construction, simulation and execution are delegated to MicroQuantum by :mod:quantsmind.quantum.bridge.

GateSpec dataclass

A single gate operation on named qubits.

Parameters:

Name Type Description Default
name str

Gate name ("h", "x", "cx", "rx", ...).

required
qubits tuple[int, ...]

Qubit indices the gate acts on (1 or 2 entries).

required
params tuple[float, ...]

Optional numeric rotation parameters ((theta,) for rx).

()
from_tuple(name, qubits, *params) classmethod

Build a GateSpec from positional parts.

to_dict()

Serialize to a JSON-safe dictionary.

QuantumProgram dataclass

A declarative quantum program for translation to MicroQuantum.

Parameters:

Name Type Description Default
num_qubits int

Fixed number of qubits.

required
operations list[GateSpec]

Ordered gate operations.

list()
name str

Optional program label (used for provenance).

'program'
metadata dict[str, Any]

Optional domain metadata attached to the program.

dict()
num_operations property

Number of gate operations in the program.

gate_names property

Ordered gate names, for quick inspection.

add(name, qubits, *params)

Append a gate operation and return self (fluent).

add_gate(spec)

Append a pre-built GateSpec and return self.

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a QuantumProgram from :meth:to_dict output.

bell_state() classmethod

Convenience constructor for a 2-qubit Bell state program.

result

Result layer of QuantsMind Quantum.

Contains the domain-level :class:SolutionReport, data-derived :class:Interpretation and :class:Provenance models, and the QMQ-06 structured result interpretation (:class:ResultInterpreter / :class:ResultInterpretation). The low-level enriched circuit result (:class:QuantumResult) lives in :mod:quantsmind.quantum.circuit_result.

Interpretation dataclass

A structured, data-derived explanation of a solution.

Parameters:

Name Type Description Default
summary str

One-line human-readable summary.

''
quality InterpretationQuality

Feasibility/evidence quality level.

UNKNOWN
confidence float | None

Optional numeric confidence in [0, 1].

None
details dict[str, Any]

Free-form facts (feasible, objective values, statuses).

dict()
metadata dict[str, Any]

Free-form metadata (e.g. strategy used).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Interpretation from :meth:to_dict output.

InterpretationQuality

Bases: Enum

Overall confidence in a solution interpretation.

Attributes:

Name Type Description
HIGH

Fully evaluated and feasible.

MEDIUM

Partially evaluated (some constraints unknown).

LOW

Infeasible (one or more constraints violated).

UNKNOWN

Nothing could be evaluated.

SolutionInterpreter

Produces conservative, data-derived interpretations of solutions.

The interpreter derives its statements only from the solution itself (feasibility, objective values, constraint statuses, score) and the strategy that produced it. No domain meaning is invented.

interpret(solution, *, strategy=None)

Interpret a solution using only its own data.

Parameters:

Name Type Description Default
solution ProblemSolution

The domain solution to interpret.

required
strategy ComputationStrategy | str | None

Optional computation strategy used (recorded as metadata only).

None

Returns:

Name Type Description
An Interpretation

class:Interpretation constructed from solution facts.

__call__(solution, *, strategy=None)

Convenience alias for :meth:interpret.

Provenance dataclass

Where-and-how metadata attached to a domain result.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Computation strategy used.

None
formulation str

Formulation kind (e.g. "optimization").

''
algorithm str

Algorithm used (e.g. "vqe", "grover", "qaoa", "exhaustive") or "".

''
executor str

Executor identity (e.g. "classical/exhaustive", "microquantum/qaoa") or "".

''
backend str

Backend that executed the workflow or "".

''
execution_metadata dict[str, Any]

Metadata from the execution layer (experiment id, actual backend, shots, counts-derived summary).

dict()
sdk_version str

QuantsMind SDK version that produced the result.

_sdk_version()
created_at str

UTC ISO timestamp of record creation.

(lambda: isoformat())()
metadata dict[str, Any]

Free-form provenance metadata.

dict()
strategy_label property

Serialized strategy label (e.g. "hybrid").

from_execution(*, strategy=None, formulation='', algorithm='', executor='', backend='', execution=None, metadata=None) classmethod

Build provenance, deriving execution metadata from a result.

execution may be any object exposing experiment_id, program_name, backend_name, shots and provenance attributes (e.g. a :class:~quantsmind.quantum.circuit_result.QuantumResult), or a QMQ-02 executor result exposing solver/energy (e.g. :class:~quantsmind.quantum.optimization.classical.ClassicalSolverResult or :class:~quantsmind.quantum.integration.microquantum.QaoaExecutionResult).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Provenance from :meth:to_dict output.

SolutionReport dataclass

Complete record of one workflow run for a domain problem.

Parameters:

Name Type Description Default
problem QuantumProblem | None

The problem that was solved.

None
formulation MathematicalModel | None

The formulation model built for the problem.

None
strategy ComputationStrategy | None

The strategy selected and used.

None
mapping MappingResult | None

The mapping record from program to runtime object.

None
execution Any | None

The execution result (QuantumResult or raw engine result).

None
solution ProblemSolution | None

The domain-level solution.

None
interpretation Interpretation | None

Data-derived interpretation of the solution.

None
provenance Provenance | None

Where-and-how metadata for the run.

None
classification ClassificationResult | None

QMQ-03 problem classification (optional).

None
recommendation AlgorithmRecommendation | None

QMQ-03 algorithm recommendation (optional).

None
plan ComputationPlan | None

QMQ-03 computation plan (optional).

None
classical_execution ClassicalExecutionResult | None

QMQ-04 classical leg result (classical/hybrid runs).

None
quantum_execution QuantumExecutionResult | None

QMQ-04 quantum leg result (quantum/hybrid runs).

None
comparison ExecutionComparison | None

QMQ-04 hybrid comparison + selection (hybrid runs).

None
selected_leg str | None

QMQ-04 selected leg ("classical"/"quantum").

None
result_interpretation ResultInterpretation | None

QMQ-06 structured interpretation (optional).

None
benchmark BenchmarkResult | None

QMQ-05 benchmark result this report belongs to (optional).

None
created_at str

UTC ISO timestamp of report creation.

(lambda: isoformat())()
to_dict()

Serialize the report to a JSON-safe dictionary.

AlgorithmInterpretation dataclass

Algorithm and runtime details of the executed run.

Parameters:

Name Type Description Default
algorithm str

Algorithm id (e.g. "qaoa", "exhaustive") or "".

''
backend str

Backend that executed the quantum leg or "".

''
optimizer str

Optimizer label used by the variational loop or "".

''
num_qubits int | None

Mapped qubit count or None.

None
circuit_depth int | None

Circuit depth or None.

None
num_gates int | None

Gate count or None.

None
shots int | None

Shot count or None.

None
microquantum_version str

MicroQuantum version string or "".

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

BenchmarkInterpretation dataclass

Interpreted benchmark outcome vs the classical baseline.

Parameters:

Name Type Description Default
benchmark_id str

Id of the benchmark (if any).

''
baseline str

Baseline label ("classical").

'classical'
winner str | None

QMQ-05 winner classification value or None.

None
objective_delta float | None

Normalized objective delta (strategy - baseline).

None
measured_basis list[str]

What the outcome was ranked on (e.g. ["objective"]).

list()
strategy_status str

Status of the benchmarked strategy leg.

''
baseline_status str

Status of the baseline leg.

''
outcome str

"better" / "worse" / "tie" / "not_comparable" for the benchmarked strategy.

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ExecutionInterpretation dataclass

Execution-level status and cost facts.

Parameters:

Name Type Description Default
executor str

Executor label (e.g. "classical/exhaustive") or "".

''
status str

Execution status ("executed" / "failed" / ...).

'executed'
error str

Recorded error message or "".

''
failure_category str | None

Coarse failure category when the run failed.

None
wall_clock_time float | None

Wall-clock time of the interpreted phase.

None
num_evaluations int | None

Number of objective evaluations.

None
iterations int | None

Variational iterations.

None
executions int

Number of executions.

0
retries int

Number of retries.

0
selected_leg str | None

Selected leg of a hybrid run ("classical" / "quantum") or None.

None
classical_status str | None

Status of the classical leg/baseline or None.

None
quantum_status str | None

Status of the quantum leg or None.

None
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FeasibilityInterpretation dataclass

Structured view of constraint satisfaction.

Parameters:

Name Type Description Default
status FeasibilityStatus

Feasibility status.

UNKNOWN
satisfied int

Number of satisfied constraints.

0
violated int

Number of violated constraints.

0
unknown int

Number of unevaluated constraints.

0
total int

Total number of assessed constraints.

0
violated_constraints list[str]

Names of violated constraints (when known).

list()
violation_magnitude float

Total numerical violation magnitude.

0.0
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

FeasibilityStatus

Bases: Enum

Constraint-satisfaction status of a solution.

Attributes:

Name Type Description
FEASIBLE

No constraint is violated.

INFEASIBLE

At least one constraint is violated.

UNKNOWN

Constraint satisfaction could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:FeasibilityStatus.

InterpretationStatus

Bases: Enum

Outcome status of the interpreted run.

Attributes:

Name Type Description
EXECUTED

The run completed as planned.

FAILED

The run recorded a failure.

DEGRADED

The run completed, but only after a fallback (e.g. a quantum-capable strategy executed classically).

UNKNOWN

No execution status could be determined.

parse(value) classmethod

Coerce a label or member to an :class:InterpretationStatus.

Limitation dataclass

One honest caveat about what an interpretation does not establish.

Parameters:

Name Type Description Default
category str

Machine-readable category, e.g. "known_optimum_unavailable".

required
message str

Human-readable limitation statement.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a limitation from :meth:to_dict output.

ObjectiveInterpretation dataclass

Structured view of the interpreted objective.

Parameters:

Name Type Description Default
sense str

Optimization sense ("minimize" / "maximize").

'minimize'
objective_value float | None

Recorded objective value of the returned solution.

None
energy float | None

Recorded QUBO/Ising energy (when reported).

None
known_optimum float | None

Known optimum supplied to the benchmark (or None).

None
optimality_gap float | None

Relative distance from the known optimum (None when no optimum is available).

None
approximation_ratio float | None

Approximation ratio vs the known optimum (None when not interpretable).

None
quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Evidential basis of the quality claim.

UNCERTAIN
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ProvenanceOverview dataclass

Consolidated provenance view of an interpreted run.

Parameters:

Name Type Description Default
problem_name str

Name of the problem that was solved.

''
formulation str

Formulation kind ("optimization") or "".

''
strategy str | None

Strategy that produced the outcome or None.

None
algorithm str

Algorithm id or "".

''
executor str

Executor label or "".

''
backend str

Backend used or "".

''
microquantum_version str

MicroQuantum version string or "".

''
sdk_version str

QuantsMind SDK version or "".

''
benchmark_id str | None

Benchmark id (if any) or None.

None
baseline str

Classical baseline label or "".

''
created_at str

UTC ISO timestamp of the report.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

Qualification

Bases: Enum

Evidential basis behind an interpretation claim.

Attributes:

Name Type Description
MATHEMATICAL_PROOF

Optimality established by an exact method (e.g. exhaustive search over the full discrete space).

EMPIRICAL

Claim rests on recorded measurements.

HEURISTIC

Claim rests on a heuristic method; optimality is not established.

UNCERTAIN

Insufficient evidence for any stronger claim.

parse(value) classmethod

Coerce a label or member to a :class:Qualification.

ResultInterpretation dataclass

Complete structured interpretation of one execution / benchmark result.

All sections are always present when constructed by :class:ResultInterpreter (they may carry None / UNKNOWN values when information is missing). The flat view properties mirror selected machine-readable fields so downstream consumers do not need to descend into the sections.

Parameters:

Name Type Description Default
status InterpretationStatus

Run :class:InterpretationStatus.

UNKNOWN
summary str

Generated human-readable narrative (only supported claims).

''
solution_quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Overall evidential basis of the quality claim.

UNCERTAIN
feasibility FeasibilityInterpretation | None

Constraint satisfaction section.

None
objective ObjectiveInterpretation | None

Objective facts and quality section.

None
benchmark BenchmarkInterpretation | None

Benchmark outcome section (None without a benchmark).

None
strategy StrategyInterpretation | None

Requested/selected/actual strategy section.

None
algorithm AlgorithmInterpretation | None

Algorithm and runtime details.

None
execution ExecutionInterpretation | None

Execution status and cost facts.

None
limitations list[Limitation]

Applicable caveats (:class:Limitation list).

list()
provenance ProvenanceOverview | None

Consolidated provenance view.

None
winner property

Benchmark winner classification value (None without a benchmark).

objective_value property

Recorded objective value of the decoded solution.

optimality_gap property

Relative distance from the known optimum (None when unavailable).

approximation_ratio property

Approximation ratio vs the known optimum (None when unavailable).

requested_strategy property

Strategy the caller asked for.

selected_strategy property

Strategy actually selected for execution.

actual_executor property

Executor label that produced the outcome.

fallback_used property

Whether execution degraded to another strategy.

feasibility_status property

Feasibility status value (None when the section is absent).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ResultInterpreter

Builds :class:ResultInterpretation objects from reports and benchmarks.

The interpreter is stateless apart from its numerical tolerances; the same inputs always produce the same interpretation (deterministic).

interpret_report(report, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a solution report without benchmark evidence.

interpret_benchmark(benchmark, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a benchmark result (using its embedded report when present).

interpret(report=None, *, benchmark=None, gap_tolerance=None, near_optimal_tolerance=None)

Produce a full structured interpretation of a run.

Parameters:

Name Type Description Default
report SolutionReport | None

The workflow :class:SolutionReport (optional when full benchmark evidence exists, otherwise required for the solution-level facts).

None
benchmark BenchmarkResult | None

The QMQ-05 :class:BenchmarkResult (optional).

None
gap_tolerance float | None

Optimality distance considered exact (overrides the interpreter default).

None
near_optimal_tolerance float | None

Gap below which a non-optimal result is labelled :attr:SolutionQuality.NEAR_OPTIMAL.

None

Returns:

Name Type Description
A ResultInterpretation

class:ResultInterpretation over the available data.

summarize(report=None, *, benchmark=None)

Shortcut returning just the generated narrative of an interpretation.

SolutionQuality

Bases: Enum

Evidence-backed quality classification of a solution.

Attributes:

Name Type Description
OPTIMAL

Feasible and equal to the known optimum (within tolerance).

NEAR_OPTIMAL

Feasible and within the near-optimal tolerance of the known optimum.

FEASIBLE

Feasible, with no evidence basis for optimality (no known optimum, or a gap beyond the near-optimal tolerance).

INFEASIBLE

One or more constraints are violated.

UNKNOWN

Feasibility could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:SolutionQuality.

StrategyInterpretation dataclass

Requested vs selected vs executed strategy.

Parameters:

Name Type Description Default
requested_strategy str | None

Strategy the caller asked for.

None
selected_strategy str | None

Strategy actually selected for execution.

None
actual_strategy str | None

Strategy that produced the outcome (may be a degraded fallback).

None
fallback_used bool

Whether execution degraded to another strategy.

False
reason str

Reason for the fallback (when used).

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

interpretation

Data-derived interpretation of quantum domain solutions.

An :class:Interpretation summarizes what the data says about a solution (feasibility, objective values, constraint status, score). QMQ-01 deliberately does not fabricate domain or business meaning — that is the task of later domain-specific interpretation modules.

InterpretationQuality

Bases: Enum

Overall confidence in a solution interpretation.

Attributes:

Name Type Description
HIGH

Fully evaluated and feasible.

MEDIUM

Partially evaluated (some constraints unknown).

LOW

Infeasible (one or more constraints violated).

UNKNOWN

Nothing could be evaluated.

Interpretation dataclass

A structured, data-derived explanation of a solution.

Parameters:

Name Type Description Default
summary str

One-line human-readable summary.

''
quality InterpretationQuality

Feasibility/evidence quality level.

UNKNOWN
confidence float | None

Optional numeric confidence in [0, 1].

None
details dict[str, Any]

Free-form facts (feasible, objective values, statuses).

dict()
metadata dict[str, Any]

Free-form metadata (e.g. strategy used).

dict()
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild an Interpretation from :meth:to_dict output.

SolutionInterpreter

Produces conservative, data-derived interpretations of solutions.

The interpreter derives its statements only from the solution itself (feasibility, objective values, constraint statuses, score) and the strategy that produced it. No domain meaning is invented.

interpret(solution, *, strategy=None)

Interpret a solution using only its own data.

Parameters:

Name Type Description Default
solution ProblemSolution

The domain solution to interpret.

required
strategy ComputationStrategy | str | None

Optional computation strategy used (recorded as metadata only).

None

Returns:

Name Type Description
An Interpretation

class:Interpretation constructed from solution facts.

__call__(solution, *, strategy=None)

Convenience alias for :meth:interpret.

provenance

Provenance recording for quantum domain solutions.

A :class:Provenance records how a domain result was produced: the strategy, formulation, algorithm, backend, execution metadata and the SDK version. It makes results auditable and reproducible without coupling to any specific execution engine.

Provenance dataclass

Where-and-how metadata attached to a domain result.

Parameters:

Name Type Description Default
strategy ComputationStrategy | str | None

Computation strategy used.

None
formulation str

Formulation kind (e.g. "optimization").

''
algorithm str

Algorithm used (e.g. "vqe", "grover", "qaoa", "exhaustive") or "".

''
executor str

Executor identity (e.g. "classical/exhaustive", "microquantum/qaoa") or "".

''
backend str

Backend that executed the workflow or "".

''
execution_metadata dict[str, Any]

Metadata from the execution layer (experiment id, actual backend, shots, counts-derived summary).

dict()
sdk_version str

QuantsMind SDK version that produced the result.

_sdk_version()
created_at str

UTC ISO timestamp of record creation.

(lambda: isoformat())()
metadata dict[str, Any]

Free-form provenance metadata.

dict()
strategy_label property

Serialized strategy label (e.g. "hybrid").

from_execution(*, strategy=None, formulation='', algorithm='', executor='', backend='', execution=None, metadata=None) classmethod

Build provenance, deriving execution metadata from a result.

execution may be any object exposing experiment_id, program_name, backend_name, shots and provenance attributes (e.g. a :class:~quantsmind.quantum.circuit_result.QuantumResult), or a QMQ-02 executor result exposing solver/energy (e.g. :class:~quantsmind.quantum.optimization.classical.ClassicalSolverResult or :class:~quantsmind.quantum.integration.microquantum.QaoaExecutionResult).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a Provenance from :meth:to_dict output.

result

Domain-level results of a QuantsMind quantum workflow.

A :class:SolutionReport bundles a problem with every artifact produced during a workflow run: the formulation, the selected strategy, the mapping record, the execution result (a :class:~quantsmind.quantum.circuit_result.QuantumResult), the domain solution, its interpretation and provenance.

SolutionReport dataclass

Complete record of one workflow run for a domain problem.

Parameters:

Name Type Description Default
problem QuantumProblem | None

The problem that was solved.

None
formulation MathematicalModel | None

The formulation model built for the problem.

None
strategy ComputationStrategy | None

The strategy selected and used.

None
mapping MappingResult | None

The mapping record from program to runtime object.

None
execution Any | None

The execution result (QuantumResult or raw engine result).

None
solution ProblemSolution | None

The domain-level solution.

None
interpretation Interpretation | None

Data-derived interpretation of the solution.

None
provenance Provenance | None

Where-and-how metadata for the run.

None
classification ClassificationResult | None

QMQ-03 problem classification (optional).

None
recommendation AlgorithmRecommendation | None

QMQ-03 algorithm recommendation (optional).

None
plan ComputationPlan | None

QMQ-03 computation plan (optional).

None
classical_execution ClassicalExecutionResult | None

QMQ-04 classical leg result (classical/hybrid runs).

None
quantum_execution QuantumExecutionResult | None

QMQ-04 quantum leg result (quantum/hybrid runs).

None
comparison ExecutionComparison | None

QMQ-04 hybrid comparison + selection (hybrid runs).

None
selected_leg str | None

QMQ-04 selected leg ("classical"/"quantum").

None
result_interpretation ResultInterpretation | None

QMQ-06 structured interpretation (optional).

None
benchmark BenchmarkResult | None

QMQ-05 benchmark result this report belongs to (optional).

None
created_at str

UTC ISO timestamp of report creation.

(lambda: isoformat())()
to_dict()

Serialize the report to a JSON-safe dictionary.

result_interpretation

QMQ-06: structured, honest interpretation of execution and benchmark results.

:class:ResultInterpreter consumes a :class:~quantsmind.quantum.result.result.SolutionReport and an optional :class:~quantsmind.quantum.benchmark.models.BenchmarkResult and produces a :class:ResultInterpretation — a domain-neutral, machine-readable explanation of what was run, what the numbers say, and what they do not justify.

The interpretation layer is deliberately conservative:

  • feasibility and objective facts are derived only from recorded data;
  • a solution is labelled optimal only when a known optimum establishes it (within the configured numerical tolerance), never from completion;
  • benchmark outcomes reuse the QMQ-05 comparison and its feasibility-first policy — no quantum-advantage claim is ever derived from a classification;
  • missing information yields None / UNKNOWN plus a :class:Limitation, never an invented value.

The existing QMQ-01 :class:~quantsmind.quantum.result.Interpretation stays the shallow solution-level summary attached by the workflow; QMQ-06 layers the full structured interpretation on top of reports and benchmark results.

InterpretationStatus

Bases: Enum

Outcome status of the interpreted run.

Attributes:

Name Type Description
EXECUTED

The run completed as planned.

FAILED

The run recorded a failure.

DEGRADED

The run completed, but only after a fallback (e.g. a quantum-capable strategy executed classically).

UNKNOWN

No execution status could be determined.

parse(value) classmethod

Coerce a label or member to an :class:InterpretationStatus.

SolutionQuality

Bases: Enum

Evidence-backed quality classification of a solution.

Attributes:

Name Type Description
OPTIMAL

Feasible and equal to the known optimum (within tolerance).

NEAR_OPTIMAL

Feasible and within the near-optimal tolerance of the known optimum.

FEASIBLE

Feasible, with no evidence basis for optimality (no known optimum, or a gap beyond the near-optimal tolerance).

INFEASIBLE

One or more constraints are violated.

UNKNOWN

Feasibility could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:SolutionQuality.

FeasibilityStatus

Bases: Enum

Constraint-satisfaction status of a solution.

Attributes:

Name Type Description
FEASIBLE

No constraint is violated.

INFEASIBLE

At least one constraint is violated.

UNKNOWN

Constraint satisfaction could not be determined.

parse(value) classmethod

Coerce a label or member to a :class:FeasibilityStatus.

Qualification

Bases: Enum

Evidential basis behind an interpretation claim.

Attributes:

Name Type Description
MATHEMATICAL_PROOF

Optimality established by an exact method (e.g. exhaustive search over the full discrete space).

EMPIRICAL

Claim rests on recorded measurements.

HEURISTIC

Claim rests on a heuristic method; optimality is not established.

UNCERTAIN

Insufficient evidence for any stronger claim.

parse(value) classmethod

Coerce a label or member to a :class:Qualification.

Limitation dataclass

One honest caveat about what an interpretation does not establish.

Parameters:

Name Type Description Default
category str

Machine-readable category, e.g. "known_optimum_unavailable".

required
message str

Human-readable limitation statement.

required
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a limitation from :meth:to_dict output.

FeasibilityInterpretation dataclass

Structured view of constraint satisfaction.

Parameters:

Name Type Description Default
status FeasibilityStatus

Feasibility status.

UNKNOWN
satisfied int

Number of satisfied constraints.

0
violated int

Number of violated constraints.

0
unknown int

Number of unevaluated constraints.

0
total int

Total number of assessed constraints.

0
violated_constraints list[str]

Names of violated constraints (when known).

list()
violation_magnitude float

Total numerical violation magnitude.

0.0
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ObjectiveInterpretation dataclass

Structured view of the interpreted objective.

Parameters:

Name Type Description Default
sense str

Optimization sense ("minimize" / "maximize").

'minimize'
objective_value float | None

Recorded objective value of the returned solution.

None
energy float | None

Recorded QUBO/Ising energy (when reported).

None
known_optimum float | None

Known optimum supplied to the benchmark (or None).

None
optimality_gap float | None

Relative distance from the known optimum (None when no optimum is available).

None
approximation_ratio float | None

Approximation ratio vs the known optimum (None when not interpretable).

None
quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Evidential basis of the quality claim.

UNCERTAIN
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

BenchmarkInterpretation dataclass

Interpreted benchmark outcome vs the classical baseline.

Parameters:

Name Type Description Default
benchmark_id str

Id of the benchmark (if any).

''
baseline str

Baseline label ("classical").

'classical'
winner str | None

QMQ-05 winner classification value or None.

None
objective_delta float | None

Normalized objective delta (strategy - baseline).

None
measured_basis list[str]

What the outcome was ranked on (e.g. ["objective"]).

list()
strategy_status str

Status of the benchmarked strategy leg.

''
baseline_status str

Status of the baseline leg.

''
outcome str

"better" / "worse" / "tie" / "not_comparable" for the benchmarked strategy.

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

StrategyInterpretation dataclass

Requested vs selected vs executed strategy.

Parameters:

Name Type Description Default
requested_strategy str | None

Strategy the caller asked for.

None
selected_strategy str | None

Strategy actually selected for execution.

None
actual_strategy str | None

Strategy that produced the outcome (may be a degraded fallback).

None
fallback_used bool

Whether execution degraded to another strategy.

False
reason str

Reason for the fallback (when used).

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

AlgorithmInterpretation dataclass

Algorithm and runtime details of the executed run.

Parameters:

Name Type Description Default
algorithm str

Algorithm id (e.g. "qaoa", "exhaustive") or "".

''
backend str

Backend that executed the quantum leg or "".

''
optimizer str

Optimizer label used by the variational loop or "".

''
num_qubits int | None

Mapped qubit count or None.

None
circuit_depth int | None

Circuit depth or None.

None
num_gates int | None

Gate count or None.

None
shots int | None

Shot count or None.

None
microquantum_version str

MicroQuantum version string or "".

''
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ExecutionInterpretation dataclass

Execution-level status and cost facts.

Parameters:

Name Type Description Default
executor str

Executor label (e.g. "classical/exhaustive") or "".

''
status str

Execution status ("executed" / "failed" / ...).

'executed'
error str

Recorded error message or "".

''
failure_category str | None

Coarse failure category when the run failed.

None
wall_clock_time float | None

Wall-clock time of the interpreted phase.

None
num_evaluations int | None

Number of objective evaluations.

None
iterations int | None

Variational iterations.

None
executions int

Number of executions.

0
retries int

Number of retries.

0
selected_leg str | None

Selected leg of a hybrid run ("classical" / "quantum") or None.

None
classical_status str | None

Status of the classical leg/baseline or None.

None
quantum_status str | None

Status of the quantum leg or None.

None
explanation str

Human-readable sentence.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ProvenanceOverview dataclass

Consolidated provenance view of an interpreted run.

Parameters:

Name Type Description Default
problem_name str

Name of the problem that was solved.

''
formulation str

Formulation kind ("optimization") or "".

''
strategy str | None

Strategy that produced the outcome or None.

None
algorithm str

Algorithm id or "".

''
executor str

Executor label or "".

''
backend str

Backend used or "".

''
microquantum_version str

MicroQuantum version string or "".

''
sdk_version str

QuantsMind SDK version or "".

''
benchmark_id str | None

Benchmark id (if any) or None.

None
baseline str

Classical baseline label or "".

''
created_at str

UTC ISO timestamp of the report.

''
to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ResultInterpretation dataclass

Complete structured interpretation of one execution / benchmark result.

All sections are always present when constructed by :class:ResultInterpreter (they may carry None / UNKNOWN values when information is missing). The flat view properties mirror selected machine-readable fields so downstream consumers do not need to descend into the sections.

Parameters:

Name Type Description Default
status InterpretationStatus

Run :class:InterpretationStatus.

UNKNOWN
summary str

Generated human-readable narrative (only supported claims).

''
solution_quality SolutionQuality

Evidence-backed :class:SolutionQuality.

UNKNOWN
qualification Qualification

Overall evidential basis of the quality claim.

UNCERTAIN
feasibility FeasibilityInterpretation | None

Constraint satisfaction section.

None
objective ObjectiveInterpretation | None

Objective facts and quality section.

None
benchmark BenchmarkInterpretation | None

Benchmark outcome section (None without a benchmark).

None
strategy StrategyInterpretation | None

Requested/selected/actual strategy section.

None
algorithm AlgorithmInterpretation | None

Algorithm and runtime details.

None
execution ExecutionInterpretation | None

Execution status and cost facts.

None
limitations list[Limitation]

Applicable caveats (:class:Limitation list).

list()
provenance ProvenanceOverview | None

Consolidated provenance view.

None
winner property

Benchmark winner classification value (None without a benchmark).

objective_value property

Recorded objective value of the decoded solution.

optimality_gap property

Relative distance from the known optimum (None when unavailable).

approximation_ratio property

Approximation ratio vs the known optimum (None when unavailable).

requested_strategy property

Strategy the caller asked for.

selected_strategy property

Strategy actually selected for execution.

actual_executor property

Executor label that produced the outcome.

fallback_used property

Whether execution degraded to another strategy.

feasibility_status property

Feasibility status value (None when the section is absent).

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild from :meth:to_dict output.

ResultInterpreter

Builds :class:ResultInterpretation objects from reports and benchmarks.

The interpreter is stateless apart from its numerical tolerances; the same inputs always produce the same interpretation (deterministic).

interpret_report(report, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a solution report without benchmark evidence.

interpret_benchmark(benchmark, *, gap_tolerance=None, near_optimal_tolerance=None)

Interpret a benchmark result (using its embedded report when present).

interpret(report=None, *, benchmark=None, gap_tolerance=None, near_optimal_tolerance=None)

Produce a full structured interpretation of a run.

Parameters:

Name Type Description Default
report SolutionReport | None

The workflow :class:SolutionReport (optional when full benchmark evidence exists, otherwise required for the solution-level facts).

None
benchmark BenchmarkResult | None

The QMQ-05 :class:BenchmarkResult (optional).

None
gap_tolerance float | None

Optimality distance considered exact (overrides the interpreter default).

None
near_optimal_tolerance float | None

Gap below which a non-optimal result is labelled :attr:SolutionQuality.NEAR_OPTIMAL.

None

Returns:

Name Type Description
A ResultInterpretation

class:ResultInterpretation over the available data.

summarize(report=None, *, benchmark=None)

Shortcut returning just the generated narrative of an interpretation.

strategy

Strategy layer of QuantsMind Quantum.

The strategy layer selects how a domain problem should be computed: classically, with a quantum kernel, hybrid, or quantum-inspired.

StrategySelector

Selects a :class:ComputationStrategy for a domain problem.

Selection rules (QMQ-01, fully deterministic):

  1. An explicit preferred_strategy is honoured; if it requires a quantum runtime that is unavailable it is downgraded to CLASSICAL.
  2. If no quantum backend is available, the strategy is CLASSICAL.
  3. Otherwise a size-based heuristic applies:

  4. n <= quantum_attempt_threshold -> HYBRID (small problems can run a quantum kernel with classical pre/post-processing).

  5. quantum_attempt_threshold < n <= quantum_inspired_threshold -> QUANTUM_INSPIRED (too large for a variational circuit with a reasonable shot budget, but suitable for classical algorithms inspired by quantum mechanics).
  6. n > quantum_inspired_threshold -> CLASSICAL (domain pre-processing only).

A problem can override rule 3 by setting problem.metadata["quantum_suitable"] = False (then CLASSICAL is returned).

Parameters:

Name Type Description Default
quantum_attempt_threshold int

Problem size at or below which a quantum kernel is attempted.

25
quantum_inspired_threshold int

Problem size at or below which QUANTUM_INSPIRED is used.

500
quantum_enabled bool

Master switch allowing quantum-family strategies.

True
select(problem, *, backend_available=None, available_algorithms=None)

Choose a strategy deterministically.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
backend_available bool | None

If given, overrides the global MicroQuantum availability check.

None
available_algorithms set[str] | None

If given and empty, forces CLASSICAL.

None
select_reasoned(problem, *, backend_available=None, available_algorithms=None, classification=None, formulation=None, capabilities=None)

Select a strategy with a full, explainable rationale (QMQ-03 §7).

The decision is made by the same deterministic rules as :meth:select, but the AUTO path may additionally consider the problem class, formulation kind and capability flags when they are provided — instead of size alone. Without those signals the result is identical to :meth:select (backward compatible).

Returns:

Name Type Description
StrategyDecision StrategyDecision

The selected strategy plus reasons and signals.

explain(problem, *, backend_available=None, available_algorithms=None)

Return the selected strategy and a human-readable rationale.

Useful for logging and testing but never consumed by the workflow itself.

ComputationStrategy

Bases: Enum

How a domain problem should be computed.

Attributes:

Name Type Description
CLASSICAL

Classical computation on CPUs/GPUs.

QUANTUM

End-to-end quantum computation (MicroQuantum runtime).

HYBRID

Classical domain pre/post-processing with a quantum kernel.

QUANTUM_INSPIRED

Classical algorithms inspired by quantum mechanics.

AUTO

Deterministic rule-based selection (see :class:StrategySelector).

uses_quantum_runtime property

True for strategies that require MicroQuantum execution.

parse(value) classmethod

Coerce a name or member to a :class:ComputationStrategy.

selector

Deterministic, rule-based strategy selection (QMQ-01).

The :class:StrategySelector uses a clear, testable, stateless decision function to choose a :class:ComputationStrategy for a domain problem. The class is a stable seam: a future learned or advisor-based selector can replace the select implementation without callers changing.

StrategyDecision dataclass

A strategy selection together with its full rationale (QMQ-03 §7).

Parameters:

Name Type Description Default
strategy ComputationStrategy

The selected :class:ComputationStrategy.

required
reasons list[str]

Ordered list of human-readable reasons for the decision.

list()
signals dict[str, Any]

Structural signals that drove the decision (problem size, variable types, formulation kind, capability flags, ...).

dict()
metadata dict[str, Any]

Free-form metadata (rule path, overrides, ...).

dict()
label property

Serialized strategy label (e.g. "hybrid").

to_dict()

Serialize to a JSON-safe dictionary.

from_dict(data) classmethod

Rebuild a decision from :meth:to_dict output.

StrategySelector

Selects a :class:ComputationStrategy for a domain problem.

Selection rules (QMQ-01, fully deterministic):

  1. An explicit preferred_strategy is honoured; if it requires a quantum runtime that is unavailable it is downgraded to CLASSICAL.
  2. If no quantum backend is available, the strategy is CLASSICAL.
  3. Otherwise a size-based heuristic applies:

  4. n <= quantum_attempt_threshold -> HYBRID (small problems can run a quantum kernel with classical pre/post-processing).

  5. quantum_attempt_threshold < n <= quantum_inspired_threshold -> QUANTUM_INSPIRED (too large for a variational circuit with a reasonable shot budget, but suitable for classical algorithms inspired by quantum mechanics).
  6. n > quantum_inspired_threshold -> CLASSICAL (domain pre-processing only).

A problem can override rule 3 by setting problem.metadata["quantum_suitable"] = False (then CLASSICAL is returned).

Parameters:

Name Type Description Default
quantum_attempt_threshold int

Problem size at or below which a quantum kernel is attempted.

25
quantum_inspired_threshold int

Problem size at or below which QUANTUM_INSPIRED is used.

500
quantum_enabled bool

Master switch allowing quantum-family strategies.

True
select(problem, *, backend_available=None, available_algorithms=None)

Choose a strategy deterministically.

Parameters:

Name Type Description Default
problem QuantumProblem

The problem to classify.

required
backend_available bool | None

If given, overrides the global MicroQuantum availability check.

None
available_algorithms set[str] | None

If given and empty, forces CLASSICAL.

None
select_reasoned(problem, *, backend_available=None, available_algorithms=None, classification=None, formulation=None, capabilities=None)

Select a strategy with a full, explainable rationale (QMQ-03 §7).

The decision is made by the same deterministic rules as :meth:select, but the AUTO path may additionally consider the problem class, formulation kind and capability flags when they are provided — instead of size alone. Without those signals the result is identical to :meth:select (backward compatible).

Returns:

Name Type Description
StrategyDecision StrategyDecision

The selected strategy plus reasons and signals.

explain(problem, *, backend_available=None, available_algorithms=None)

Return the selected strategy and a human-readable rationale.

Useful for logging and testing but never consumed by the workflow itself.

strategy

Computation strategies for QuantsMind Quantum.

The strategy enumerates how a domain problem should be computed. QMQ-01 ships a deterministic, rule-based :class:StrategySelector. A future learned or advice-based selector can replace the select implementation without callers changing.

ComputationStrategy

Bases: Enum

How a domain problem should be computed.

Attributes:

Name Type Description
CLASSICAL

Classical computation on CPUs/GPUs.

QUANTUM

End-to-end quantum computation (MicroQuantum runtime).

HYBRID

Classical domain pre/post-processing with a quantum kernel.

QUANTUM_INSPIRED

Classical algorithms inspired by quantum mechanics.

AUTO

Deterministic rule-based selection (see :class:StrategySelector).

uses_quantum_runtime property

True for strategies that require MicroQuantum execution.

parse(value) classmethod

Coerce a name or member to a :class:ComputationStrategy.

workflow

Workflow layer of QuantsMind Quantum.

Pipelines a domain problem through formulation, strategy selection, mapping, execution and solution reporting.

QuantumWorkflow

Pipelines a domain problem through formulation, strategy, mapping, execution and solution reporting.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem to process.

required
program Any | None

Optional :class:QuantumProgram attached for the QMQ-01 low-level quantum execution path. When provided, the quantum strategy runs the explicit program instead of the automatic QUBO/Ising path.

None
backend str | None

Backend name (e.g. "statevector") or an engine backend instance.

None
shots int

Number of shots per execution.

1024
seed int | None

Optional RNG seed for reproducibility.

None
name str

Workflow/experiment label.

'quantum_workflow'
selector StrategySelector | None

Optional :class:StrategySelector (defaults to a fresh rule-based selector).

None
mapper DomainMapper | None

Optional :class:DomainMapper (defaults to :class:QuantumCircuitMapper); only used for the explicit program path.

None
classical_executor ExhaustiveSolver | None

Optional :class:ExhaustiveSolver for the classical baseline (defaults to a fresh solver with max_variables=20).

None
num_layers int

QAOA layers for the automatic quantum path.

1
penalty float | None

Optional constraint penalty multiplier for the QUBO mapping.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (useful to bound runtime in tests/CI).

None
classifier ProblemClassifier | None

Optional :class:ProblemClassifier (QMQ-03).

None
algorithm_selector AlgorithmSelector | None

Optional :class:AlgorithmSelector (QMQ-03).

None
capabilities CapabilityModel | None

Optional :class:CapabilityModel snapshot (detected on demand when omitted).

None
requested_algorithm str | None

Optional explicit algorithm id honoured by the QMQ-03 recommender.

None
allow_algorithm_fallback bool

If True, an unavailable requested algorithm falls back to an executable replacement (recorded, never silent).

False
executor Executor | None

Optional QMQ-04 :class:Executor overriding the strategy-derived executor (used as-is by :meth:create_executor).

None
options ExecutionOptions | None

Optional QMQ-04 :class:ExecutionOptions; workflow-level arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults it can override.

None
execution_options()

Resolve execution options for the current decisions.

Workflow constructor arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults; an explicit :class:ExecutionOptions on the constructor overrides them.

create_executor()

Build (or reuse) the executor for the selected strategy (QMQ-04 §4).

The classical executor reuses the workflow's configured :class:ExhaustiveSolver; the quantum executor delegates to MicroQuantum's QAOA.

formulate()

Build (or reuse) a formulation for the problem.

classify()

Classify the problem (QMQ-03).

Returns:

Name Type Description
ClassificationResult ClassificationResult

Deterministic structural classification of

ClassificationResult

the problem.

select_strategy()

Select the computation strategy for the problem.

Uses the reasoned (QMQ-03) path once the problem has been classified; otherwise the legacy QMQ-01 selector is used so callers that never classify keep identical behaviour.

recommend()

Recommend an algorithm for the classified problem (QMQ-03).

Runs classification + strategy selection first, then asks the :class:AlgorithmSelector for a scored recommendation with an executable fallback chain.

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

The scored recommendation.

plan()

Build a declarative computation plan for the current decisions.

Returns:

Name Type Description
ComputationPlan ComputationPlan

The plan (QMQ-03, ready for QMQ-04).

map()

Map the problem to a computational representation.

Routing rules:

  • An attached :class:QuantumProgram uses the QMQ-01 circuit mapping (quantum strategies only).
  • Otherwise CLASSICAL uses QUBOMapper (problem -> QUBO).
  • QUANTUM/HYBRID additionally use IsingMapper (QUBO -> Ising). QUANTUM requires MicroQuantum; HYBRID degrades to the QUBO mapping when MicroQuantum is absent (the quantum leg is then recorded as unavailable during execution — a documented fallback, never a fabricated quantum result).

Raises:

Type Description
MicroQuantumUnavailableError

For a QUANTUM strategy when the optional dependency is missing (an ImportError-compatible subclass of :class:WorkflowError).

WorkflowError

For unsupported strategies.

execute()

Execute the mapped representation via the strategy-derived executor.

QMQ-04: the QMQ-03 computation plan is executed through the :class:Executor built by :meth:create_executor using :meth:execution_options:

  • CLASSICAL: exhaustive baseline over the QUBO.
  • QUANTUM: QAOA delegated to MicroQuantum (validated).
  • HYBRID: both legs run; an unavailable quantum leg falls back to the classical result and is recorded as skipped — never fabricated.
  • Explicit-program path: run through :class:QuantumExperiment.

Raises:

Type Description
WorkflowError

If mapping/planning/execution cannot proceed.

UnsupportedStrategyError

If the plan resolves to a strategy this layer cannot execute.

build_solution()

Derive a domain solution from the execution result.

Quantum-program executions decode the most probable measurement bitstring using problem.metadata["encoding"] (QMQ-01). QMQ-02 executions (classical baseline, QAOA) carry an explicit assignment and are used directly. Objectives and constraints support callable and symbolic string expressions.

interpret(solution)

Produce a data-derived interpretation of the solution.

build_provenance(execution=None)

Build provenance for the current run.

Hybrid executions record the selected leg as the provenance executor ("hybrid") and carry the explicit comparison in metadata.

run()

Run the full pipeline and return a :class:SolutionReport.

Pipeline (QMQ-03): formulate -> classify -> select strategy -> recommend algorithm -> build plan -> map -> execute.

WorkflowError

Bases: ValueError

Raised when a workflow step cannot proceed.

Kept in this module (rather than the workflow package) so dependency errors can subclass it without creating an import cycle.

WorkflowState

Bases: Enum

Lifecycle state of one :class:QuantumWorkflow run (QMQ-04 §3).

Transitions are forward-only and lenient: intermediate stages may be skipped (e.g. map() jumps straight to MAPPED), but a completed or failed workflow cannot be reused and no stage can move backwards.

workflow

Execution workflows for quantum domain problems.

A :class:QuantumWorkflow pipelines a domain problem through the full foundation::

Problem -> Formulation -> Strategy Selection -> Mapping -> Execution -> Solution

QMQ-01 executed genuinely only when a :class:QuantumProgram was attached. QMQ-02 completes the automatic path::

QuantumProblem
    -> OptimizationModel
    -> QUBOModel
    -> IsingModel         (quantum strategies only)
    -> MicroQuantum       (QAOA)          | quantum / hybrid
    -> classical/exhaustive solver        | classical

QMQ-03 adds the intelligence pipeline (decisions are recorded, never faked)::

QuantumProblem
    -> formulate -> classify -> select strategy -> recommend algorithm
    -> build computation plan -> map -> execute

The classical baseline and the MicroQuantum QAOA delegation are real work — not placeholders. Unsupported paths (e.g. a QUANTUM_INSPIRED execution, non-binary problems) raise explicit :class:WorkflowError messages that say what is missing, never silently pretending to run.

WorkflowError

Bases: ValueError

Raised when a workflow step cannot proceed.

Kept in this module (rather than the workflow package) so dependency errors can subclass it without creating an import cycle.

WorkflowState

Bases: Enum

Lifecycle state of one :class:QuantumWorkflow run (QMQ-04 §3).

Transitions are forward-only and lenient: intermediate stages may be skipped (e.g. map() jumps straight to MAPPED), but a completed or failed workflow cannot be reused and no stage can move backwards.

QuantumWorkflow

Pipelines a domain problem through formulation, strategy, mapping, execution and solution reporting.

Parameters:

Name Type Description Default
problem QuantumProblem

The domain problem to process.

required
program Any | None

Optional :class:QuantumProgram attached for the QMQ-01 low-level quantum execution path. When provided, the quantum strategy runs the explicit program instead of the automatic QUBO/Ising path.

None
backend str | None

Backend name (e.g. "statevector") or an engine backend instance.

None
shots int

Number of shots per execution.

1024
seed int | None

Optional RNG seed for reproducibility.

None
name str

Workflow/experiment label.

'quantum_workflow'
selector StrategySelector | None

Optional :class:StrategySelector (defaults to a fresh rule-based selector).

None
mapper DomainMapper | None

Optional :class:DomainMapper (defaults to :class:QuantumCircuitMapper); only used for the explicit program path.

None
classical_executor ExhaustiveSolver | None

Optional :class:ExhaustiveSolver for the classical baseline (defaults to a fresh solver with max_variables=20).

None
num_layers int

QAOA layers for the automatic quantum path.

1
penalty float | None

Optional constraint penalty multiplier for the QUBO mapping.

None
qaoa_optimizer Any | None

Optional MicroQuantum optimizer for the QAOA variational loop (useful to bound runtime in tests/CI).

None
classifier ProblemClassifier | None

Optional :class:ProblemClassifier (QMQ-03).

None
algorithm_selector AlgorithmSelector | None

Optional :class:AlgorithmSelector (QMQ-03).

None
capabilities CapabilityModel | None

Optional :class:CapabilityModel snapshot (detected on demand when omitted).

None
requested_algorithm str | None

Optional explicit algorithm id honoured by the QMQ-03 recommender.

None
allow_algorithm_fallback bool

If True, an unavailable requested algorithm falls back to an executable replacement (recorded, never silent).

False
executor Executor | None

Optional QMQ-04 :class:Executor overriding the strategy-derived executor (used as-is by :meth:create_executor).

None
options ExecutionOptions | None

Optional QMQ-04 :class:ExecutionOptions; workflow-level arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults it can override.

None
execution_options()

Resolve execution options for the current decisions.

Workflow constructor arguments (backend, shots, seed, num_layers, penalty, qaoa_optimizer) act as defaults; an explicit :class:ExecutionOptions on the constructor overrides them.

create_executor()

Build (or reuse) the executor for the selected strategy (QMQ-04 §4).

The classical executor reuses the workflow's configured :class:ExhaustiveSolver; the quantum executor delegates to MicroQuantum's QAOA.

formulate()

Build (or reuse) a formulation for the problem.

classify()

Classify the problem (QMQ-03).

Returns:

Name Type Description
ClassificationResult ClassificationResult

Deterministic structural classification of

ClassificationResult

the problem.

select_strategy()

Select the computation strategy for the problem.

Uses the reasoned (QMQ-03) path once the problem has been classified; otherwise the legacy QMQ-01 selector is used so callers that never classify keep identical behaviour.

recommend()

Recommend an algorithm for the classified problem (QMQ-03).

Runs classification + strategy selection first, then asks the :class:AlgorithmSelector for a scored recommendation with an executable fallback chain.

Returns:

Name Type Description
AlgorithmRecommendation AlgorithmRecommendation

The scored recommendation.

plan()

Build a declarative computation plan for the current decisions.

Returns:

Name Type Description
ComputationPlan ComputationPlan

The plan (QMQ-03, ready for QMQ-04).

map()

Map the problem to a computational representation.

Routing rules:

  • An attached :class:QuantumProgram uses the QMQ-01 circuit mapping (quantum strategies only).
  • Otherwise CLASSICAL uses QUBOMapper (problem -> QUBO).
  • QUANTUM/HYBRID additionally use IsingMapper (QUBO -> Ising). QUANTUM requires MicroQuantum; HYBRID degrades to the QUBO mapping when MicroQuantum is absent (the quantum leg is then recorded as unavailable during execution — a documented fallback, never a fabricated quantum result).

Raises:

Type Description
MicroQuantumUnavailableError

For a QUANTUM strategy when the optional dependency is missing (an ImportError-compatible subclass of :class:WorkflowError).

WorkflowError

For unsupported strategies.

execute()

Execute the mapped representation via the strategy-derived executor.

QMQ-04: the QMQ-03 computation plan is executed through the :class:Executor built by :meth:create_executor using :meth:execution_options:

  • CLASSICAL: exhaustive baseline over the QUBO.
  • QUANTUM: QAOA delegated to MicroQuantum (validated).
  • HYBRID: both legs run; an unavailable quantum leg falls back to the classical result and is recorded as skipped — never fabricated.
  • Explicit-program path: run through :class:QuantumExperiment.

Raises:

Type Description
WorkflowError

If mapping/planning/execution cannot proceed.

UnsupportedStrategyError

If the plan resolves to a strategy this layer cannot execute.

build_solution()

Derive a domain solution from the execution result.

Quantum-program executions decode the most probable measurement bitstring using problem.metadata["encoding"] (QMQ-01). QMQ-02 executions (classical baseline, QAOA) carry an explicit assignment and are used directly. Objectives and constraints support callable and symbolic string expressions.

interpret(solution)

Produce a data-derived interpretation of the solution.

build_provenance(execution=None)

Build provenance for the current run.

Hybrid executions record the selected leg as the provenance executor ("hybrid") and carry the explicit comparison in metadata.

run()

Run the full pipeline and return a :class:SolutionReport.

Pipeline (QMQ-03): formulate -> classify -> select strategy -> recommend algorithm -> build plan -> map -> execute.