Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_lb_only(self):
bqm = BinaryQuadraticModel({0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},
{(0, 1): -2.0, (0, 2): -5.0, (0, 3): -2.0,
(0, 4): -2.0, (1, 2): -2.0, (1, 3): -2.0, (1, 4): 4.0,
(2, 3): -3.0, (2, 4): -5.0, (3, 4): -4.0}, 0, dimod.SPIN)
sampler = ClipComposite(ExactSolver())
solver = ExactSolver()
response = sampler.sample(bqm, lower_bound=-1)
response_exact = solver.sample(bqm)
self.assertEqual(response.first.sample, response_exact.first.sample)
self.assertAlmostEqual(response.first.energy, response_exact.first.energy)
def test_sample_SPIN(self):
bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0, 2: 0.0},
{(0, 1): -1.0, (1, 2): 1.0, (0, 2): 1.0},
1.0,
dimod.SPIN)
response = dimod.ExactSolver().sample(bqm)
# every possible conbination should be present
self.assertEqual(len(response), 2**len(bqm))
self.assertEqual(response.record.sample.shape, (2**len(bqm), len(bqm)))
# confirm vartype
self.assertIs(response.vartype, bqm.vartype)
dimod.testing.assert_response_energies(response, bqm)
def test_sample(self):
linear = {0: -0.5, 1: -0.3, 2: -0.8}
quadratic = {(0, 1, 2): -1.7}
sampler = HigherOrderComposite(ExactSolver())
response = sampler.sample_ising(linear, quadratic, penalty_strength=10,
keep_penalty_variables=False,
discard_unsatisfied=False)
self.assertEqual(response.first.sample, {0: 1, 1: 1, 2: 1})
self.assertAlmostEqual(response.first.energy, -3.3)
self.assertFalse(np.prod(response.record.penalty_satisfaction))
class TestConstruction(unittest.TestCase):
def test_10(self):
sampler = TruncateComposite(ExactSolver(), 10)
dtest.assert_sampler_api(sampler)
dtest.assert_composite_api(sampler)
self.assertEqual(sampler.parameters, {})
def test_0(self):
with self.assertRaises(ValueError):
TruncateComposite(ExactSolver(), 0)
@dtest.load_sampler_bqm_tests(TruncateComposite(ExactSolver(), 100))
class TestSample(unittest.TestCase):
def test_sampleset_shorter(self):
h = {'a': -4.0, 'b': -4.0, 'c': 0}
J = {('a', 'b'): 3.2}
sampler = TruncateComposite(ExactSolver(), 10)
samples = sampler.sample_ising(h, J)
# we should see 2**n < 10 rows
self.assertEqual(len(samples), 8)
def test_sampleset_trim(self):
h = {'a': -4.0, 'b': -4.0, 'c': 0}
J = {('a', 'b'): 3.2}
sampler = TruncateComposite(ExactSolver(), 6)
def test_csp_one_xor(self):
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
variables = ['a', 'b', 'c']
xor = dwavebinarycsp.factories.constraint.gates.xor_gate(variables)
csp.add_constraint(xor)
bqm = dwavebinarycsp.stitch(csp)
resp = dimod.ExactSolver().sample(bqm)
ground_energy = min(resp.record['energy'])
for sample, energy in resp.data(['sample', 'energy']):
if energy == ground_energy:
self.assertTrue(csp.check(sample))
else:
if abs(energy - ground_energy) < 2:
# if classical gap is less than 2
self.assertTrue(csp.check(sample))
def test_sample(self):
bqm = BinaryQuadraticModel({1: -1.3, 4: -0.5},
{(1, 4): -0.6},
0,
vartype=Vartype.SPIN)
sampler = ConnectedComponentsComposite(ExactSolver())
response = sampler.sample(bqm)
self.assertEqual(response.first.sample, {4: 1, 1: 1})
self.assertAlmostEqual(response.first.energy, -2.4)
def test_returned_gap(self):
"""Verify that stitch is only allowing gaps that satisfy min_classical_gap to be returned.
"""
# Set up CSP
csp = dwavebinarycsp.ConstraintSatisfactionProblem("SPIN")
csp.add_constraint(operator.ne, ['a', 'b'])
# Show that CSP has a valid BQM
small_gap = 2
bqm = dwavebinarycsp.stitch(csp, min_classical_gap=small_gap, max_graph_size=2)
# Verify the gap based on returned bqm
sampleset = dimod.ExactSolver().sample(bqm)
energy_array = sampleset.record['energy']
gap = max(energy_array) - min(energy_array)
self.assertGreaterEqual(gap, small_gap)
# Same CSP with a larger min_classical_gap
# Note: Even though there is a BQM for this CSP (shown above), stitch should throw an
# exception because the BQM does not satisfy the following min_classical_gap requirement.
with self.assertRaises(dwavebinarycsp.exceptions.ImpossibleBQM):
dwavebinarycsp.stitch(csp, min_classical_gap=4, max_graph_size=2)
def test_empty_fix(self):
linear = {1: -1.3, 4: -0.5}
quadratic = {(1, 4): -0.6}
sampler = FixedVariableComposite(ExactSolver())
response = sampler.sample_ising(linear, quadratic)
self.assertIsInstance(response, SampleSet)
self.assertEqual(response.first.sample, {4: 1, 1: 1})
self.assertAlmostEqual(response.first.energy, -2.4)
def test_sample_qubo(self):
sampler = dimod.TrackingComposite(dimod.ExactSolver())
Q = {('a', 'b'): -1}
ss = sampler.sample_qubo(Q)
self.assertEqual(sampler.input, dict(Q=Q))
self.assertEqual(sampler.output, ss)
def get_sampler(self, profile, solver):
"Return a dimod.Sampler object and associated solver information."
# Handle built-in software samplers as special cases.
info = {}
if solver != None:
info["solver_name"] = solver
if solver == "exact":
return ExactSolver(), info, {}
elif solver == "neal":
return SimulatedAnnealingSampler(), info, {}
elif solver == "tabu":
return TabuSampler(), info, {}
elif solver == "kerberos" or (solver != None and solver[:9] == "kerberos,"):
base_sampler = KerberosSampler()
try:
sub_sampler_name = solver.split(",")[1]
except IndexError:
sub_sampler_name = None
sub_sampler, sub_info, params = self.get_sampler_from_config(profile, sub_sampler_name, "qpu")
info.update(self._recursive_properties(sub_sampler))
info["solver_name"] = "kerberos + %s" % sub_info["solver_name"]
params["qpu_sampler"] = sub_sampler
return base_sampler, info, params
elif solver == "qbsolv" or (solver != None and solver[:7] == "qbsolv,"):