Samplers and Composites#
Samplers#
The dimod package includes several example samplers.
Other Ocean packages provide production samplers; for example, the dwave-system package provides samplers for D-Wave quantum computers and dwave-samplers provides a simulated-annealing sampler.
Exact Solver#
- class ExactSolver[source]#
A simple exact solver for testing and debugging code using your local CPU.
Notes
This solver becomes slow for problems with 18 or more variables.
Examples
This example solves a two-variable Ising model.
>>> h = {'a': -0.5, 'b': 1.0} >>> J = {('a', 'b'): -1.5} >>> sampleset = dimod.ExactSolver().sample_ising(h, J) >>> print(sampleset) a b energy num_oc. 0 -1 -1 -2.0 1 2 +1 +1 -1.0 1 1 +1 -1 0.0 1 3 -1 +1 3.0 1 ['SPIN', 4 rows, 4 samples, 2 variables]
Methods#
|
Sample from a binary quadratic model. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Exact CQM Solver#
- class ExactCQMSolver[source]#
A simple exact solver for testing and debugging code using your local CPU.
Notes
This solver calculates the energy for every possible combination of variable assignments. It becomes slow very quickly
Examples
This example solves a CQM with 3 variables and 1 constraint.
>>> from dimod import ConstrainedQuadraticModel, Binaries, ExactCQMSolver >>> cqm = ConstrainedQuadraticModel() >>> x, y, z = Binaries(['x', 'y', 'z']) >>> cqm.set_objective(x*y + 2*y*z) >>> cqm.add_constraint(x*y == 1, label='constraint_1') 'constraint_1' >>> sampleset = ExactCQMSolver().sample_cqm(cqm) >>> print(sampleset) x y z energy num_oc. is_sat. is_fea. 0 0 0 0 0.0 1 arra... False 1 0 1 0 0.0 1 arra... False 2 1 0 0 0.0 1 arra... False 4 0 0 1 0.0 1 arra... False 6 1 0 1 0.0 1 arra... False 3 1 1 0 1.0 1 arra... True 5 0 1 1 2.0 1 arra... False 7 1 1 1 3.0 1 arra... True ['INTEGER', 8 rows, 8 samples, 3 variables]
Methods#
|
Sample from a constrained quadratic model. |
Exact DQM Solver#
- class ExactDQMSolver[source]#
A simple exact solver for testing and debugging code using your local CPU.
Notes
This solver calculates the energy for every possible combination of variable cases. If variable \(i\) has \(k_i\) cases, this results in \(k_1 * k_2 * ... * k_n\) cases, which grows exponentially for constant \(k_i\) in the number of variables.
Methods#
|
Sample from a discrete quadratic model. |
Identity Sampler#
- class IdentitySampler[source]#
A sampler that can return, expand, or truncate the provided initial states.
Examples:
>>> samples = [{'a': 1, 'b': 0}, {'a': 0, 'b': 1}] >>> Q = {('a', 'b'): -1} >>> sampler = dimod.IdentitySampler() >>> sampleset = sampler.sample_qubo(Q, initial_states=samples) >>> print(sampleset) a b energy num_oc. 0 1 0 0.0 1 1 0 1 0.0 1 ['BINARY', 2 rows, 2 samples, 2 variables]
Add randomly generated samples:
>>> sampleset = sampler.sample_qubo(Q, initial_states=samples, num_reads=4) >>> print(sampleset) a b energy num_oc. 2 1 1 -1.0 1 3 1 1 -1.0 1 0 1 0 0.0 1 1 0 1 0.0 1 ['BINARY', 4 rows, 4 samples, 2 variables]
Note that in the above output, the specified initial states are printed after the generated lower-energy samples but are the first samples in the
record
.
Properties#
Keyword arguments accepted by the sampling methods. |
Methods#
|
Return, expand, or truncate the provided initial states. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Null Sampler#
- class NullSampler(parameters=None)[source]#
A sampler that always returns an empty sample set.
This sampler is useful for writing unit tests where the result is not important.
- Parameters:
parameters (iterable/dict, optional) – If provided, sets the parameters accepted by the sample methods. The values given in these parameters are ignored.
Examples
>>> bqm = dimod.BinaryQuadraticModel.from_qubo({('a', 'b'): 1}) >>> sampler = dimod.NullSampler() >>> sampleset = sampler.sample(bqm) >>> len(sampleset) 0
The next example shows how to enable additional parameters for the null sampler.
>>> bqm = dimod.BinaryQuadraticModel.from_qubo({('a', 'b'): 1}) >>> sampler = dimod.NullSampler(parameters=['a']) >>> sampleset = sampler.sample(bqm, a=5)
Properties#
Keyword arguments accepted by the sampling methods. |
Methods#
|
Return an empty sample set. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Random Sampler#
- class RandomSampler[source]#
A sampler that gives random samples for testing.
Examples
This example produces 10 samples for a two-variable problem.
>>> bqm = dimod.BinaryQuadraticModel.from_qubo({('a', 'b'): 1}) >>> sampler = dimod.RandomSampler() >>> sampleset = sampler.sample(bqm, num_reads=10) >>> len(sampleset) 10
Properties#
Keyword arguments accepted by the sampling methods. |
Methods#
|
Return random samples for a binary quadratic model. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Simulated Annealing Sampler#
Tip
SimulatedAnnealingSampler
is a more performant
implementation of simulated annealing you can use for solving problems.
- class SimulatedAnnealingSampler[source]#
A simple simulated annealing sampler for testing and debugging code.
Examples
This example solves a two-variable Ising model.
>>> h = {'a': -0.5, 'b': 1.0} >>> J = {('a', 'b'): -1.5} >>> sampleset = dimod.SimulatedAnnealingSampler().sample_ising(h, J) >>> sampleset.first.sample {'a': -1, 'b': -1}
Properties#
Keyword arguments accepted by the sampling methods. |
Methods#
|
Sample from low-energy spin states using simulated annealing. |
|
Sample from an Ising model using the implemented sample method. |
Sample from a QUBO using the implemented sample method. |
Higher-Order Samplers#
The dimod package includes the following example higher-order samplers.
Exact Polynomial Solver#
A simple exact solver for testing and debugging code using your local CPU.
- Note:
This sampler is designed for use in testing. Because it calculates the energy for every possible sample, it is very slow.
Class#
- class ExactPolySolver[source]#
A simple exact polynomial solver for testing/debugging code on your CPU.
Notes
This solver becomes slow for problems with 18 or more variables.
Examples
This example solves a three-variable hising model.
>>> h = {'a': -0.5, 'b': 1.0, 'c': 0.} >>> J = {('a', 'b'): -1.5, ('a', 'b', 'c'): -1.0} >>> sampleset = dimod.ExactPolySolver().sample_hising(h, J) >>> print(sampleset) a b c energy num_oc. 1 -1 -1 +1 -3.0 1 5 +1 +1 +1 -2.0 1 0 -1 -1 -1 -1.0 1 3 +1 -1 -1 -1.0 1 4 +1 +1 -1 0.0 1 2 +1 -1 +1 1.0 1 7 -1 +1 -1 2.0 1 6 -1 +1 +1 4.0 1 ['SPIN', 8 rows, 8 samples, 3 variables]
This example solves a three-variable binary polynomial
>>> poly = dimod.BinaryPolynomial({('a',): 1.5, ('a', 'b'): -1, ('a', 'b', 'c'): 0.5}, 'SPIN') >>> sampleset = dimod.ExactPolySolver().sample_poly(poly) >>> sampleset.first.sample {'a': -1, 'b': -1, 'c': -1}
Methods#
|
Sample from a higher-order Ising model. |
|
Sample from a higher-order unconstrained binary optimization problem. |
|
Sample from a binary polynomial. |
Composites#
The dimod package includes several example composed samplers:
The dwave-system package provides additional composites for D-Wave quantum computers such as those used for minor-embedding.
Structure Composite#
A composite that structures a sampler.
Class#
- class StructureComposite(sampler, nodelist, edgelist)[source]#
Creates a structured composed sampler from an unstructured sampler.
Useful for simulation; for example testing a QPU’s working graph with the
SimulatedAnnealingSampler
class.- Parameters:
Examples
This example creates a composed sampler from the unstructured dimod ExactSolver sampler. The target structure is a square graph.
>>> base_sampler = dimod.ExactSolver() >>> node_list = [0, 1, 2, 3] >>> edge_list = [(0, 1), (1, 2), (2, 3), (0, 3)] >>> structured_sampler = dimod.StructureComposite(base_sampler, node_list, edge_list) ... >>> linear = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0} >>> quadratic = {(0, 1): 1.0, (1, 2): 1.0, (0, 3): 1.0, (2, 3): -1.0} >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 1.0, dimod.Vartype.SPIN) ... >>> response = structured_sampler.sample(bqm) >>> response.first.energy -1.0
The next part of the example tries giving the composed sampler a non-square model:
>>> del quadratic[(0, 1)] >>> quadratic[(0, 2)] = 1.0 >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 1.0, dimod.Vartype.SPIN) ... >>> try: ... response = structured_sampler.sample(bqm) ... except dimod.BinaryQuadraticModelStructureError as details: ... print(details) ... given bqm contains an interaction, (0, 2), not supported by the structured solver
Properties#
The child sampler. |
|
Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. |
|
Properties as a dict containing any additional information about the sampler. |
Methods#
|
Sample from the binary quadratic model. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Tracking Composite#
A composite that tracks inputs and outputs.
Class#
- class TrackingComposite(child, copy=False)[source]#
Composite that tracks inputs and outputs for debugging and testing.
- Parameters:
child (
dimod.Sampler
) – A dimod sampler.copy (bool, optional, default=False) – If True, the inputs/outputs are copied (with
copy.deepcopy()
) before they are stored. This is useful if the child sampler mutates the values.
Examples
>>> sampler = dimod.TrackingComposite(dimod.RandomSampler()) >>> sampleset = sampler.sample_ising({'a': -1}, {('a', 'b'): 1}, ... num_reads=5) >>> sampler.input {'h': {'a': -1}, 'J': {('a', 'b'): 1}, 'num_reads': 5} >>> sampleset == sampler.output True
If we make additional calls to the sampler, the most recent input/output are stored in
input
andoutput
respectively. However, all are tracked ininputs
andoutputs
.>>> sampleset = sampler.sample_qubo({('a', 'b'): 1}) >>> sampler.input {'Q': {('a', 'b'): 1}} >>> sampler.inputs [{'h': {'a': -1}, 'J': {('a', 'b'): 1}, 'num_reads': 5}, {'Q': {('a', 'b'): 1}}]
In the case that you want to nest the tracking composite, there are two patterns for retrieving the data
>>> from dimod import TruncateComposite, TrackingComposite, ExactSolver ... >>> sampler = TruncateComposite(TrackingComposite(ExactSolver()), 10) >>> sampler.child.inputs # empty because we haven't called sample []
>>> intermediate_sampler = TrackingComposite(ExactSolver()) >>> sampler = TruncateComposite(intermediate_sampler, 10) >>> intermediate_sampler.inputs []
Properties#
The most recent input to any sampling method. |
|
All of the inputs to any sampling methods. |
|
The most recent output of any sampling method. |
|
All of the outputs from any sampling methods. |
|
Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. |
|
Properties as a dict containing any additional information about the sampler. |
Methods#
Clear all the inputs/outputs. |
|
|
Sample from the child sampler and store the given inputs/outputs. |
|
Sample from the child sampler and store the given inputs/outputs. |
|
Sample from the child sampler and store the given inputs/outputs. |
Truncate Composite#
A composite that truncates the returned dimod.SampleSet
based on options
specified by the user.
Class#
- class TruncateComposite(child_sampler, n, sorted_by='energy', aggregate=False)[source]#
Composite to truncate the returned sample set.
Inherits from
dimod.ComposedSampler
.Post-processing can be expensive and sometimes you might want to only handle the lowest-energy samples. This composite layer allows you to pre-select the samples within a multi-composite pipeline.
- Parameters:
child_sampler (
dimod.Sampler
) – A dimod sampler.n (int) – Maximum number of rows in the returned sample set.
sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before truncating. Note that sample order is maintained in the underlying array.
aggregate (bool, optional, default=False) – If True, aggregates the samples before truncating and sets the value of the
num_occurrences
field in the returnedSampleSet
to the number of accumulated samples for each occurrence.
Examples
>>> sampler = dimod.TruncateComposite(dimod.RandomSampler(), n=2, aggregate=True) >>> bqm = dimod.BinaryQuadraticModel.from_ising({"a": 1, "b": 2}, {("a", "b"): -1}) >>> sampleset = sampler.sample(bqm, num_reads=100) >>> print(sampleset) a b energy num_oc. 0 -1 -1 -4.0 16 1 +1 -1 0.0 22 ['SPIN', 2 rows, 38 samples, 2 variables]
Properties#
The child sampler. |
|
List of child samplers that that are used by this composite. |
|
Parameters as a dict, where keys are keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter. |
|
Properties as a dict containing any additional information about the sampler. |
Methods#
|
Sample from the binary quadratic model and truncate returned sample set. |
|
Sample from an Ising model using the implemented sample method. |
|
Sample from a QUBO using the implemented sample method. |
Higher-Order Composites#
The dimod package includes several example higher-order composed samplers.
HigherOrderComposite#
- class HigherOrderComposite(child_sampler)[source]#
Convert a binary quadratic model sampler to a binary polynomial sampler.
Energies of the returned samples do not include the penalties.
- Parameters:
sampler (
dimod.Sampler
) – A dimod sampler
Example
This example uses
HigherOrderComposite
to instantiate a composed sampler that submits a simple Ising problem to a sampler. The composed sampler creates a binary quadratic model (BQM) from a higher order problem.>>> sampler = dimod.HigherOrderComposite(dimod.ExactSolver()) >>> h = {0: -0.5, 1: -0.3, 2: -0.8} >>> J = {(0, 1, 2): -1.7} >>> sampleset = sampler.sample_hising(h, J, discard_unsatisfied=True) >>> set(sampleset.first.sample.values()) == {1} True
Properties#
The child sampler. |
|
A list containing the wrapped sampler. |
|
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. |
|
A dict containing any additional information about the sampler. |
Methods#
|
Sample from the given binary polynomial. |
|
Sample from a higher-order Ising model. |
|
Sample from a higher-order unconstrained binary optimization problem. |
PolyFixedVariableComposite#
- class PolyFixedVariableComposite(child_sampler)[source]#
Composite that fixes variables of a problem.
Fixes variables of a binary polynomial and modifies linear and k-local terms accordingly. Returned samples include the fixed variable.
- Parameters:
sampler (
dimod.PolySampler
) – A dimod polynomial sampler.
Examples
This example uses
PolyFixedVariableComposite
to instantiate a composed sampler that submits a simple high-order Ising problem to a sampler. The composed sampler fixes a variable and modifies linear and k-local terms biases.>>> h = {1: -1.3, 2: 1.2, 3: -3.4, 4: -0.5} >>> J = {(1, 4): -0.6, (1, 2, 3): 0.2, (1, 2, 3, 4): -0.1} >>> poly = dimod.BinaryPolynomial.from_hising(h, J, offset=0) >>> sampler = dimod.PolyFixedVariableComposite(dimod.ExactPolySolver()) >>> sampleset = sampler.sample_poly(poly, fixed_variables={3: -1, 4: 1})
Properties#
The child sampler. |
|
List of child samplers that that are used by this composite. |
|
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. |
|
A dict containing any additional information about the sampler. |
Methods#
Sample from the provided binary quadratic model. |
|
Sample from a higher-order Ising model. |
|
Sample from a higher-order unconstrained binary optimization problem. |
PolyScaleComposite#
- class PolyScaleComposite(child)[source]#
Composite to scale biases of a binary polynomial.
- Parameters:
child (
PolySampler
) – A binary polynomial sampler.
Examples
>>> linear = {'a': -4.0, 'b': -4.0} >>> quadratic = {('a', 'b'): 3.2, ('a', 'b', 'c'): 1} >>> sampler = dimod.PolyScaleComposite(dimod.HigherOrderComposite(dimod.ExactSolver())) >>> response = sampler.sample_hising(linear, quadratic, scalar=0.5, ... ignored_terms=[('a','b')])
Properties#
The child sampler. |
|
The child sampler in a list |
|
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. |
|
A dict containing any additional information about the sampler. |
Methods#
|
Scale and sample from the given binary polynomial. |
|
Sample from a higher-order Ising model. |
|
Sample from a higher-order unconstrained binary optimization problem. |
PolyTruncateComposite#
- class PolyTruncateComposite(child_sampler, n, sorted_by='energy', aggregate=False)[source]#
Composite that truncates returned samples.
Post-processing is expensive and sometimes one might want to only treat the lowest-energy samples. This composite layer allows one to pre-select the samples within a multi-composite pipeline.
- Parameters:
child_sampler (
dimod.PolySampler
) – A dimod binary polynomial sampler.n (int) – Maximum number of rows in the returned sample set.
sorted_by (str/None, optional, default='energy') – Selects the record field used to sort the samples before truncating. Note that sample order is maintained in the underlying array.
aggregate (bool, optional, default=False) – If True, aggregate the samples before truncating.
Note
If aggregate is True,
SampleSet.record.num_occurrences
are accumulated but no other fields are.
Properties#
The child sampler. |
|
List of child samplers that that are used by this composite. |
|
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter. |
|
A dict containing any additional information about the sampler. |
Methods#
|
Sample from the binary polynomial and truncate output. |
|
Sample from a higher-order Ising model. |
|
Sample from a higher-order unconstrained binary optimization problem. |