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()anddecode()to serialize and recover solutions.
best_sample_idx property ¶
Get the index of the sample with the best objective value.
obj_values property ¶
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 ¶
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.
add_var method descriptor ¶
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 | 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 | ... |
Raises:
| Type | Description |
|---|---|
SampleColumnCreationError | |
cvar method descriptor ¶
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 | 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 ¶
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 ¶
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 ¶
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 |
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 |
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 |
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 ¶
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 ¶
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 | 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 | 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.
| 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 ¶
Represent the solution as a html table.
Returns:
| Type | Description |
|---|---|
str | |
serialize method descriptor ¶
Alias for encode().