def test_sa(self): sampler = oj.SASampler() self.samplers(sampler) self.samplers(sampler, init_state=[1 for _ in range(len(self.ground_state))], init_q_state=[1 for _ in range(len(self.ground_state))]) self.samplers(sampler, init_state={i: 1 for i in range(len(self.ground_state))}) # schedule [[beta, one_mc_steps], ...] # schedule test (list of list) self.samplers(sampler, init_state={i: 1 for i in range(len(self.ground_state))}, schedule=[[0.1, 10], [1, 10], [10, 10]]) # schedule test (list of tuple) self.samplers(sampler, init_state={i: 1 for i in range(len(self.ground_state))}, schedule=[(0.1, 10), (1, 10), (10, 10)]) self._test_num_reads(oj.SASampler) #antiferromagnetic one-dimensional Ising model sampler = oj.SASampler(num_sweeps=51, num_reads=100) res = sampler.sample_ising(self.afih, self.afiJ) self.assertDictEqual(self.afiground, res.first.sample)
def test_sa(self): response = oj.SASampler().sample_ising(self.h, self.J) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [1, 1, 1]) response = oj.SASampler().sample_qubo(self.Q) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [1, 1, 1])
def test_sa(self): response = oj.SASampler(beta_max=100).sample_ising(self.h, self.J) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [-1, -1, -1]) response = oj.SASampler().sample_qubo(self.Q) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [0, 0, 0])
def test_sa_sweeps(self): iteration = 10 sampler = oj.SASampler() res = sampler.sample_ising(self.h, self.J, num_reads=iteration) self.assertEqual(iteration, len(res.energies)) sampler = oj.SASampler(num_reads=iteration) res = sampler.sample_ising(self.h, self.J) self.assertEqual(iteration, len(res.energies))
def test_time_sa(self): fast_res = oj.SASampler(beta_max=100, step_num=10, iteration=10).sample_ising(self.h, self.J) slow_res = oj.SASampler(beta_max=100, step_num=50, iteration=10).sample_ising(self.h, self.J) self.assertEqual(len(fast_res.info['list_exec_times']), 10) self.assertTrue( fast_res.info['execution_time'] < slow_res.info['execution_time'])
def test_sa(self): response = oj.SASampler(beta_max=100).sample_ising(self.h, self.J) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [-1, -1, -1]) response = oj.SASampler(beta_max=100).sample_qubo(self.Q) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [0, 0, 0]) valid_sche = [(beta, 1) for beta in np.linspace(-1, 1, 5)] with self.assertRaises(ValueError): sampler = oj.SASampler(schedule=valid_sche)
def test_openjij_cxxjij_compare(self): seed_for_mc = 1 Q = { (0, 0): 1, (1, 1): -1, (2, 2): 2, (0, 1): 1, (1, 2): -1, (2, 0): -1 } # solution is [0, 1, 0] init_binary = [1, 0, 1] init_spin = [1, -1, 1] # openjij sampler = oj.SASampler(beta_min=0.01, beta_max=10, step_length=10, step_num=100) res = sampler.sample_qubo(Q=Q, initial_state=init_binary, seed=seed_for_mc) # cxxjij model = oj.BinaryQuadraticModel(Q=Q, var_type='BINARY') graph = model.get_cxxjij_ising_graph() system = cj.system.make_classical_ising_Eigen(init_spin, graph) sch = cj.utility.make_classical_schedule_list(beta_min=0.01, beta_max=10, one_mc_step=10, num_call_updater=100) cj.algorithm.Algorithm_SingleSpinFlip_run(system, seed_for_mc, sch) self.assertListEqual(res.states[0], list((system.spin[:-1] + 1) / 2))
def test_sa(self): initial_state = [1 for _ in range(self.size)] response = oj.SASampler().sample_ising( self.h, self.J, initial_state=initial_state, seed=1) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [-1, -1, -1]) response = oj.SASampler(beta_max=100).sample_qubo(self.Q, seed=1) self.assertEqual(len(response.states), 1) self.assertListEqual(response.states[0], [0, 0, 0]) vaild_sche = [(beta, 1) for beta in np.linspace(-1, 1, 5)] with self.assertRaises(ValueError): sampler = oj.SASampler(schedule=vaild_sche) sampler.sample_ising({}, {})
def test_sa_sparse(self): #sampler = oj.SASampler() #self.samplers(sampler) #self.samplers(sampler, # init_state=[1 for _ in range(len(self.ground_state))], # init_q_state=[1 for _ in range(len(self.ground_state))]) #self.samplers(sampler, # init_state={i: 1 for i in range(len(self.ground_state))} # ) ## schedule [[beta, one_mc_steps], ...] ## schedule test (list of list) #self.samplers(sampler, # init_state={i: 1 for i in range(len(self.ground_state))}, # schedule=[[0.1, 10], [1, 10], [10, 10]] # ) ## schedule test (list of tuple) #self.samplers(sampler, # init_state={i: 1 for i in range(len(self.ground_state))}, # schedule=[(0.1, 10), (1, 10), (10, 10)] # ) #self._test_num_reads(oj.SASampler) #antiferromagnetic one-dimensional Ising model sampler = oj.SASampler(num_reads=100) res = sampler.sample_ising(self.afih, self.afiJ, sparse=True, seed=1) self.assertDictEqual(self.afiground, res.first.sample)
def test_reverse_annealing(self): seed_for_mc = 1 initial_state = [0, 0, 0] qubo = { (0, 0): 1, (1, 1): -1, (2, 2): 2, (0, 1): 1, (1, 2): -1, (2, 0): -1 } # solution is [0, 1, 0] solution = [0, 1, 0] # Reverse simulated annealing # beta, step_length reverse_schedule = [[10, 3], [1, 3], [0.5, 3], [1, 3], [10, 5]] rsa_sampler = oj.SASampler(schedule=reverse_schedule, iteration=10) res = rsa_sampler.sample_qubo(qubo, initial_state=initial_state, seed=seed_for_mc) self.assertListEqual(solution, list(res.min_samples['states'][0])) # Reverse simulated quantum annealing # annealing parameter s, step_length reverse_schedule = [[1, 1], [0.3, 3], [0.1, 5], [0.3, 3], [1, 3]] rqa_sampler = oj.SQASampler(schedule=reverse_schedule, iteration=10) res = rqa_sampler.sample_qubo(qubo, initial_state=initial_state, seed=seed_for_mc) self.assertListEqual(solution, list(res.min_samples['states'][0]))
def test_hubo_sampler(self): sampler = oj.SASampler() h = {0: -1} J = {(0, 1): -1} K = {(0, 1, 2): 1} response = sampler.sample_hubo([h, J, K], var_type='SPIN') print(response.info) self.assertListEqual([1, 1, -1], list(response.states[0]))
def test_swendsenwang(self): sampler = oj.SASampler() initial_state = [1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1] h = {0: -1, 10: -1} J = {(i, i+1): -1 for i in range(10)} res = sampler.sample_ising(h, J, updater="swendsenwang", seed=1, initial_state=initial_state) self.assertListEqual(res.states[0], [1]*11)
def test_hubo_sampling(self): sampler = oj.SASampler() # make HUBO h = {0: -1} J = {(0, 1): -1} K = {(0, 1, 2): 1} response = sampler.sample_hubo([h, J, K], var_type="SPIN")
def test_seed(self): initial_state = [1 for _ in range(self.size)] _J = self.J.copy() _J[(1, 2)] = 1 sampler = oj.SASampler(iteration=10) response = sampler.sample_ising(h=self.h, J=_J, initial_state=initial_state, seed=1) unique_energy = np.unique(response.energies) self.assertEqual(len(unique_energy), 1)
def solve_problem(model, feed_dict): # convert to qubo qubo, offset = model.to_qubo(feed_dict=feed_dict) # solve with OpenJij (SA) sampler = oj.SASampler(num_reads=10) response = sampler.sample_qubo(Q=qubo) # take mininum state dict_solution = response.first.sample solution = model.decode_sample(dict_solution, vartype='BINARY', feed_dict=feed_dict) broken = solution.constraints(only_broken=True) return solution, broken
def solve_problem(problem, instance_data, feed_dict): # convert to PyQUBO pyq = problem.to_pyqubo(placeholder=instance_data) # compile compiled = pyq.compile() # convert to bqm bqm = compiled.to_bqm(feed_dict=feed_dict) # solve with SA (OpenJij) sampler = oj.SASampler() response = sampler.sample(bqm, num_reads=1000, num_sweeps=100) # decode for analysis # decoded_lowest = problem.decode(response.lowest()) decoded_all = problem.decode(response) # extract result result = decoded_all return result
def reverse_annealing(): initial_state = [0, 0, 0] qubo = make_qubo() reverse_schedule = [[10, 3], (1, 3), (0.5, 3), (1, 3), (10, 5)] sqa = oj.SASampler(schedule=reverse_schedule, iteration=20) res = sqa.sample_qubo(qubo, initial_state=initial_state) print(res.min_samples) model = oj.BinaryQuadraticModel(Q=qubo, vartype='BINARY') print(model.calc_energy(res.min_samples['min_states'][0])) print('RQA') reverse_schedule = [[1, 1], [0.3, 3], [0.1, 5], [0.3, 3], [1, 3]] rqa_sampler = oj.SQASampler(schedule=reverse_schedule, iteration=10, beta=10) rqa_sampler = SQASampler(schedule=reverse_schedule, iteration=10) res = rqa_sampler.sample_qubo(qubo, initial_state=initial_state, seed=1) print(res.min_samples)
def test_benchmark(self): h = {0: 1} J = {(0, 1): -1.0, (1, 2): -1.0} sa_samp = oj.SASampler() def solver(time_param, iteration): sa_samp.step_num = time_param sa_samp.iteration = iteration return sa_samp.sample_ising(h, J) ground_state = [-1, -1, -1] ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state) step_num_list = np.linspace(10, 50, 5, dtype=np.int) bm_res = oj.benchmark([ground_state], ground_energy, solver, time_param_list=step_num_list) self.assertTrue( set(bm_res) >= {'time', 'error', 'e_res', 'tts', 'tts_threshold_prob'}) self.assertEqual(len(bm_res), len(step_num_list))
def test_sa_with_negative_interactions(self): # sa with negative interactions sampler = oj.SASampler() sampler.sample_ising({}, {(0, 1): -1}) sampler.sample_ising({2: -1}, {(0, 1): -1})
def solver(time_param, iteration): sa_samp = oj.SASampler() sa_samp.step_num = time_param sa_samp.iteration = iteration return sa_samp.sample_ising(h, J)
# for antiferromagnetic one-dimensional Ising model import openjij as oj import numpy as np N = 30 afih = {0: -10} afiJ = {(i, i+1): 1+(0.1*np.sqrt(i)) for i in range(N-1)} afiground = {i:(-1)**i for i in range(N)} init_spin = [1]*N sampler = oj.SASampler(num_sweeps=51, num_reads=100) res = sampler.sample_ising(afih, afiJ, initial_state=init_spin, seed=5) print(res)
#価値 total_value = sum(x_i * v_1 for x_i, v_1 in zip(x, values)) #重さ total_weight = sum(x_i * w_1 for x_i, w_1 in zip(x, weights)) #ハミルトニアン H = -1 * total_value + alpha * Constraint( (total_weight - weight_limit + sum(s_i for s_i in s))**2, label='weight_limit') #quboモデル model = H.compile() qubo, offset = model.to_qubo() # OpenJijで解く #-------------------------------------- sampler = oj.SASampler() response = sampler.sample_qubo(qubo, num_reads=1000) plt.hist(-(response.energies + offset)) ## エネルギーが一番低い状態を取り出します。 dict_solution = response.first.sample ## デコードします。 decoded_solution, broken, energy = model.decode_solution(dict_solution, vartype="BINARY") #-------------------------------------- # Cmosで解く #-------------------------------------- cmos_fpga = oj.CMOSAnnealer(token="", machine_type="FPGA") qubo_cmos = {} for key in qubo.keys():
if __name__ == "__main__": # make target instance N = 50 h = {0: 1, 1: 1} J = {} for i in range(N - 1): for j in range(i + 1, N): J[(i, j)] = -1.0 N = 30 h = {0: -10} J = {(i, i + 1): 1 for i in range(N - 1)} ground_state = correct_state = [(-1)**i for i in range(N)] # [-1]*N sa_samp = oj.SASampler() ground_energy = oj.BinaryQuadraticModel(h, J).calc_energy(ground_state) # make benchmark target solver def solver(time_param): return sa_samp.sample_ising(h, J, num_reads=100, num_sweeps=time_param) # benchmarking time_list = list(range(10, 101, 10)) b_res = oj.solver_benchmark(solver, time_list=time_list, solutions=[ground_state]) plt.xlabel('annealing time') plt.ylabel('TTS') plt.plot(b_res['time'], np.array(b_res['tts']), '.')
def solver(time_param, *args): sa_samp = oj.SASampler() sa_samp.num_sweeps = time_param return sa_samp.sample_ising(h, J, num_reads=10)
import numpy as np import openjij as oj if __name__ == '__main__': h = {0: -1} J = {(0, 1): -1, (1, 2): -1} # Simulated annealing (classical) 10 times response = oj.SASampler(iteration=10).sample_ising(h, J) # show the lowest energy solution in ten times min_index = np.argmin(response.energies) print("SA results: ", response.states[min_index]) # > SA results: [1, 1, 1] # Simulated quantum annealing (quantum simulation) 10 times response = oj.SQASampler(iteration=10).sample_ising(h, J) # show the lowest energy solution in ten times min_index = np.argmin(response.energies) print("SQA results: ", response.states[min_index]) # > SQA results: [1, 1, 1]
def optimize(game_type, W, c, w, min_count): N = len(w) # x_max = {k: int(W / v) for k, v in w.items()} offset_value = {x: int(min_count[x]) * int(y) for x, y in w.items()} new_W = W - sum(offset_value.values()) x_max = {k: int((new_W) / v) for k, v in w.items()} print('min_count') print(min_count) print('offset_value') print(offset_value) print('sum_offset_value') print(sum(offset_value.values())) print('new_W') print(new_W) print('x_max') print(x_max) for k, v in x_max.items(): if v <= 0: return "paramater error" # print("x_max: ") # print(x_max) x = pyq.Array([ pyq.LogEncInteger('x_{}'.format(i), (0, x_max[i])) for i in x_max.keys() ]) y = pyq.LogEncInteger('y', (0, new_W)) A, B = pyq.Placeholder("A"), pyq.Placeholder("B") HA = pyq.Constraint(A * (new_W - sum(w[a] * x[a] for a in range(N)) - y)**2, label='HA') HB = -B * sum(c[a] * x[a] for a in range(N)) Q = HA + HB model = Q.compile() feed_dict = {'A': 1, 'B': 1} qubo, offset = model.to_qubo(feed_dict=feed_dict) #iteration回数 iteration = 1000 sampler = oj.SASampler(num_reads=iteration) response = sampler.sample_qubo(qubo) def decode_solution(sampleset): decoded = model.decode_sampleset(response, feed_dict=feed_dict) solution = decoded[0].subh x = np.zeros(N, dtype=int) y = 0 for k, v in solution.items(): if 'x' in k: index = int(k.split('_')[1]) x[index] = v elif 'y' in k: y = v return {'x': x, 'y': y} result = decode_solution(response) print(result['x']) result_x = result['x'] print('result_x') print(result_x) # gacha_count = {v: result_x[k] for k,v in game_type.items()} # print(gacha_count) gacha_result = { game_id[str(v)]: result_x[k] + min_count[k] for k, v in enumerate(game_type) } gacha_count = { str(v): result_x[k] + min_count[k] for k, v in enumerate(game_type) } print('gacha_result') print(gacha_result) print('gacha_count') print(gacha_count) for k, v in gacha_result.items(): print(k) print(v) sum_money = sum(offset_value) for k, v in gacha_count.items(): sum_money += v * int(gacha_bid[k]) print('合計金額:') print(sum_money) return gacha_result