Skip to content

Solution

The solution object that is obtained by running an algorihtm.

The Solution class represents a summary of all data obtained from solving a model. It contains samples, i.e., assignments of values to each model variable as returned by the algorithm, metadata about the solution quality, e.g., the objective value, and the runtime of the algorithm.

A Solution can be constructed explicitly using from_dict, from_dicts or by obtaining a solution from an algorithm or by converting a different solution format with one of the available translators. Note that the latter requires the environment the model was created in.

Examples:

Basic usage, assuming that the algorithm already returns a Solution:

>>> from luna_quantum import Model, Solution
>>> model: Model = ...
>>> algorithm = ...
>>> solution: Solution = algorithm.run(model)
>>> solution.samples
[[1, 0, 1], [0, 0, 1]]

When you have a dimod.Sampleset as the raw solution format:

>>> from luna_quantum.translator import BqmTranslator
>>> from luna_quantum import Model, Solution, DwaveTranslator
>>> from dimod import SimulatedAnnealingSampler
>>> model: Model = ...
>>> bqm = BqmTranslator.from_aq(model)
>>> sampleset = SimulatedAnnealingSampler().sample(bqm)
>>> solution = DwaveTranslator.from_dimod_sample_set(sampleset)
>>> solution.samples
[[1, 0, 1], [0, 0, 1]]

Serialization:

>>> blob = solution.encode()
>>> restored = Solution.decode(blob)
>>> restored.samples
[[1, 0, 1], [0, 0, 1]]
Notes
  • To ensure metadata like objective values or feasibility, use model.evaluate(solution).
  • Use encode() and decode() to serialize and recover solutions.

best_sample_idx property

best_sample_idx: int | None

Get the index of the sample with the best objective value.

counts property

counts: NDArray

Return how often each sample occurred in the solution.

obj_values property

obj_values: NDArray | None

Get the objective values of the single samples as a ndarray. A value will be None if the sample hasn't yet been evaluated.

raw_energies property

raw_energies: NDArray | None

Get the raw energy values of the single samples as returned by the solver / algorithm. Will be None if the solver / algorithm did not provide a value.

results property

results: ResultIterator

Get an iterator over the single results of the solution.

runtime property

runtime: Timing | None

Get the solver / algorithm runtime.

samples property

samples: Samples

Get a view into the samples of the solution.

sense property

sense: Sense

Get the optimization sense.

variable_names property

variable_names: list[str]

Get the names of all variables in the solution.

__eq__ method descriptor

__eq__(value) -> bool

Return self==value.

__ge__ method descriptor

__ge__(value)

Return self>=value.

__getitem__ method descriptor

__getitem__(key) -> ResultView

Return self[key].

__iter__ method descriptor

__iter__() -> ResultIterator

Implement iter(self).

__le__ method descriptor

__le__(value)

Return self<=value.

__len__ method descriptor

__len__() -> int

Return len(self).

__repr__ method descriptor

__repr__() -> str

Return repr(self).

__str__ method descriptor

__str__() -> str

Return str(self).

add_var method descriptor

add_var(
    var: str | Variable, data: list[int | float], vtype: Vtype | None = None
) -> None

Add a variable column to the solution.

Parameters:

Name Type Description Default
var str | Variable

The name of the variable for which the sample column is created, or the variable itself.

required
data list[int | float]

The contents of the sample column to be added.

required
vtype Vtype | None

The vtype of the variable for which the sample column is created. If the var parameter is a str, the vtype is defaulted to Vtype.Binary. If the var is a Variable, the vtype parameter is ignored and the vtype of the variable is used.

None

Raises:

Type Description
SampleColumnCreationError

add_vars method descriptor

add_vars(
    variables: list[Variable | str],
    data: list[list[int | float]],
    vtypes: list[Vtype | None] | None = None,
) -> None

Add multiple variable columns to the solution.

Parameters:

Name Type Description Default
vars list[str | Variable]

The names of the variable for which the sample columns are created, or a list of the variables itself.

required
data list[list[int | float]]

A list of the contents of the sample columns to be added.

required
vtypes list[Vtype] | None

