def test_ising_simulated_annealing_sample_quality(self): # because simulated annealing has randomness, we cannot # really test that it finds the solution. Instead we # note that it should return better-than-average solutions, # so if we test the returned energy against the energy of # 100 random samples, it should do better than the average nV = 100 # number of variables in h,J nS = 100 # number of samples h = {v: random.uniform(-2, 2) for v in range(nV)} J = {} for u, v in itertools.combinations(h, 2): if random.random() < .05: J[(u, v)] = random.uniform(-1, 1) random_energies = [ dimod.ising_energy({v: random.choice((-1, 1)) for v in h}, h, J) for __ in range(nS) ] average_energy = sum(random_energies) / float(nS) sample, energy = ising_simulated_annealing(h, J) self.assertLess(energy, average_energy)
def test_ising_simulated_annealing_empty_J(self): h = {0: -1, 1: 1, 2: -.5} J = {} sample, energy = ising_simulated_annealing(h, J) self.assertIsInstance(sample, dict) self.assertIsInstance(energy, float) # make sure all of the nodes are present in sample for v in range(3): self.assertIn(v, sample)
def test_ising_simulated_annealing_basic(self): # AND gate h = {0: -.5, 1: 0, 2: 1, 3: -.5} J = {(0, 2): -1, (1, 2): -1, (0, 3): .5, (1, 3): -1} sample, energy = ising_simulated_annealing(h, J) self.assertIsInstance(sample, dict) self.assertIsInstance(energy, float) # make sure all of the nodes are present in sample for v in range(4): self.assertIn(v, sample)