本文整理匯總了Python中dimod.SampleSet方法的典型用法代碼示例。如果您正苦於以下問題:Python dimod.SampleSet方法的具體用法?Python dimod.SampleSet怎麽用?Python dimod.SampleSet使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dimod
的用法示例。
在下文中一共展示了dimod.SampleSet方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: next
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def next(self, state, **runopts):
beta = runopts.get('beta', self.beta)
beta = state.get('beta', beta)
if beta is None:
raise ValueError('beta must be given on construction or during run-time')
ss = state.samples
# calculate weights
w = np.exp(-beta * ss.record.energy)
p = w / sum(w)
# resample
idx = self.random.choice(len(ss), len(ss), p=p)
record = ss.record[idx]
info = ss.info.copy()
info.update(beta=beta)
new_samples = dimod.SampleSet(record, ss.variables, info, ss.vartype)
return state.updated(samples=new_samples)
示例2: assert_response_energies
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def assert_response_energies(response, bqm, precision=7):
"""Assert that each sample in the given response has the correct energy.
Args:
response (:obj:`.SampleSet`):
Response as returned by a dimod sampler.
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model (BQM) used to generate the samples.
precision (int, optional, default=7):
Equality of energy is tested by calculating the difference between
the `response`'s sample energy and that returned by BQM's
:meth:`~.BinaryQuadraticModel.energy`, rounding to the closest
multiple of 10 to the power of minus `precision`.
Raises:
AssertionError: If any of the samples in the response do not match their
associated energy.
See also:
:func:`.assert_sampleset_energies`
"""
return assert_sampleset_energies(response, bqm, precision)
示例3: test_sample
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_sample(self):
poly = BinaryPolynomial.from_hising(h={1: -1.3, 2: 1.2, 3: -1.2, 4: -0.5},
J={(1, 2, 3, 4): -0.6, (1, 2, 4): -0.3, (1, 3, 4): -0.8},
offset=0)
exact_sampler = ExactPolySolver()
response_exact = exact_sampler.sample_poly(poly)
gs = response_exact.first.sample
gse = response_exact.first.energy
sampler = PolyFixedVariableComposite(ExactPolySolver())
fixed_variables = {k: v for k, v in gs.items() if k % 2 == 0}
response = sampler.sample_poly(poly, fixed_variables=fixed_variables)
self.assertIsInstance(response, SampleSet)
self.assertEqual(response.first.sample, gs)
self.assertAlmostEqual(response.first.energy, gse)
示例4: test_fix_all
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_fix_all(self):
poly = BinaryPolynomial.from_hising(h={1: -1.3, 2: 1.2, 3: -1.2, 4: -0.5},
J={(1, 2, 3, 4): -0.6, (1, 2, 4): -0.3, (1, 3, 4): -0.8},
offset=0)
exact_sampler = ExactPolySolver()
response_exact = exact_sampler.sample_poly(poly)
gs = response_exact.first.sample
gse = response_exact.first.energy
sampler = PolyFixedVariableComposite(ExactPolySolver())
fixed_variables = {k: v for k, v in gs.items()}
response = sampler.sample_poly(poly, fixed_variables=fixed_variables)
self.assertIsInstance(response, SampleSet)
self.assertEqual(response.first.sample, gs)
self.assertAlmostEqual(response.first.energy, gse)
示例5: test_order_preservation_doubled
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_order_preservation_doubled(self):
bqm = dimod.BinaryQuadraticModel({}, {'ab': 1, 'bc': -1}, 0, dimod.SPIN)
ss1 = dimod.SampleSet.from_samples_bqm(([[1, 1, 0],
[1, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 0]], 'abc'),
bqm)
target = dimod.SampleSet.from_samples_bqm(([[1, 1, 0],
[1, 0, 0],
[0, 0, 0]], 'abc'),
bqm,
num_occurrences=[2, 2, 3])
self.assertEqual(target, ss1.aggregate())
示例6: test_num_occurences
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_num_occurences(self):
samples = [[-1, -1, +1],
[-1, +1, +1],
[-1, +1, +1],
[-1, -1, -1],
[-1, +1, +1]]
agg_samples = [[-1, -1, +1],
[-1, +1, +1],
[-1, -1, -1]]
labels = 'abc'
sampleset = dimod.SampleSet.from_samples((samples, labels), energy=0,
vartype=dimod.SPIN)
aggregated = dimod.SampleSet.from_samples((agg_samples, labels), energy=0,
vartype=dimod.SPIN,
num_occurrences=[1, 3, 1])
self.assertEqual(sampleset.aggregate(), aggregated)
示例7: test_majority_vote
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_majority_vote(self):
"""should return the most common value in the chain"""
sample0 = {0: -1, 1: -1, 2: +1}
sample1 = {0: +1, 1: -1, 2: +1}
samples = [sample0, sample1]
embedding = {'a': {0, 1, 2}}
bqm = dimod.BinaryQuadraticModel.from_ising({'a': 1}, {})
resp = dimod.SampleSet.from_samples(samples, energy=[-1, 1], info={}, vartype=dimod.SPIN)
resp = dwave.embedding.unembed_sampleset(resp, embedding, bqm, chain_break_method=dwave.embedding.majority_vote)
# specify that majority vote should be used
source_samples = list(resp)
self.assertEqual(source_samples, [{'a': -1}, {'a': +1}])
示例8: __init__
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def __init__(self, *args, **kwargs):
if not args and not kwargs:
# construct empty SampleSet
empty = self.empty()
super(SampleSet, self).__init__(empty.record, empty.variables,
empty.info, empty.vartype)
else:
super(SampleSet, self).__init__(*args, **kwargs)
示例9: hstack
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def hstack(self, *others):
"""Combine the first sample in this SampleSet with first samples in all
other SampleSets. Energy is reset to zero, and vartype is cast to the
local vartype (first sampleset's vartype).
"""
return hstack_samplesets(self, *others)
示例10: from_samples
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def from_samples(cls, samples, bqm, **kwargs):
"""Convenience method for constructing a state from raw (dict) samples.
Per-sample energy is calculated from the binary quadratic model (BQM),
and `State.problem` is set to the BQM.
Example:
>>> import dimod
>>> bqm = dimod.BQM.from_ising({}, {'ab': 0.5, 'bc': 0.5, 'ca': 0.5})
>>> state = State.from_samples([{'a': -1, 'b': -1, 'c': -1},
... {'a': -1, 'b': -1, 'c': 1}], bqm)
"""
return cls(problem=bqm,
samples=SampleSet.from_samples_bqm(samples, bqm), **kwargs)
示例11: from_subsamples
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def from_subsamples(cls, subsamples, bqm, **kwargs):
"""Similar to :meth:`.from_samples`, but initializes `subproblem` and
`subsamples`.
"""
return cls(subproblem=bqm,
subsamples=SampleSet.from_samples_bqm(subsamples, bqm), **kwargs)
示例12: spread
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def spread(samples):
"""Multiplies each sample its num_occurrences times."""
record = samples.record
labels = samples.variables
sample = np.repeat(record.sample, repeats=record.num_occurrences, axis=0)
energy = np.repeat(record.energy, repeats=record.num_occurrences, axis=0)
num_occurrences = np.ones(sum(record.num_occurrences))
return SampleSet.from_samples(
samples_like=(sample, labels), vartype=samples.vartype,
energy=energy, num_occurrences=num_occurrences,
info=copy.deepcopy(samples.info))
示例13: fprint
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def fprint(self, obj, stream=None, **kwargs):
"""Prints the formatted representation of the object on stream"""
if stream is None:
stream = sys.stdout
options = self.options
options.update(kwargs)
if isinstance(obj, dimod.SampleSet):
self._print_sampleset(obj, stream, **options)
return
raise TypeError("cannot format type {}".format(type(obj)))
示例14: _print_sampleset
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def _print_sampleset(self, sampleset, stream,
width, depth, sorted_by,
**other):
if len(sampleset) > 0:
self._print_samples(sampleset, stream, width, depth, sorted_by)
else:
stream.write('Empty SampleSet\n')
# write the data vectors
stream.write('Record Fields: [')
self._print_items(sampleset.record.dtype.names, stream, width - len('Data Vectors: [') - 1)
stream.write(']\n')
# write the variables
stream.write('Variables: [')
self._print_items(sampleset.variables, stream, width - len('Variables: [') - 1)
stream.write(']\n')
# add the footer
stream.write('[')
footer = [repr(sampleset.vartype.name),
'{} rows'.format(len(sampleset)),
'{} samples'.format(sampleset.record.num_occurrences.sum()),
'{} variables'.format(len(sampleset.variables))
]
if sum(map(len, footer)) + (len(footer) - 1)*2 > width - 2:
# if the footer won't fit in width
stream.write(',\n '.join(footer))
else:
# if width the minimum footer object then we don't respect it
stream.write(', '.join(footer))
stream.write(']')
示例15: test_empty_poly
# 需要導入模塊: import dimod [as 別名]
# 或者: from dimod import SampleSet [as 別名]
def test_empty_poly(self):
poly = BinaryPolynomial({}, 'SPIN')
sampler = PolyFixedVariableComposite(ExactPolySolver())
response = sampler.sample_poly(poly)
self.assertIsInstance(response, SampleSet)