The vtypes of the variables for which the sample columns are created. If the vars parameter is a list[str], the vtypes are defaulted to Vtype.Binary. If thevarsis a list[Variable], thevtypesparameter is ignored and the vtypes of the variable is used. For mixedvars`, the vtype is chosen dynamically following the two rules above.

...

Raises:

Type Description
SampleColumnCreationError

best method descriptor

best() -> ResultView | None

Get the best result.

cvar method descriptor

cvar(alpha: float) -> float

Compute the Conditional Value at Rist (CVaR) of the solution.

Returns:

Type Description
float

The CVaR.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

decode builtin

decode(data: bytes) -> Solution

Reconstruct a solution object from binary data.

Parameters:

Name Type Description Default
data bytes

Serialized model blob created by encode().

required

Returns:

Type Description
Solution

The reconstructed solution.

Raises:

Type Description
DecodeError

If decoding fails due to corruption or incompatibility.

deserialize builtin

deserialize(data: bytes) -> Solution

Alias for decode().

See decode() for full documentation.

encode method descriptor

encode(compress: bool = True, level: int = 3) -> bytes

Serialize the solution into a compact binary format.

Parameters:

Name Type Description Default
compress bool

Whether to compress the binary output. Default is True.

True
level int

Compression level (0–9). Default is 3.

3

Returns:

Type Description
bytes

Encoded model representation.

Raises:

Type Description
IOError

If serialization fails.

expectation_value method descriptor

expectation_value() -> float

Compute the expectation value of the solution.

Returns:

Type Description
float

The expectation value.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

feasibility_ratio method descriptor

feasibility_ratio() -> float

Compute the expectation value of the solution.

Returns:

Type Description
float

The feasibility ratio.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

filter method descriptor

filter(f: Callable[[ResultView], bool]) -> Solution

Get a new solution with all samples for which the condition f is true.

Parameters:

Name Type Description Default
f Callable[[ResultView], bool]

A filter function yielding true for all samples to be contained in the new solution.

required

Returns:

Type Description
Solution

The new solution with only samples for which the condition is true.

filter_feasible method descriptor

filter_feasible() -> Solution

Get a new solution with all infeasible samples removed.

Returns:

Type Description
The new solution with only feasible samples.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

from_counts staticmethod

from_counts(
    data: dict[str, int],
    env: Environment | None = None,
    model: Model | None = None,
    timing: Timing | None = None,
    sense: Sense | None = None,
    bit_order: Literal["LTR", "RTL"] = Ellipsis,
    energies=None,
) -> Solution

Create a Solution from a dict that maps measured bitstrings to counts.

If a Model is passed, the solution will be evaluated immediately. Otherwise, there has to be an environment present to determine the correct variable types. Only applicable to binary or spin models.

Parameters:

Name Type Description Default
data dict[str, int]

The counts that shall be part of the solution.

required
env Environment

The environment the variable types shall be determined from.

None
model Model

A model to evaluate the sample with.

None
timing Timing

The timing for acquiring the solution.

None
sense Sense

The sense the model the solution belongs to. Default: Sense.Min

None
bit_order Literal['LTR', 'RTL']

The order of the bits in the bitstring. Default "RTL".

Ellipsis

Returns:

Type Description
Solution

The solution object created from the sample dict.

Raises:

Type Description
NoActiveEnvironmentFoundError

If no environment or model is passed to the method or available from the context.

ValueError

If env and model are both present. When this is the case, the user's intention is unclear as the model itself already contains an environment. Or if sense and model are both present as the sense is then ambiguous. Or if the the environment contains non-(binary or spin) variables. Or if a bitstring contains chars other than '0' and '1'.

SolutionTranslationError

Generally if the sample translation fails. Might be specified by one of the three following errors.

SampleIncorrectLengthErr

If a sample has a different number of variables than the environment.

from_dict staticmethod

from_dict(
    data: dict[Variable | str, int | float],
    env: Environment | None = None,
    model: Model | None = None,
    timing: Timing | None = None,
    counts: int | None = None,
    sense: Sense | None = None,
    energy=None,
) -> Solution

Create a Solution from a dict that maps variables or variable names to their assigned values.

If a Model is passed, the solution will be evaluated immediately. Otherwise, there has to be an environment present to determine the correct variable types.

Parameters:

Name Type Description Default
data dict[Variable | str, int | float]

The sample that shall be part of the solution.

required
env Environment

The environment the variable types shall be determined from.

None
model Model

A model to evaluate the sample with.

None
counts int

The number of occurrences of this sample.

None

Returns:

Type Description
Solution

The solution object created from the sample dict.

Raises:

Type Description
NoActiveEnvironmentFoundError

If no environment or model is passed to the method or available from the context.

ValueError

If env and model are both present. When this is the case, the user's intention is unclear as the model itself already contains an environment. Or if sense and model are both present as the sense is then ambiguous.

SolutionTranslationError

Generally if the sample translation fails. Might be specified by one of the three following errors.

SampleIncorrectLengthErr

If a sample has a different number of variables than the environment.

SampleUnexpectedVariableError

If a sample has a variable that is not present in the environment.

ModelVtypeError

If the result's variable types are incompatible with the model environment's variable types.

from_dicts staticmethod

from_dicts(
    data: list[dict[Variable | str, int | float]],
    env: Environment | None = None,
    model: Model | None = None,
    timing: Timing | None = None,
    counts: list[int] | None = None,
    sense: Sense | None = None,
    energies=None,
) -> Solution

Create a Solution from multiple dicts that map variables or variable names to their assigned values.

If a Model is passed, the solution will be evaluated immediately. Otherwise, there has to be an environment present to determine the correct variable types.

Parameters:

Name Type Description Default
data list[dict[Variable | str, int | float]]

The samples that shall be part of the solution.

required
env Environment

The environment the variable types shall be determined from.

None
model Model

A model to evaluate the sample with.

None
counts int

The number of occurrences for each sample.

None
timing Timing

The timing for acquiring the solution.

None
sense Sense

The sense the model the solution belongs to. Default: Sense.Min

None

Returns:

Type Description
Solution

The solution object created from the sample dict.

Raises:

Type Description
NoActiveEnvironmentFoundError

If no environment or model is passed to the method or available from the context.

ValueError

If env and model are both present. When this is the case, the user's intention is unclear as the model itself already contains an environment. Or if sense and model are both present as the sense is then ambiguous. Or if the the number of samples and the number of counts do not match.

SolutionTranslationError

Generally if the sample translation fails. Might be specified by one of the three following errors.

SampleIncorrectLengthErr

If a sample has a different number of variables than the environment.

SampleUnexpectedVariableError

If a sample has a variable that is not present in the environment.

ModelVtypeError

If the result's variable types are incompatible with the model environment's variable types.

highest_constraint_violation

highest_constraint_violation() -> int | None

Get the index of the constraint with the highest number of violations.

Returns:

Type Description
int | None

The index of the constraint with the most violations. None, if the solution was created for an unconstrained model.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

highest_constraint_violations method descriptor

highest_constraint_violations()

Get the index of the constraint with the highest number of violations.

Returns:

Type Description
int | None

The index of the constraint with the most violations. None, if the solution was created for an unconstrained model.

Raises:

Type Description
ComputationError

If the computation fails for any reason.

print method descriptor

print(
    layout: Literal["row", "column"] = Ellipsis,
    max_line_length: int = Ellipsis,
    max_column_length: int = Ellipsis,
    max_lines: int = Ellipsis,
    max_var_name_length: int = Ellipsis,
    show_metadata: Literal["before", "after", "hide"] = Ellipsis,
) -> None

Show a solution object as a human-readable string.

This method provides various ways to customize the way the solution is represented as a string.

Parameters:

Name Type Description Default
layout Literal['row', 'column']

With "row" layout, all assignments to one variable across different samples are shown in the same row, and each sample is shown in one column. With "column" layout, all assignments to one variable across different samples are shown in the same column, and each sample is shown in one row.

Ellipsis
max_line_length int

The max number of chars shown in one line or, in other words, the max width of a row.

Ellipsis
max_column_length int

The maximal number of chars in one column. For both the row and column layout, this controls the max number of chars a single variable assignment may be shown with. For the column layout, this also controls the max number of chars that a variable name is shown with. Note: the max column length cannot always be adhered to. This is specifically the case when a variable assignment is so high that the max column length is not sufficient to show the number correctly.

Ellipsis
max_lines int

The max number of lines used for showing the samples. Note that this parameter does not influence how metadata are shown, s.t. the total number of lines may be higher than max_lines.

Ellipsis
max_var_name_length int

The max number of chars that a variable is shown with in row layout. This parameter is ignored in column layout.

Ellipsis
show_metadata Literal['before', 'after', 'hide']

Whether and where to show sample-specific metadata such as feasibility and objective value. Note that this parameter only controls how sample-specific metadata are shown. Other metadata, like the solution timing will be shown after the samples regardless of the value of this parameter.

  • "before": show metadata before the actual sample, i.e., above the sample in row layout, and left of the sample in column layout.
  • "after": show metadata after the actual sample, i.e., below the sample in row layout, and right of the sample in column layout.
  • "hide": do not show sample-specific metadata.
Ellipsis

Returns:

Type Description
str

The solution represented as a string.

Raises:

Type Description
ValueError

If at least one of the params has an invalid value.

remove_var method descriptor

remove_var(var: str | Variable) -> None

Remove the sample column for the given variable.

remove_vars method descriptor

remove_vars(variables: list[str | Variable]) -> None

Remove the sample columns for the given variables.

repr_html

repr_html() -> str

Represent the solution as a html table.

Returns:

Type Description
str

serialize method descriptor

serialize(compress: bool | None = True, level: int | None = 3) -> bytes

Alias for encode().