qubosolver
qubosolver
QUBO Solver: a library for solving QUBO problems with classical, quantum, and hybrid algorithms.
Solves Quadratic Unconstrained Binary Optimization (QUBO) problems using classical, quantum, and hybrid algorithms, including on Pasqal neutral-atom QPUs.
Exposes the core data types (Instance, Solution, Dataset, ...), the
Solver entry point, and the transforms, embedding,
drive_shaping, and solving submodules used to build and run quantum,
hybrid, and classical QUBO solvers.
Modules:
-
analysis–Free functions for analysing QUBO solutions.
-
bitstring–Bitstring utilities for QUBO solvers.
-
bitstrings–Batch bitstring utilities for QUBO solvers.
-
drive_shaping–Drive shaping algorithms for generating quantum drive schedules.
-
embedding–Embedding algorithms for mapping QUBO variables onto quantum hardware registers.
-
matrix–Square matrix utilities for QUBO solvers.
-
protocols–Structural protocols for the QUBO solver, using PEP 544
Protocoltyping. -
solver–Config-based entry point for building and running QUBO solvers.
-
solving–Solving algorithms for QUBO problems.
-
tensor–Arbitrary-rank tensor utilities for QUBO solvers.
-
transforms–Transforms for QUBO instances.
-
vector–1-D vector utilities for QUBO solvers.
-
vectori–1-D integer vector utilities for QUBO solvers.
Classes:
-
AutoLocalEmulatorBackend–Factory class that automatically selects optimal emulator backends.
-
AutoRemoteEmulatorBackend–Factory class that automatically selects optimal remote emulator backends.
-
Candidate–A single candidate solution extracted from a
Solution. -
Dataset–A dataset of QUBO instances.
-
Instance–A single QUBO problem instance.
-
LocalEmulator–Local quantum emulator with automatic backend selection.
-
RemoteEmulator–Remote quantum emulator with automatic backend selection.
-
Solution–A collection of candidate solutions for a QUBO problem.
Functions:
-
extract_qubo–Reconstruct the QUBO encoded by a register's geometry and a drive's final detuning.
-
torch_rng–Creates a
torch.Generatorcompatible withqubosolver's torch typing.
AutoLocalEmulatorBackend
Factory class that automatically selects optimal emulator backends.
This factory uses __new__ to return instances of different backend types
based on quantum register size for optimal performance:
MPSBackendfor large problems (≥26 qubits)SVBackendfor medium problems (15-25 qubits)QutipBackendV2for small problems (<15 qubits)
Note
This class acts as a factory and never instantiates itself.
The __new__ method directly returns instances of the selected backend type.
AutoRemoteEmulatorBackend
Factory class that automatically selects optimal remote emulator backends.
This factory uses __new__ to return instances of different remote backend types
based on quantum register size for optimal performance:
RemoteMPSBackendfor large problems (≥26 qubits)RemoteSVBackendfor medium problems (15-25 qubits)RemoteEmuFreeBackendfor small problems (<15 qubits)
Note
This class acts as a factory and never instantiates itself.
The __new__ method directly returns instances of the selected remote backend type.
Candidate
dataclass
Candidate(bitstring: Bitstring, cost: float = float('inf'), count: int = 0, probability: float = 0.0)
A single candidate solution extracted from a Solution.
Instances are normally obtained via Solution.__getitem__ rather
than constructed directly.
Attributes:
-
bitstring(Bitstring) –Binary vector of shape
(n,)with values in \(\\{0, 1\\}^n\) (int8). -
cost(float) –Objective value \(x^T Q x\). Defaults to \(+\\infty\) when constructed without one.
-
count(int) –Number of times this bitstring was sampled. Defaults to
0when constructed without one. -
probability(float) –Sampling probability of this bitstring. Defaults to
0.0when constructed without one.
Dataset
A dataset of QUBO instances.
Each instance is represented by a square matrix \(Q\) such that the optimization objective is \(x^T Q x\), where \(x\) is a binary vector.
Parameters:
-
matrices(torch.Tensor) –Matrices of shape
(size, size, num_instances).matrices[:, :, i]is thei-th QUBO matrix. -
solutions(Sequence[Solution], default:()) –Ground-truth solutions, one per instance. Pass an empty list (default) when solutions are unknown.
-
copy(bool, default:True) –Whether to deep-copy
matricesandsolutionson construction. PassFalseto store the given values directly (no copy), e.g. when the caller already owns them exclusively.
Attributes:
-
matrices–Matrices stored as a 3-D tensor of shape
(size, size, num_instances). The third axis indexes individual problem instances. -
solutions–Known solutions for each instance. Empty when the dataset was created without ground-truth solutions (e.g. via
from_random).
Note
matrices and solutions are deep-copied on construction by
default. Mutating the values passed in afterwards will not affect
the dataset, unless copy=False was given.
Methods:
-
__getitem__–Return the matrix and solution for instance idx.
-
__iter__–Iterate over all
(matrix, solution)pairs in order. -
__len__–Return the number of QUBO instances in the dataset.
-
from_random–Generates a Dataset of random, symmetric QUBO coefficient matrices.
-
load–Load a dataset previously saved with
save. -
save–Persist this dataset to disk using
torch.save.
Source code in qubosolver/types/dataset.py
__getitem__
Return the matrix and solution for instance idx.
Parameters:
-
idx(int) –Zero-based index of the instance.
Returns:
-
tuple[Instance, Solution]–A symmetric matrix and a solution
(Q, solution). When no solutions were provided,solutionis an emptySolution.
Source code in qubosolver/types/dataset.py
__iter__
Iterate over all (matrix, solution) pairs in order.
Yields:
-
tuple[Instance, Solution]–A matrix and a solution. Same as
__getitem__for each index0 … len(self)-1.
Source code in qubosolver/types/dataset.py
__len__
__len__() -> int
from_random
classmethod
from_random(n_matrices: int, matrix_dim: int, *, densities: Sequence[float] = (0.5,), coefficient_bounds: tuple[float, float] = (-10.0, 10.0), dtype: torch.dtype | None = None, rng: torch.Generator | None = None, negative_offdiag_rate: float = 0.0) -> Dataset
Generates a Dataset of random, symmetric QUBO coefficient matrices.
For each requested density, n_matrices symmetric matrices of shape
(matrix_dim, matrix_dim) are generated with (approximately) that
fraction of non-zero entries. Off-diagonal coefficients are positive
(unless flipped negative by negative_offdiag_rate), each matrix is
guaranteed at least one negative diagonal element and at least one
coefficient equal to coefficient_bounds[1], so that the resulting
instances are non-trivial to solve.
Parameters:
-
n_matrices(int) –Number of QUBO matrices to generate for each density.
-
matrix_dim(int) –The dimension of each QUBO matrix.
-
densities(Sequence[float], default:(0.5,)) –List of densities (ratio of non-zero elements).
-
coefficient_bounds(tuple[float, float], default:(-10.0, 10.0)) –Range (min, max) of random values for the coefficients.
-
dtype(torch.dtype | None, default:None) –Data type for the coefficient matrices.
-
rng(torch.Generator | None, default:None) –Random number generator controlling the sampling.
-
negative_offdiag_rate(float, default:0.0) –Fraction of the non-zero off-diagonal coefficients to flip negative. A value of 0 means that no off-diagonal coefficient is negative.
Returns:
-
Dataset–A dataset containing
n_matrices * len(densities)generated coefficient matrices, with no associated solutions.
Source code in qubosolver/types/dataset.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
load
staticmethod
Load a dataset previously saved with save.
Parameters:
-
file_like(FileLike[bytes]) –Source file path or readable binary file object, as produced by
save.
Returns:
-
Dataset–The deserialized dataset, including solutions if they were present when the file was saved.
Raises:
-
ValueError–If the stream is not a qubosolver file.
Example
Source code in qubosolver/types/dataset.py
save
save(file_like: FileLike[bytes]) -> None
Persist this dataset to disk using torch.save.
Parameters:
-
file_like(FileLike[bytes]) –Destination file path or writable binary file object.
Source code in qubosolver/types/dataset.py
Instance
Instance(matrix: Matrix | None = None)
A single QUBO problem instance.
Wraps a symmetric square matrix \(Q\) and exposes helpers for evaluation, serialization, and introspection. The objective to minimize is:
Parameters:
-
matrix(Matrix | None, default:None) –Symmetric matrix \(Q\) of shape
(n, n). Defaults to an empty(0, 0)zero matrix, which represents a trivial problem with no variables.
Methods:
-
__init_subclass__–Register
clsunder its_tagsoloadcan dispatch to it. -
__len__–Number of binary variables in the QUBO problem (same as
size). -
cost–Compute the QUBO objective \(x^T Q x\) for a candidate solution \(x\).
-
load– -
save–Serialize this instance to
file_like, tagged with its type.
Attributes:
-
matrix(Matrix) –The QUBO symmetric matrix.
-
negative_bitflip(negative_bitflip.Instance) –View of this instance as a negative-bitflip instance.
-
size(int) –Number of binary variables in the QUBO problem.
-
variable_fixing(variable_fixing.Instance) –View of this instance as a variable-fixing instance.
-
zeroing(zeroing.Instance) –View of this instance as a zeroing instance.
Source code in qubosolver/types/instance.py
matrix
property
matrix: Matrix
The QUBO symmetric matrix.
Returns:
-
Matrix–QUBO symmetric matrix of shape
(size, size).
Raises:
-
AssertionError–If the internal tensor is not 2-D or not square.
negative_bitflip
property
negative_bitflip: negative_bitflip.Instance
View of this instance as a negative-bitflip instance.
Convenience property to avoid the boilerplate of
assert isinstance(instance, negative_bitflip.Instance) before calling
a method specific to that subclass. It exists purely to satisfy static
type checkers (mypy) and enable IDE code completion — the runtime
isinstance check and the TypeError below just mirror the guarantee that
the assert
would otherwise provide.
Returns:
-
negative_bitflip.Instance–This instance, narrowed to the negative-bitflip subclass.
Raises:
-
TypeError–If this instance is not a
negative_bitflip.Instance.
variable_fixing
property
variable_fixing: variable_fixing.Instance
View of this instance as a variable-fixing instance.
Convenience property to avoid the boilerplate of
assert isinstance(instance, variable_fixing.Instance) before calling
a method specific to that subclass. It exists purely to satisfy static
type checkers (mypy) and enable IDE code completion — the runtime
isinstance check and the TypeError below just mirror the guarantee that
the assert
would otherwise provide.
Returns:
-
variable_fixing.Instance–This instance, narrowed to the variable-fixing subclass.
Raises:
-
TypeError–If this instance is not a
variable_fixing.Instance.
zeroing
property
zeroing: zeroing.Instance
View of this instance as a zeroing instance.
Convenience property to avoid the boilerplate of
assert isinstance(instance, zeroing.Instance) before calling
a method specific to that subclass. It exists purely to satisfy static
type checkers (mypy) and enable IDE code completion — the runtime
isinstance check and the TypeError below just mirror the guarantee that
the assert
would otherwise provide.
Returns:
-
zeroing.Instance–This instance, narrowed to the zeroing subclass.
Raises:
-
TypeError–If this instance is not a
zeroing.Instance.
__init_subclass__
__init_subclass__(**kwargs: object) -> None
Register cls under its _tag so load can dispatch to it.
Automatic, so a new Instance subclass never needs to be added to a
separate registry by hand.
Source code in qubosolver/types/instance.py
__len__
__len__() -> int
cost
Compute the QUBO objective \(x^T Q x\) for a candidate solution \(x\).
Parameters:
-
solution(Bitstring) –Binary vector \(x\) of shape
(size,).
Returns:
-
float–Scalar cost value.
Source code in qubosolver/types/instance.py
load
classmethod
load(file_like: FileLike[bytes]) -> Self
Deserialize an Instance previously saved with save.
Called on the base class qubosolver.Instance, it loads any instance with
automatic dispatch.
Called on a subclass (e.g.
variable_fixing.Instance.load(f)),
it additionally requires the loaded Instance to be an instance of that subclass
(raising TypeError otherwise).
Parameters:
-
file_like(FileLike[bytes]) –Source file path or readable binary file object, as produced by
save.
Returns:
-
Self–A new instance of whichever concrete type wrote the tag.
Raises:
-
ValueError–If the stream is not a qubosolver file, or if its type tag is missing or unrecognized.
-
TypeError–If the loaded instance's type is not
clsor a subclass thereof.
Example
from pathlib import Path
from qubosolver import Instance
from qubosolver.transforms import variable_fixing
file = Path("instance.bin")
instance = variable_fixing.Instance(Instance())
with file.open("wb") as f:
instance.save(f)
# Three ways to load it back, from least to most strict:
with file.open("rb") as f:
loaded = Instance.load(f) # accepts any Instance subtype
# loads, then narrows (fails after loading)
loaded = Instance.load(f).variable_fixing
loaded = variable_fixing.Instance.load(f) # narrows first (fails before loading)
Source code in qubosolver/types/instance.py
save
save(file_like: FileLike[bytes]) -> None
Serialize this instance to file_like, tagged with its type.
Parameters:
-
file_like(FileLike[bytes]) –Destination — a file path (
stroros.PathLike), or a binary-writabletyping.IOstream.
Source code in qubosolver/types/instance.py
LocalEmulator
LocalEmulator(backend_type: type[EmulatorBackend] = AutoLocalEmulatorBackend, **kwargs: Any)
Local quantum emulator with automatic backend selection.
This class wraps qoolqit.execution.LocalEmulator and automatically selects
the optimal local backend based on the quantum register size.
It provides the same interface as the base qoolqit.execution.LocalEmulator but with
improved performance through intelligent backend selection.
The optimal backend selection follows these guidelines:
- Small problems (< 15 qubits):
QutipBackendV2 - Medium problems (15-25 qubits):
SVBackend - Large problems (≥ 26 qubits):
MPSBackend
Parameters:
-
backend_type(type[EmulatorBackend], default:AutoLocalEmulatorBackend) –Backend type to use.
-
**kwargs(Any, default:{}) –Additional keyword arguments passed to the base
qoolqit.execution.LocalEmulator.
Example
Methods:
-
run–Run the quantum program on the selected backend.
Source code in qubosolver/types/backends.py
run
run(program: qoolqit.QuantumProgram, *args: Any, **kwargs: Any) -> Any
Run the quantum program on the selected backend.
Parameters:
-
program(qoolqit.QuantumProgram) –The quantum program to execute.
-
*args(Any, default:()) –Additional positional arguments from
qoolqit.execution.LocalEmulator. -
**kwargs(Any, default:{}) –Additional keyword arguments from
qoolqit.execution.LocalEmulator.
Returns:
-
Any–The execution results from the local backend.
Source code in qubosolver/types/backends.py
RemoteEmulator
Remote quantum emulator with automatic backend selection.
This class wraps qoolqit.execution.RemoteEmulator and provides backend selection
recommendations based on quantum register size and tractability constraints.
Backend selection guidelines based on computational tractability:
- Small problems (< 15 qubits):
RemoteEmuFreeBackend(default) - Medium problems (15-25 qubits):
RemoteSVBackend - Large problems (≥ 26 qubits):
RemoteMPSBackend
Note
RemoteEmuFreeBackend becomes intractable beyond ~15 qubits, similar to its
local counterpart QutipBackendV2. For larger problems, RemoteSVBackend and
RemoteMPSBackend are necessary. Fees may apply for remote execution.
Parameters:
-
backend_type(type[RemoteEmulatorBackend], default:RemoteEmuFreeBackend) –Backend type to use.
-
**kwargs(Any, default:{}) –Additional keyword arguments passed to the base
qoolqit.execution.RemoteEmulator.
Example
Methods:
-
run–Run the quantum program on the selected backend.
Source code in qubosolver/types/backends.py
run
run(program: qoolqit.QuantumProgram, *args: Any, **kwargs: Any) -> Any
Run the quantum program on the selected backend.
Parameters:
-
program(qoolqit.QuantumProgram) –The quantum program to execute.
-
*args(Any, default:()) –Additional positional arguments for
qoolqit.execution.RemoteEmulator. -
**kwargs(Any, default:{}) –Additional keyword arguments for
qoolqit.execution.RemoteEmulator.
Returns:
-
Any–The execution results from the remote backend.
Source code in qubosolver/types/backends.py
Solution
dataclass
Solution(bitstrings: Bitstrings = _bitstrings.zeros_field(0, 0), costs: Vector = vector.zeros_field(0), counts: Vectori = vectori.zeros_field(0), probabilities: Vector = vector.zeros_field(0))
A collection of candidate solutions for a QUBO problem.
Stores all bitstrings returned by a solver together with their associated metadata (costs, sample counts, probabilities).
Attributes:
-
bitstrings(Bitstrings) –int8tensor of shape(num_solutions, n)containing candidate binary vectors (values in \(\\{0, 1\\}^n\)). -
costs(Vector) –Float tensor of shape
(num_solutions,)with the QUBO objective \(x^T Q x\) for each bitstring. -
counts(Vectori) –int64tensor of shape(num_solutions,)with the number of times each bitstring was sampled. -
probabilities(Vector) –Float tensor of shape
(num_solutions,)with the empirical sampling probability of each bitstring.
Methods:
-
__getitem__–Return the candidate at position
idxas aCandidate. -
__iter__–Iterate over all candidates in index order, yielding
Candidateobjects. -
__len__–Return the number of candidate solutions (
num_solutions). -
check_consistency–Check internal consistency of this solution against a QUBO instance.
-
concat–Concatenate several solutions into a new one, without deduplication.
-
deduplicate–Collapse duplicate bitstrings in-place, summing their counts.
-
from_results–Build a
Solutionfrom Pulser quantum-simulation results. -
load– -
save–Serialize this solution to
file_likeusingtorch.save. -
truncate–Keep only the first
kcandidates in-place. -
zeros–Build a single all-zero candidate solution of zero cost.
__getitem__
Return the candidate at position idx as a Candidate.
Parameters:
-
idx(int) –Zero-based index into the
num_solutionsaxis.
Returns:
-
Candidate–Snapshot of the candidate at
idx.
Source code in qubosolver/types/solution.py
__iter__
Iterate over all candidates in index order, yielding Candidate objects.
Yields:
-
Candidate–Same as
__getitem__for each index0 … len(self)-1.
Source code in qubosolver/types/solution.py
__len__
__len__() -> int
check_consistency
check_consistency(*, instance: Instance | None = None, throw: bool = False, full: bool = True, rtol: float = 1e-05, atol: float = 1e-08) -> bool
Check internal consistency of this solution against a QUBO instance.
Recomputes costs from bitstrings and instance.matrix and checks
for duplicate rows, so this can be slow on large solutions — prefer
calling it in tests / debugging rather than on every solver result.
Pass full=False to restrict this to the O(1) shape checks when
calling on a hot path.
Verifies that:
bitstringshasinstance.sizecolumns (wheninstanceis given; otherwise this check is skipped).costs,counts, andprobabilitieseach have exactlylen(self)elements (i.e. none of them is empty).costsmatches \(x^T Q x\) for every bitstring, computed frominstance.matrix(wheninstanceis given; otherwise this check is skipped).costsis sorted in non-decreasing order.probabilitiesmatchescountsnormalized by their sum.countsare strictly positive integers.bitstringscontains no duplicate rows.bitstringsentries are all0or1.
Parameters:
-
instance(Instance | None, default:None) –The QUBO instance this solution is expected to solve.
-
throw(bool, default:False) –When
True, raise anAssertionErroron the first failing check instead of returningFalse. -
full(bool, default:True) –When
True(default), run every check listed above. WhenFalse, only check tensor shapes (constant-time) and skip the rest (cost recomputation, sortedness, duplicate/binary/count/probability checks), which scale with the number of solutions. -
rtol(float, default:1e-05) –Relative tolerance forwarded to
torch.allclosewhen comparingcostsagainst \(x^T Q x\) andprobabilitiesagainst normalizedcounts. -
atol(float, default:1e-08) –Absolute tolerance forwarded to
torch.allclosewhen comparingcostsagainst \(x^T Q x\) andprobabilitiesagainst normalizedcounts.
Returns:
-
bool–Trueif all checks pass,Falseotherwise (unlessthrowisTrue, in which case an exception is raised).
Source code in qubosolver/types/solution.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | |
concat
staticmethod
Concatenate several solutions into a new one, without deduplication.
Concatenates bitstrings, costs, counts, and
probabilities from every solution in solutions. Duplicate
bitstrings, if any, are kept as separate rows — call
deduplicate on the result to collapse them.
Parameters:
-
solutions(Iterable[Solution]) –Solutions to concatenate. Empty solutions (no bitstrings) are skipped. Each remaining solution must have
costs,counts, andprobabilitiespopulated (checked viacheck_consistency(full=False), which raisesAssertionErrorotherwise). -
unit_counts(bool, default:False) –When
True, setcountsto1for every concatenated candidate instead of concatenating their original counts — useful when each candidate should count as a single vote once merged.probabilitiesare always recomputed from the resultingcountsrather than concatenated, so they still sum to 1.
Returns:
-
Solution–
Example
Source code in qubosolver/types/solution.py
deduplicate
deduplicate(update: bool = True) -> Self
Collapse duplicate bitstrings in-place, summing their counts.
Rows sharing the same bitstring are merged into a single row:
counts are summed and the minimum cost is kept.
Parameters:
-
update(bool, default:True) –When
True(default), sort the result by cost and recomputeprobabilitiesfrom the new counts before returning. PassFalseto skip both.
Returns:
-
Self–The same
Solutioninstance, allowing method chaining.
Raises:
-
AssertionError–If this solution is non-empty and
costs,counts, orprobabilitiesis not populated (checked viacheck_consistency(full=False)).
Warning
With update=False, probabilities is left stale and
bitstrings unsorted by cost. Most (if not all) algorithms
expect a consistent solution (see
check_consistency),
so only pass update=False if you will restore consistency
yourself before the solution is used further.
Note
Rows sharing a bitstring are expected to also share the same
cost, since they represent the same candidate — but this
is not checked. The minimum of their costs is kept as a
conservative choice in case that expectation doesn't hold.
Use solution.check_consistency(instance=instance, full=True)
(see check_consistency)
to check the result against that instance — this check is
expensive, so prefer it in tests / debugging rather than
on every call.
Source code in qubosolver/types/solution.py
from_results
staticmethod
Build a Solution from Pulser quantum-simulation results.
Parameters:
-
results(Results) –Pulser results object whose
final_bitstringsattribute is adict[str, int]. -
instance(Instance) –The QUBO instance whose matrix is used to compute
costs.
Returns:
-
Solution–A new solution with all four fields populated, sorted by ascending cost.
Note
When final_bitstrings is empty (no samples recorded),
bitstrings is set to a (0, 0) tensor rather than the
default shape inferred from an empty list, avoiding shape ambiguity.
Source code in qubosolver/types/solution.py
load
staticmethod
Deserialize a Solution previously saved with save.
Parameters:
-
file_like(FileLike[bytes]) –Source — a file path (
stroros.PathLike), or a binary-readabletyping.IOstream. Must contain data written bysave.
Returns:
-
Solution–A new solution with the tensor fields deserialized from
file_like.
Raises:
-
ValueError–If the stream is not a qubosolver file.
Note
torch.load is called with weights_only=True to prevent
arbitrary code execution from untrusted checkpoint files.
Example
Source code in qubosolver/types/solution.py
save
save(file_like: FileLike[bytes]) -> None
Serialize this solution to file_like using torch.save.
Parameters:
-
file_like(FileLike[bytes]) –Destination — a file path (
stroros.PathLike), or a binary-writabletyping.IOstream.
Source code in qubosolver/types/solution.py
truncate
truncate(k: int) -> Self
Keep only the first k candidates in-place.
Recomputes probabilities so they still sum to 1. Does not sort
first; assumes solution is already sorted by ascending cost.
Parameters:
-
k(int) –Number of candidates to keep. When
k >= len(self), this is a no-op.
Returns:
-
Self–The same
Solutioninstance, allowing method chaining.
Raises:
-
AssertionError–If this solution is non-empty and
costs,counts, orprobabilitiesis not populated (checked viacheck_consistency(full=False)).
Source code in qubosolver/types/solution.py
zeros
staticmethod
Build a single all-zero candidate solution of zero cost.
Parameters:
-
length(int) –Number of variables in the bitstring.
-
count(int, default:1) –Number of samples to attribute to this candidate.
Returns:
-
Solution–A
Solutionholding one all-zero candidate.
Source code in qubosolver/types/solution.py
extract_qubo
Reconstruct the QUBO encoded by a register's geometry and a drive's final detuning.
Parameters:
-
register(qoolqit.Register) –The physical register whose geometry encodes the QUBO's off-diagonal coefficients.
-
drive(qoolqit.Drive) –The drive whose final detuning (and, if present, DMM) encodes the QUBO's diagonal coefficients.
Returns:
-
Instance–The reconstructed QUBO instance.
Source code in qubosolver/utils/quantum.py
torch_rng
Creates a torch.Generator compatible with qubosolver's torch typing.
Parameters:
-
seed(int | None, default:None) –Optional seed for reproducibility. If
None, the generator is left with its default (non-deterministic) state.
Returns: