Composites#
dimod composites that provide layers of pre- and post-processing (e.g., minor-embedding) when using the D-Wave system:
Other Ocean packages provide additional composites; for example, dimod provides composites that operate on the problem (e.g., scaling values), track inputs and outputs for debugging, and other useful functionality relevant to generic samplers.
CutOffs#
Prunes the binary quadratic model (BQM) submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision.
The following composites are supported:
- class CutOffComposite(child_sampler, cutoff, cutoff_vartype=Vartype.SPIN, comparison=<built-in function lt>)[source]#
Bases:
ComposedSamplerComposite to remove interactions below a specified cutoff value.
Prunes the binary quadratic model (BQM) submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision as specified by the
cutoffargument. Also removes variables isolated post- or pre-removal of these interactions from the BQM passed on to the child sampler, setting these variables to values that minimize the original BQM’s energy for the returned samples.- Parameters:
sampler (
dimod.Sampler) – A dimod sampler.cutoff (number) – Lower bound for absolute value of interactions. Interactions with absolute values lower than
cutoffare removed. Isolated variables are also not passed on to the child sampler.cutoff_vartype (
Vartype/str/set, default=’SPIN’) –Variable space to execute the removal in. Accepted input values:
Vartype.SPIN,'SPIN',{-1, 1}Vartype.BINARY,'BINARY',{0, 1}
comparison (function, optional) – A comparison operator for comparing interaction values to the cutoff value. Defaults to
operator.lt().
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
This example removes one interaction,
'ac': -0.7, before embedding on a D-Wave system. Note that the lowest-energy sample for the embedded problem is unchanged{'a': 1, 'b': -1, 'c': -1}and this solution is found. However, the sample is attributed the energy appropriate to the bqm without thresholding.>>> import dimod >>> sampler = DWaveSampler(solver={'qpu': True}) >>> bqm = dimod.BinaryQuadraticModel({'a': -1, 'b': 1, 'c': 1}, ... {'ab': 0.8, 'ac': 0.7, 'bc': -1}, ... 0, ... dimod.SPIN) >>> samples = CutOffComposite( ... AutoEmbeddingComposite(sampler), 0.75).sample(bqm, num_reads=1000) >>> print(samples.first.energy) -5.5
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- property children#
List of child samplers that that are used by this composite.
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- property parameters#
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevant to each parameter.
- property properties#
A dict containing any additional information about the sampler.
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- sample(bqm, **parameters)[source]#
Cut off interactions and sample from the provided binary quadratic model.
Prunes the binary quadratic model (BQM) submitted to the child sampler by retaining only interactions with value commensurate with the sampler’s precision as specified by the
cutoffargument. Also removes variables isolated post- or pre-removal of these interactions from the BQM passed on to the child sampler, setting these variables to values that minimize the original BQM’s energy for the returned samples.- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
Examples
See the example in
CutOffComposite.
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- class PolyCutOffComposite(child_sampler, cutoff, cutoff_vartype=Vartype.SPIN, comparison=<built-in function lt>)[source]#
Bases:
ComposedPolySamplerComposite to remove polynomial interactions below a specified cutoff value.
Prunes the binary polynomial submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision as specified by the
cutoffargument. Also removes variables isolated post- or pre-removal of these interactions from the polynomial passed on to the child sampler, setting these variables to values that minimize the original polynomial’s energy for the returned samples.- Parameters:
sampler (
dimod.PolySampler) – A dimod binary polynomial sampler.cutoff (number) – Lower bound for absolute value of interactions. Interactions with absolute values lower than
cutoffare removed. Isolated variables are also not passed on to the child sampler.cutoff_vartype (
Vartype/str/set, default=’SPIN’) –Variable space to do the cutoff in. Accepted input values:
Vartype.SPIN,'SPIN',{-1, 1}Vartype.BINARY,'BINARY',{0, 1}
comparison (function, optional) – A comparison operator for comparing the interaction value to the cutoff value. Defaults to
operator.lt().
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
This example removes one interaction,
'ac': 0.2, before submitting the polynomial to child samplerExactSolver.>>> import dimod >>> sampler = dimod.HigherOrderComposite(dimod.ExactSolver()) >>> poly = dimod.BinaryPolynomial({'a': 3, 'abc':-4, 'ac': 0.2}, dimod.SPIN) >>> samples = PolyCutOffComposite(sampler, 1).sample_poly(poly) >>> print(samples.first.sample['a']) -1
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- property children#
List of child samplers that that are used by this composite.
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- property parameters#
A dict where keys are the keyword parameters accepted by the sampler methods and values are lists of the properties relevent to each parameter.
- property properties#
A dict containing any additional information about the sampler.
- sample_hising(h: Mapping[Hashable, float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **kwargs) SampleSet#
Sample from a higher-order Ising model.
Converts the given higher-order Ising model to a
BinaryPolynomialand callssample_poly().- Parameters:
h – Variable biases of the Ising problem.
J – Interaction biases of the Ising problem.
**kwargs – See
sample_poly()for additional keyword definitions.
- Returns:
Samples from the higher-order Ising model.
See also
- sample_hubo(H: Mapping[tuple[Hashable, Hashable], float | floating | integer], **kwargs) SampleSet#
Sample from a higher-order unconstrained binary optimization problem.
Converts the given higher-order unconstrained binary optimization problem to a
BinaryPolynomialand then callssample_poly().- Parameters:
H – Coefficients of the HUBO.
**kwargs – See
sample_poly()for additional keyword definitions.
- Returns:
Samples from a higher-order unconstrained binary optimization problem.
See also
- sample_poly(poly, **kwargs)[source]#
Cutoff and sample from the provided binary polynomial.
Prunes the binary polynomial submitted to the child sampler by retaining only interactions with values commensurate with the sampler’s precision as specified by the
cutoffargument. Also removes variables isolated post- or pre-removal of these interactions from the polynomial passed on to the child sampler, setting these variables to values that minimize the original polynomial’s energy for the returned samples.- Parameters:
poly (
dimod.BinaryPolynomial) – Binary polynomial to be sampled from.**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
Examples
See the example in
PolyCutOffComposite.
Embedding#
Minor-embed a problem BQM into a D-Wave system.
Embedding composites for various types of problems and application. For example:
EmbeddingCompositefor a problem with arbitrary structure that likely requires hueristic embedding.AutoEmbeddingCompositecan save unnecessary embedding for problems that might have a structure similar to the child sampler.LazyFixedEmbeddingCompositecan benefit applications that resubmit a BQM with changes in some values.
The following composites are supported:
- class AutoEmbeddingComposite(child_sampler, **kwargs)[source]#
Bases:
EmbeddingCompositeMaps problems to a structured sampler, embedding if needed.
This composite first tries to submit the binary quadratic model directly to the child sampler and only embeds if a
BinaryQuadraticModelStructureErrorexception is raised.- Parameters:
child_sampler (
dimod.Sampler) – Structured dimod sampler, such as aDWaveSampler().find_embedding (function, optional) – A function
find_embedding(S, T, **kwargs)whereSandTare edgelists. The function can accept additional keyword arguments. Defaults tominorminer.find_embedding().kwargs – See the
EmbeddingCompositeclass for additional keyword arguments.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- return_embedding_default = False#
Defines the default behavior for returning embeddings.
Sets the default for the
sample()method’sreturn_embeddingoptional parameter (kwarg).
- sample(bqm, **parameters)[source]#
Sample from the provided binary quadratic model.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default,
chain_strengthis calculated withuniform_torque_compensation().chain_break_method (function/list, optional) – Method or methods used to resolve chain breaks. If multiple methods are given, the results are concatenated and a new field called
chain_break_methodspecifying the index of the method is appended to the sample set. Seeunembed_sampleset()andchain_breaks.chain_break_fraction (bool, optional, default=True) – Add a
chain_break_fractionfield to the unembedded response with the fraction of chains broken before unembedding.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments. Overrides any embedding parameters passed to the constructor.
return_embedding (bool, optional) – If True, the embedding, chain strength, chain break method and embedding parameters are added to the
infofield of the returned sample set. The default behavior is defined by thereturn_embedding_defaultattribute, which by default is False.warnings (
WarningAction, optional) – Defines what warning action to take, if any (see the Warnings section). The default behavior is defined by thewarnings_defaultattribute, which by default isIGNORE**parameters – Parameters for the sampling method, specified by the child sampler.
Changed in version 1.33.0: For native embeddings,
chain_strength,chain_break_methodandembedding_parametersparameters are ignored.chain_break_fractionare set to zero for all samples.Added in version 1.33.0: Embedding/unembedding duration included under
timingkey of theembedding_contextwhen embedding is returned.- Returns:
Examples
See the example in
EmbeddingComposite.
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- class EmbeddingComposite(child_sampler, find_embedding=<function find_embedding>, embedding_parameters=None, scale_aware=False, child_structure_search=<function child_structure_dfs>)[source]#
Bases:
ComposedSamplerMaps problems to a structured sampler.
Automatically minor-embeds a problem into a structured sampler such as a D-Wave quantum computer. A new minor-embedding is calculated each time one of its sampling methods is called.
In case a native embedding is found (one to one mapping between source and target variables), embedding and unembedding steps are simplified as they are reduced to variable relabeling.
- Parameters:
child_sampler (
dimod.Sampler) – A dimod sampler, such as aDWaveSampler, that accepts only binary quadratic models of a particular structure.find_embedding (function, optional) – A function find_embedding(S, T, **kwargs) where S and T are edgelists. The function can accept additional keyword arguments. Defaults to
minorminer.find_embedding().embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments.
scale_aware (bool, optional, default=False) – Pass chain interactions to child samplers that accept an
ignored_interactionsparameter.child_structure_search (function, optional) – A function that accepts a sampler and returns the
structureattribute. Defaults todimod.child_structure_dfs().
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Changed in version 1.33.0: For native embeddings, chain strength is not calculated anymore, and chain break resolution method is ignored (both
chain_strengthandchain_break_methodare set toNonein the returnedembedding_context).Examples
>>> from dwave.system import DWaveSampler, EmbeddingComposite ... >>> with EmbeddingComposite(DWaveSampler()) as sampler: ... h = {'a': -1., 'b': 2} ... J = {('a', 'b'): 1.5} ... sampleset = sampler.sample_ising(h, J, num_reads=100) ... print(sampleset.first.energy) -4.5
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- return_embedding_default = False#
Defines the default behavior for returning embeddings.
Sets the default for the
sample()method’sreturn_embeddingoptional parameter (kwarg).
- sample(bqm, chain_strength=None, chain_break_method=None, chain_break_fraction=True, embedding_parameters=None, return_embedding=None, warnings=None, **parameters)[source]#
Sample from the provided binary quadratic model.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default,
chain_strengthis calculated withuniform_torque_compensation().chain_break_method (function/list, optional) – Method or methods used to resolve chain breaks. If multiple methods are given, the results are concatenated and a new field called
chain_break_methodspecifying the index of the method is appended to the sample set. Seeunembed_sampleset()andchain_breaks.chain_break_fraction (bool, optional, default=True) – Add a
chain_break_fractionfield to the unembedded response with the fraction of chains broken before unembedding.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments. Overrides any embedding parameters passed to the constructor.
return_embedding (bool, optional) – If True, the embedding, chain strength, chain break method and embedding parameters are added to the
infofield of the returned sample set. The default behavior is defined by thereturn_embedding_defaultattribute, which by default is False.warnings (
WarningAction, optional) – Defines what warning action to take, if any (see the Warnings section). The default behavior is defined by thewarnings_defaultattribute, which by default isIGNORE**parameters – Parameters for the sampling method, specified by the child sampler.
Changed in version 1.33.0: For native embeddings,
chain_strength,chain_break_methodandembedding_parametersparameters are ignored.chain_break_fractionare set to zero for all samples.Added in version 1.33.0: Embedding/unembedding duration included under
timingkey of theembedding_contextwhen embedding is returned.- Returns:
Examples
See the example in
EmbeddingComposite.
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- class FixedEmbeddingComposite(child_sampler, embedding=None, source_adjacency=None, **kwargs)[source]#
Bases:
LazyFixedEmbeddingCompositeMaps problems to a structured sampler with the specified minor-embedding.
- Parameters:
child_sampler (dimod.Sampler) – Structured dimod sampler such as a D-Wave quantum computer.
embedding (dict[hashable, iterable], optional) – Mapping from a source graph to the specified sampler’s graph (the target graph).
source_adjacency (dict[hashable, iterable]) – Deprecated. Dictionary to describe source graph as
{node: {node neighbours}}.kwargs – See the
EmbeddingCompositeclass for additional keyword arguments. Note thatfind_embeddingandembedding_parameterskeyword arguments are ignored.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
To embed a triangular problem (a problem with a three-node complete graph, or clique) in the Chimera topology, you need to chain two qubits. This example maps triangular problems to a composed sampler (based on the unstructured
ExactSolver) with a Chimera unit-cell structure.>>> import dimod >>> import dwave_networkx as dnx >>> from dwave.system import FixedEmbeddingComposite ... >>> c1 = dnx.chimera_graph(1) >>> embedding = {'a': [0, 4], 'b': [1], 'c': [5]} >>> structured_sampler = dimod.StructureComposite(dimod.ExactSolver(), ... c1.nodes, c1.edges) >>> sampler = FixedEmbeddingComposite(structured_sampler, embedding) >>> sampler.edgelist [('a', 'b'), ('a', 'c'), ('b', 'c')]
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- embedding = None#
Embedding used to map binary quadratic models to the child sampler.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- return_embedding_default = False#
Defines the default behavior for returning embeddings.
Sets the default for the
sample()method’sreturn_embeddingoptional parameter (kwarg).
- sample(bqm, **parameters)#
Sample the binary quadratic model.
On the first call of a sampling method, finds a minor-embedding for the given binary quadratic model (BQM). All subsequent calls to its sampling methods reuse this embedding.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default,
chain_strengthis calculated withuniform_torque_compensation().chain_break_method (function, optional) – Method used to resolve chain breaks during sample unembedding. See
unembed_sampleset().chain_break_fraction (bool, optional, default=True) – Add a
chain_break_fractionfield to the unembedded response with the fraction of chains broken before unembedding.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments. Overrides any embedding parameters passed to the constructor. Only used on the first call.
**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- to_networkx_graph()#
Convert structure to NetworkX graph format.
Note that NetworkX must be installed for this method to work.
- Returns:
A NetworkX graph containing the nodes and edges from the sampler’s structure.
- Return type:
- class LazyFixedEmbeddingComposite(child_sampler, find_embedding=<function find_embedding>, embedding_parameters=None, scale_aware=False, child_structure_search=<function child_structure_dfs>)[source]#
Bases:
EmbeddingComposite,StructuredMaps problems to the structure of its first given problem.
This composite reuses the minor-embedding found for its first given problem without recalculating a new minor-embedding for subsequent calls of its sampling methods.
- Parameters:
child_sampler (dimod.Sampler) – Structured dimod sampler.
find_embedding (function, default=:func:minorminer.find_embedding) – A function
find_embedding(S, T, **kwargs)whereSandTare edgelists. The function can accept additional keyword arguments. The function is used to find the embedding for the first problem solved.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
>>> from dwave.system import LazyFixedEmbeddingComposite, DWaveSampler ... >>> sampler = LazyFixedEmbeddingComposite(DWaveSampler()) >>> sampler.nodelist is None # no structure prior to first sampling True >>> __ = sampler.sample_ising({}, {('a', 'b'): -1}) >>> sampler.nodelist # has structure based on given problem ['a', 'b']
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- embedding = None#
Embedding used to map binary quadratic models to the child sampler.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- return_embedding_default = False#
Defines the default behavior for returning embeddings.
Sets the default for the
sample()method’sreturn_embeddingoptional parameter (kwarg).
- sample(bqm, **parameters)[source]#
Sample the binary quadratic model.
On the first call of a sampling method, finds a minor-embedding for the given binary quadratic model (BQM). All subsequent calls to its sampling methods reuse this embedding.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default,
chain_strengthis calculated withuniform_torque_compensation().chain_break_method (function, optional) – Method used to resolve chain breaks during sample unembedding. See
unembed_sampleset().chain_break_fraction (bool, optional, default=True) – Add a
chain_break_fractionfield to the unembedded response with the fraction of chains broken before unembedding.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments. Overrides any embedding parameters passed to the constructor. Only used on the first call.
**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- to_networkx_graph()#
Convert structure to NetworkX graph format.
Note that NetworkX must be installed for this method to work.
- Returns:
A NetworkX graph containing the nodes and edges from the sampler’s structure.
- Return type:
- class ParallelEmbeddingComposite(child_sampler, *, embeddings=None, source=None, embedder=None, embedder_kwargs=None, one_to_iterable=False, child_structure_search=<function child_structure_dfs>)[source]#
Bases:
Composite,Structured,SamplerComposite to parallelize sampling of a small problem on a structured sampler
Enables parallel sampling on a (target) sampler by use of multiple disjoint embeddings. If a list of embeddings is not provided, the function
find_multiple_embeddings()is called by default to attempt a maximum number of embeddings. If the target and source graph match processor architecture on a Chimera, Pegasus or Zephyr then tiling of a known embedding in a regular pattern may be a useful embedding strategy and find_sublattice_embeddings can be considered. Seeparallel_embeddingsdocumentation for customizable options including specification of the time_out and maximum number of embeddings. Seetests/test_parallel_embeddings.pyfor use cases beyond the examples provided.Embeddings, particularly for large subgraphs of large target graphs can be difficult to obtain. Relying on the defaults of this routine may result in slow embedding, see
parallel_embeddingsfor methods. Note that parallelization of job submissions can mitigate for network latency, programming time and readout time in the case of QPU samplers, subject to additional complexity in the embedding process.- Parameters:
child_sampler (
Sampler) – dimod sampler such as aDWaveSampler.embeddings (list, optional) – A list of embeddings. Each embedding is assumed to be a dictionary with source-graph nodes as keys and iterables on target-graph nodes to as values. The embeddings can include keys not required by the source graph. Note that one_to_iterable is ignored (assumed True).
source (nx.Graph, optional) – A source graph must be provided if embeddings are not specified. The source graph nodes should be supported by every embedding.
embedder (Callable, optional) – A function that returns embeddings when it is not provided. The first two arguments are assumed to be the source and target graph.
embedder_kwargs (dict, optional) – keyword arguments for the embedder function. The default is an empty dictionary.
one_to_iterable (bool, default=False) – This parameter should be fixed to match the value type returned by embedder. If False the values in every dictionary are target nodes (defining a subgraph embedding), these are transformed to tuples for compatibility with embed_bqm and unembed_sampleset. If True, the values are iterables over target nodes and no transformation is required.
child_structure_search (function, optional) – A function that accepts a sampler and returns the
structureattribute. Defaults todimod.child_structure_dfs().
- Raises:
ValueError – If the child_sampler is not structured, and the structure cannot be inferred from child_structure_search. If neither embeddings, nor a source graph, are provided. If the embeddings provided are an empty list, or no embeddings are found. If embeddings and source graph nodes are inconsistent. If embeddings and target graph nodes are inconsistent.
Examples
This example submits a simple Ising problem of just two variables on a D-Wave system. We use the default subgraph embedder finding a maximum number of embeddings. Note that searching for O(1000) of embeddings takes several seconds.
>>> from dwave.system import DWaveSampler >>> from dwave.system import ParallelEmbeddingComposite >>> from networkx import from_edgelist >>> embedder_kwargs = {'max_num_emb': None} # Without this, only 1 embedding will be sought >>> source = from_edgelist([('a', 'b')]) >>> qpu = DWaveSampler() >>> sampler = ParallelEmbeddingComposite(qpu, source=source, embedder_kwargs=embedder_kwargs) >>> sampleset = sampler.sample_ising({},{('a', 'b'): 1}, num_reads=1) >>> len(sampleset) > 1 # Equal to the number of parallel embeddings True
If an embedding can be found for a Chimera tile, we can try many dispacements on a target QPU graph (tiling). If all variables on the Chimera tile are used, and the target graph is defect free, this allows an optimal parallelization. Note that find_sublattice_embeddings should only be preferred to the default find_multiple_embeddings where the source and target graph have a special lattice relationship. Finding a large set of disjoint chimera cells within a typical processor graph can take several seconds. See tests/ for other examples.
>>> from dwave.system import DWaveSampler >>> from dwave.system import ParallelEmbeddingComposite >>> from dwave_networkx import chimera_graph >>> from minorminer.utils.parallel_embeddings import find_sublattice_embeddings >>> source = tile = chimera_graph(1, 1, 4) # A 1:1 mapping assumed >>> qpu = DWaveSampler() >>> embedder = find_sublattice_embeddings >>> embedder_kwargs = {'max_num_emb': None, 'tile': tile} >>> sampler = ParallelEmbeddingComposite(qpu, source=source, embedder=embedder, embedder_kwargs=embedder_kwargs) >>> J = {e: -1 for e in tile.edges} # A ferromagnet on the Chimera tile. >>> sampleset = sampler.sample_ising({}, J, num_reads=1) >>> len(sampleset) > 1 # Equal to the number of parallel embeddings True
Consider use of
draw_parallel_embeddings()for visualization of the embeddings found (embeddings=sampler.embeddingsovertarget=qpu.to_networkx_graph()).See the Concepts section for explanations of technical terms in descriptions of Ocean tools.
- property adjacency: dict[Hashable, set]#
Adjacency structure formatted as a dict, where keys are the nodes of the structured sampler and values are sets of all adjacent nodes for each key node.
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- property num_embeddings#
Number of embedding available for replicating the problem.
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- sample(bqm, **kwargs)[source]#
Sample from the specified binary quadratic model. Samplesets are concatenated together in the the same order as the embeddings class variable, the info field is returned from the child sampler unmodified.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.**kwargs – Optional keyword arguments for the sampling method, specified per solver.
- Returns:
Examples
See class examples.
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- to_networkx_graph()#
Convert structure to NetworkX graph format.
Note that NetworkX must be installed for this method to work.
- Returns:
A NetworkX graph containing the nodes and edges from the sampler’s structure.
- Return type:
- class VirtualGraphComposite(sampler, embedding, chain_strength=None, **kwargs)[source]#
Bases:
FixedEmbeddingCompositeRemoved. Used to provide access to the D-Wave virtual graph feature for minor-embedding, but now is just a thin wrapper around the
FixedEmbeddingComposite.Deprecated since version 1.25.0: This class is deprecated due to improved calibration of newer QPUs and will be removed in 1.27.0; to calibrate chains for residual biases, follow the instructions in the shimming tutorial.
Removed in version 1.28.0: This class is now only a pass-through wrapper around the
FixedEmbeddingComposite.It will be completely removed in dwave-system 2.0.
For removal reasons and alternatives, see the deprecation note above.
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- embedding = None#
Embedding used to map binary quadratic models to the child sampler.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- return_embedding_default = False#
Defines the default behavior for returning embeddings.
Sets the default for the
sample()method’sreturn_embeddingoptional parameter (kwarg).
- sample(bqm, apply_flux_bias_offsets=True, **kwargs)[source]#
Sample the binary quadratic model.
On the first call of a sampling method, finds a minor-embedding for the given binary quadratic model (BQM). All subsequent calls to its sampling methods reuse this embedding.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.chain_strength (float/mapping/callable, optional) – Sets the coupling strength between qubits representing variables that form a chain. Mappings should specify the required chain strength for each variable. Callables should accept the BQM and embedding and return a float or mapping. By default,
chain_strengthis calculated withuniform_torque_compensation().chain_break_method (function, optional) – Method used to resolve chain breaks during sample unembedding. See
unembed_sampleset().chain_break_fraction (bool, optional, default=True) – Add a
chain_break_fractionfield to the unembedded response with the fraction of chains broken before unembedding.embedding_parameters (dict, optional) – If provided, parameters are passed to the embedding method as keyword arguments. Overrides any embedding parameters passed to the constructor. Only used on the first call.
**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- to_networkx_graph()#
Convert structure to NetworkX graph format.
Note that NetworkX must be installed for this method to work.
- Returns:
A NetworkX graph containing the nodes and edges from the sampler’s structure.
- Return type:
Linear Bias#
Composite for using auxiliary qubits to bias problem qubits.
The following composites are supported:
- class LinearAncillaComposite(child_sampler: Sampler)[source]#
Bases:
ComposedSampler,StructuredImplements linear biases as ancilla qubits polarized with strong flux biases.
Linear bias \(h_i\) of qubit \(i\) is implemented through a coupling \(J_{ij}\) between the qubit and a neighboring qubit \(j\) that has a large flux-bias offset.
- Parameters:
child_sampler (
dimod.Sampler) – A dimod sampler, such as aDWaveSampler(), that has flux bias controls.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
This example submits a two-qubit problem consisting of linear biases with opposed signs and anti-ferromagnetic coupling. A D-Wave quantum computer solves it with the fast-anneal protocol using ancilla qubits to represent the linear biases.
>>> from dwave.system import DWaveSampler, EmbeddingComposite, LinearAncillaComposite ... >>> with EmbeddingComposite(LinearAncillaComposite(DWaveSampler())) as sampler: ... sampleset = sampler.sample_ising({0:1, 1:-1}, {(0, 1): 1}, fast_anneal=True) ... sampleset.first.energy -3
- property adjacency: dict[Hashable, set]#
Adjacency structure formatted as a dict, where keys are the nodes of the structured sampler and values are sets of all adjacent nodes for each key node.
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- parameters = None#
Parameters in the form of a dict.
For an instantiated composed sampler, keys are the keyword parameters accepted by the child sampler and parameters added by the composite.
- properties = None#
Properties in the form of a dict.
Contains the properties of the child sampler.
- Type:
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- sample(bqm: BinaryQuadraticModel, *, h_tolerance: Number = 0, default_flux_bias_range: tuple[float, float] = (-0.005, 0.005), **parameters)[source]#
Sample from the provided binary quadratic model.
Note
This composite does not support the auto_scale parameter; use the
ScaleCompositefor scaling.- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.h_tolerance (
numbers.Number) – Magnitude of the linear bias to be set directly on problem qubits; above this the bias is emulated by the flux-bias offset to an ancilla qubit. Assumed to be positive. Defaults to zero.default_flux_bias_range (
tuple) – Flux-bias range, as a two-tuple, supported by the QPU. The values must be large enough to ensure qubits remain polarized throughout the annealing process.**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- property structure: _Structure#
Structure of the structured sampler formatted as a
namedtuple()where the 3-tuple values are thenodelist,edgelistandadjacencyattributes.
- to_networkx_graph()#
Convert structure to NetworkX graph format.
Note that NetworkX must be installed for this method to work.
- Returns:
A NetworkX graph containing the nodes and edges from the sampler’s structure.
- Return type:
Reverse Anneal#
Composites that do batch operations for reverse annealing based on sets of initial states or anneal schedules.
The following composites are supported:
- class ReverseBatchStatesComposite(child_sampler)[source]#
Bases:
ComposedSampler,InitializedComposite that reverse anneals from multiple initial samples.
Each submission is independent from one another.
- Parameters:
sampler (
Sampler) – A dimod sampler.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
This example runs three reverse anneals from two configured and one randomly generated initial states on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minor-embedded on a D-Wave system using the
DWaveCliqueSamplersampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseBatchStatesComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseBatchStatesComposite(sampler) >>> schedule = [[0.0, 1.0], [10.0, 0.5], [20, 1.0]] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = [{i: -1 for i in range(15)}, {i: 1 for i in range(15)}] >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedule=schedule, ... initial_states=init_samples, ... num_reads=3, ... reinitialize_state=True)
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- property children#
List of child samplers that that are used by this composite.
- Type:
list[
Sampler]
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- property parameters#
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.
- parse_initial_states(bqm: BinaryQuadraticModel, initial_states: Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | tuple[Sequence[float | floating | integer], Sequence[Hashable]] | tuple[ndarray, Sequence[Hashable]] | ndarray | Sequence[Sequence[float | floating | integer]] | tuple[Sequence[Sequence[float | floating | integer]], Sequence[Hashable]] | Sequence[Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | tuple[Sequence[float | floating | integer], Sequence[Hashable]] | tuple[ndarray, Sequence[Hashable]] | ndarray] | Iterator[Sequence[float | floating | integer] | Mapping[Hashable, float | floating | integer] | tuple[Sequence[float | floating | integer], Sequence[Hashable]] | tuple[ndarray, Sequence[Hashable]] | ndarray] | None = None, initial_states_generator: Literal['none', 'tile', 'random'] = 'random', num_reads: int | None = None, seed: int | None = None, copy_always: bool = False) ParsedInputs#
Parse or generate initial states for an initialized sampler.
- Parameters:
bqm – Binary quadratic model.
initial_states (samples-like) – One or more samples, each defining an initial state for all the problem variables. Initial states are given one per read, but if fewer than
num_readsinitial states are defined, additional values are generated as specified byinitial_states_generator. See func:dimod.as_samples for a description of “samples-like”.initial_states_generator –
Defines the expansion of
initial_statesif fewer thannum_readsare specified:- ”none”:
If the number of initial states specified is smaller than
num_reads, raises ValueError.
- ”tile”:
Reuses the specified initial states if fewer than
num_readsor truncates if greater.
- ”random”:
Expands the specified initial states with randomly generated states if fewer than
num_readsor truncates if greater.
num_reads – Number of reads. Defaults to the number of initial states, if
initial_statesis specified, or to 1, if not.seed – 32-bit unsigned integer seed to use for the PRNG. Specifying a particular seed with a constant set of parameters produces identical results. If not provided, a random seed is chosen.
copy_always – If True,
initial_statesis always copied; otherwise it is copied only if necessary.
- Returns:
A named tuple with
['initial_states', 'initial_states_generator', 'num_reads', 'seed']as generated by this function.
- property properties#
Properties as a dict containing any additional information about the sampler.
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- sample(bqm, initial_states=None, initial_states_generator='random', num_reads=None, seed=None, **parameters)[source]#
Sample the binary quadratic model using reverse annealing from multiple initial states.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.initial_states (samples-like, optional, default=None) – One or more samples, each defining an initial state for all the problem variables. If fewer than
num_readsinitial states are defined, additional values are generated as specified byinitial_states_generator. Seedimod.as_samples()for a description of “samples-like”.initial_states_generator ({'none', 'tile', 'random'}, optional, default='random') –
Defines the expansion of initial_states if fewer than
num_readsare specified:- ”none”:
If the number of initial states specified is smaller than
num_reads, raises ValueError.
- ”tile”:
Reuses the specified initial states if fewer than
num_readsor truncates if greater.
- ”random”:
Expands the specified initial states with randomly generated states if fewer than
num_readsor truncates if greater.
num_reads (int, optional, default=len(initial_states) or 1) – Equivalent to number of desired initial states. If greater than the number of provided initial states, additional states will be generated. If not provided, it is selected to match the length of
initial_states. Ifinitial_statesis not provided, num_reads defaults to 1.seed (int (32-bit unsigned integer), optional) – Seed to use for the PRNG. Specifying a particular seed with a constant set of parameters produces identical results. If not provided, a random seed is chosen.
**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
SampleSetthat has aninitial_statefield.
Examples
This example runs three reverse anneals from two configured and one randomly generated initial states on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minor-embedded on a D-Wave system using the
DWaveCliqueSamplersampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseBatchStatesComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseBatchStatesComposite(sampler) >>> schedule = [[0.0, 1.0], [10.0, 0.5], [20, 1.0]] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = [{i: -1 for i in range(15)}, {i: 1 for i in range(15)}] >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedule=schedule, ... initial_states=init_samples, ... num_reads=3, ... reinitialize_state=True)
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also
- class ReverseAdvanceComposite(child_sampler)[source]#
Bases:
ComposedSamplerComposite that reverse anneals an initial sample through a sequence of anneal schedules.
If you do not specify an initial sample, a random sample is used for the first submission. By default, each subsequent submission selects the most-found lowest-energy sample as its initial state. If you set reinitialize_state to False, which makes each submission behave like a random walk, the subsequent submission selects the last returned sample as its initial state.
- Parameters:
sampler (
dimod.Sampler) – A dimod sampler.
Added in version 1.30.0: Support for context manager protocol with
dimod.Scoped()implemented.Examples
This example runs 100 reverse anneals each for three schedules on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minor-embedded on a D-Wave system using the
DWaveCliqueSamplersampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseAdvanceComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseAdvanceComposite(sampler) >>> schedule = [[[0.0, 1.0], [t, 0.5], [20, 1.0]] for t in (5, 10, 15)] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = {i: -1 for i in range(15)} >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedules=schedule, ... initial_state=init_samples, ... num_reads=100, ... reinitialize_state=True)
- property child#
The child sampler. First sampler in
Composite.children.- Type:
Sampler
- property children#
List of child samplers that that are used by this composite.
- Type:
list[
Sampler]
- close()#
Release any scope-bound resources of child samplers or composites.
Note
If a
Compositesubclass doesn’t allocate resources that have to be explicitly released, there’s no need to override the defaultclose()implementation.However, if you do implement
close()on a subclass, make sure to either callsuper().close(), or to explicitly close all child samplers/composites.Added in version 0.12.19:
Compositenow implements theScopedinterface. The defaultclose()method recursively closes composite’s children.
- property parameters#
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.
- property properties#
Properties as a dict containing any additional information about the sampler.
- remove_unknown_kwargs(**kwargs) dict[str, Any]#
Remove with warnings any keyword arguments not accepted by the sampler.
- Parameters:
**kwargs – Keyword arguments to be validated.
Returns: Updated kwargs dict.
Examples
>>> import warnings >>> sampler = dimod.RandomSampler() >>> with warnings.catch_warnings(): ... warnings.filterwarnings('ignore') ... try: ... sampler.remove_unknown_kwargs(num_reads=10, non_param=3) ... except dimod.exceptions.SamplerUnknownArgWarning: ... pass {'num_reads': 10}
- sample(bqm, anneal_schedules=None, **parameters)[source]#
Sample the binary quadratic model using reverse annealing along a given set of anneal schedules.
- Parameters:
bqm (
BinaryQuadraticModel) – Binary quadratic model to be sampled from.anneal_schedules (list of lists, optional, default=[[[0, 1], [1, 0.35], [9, 0.35], [10, 1]]]) – Anneal schedules in order of submission. Each schedule is formatted as a list of [time, s] pairs, in which time is in microseconds and s is the normalized persistent current in the range [0,1].
initial_state (dict, optional) – The state to reverse anneal from. If not provided, it will be randomly generated.
**parameters – Parameters for the sampling method, specified by the child sampler.
- Returns:
SampleSetthat hasinitial_stateandschedule_indexfields.
Examples
This example runs 100 reverse anneals each for three schedules on a problem constructed by setting random \(\pm 1\) values on a clique (complete graph) of 15 nodes, minor-embedded on a D-Wave system using the
DWaveCliqueSamplersampler.>>> import dimod >>> from dwave.system import DWaveCliqueSampler, ReverseAdvanceComposite ... >>> sampler = DWaveCliqueSampler() >>> sampler_reverse = ReverseAdvanceComposite(sampler) >>> schedule = [[[0.0, 1.0], [t, 0.5], [20, 1.0]] for t in (5, 10, 15)] ... >>> bqm = dimod.generators.ran_r(1, 15) >>> init_samples = {i: -1 for i in range(15)} >>> sampleset = sampler_reverse.sample(bqm, ... anneal_schedules=schedule, ... initial_state=init_samples, ... num_reads=100, ... reinitialize_state=True)
- sample_ising(h: Mapping[Hashable, float | floating | integer] | Sequence[float | floating | integer], J: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from an Ising model using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the Ising model into a
BinaryQuadraticModeland then callssample().- Parameters:
h – Linear biases of the Ising problem. If a list, indices are the variable labels.
J – Quadratic biases of the Ising problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from the Ising model.
See also
- sample_qubo(Q: Mapping[tuple[Hashable, Hashable], float | floating | integer], **parameters) SampleSet#
Sample from a QUBO using the implemented sample method.
This method is inherited from the
Samplerbase class.Converts the quadratic unconstrained binary optimization (QUBO) into a
BinaryQuadraticModeland then callssample().- Parameters:
Q – Coefficients of a QUBO problem.
**kwargs – See the implemented sampling for additional keyword definitions.
Returns: Samples from a QUBO.
See also