Overview¶
| Function | Description |
|---|---|
binary_sampleset_to_ommx_samples | Convert a BINARY sample set into an OMMX Samples container. |
evaluate_original_instance | Evaluate transformed binary samples against the original problem. |
normalize_problem_input | Normalize a problem into evaluation, transformed, and spin forms. |
| Class | Description |
|---|---|
MathematicalProblemConverter | |
SampleResult | Result of a sample() execution. |
Functions¶
binary_sampleset_to_ommx_samples [source]¶
def binary_sampleset_to_ommx_samples(binary_sampleset: BinarySampleSet) -> ommx.v1.SamplesConvert a BINARY sample set into an OMMX Samples container.
Each unique sample state is appended once with a list of sample IDs of
length num_occurrences, so OMMX-side aggregation reflects the
original shot counts without duplicating the underlying state. States
with num_occurrences == 0 are skipped.
This is the canonical bridge from Qamomile’s
:class:BinarySampleSet to OMMX’s
:class:ommx.v1.Samples. It is the helper that
:meth:MathematicalProblemConverter.decode and
:meth:~qamomile.optimization.pce.PCEConverter.decode use to feed
samples into :meth:ommx.v1.Instance.evaluate_samples for feasibility
and original-objective evaluation.
Parameters:
| Name | Type | Description |
|---|---|---|
binary_sampleset | BinarySampleSet | A sample set with vartype=VarType.BINARY. SPIN sample sets must be converted to BINARY first because OMMX expects 0/1 decision-variable values. |
Returns:
ommx.v1.Samples — ommx.v1.Samples: An OMMX Samples object with
ommx.v1.Samples — sum(num_occurrences) sample IDs, where IDs sharing the same
ommx.v1.Samples — state are grouped together. The returned object is empty when the
ommx.v1.Samples — input has no samples.
Raises:
ValueError— Ifbinary_sampleset.vartypeis notVarType.BINARY. SPIN sample sets must be converted first.ValueError— If the lengths ofbinary_sampleset.samplesandbinary_sampleset.num_occurrencesare inconsistent (and, when present,binary_sampleset.energyas well).
evaluate_original_instance [source]¶
def evaluate_original_instance(
original_instance: ommx.v1.Instance,
transformed_instance: ommx.v1.Instance,
samples: ommx.v1.Samples,
) -> ommx.v1.SampleSetEvaluate transformed binary samples against the original problem.
The transformed instance first reconstructs substituted integer and slack variables. Only the caller’s original decision-variable IDs are then copied into a new sample container and evaluated against the untouched original instance. This keeps feasibility and objective values free of penalty terms while retaining OMMX’s binary-substitution semantics.
Parameters:
| Name | Type | Description |
|---|---|---|
original_instance | ommx.v1.Instance | Untouched problem copy used for objective and constraint evaluation. |
transformed_instance | ommx.v1.Instance | Post-to_hubo problem copy used to reconstruct original decision-variable values. |
samples | ommx.v1.Samples | Binary samples in the transformed problem’s variable space. |
Returns:
ommx.v1.SampleSet — ommx.v1.SampleSet: Samples evaluated against the original objective
ommx.v1.SampleSet — and constraints.
normalize_problem_input [source]¶
def normalize_problem_input(
instance: ommx.v1.Instance | BinaryModel,
*,
uniform_penalty_weight: float | None = None,
penalty_weights: dict[int, float] | None = None,
) -> tuple[ommx.v1.Instance | None, ommx.v1.Instance | None, VarType, BinaryModel]Normalize a problem into evaluation, transformed, and spin forms.
Shared canonical entry point used by every converter that consumes a
combinatorial optimization problem expressed either as an OMMX
:class:ommx.v1.Instance or a Qamomile :class:BinaryModel. The
:class:MathematicalProblemConverter base class and
:class:~qamomile.optimization.pce.PCEConverter (which deliberately
does not inherit from that base) both delegate to this helper so the
OMMX deep-copy / to_hubo semantics live in exactly one place.
For OMMX inputs, the instance is deep-copied via a bytes round-trip
before to_hubo is called: to_hubo mutates the instance it is
called on (it appends slack decision variables for non-binary vars
and absorbs constraints into the objective via the penalty method).
Mutating the caller’s instance silently is surprising; copying first
leaves the caller’s view untouched. Separate original and transformed
copies let downstream decoding reconstruct substituted variables with the
transformed instance, then evaluate the untouched objective and
constraints with the original instance.
to_hubo is used instead of to_qubo so that both purely
quadratic (QUBO) and higher-order (HUBO) instances are handled
uniformly. For quadratic-only instances the two paths produce
equivalent optimization problems (same coefficients and vartype).
Parameters:
| Name | Type | Description |
|---|---|---|
instance | ommx.v1.Instance | BinaryModel | The combinatorial optimization problem. ommx.v1.Instance inputs are deep-copied and converted via to_hubo(); BinaryModel inputs retain their declared vartype as the target output vartype. |
uniform_penalty_weight | float | None | Uniform weight passed to :meth:ommx.v1.Instance.to_hubo. None delegates weight selection to OMMX. Ignored for :class:BinaryModel inputs only when left at its default. |
penalty_weights | dict[int, float] | None | Per-constraint penalty weights passed to :meth:ommx.v1.Instance.to_hubo. Keys are constraint IDs. Defaults to no explicit overrides. |
Returns:
ommx.v1.Instance | None — tuple[ommx.v1.Instance | None, ommx.v1.Instance | None, VarType,
ommx.v1.Instance | None — BinaryModel]: A tuple (original_instance, transformed_instance, `VarType` — original_vartype, spin_model). The two instances are None for a
BinaryModel — class:BinaryModel input. The original copy is reserved for
tuple[ommx.v1.Instance | None, ommx.v1.Instance | None, VarType, BinaryModel] — unpenalized result evaluation; the transformed copy owns the binary
tuple[ommx.v1.Instance | None, ommx.v1.Instance | None, VarType, BinaryModel] — substitutions and penalty metadata needed to reconstruct samples.
Raises:
TypeError— Ifinstanceis neither an :class:ommx.v1.Instancenor a :class:BinaryModel.ValueError— If penalty options are supplied for a :class:BinaryModel, which has no OMMX constraints to absorb.
Classes¶
MathematicalProblemConverter [source]¶
class MathematicalProblemConverter(abc.ABC)Constructor¶
def __init__(
self,
instance: ommx.v1.Instance | BinaryModel,
*,
uniform_penalty_weight: float | None = None,
penalty_weights: dict[int, float] | None = None,
) -> NoneInitialize a converter from an OMMX instance or binary model.
Parameters:
| Name | Type | Description |
|---|---|---|
instance | ommx.v1.Instance | BinaryModel | Optimization problem. |
uniform_penalty_weight | float | None | Uniform constraint penalty passed to OMMX. None delegates selection to OMMX. |
penalty_weights | dict[int, float] | None | Optional per-constraint penalty weights keyed by constraint ID. |
Methods¶
decode¶
def decode(self, samples: SampleResult[list[int]]) -> BinarySampleSet | ommx.v1.SampleSetDecode quantum measurement results.
The return type tracks the input that built this converter:
Built from an :class:
ommx.v1.Instance— returns an :class:ommx.v1.SampleSetevaluated against the original (un-penalized) instance, so feasibility, objective, and per-constraint violations are available through OMMX’s own API (.summary,.summary_with_constraints,.best_feasible,.feasible,.objectives).Built from a :class:
BinaryModel— returns a :class:BinarySampleSetwith samples in the model’s original vartype (BINARY 0/1 or SPIN ±1), energies, and shot counts.
Parameters:
| Name | Type | Description |
|---|---|---|
samples | SampleResult[list[int]] | Raw quantum measurement results from ExecutableProgram.sample(...).result(). |
Returns:
BinarySampleSet | ommx.v1.SampleSet — BinarySampleSet | ommx.v1.SampleSet: see method description.
See Also:
:meth:decode_to_binary_sampleset: always returns a
:class:BinarySampleSet. Use it when you need the
QUBO-domain (penalty-included) energy — e.g. to drive a
classical optimizer that must penalize infeasibility.
Example:
>>> # OMMX in → OMMX out
>>> converter = QAOAConverter(ommx_instance)
>>> exe = converter.transpile(QiskitTranspiler(), p=2)
>>> result = exe.sample(QiskitTranspiler().executor(),
... shots=1024,
... bindings={"gammas": gs, "betas": bs}).result()
>>> sample_set = converter.decode(result)
>>> sample_set.best_feasible.objectivedecode_to_binary_sampleset¶
def decode_to_binary_sampleset(self, samples: SampleResult[list[int]]) -> BinarySampleSetDecode samples into a :class:BinarySampleSet.
Always returns a :class:BinarySampleSet, regardless of whether
this converter was constructed with an :class:ommx.v1.Instance
or a :class:BinaryModel. Use this when you need:
The QUBO-domain
energy(penalty-included), e.g. as the cost driving a classical optimizer like COBYLA — :meth:decodeon OMMX-backed converters returns the un-penalized OMMX objective which won’t penalize infeasibility.The per-state
samples/num_occurrences/vartypeviews from :class:BinarySampleSet.
For most usage — feasibility, original-objective evaluation,
per-constraint diagnostics — prefer the polymorphic
:meth:decode, which returns an :class:ommx.v1.SampleSet for
OMMX-backed converters.
Parameters:
| Name | Type | Description |
|---|---|---|
samples | SampleResult[list[int]] | Raw quantum measurement results from ExecutableProgram.sample(...).result(). |
Returns:
BinarySampleSet — keyed by the SPIN model’s original variable
BinarySampleSet — indices (the QUBO variable IDs for OMMX-backed converters)
BinarySampleSet — in the converter’s original_vartype — BINARY for
BinarySampleSet — OMMX-backed converters, the :class:BinaryModel’s declared
BinarySampleSet — vartype otherwise.
get_cost_hamiltonian¶
def get_cost_hamiltonian(self) -> qm_o.HamiltonianConstruct the cost Hamiltonian.
Subclasses must implement this method to build the appropriate
Hamiltonian for their specific algorithm (e.g., Pauli-Z for QAOA,
QRAC-encoded for QRAO). Oracle-based converters that do not use a cost
Hamiltonian (e.g., GASConverter) should raise NotImplementedError.
Returns:
qm_o.Hamiltonian — qm_o.Hamiltonian: The cost Hamiltonian.
Raises:
NotImplementedError— If the converter does not expose a cost Hamiltonian.
SampleResult [source]¶
class SampleResult(Generic[T])Result of a sample() execution.
Contains results as a list of (value, count) tuples.
Example:
result.results # [(0.25, 500), (0.75, 500)]Constructor¶
def __init__(self, results: list[tuple[T, int]], shots: int) -> NoneAttributes¶
results: list[tuple[T, int]] List of (value, count) tuples.shots: int Total number of shots executed.
Methods¶
most_common¶
def most_common(self, n: int = 1) -> list[tuple[T, int]]Return the n most common results.
Parameters:
| Name | Type | Description |
|---|---|---|
n | int | Number of results to return. |
Returns:
list[tuple[T, int]] — List of (result, count) tuples sorted by count descending.
probabilities¶
def probabilities(self) -> list[tuple[T, float]]Return probability distribution over results.
Returns:
list[tuple[T, float]] — List of (value, probability) tuples.