def solve( self, objectives: List[ObjectiveTerm] = [], constraints: List[ConstraintTerm] = [], num_reads=10, sweeps=1000, beta_range=(1, 50), ): pyqubo_model = self.parse_to_pyqubo_model(objectives, constraints) feed_dict = {} feed_dict.update({o["label"]: o["weight"] for o in objectives}) feed_dict.update({c["label"]: c["weight"] for c in constraints}) if self.vartype == "SPIN": linear, quad, offset = pyqubo_model.to_ising(feed_dict=feed_dict) solution = solve_ising(linear, quad, num_reads=num_reads, sweeps=sweeps, beta_range=beta_range) else: model, offset = pyqubo_model.to_qubo(feed_dict=feed_dict) solution = solve_qubo(model, num_reads=num_reads, sweeps=sweeps, beta_range=beta_range) return pyqubo_model.decode_solution(solution, vartype=self.vartype, feed_dict=feed_dict)
def get_qubo(num_nodes, num_colors, edges): x = Array.create('x', (num_nodes, num_colors), "BINARY") adjacent_const = 0.0 for (i, j) in edges: for k in range(num_colors): adjacent_const += Constraint(x[i, k] * x[j, k], label="adjacent({},{})".format(i, j)) onecolor_const = 0.0 for i in range(num_nodes): onecolor_const += Constraint( (Sum(0, num_colors, lambda j: x[i, j]) - 1)**2, label="onecolor{}".format(i)) # combine the two components alpha = Placeholder("alpha") H = alpha * onecolor_const + adjacent_const model = H.compile() alpha = 1.0 # search for an alpha for which each node has only one color print("Broken constraints") while True: qubo, offset = model.to_qubo(feed_dict={"alpha": alpha}) solution = solve_qubo(qubo) decoded_solution, broken_constraints, energy = model.decode_solution( solution, vartype="BINARY", feed_dict={"alpha": alpha}) print(len(broken_constraints)) if not broken_constraints: break for (key, value) in broken_constraints.items(): if 'o' == key[0]: # onecolor alpha += 0.1 break if 'a' == key[0]: # adjacent break return qubo, decoded_solution
def solve(self,model,shape=None,feed_dict=None): if feed_dict is None: feed_dict = {'PTMO': 2,'PDMO': 2,'PMC': 1} qubo, offset = model.to_qubo(feed_dict=feed_dict) sol = solve_qubo(qubo) if shape is None: np_X = self.decode(sol) else: np_X = self.decode_(sol,shape) return np_X
def test_solve_qubo(self): model = TestSolver.create_number_partition_model() qubo, offset = model.to_qubo() solution = solve_qubo(qubo, num_reads=1, sweeps=10) self.assertTrue(solution == { 's1': 0, 's2': 0, 's3': 1 } or { 's1': 1, 's2': 1, 's3': 0 })
q = {} if solution_type == 'D-wave': q = response.record['sample'][0][:NUM_PACKAGE] elif solution_type == 'SA': q = list(decoded_solution['q'].values()) package = [] weight = 0 value = 0 for i in range(NUM_PACKAGE): if q[i] == 1: package.append(PACKAGE_NAME[i]) weight += WEIGHT[i] value += VALUE[i] print('knapsack <-', package) print('weight = ', weight, 'g') print('value = ', value, 'yen') if solution_type == 'D-wave': # PyQUBOのQAで解を探索する sampler = EmbeddingComposite(DWaveSampler()) response = sampler.sample_qubo(qubo) # 結果出力 print_result(response) elif solution_type == 'SA': # PyQUBOのSAで解を探索する raw_solution = solve_qubo(qubo) # 得られた結果をデコードする decoded_solution, broken, energy = model.decode_solution(raw_solution, vartype="BINARY", feed_dict=feed_dict) print_result(decoded_solution)
if i not in orderList: print(""" Solutions doesn't fulfill requirements. There are cities you visit more than once. """) sys.exit() return orderList if __name__ == "__main__": cities = 5 citiesLocation, paths = makeDemoData(citiesSize=cities) hamiltonian = TSPHamiltonian(citiesSize=cities, pathsWeight=paths) feedDict = {"lamTime": 250.0, "lamVisit": 250.0} qubo, offset = hamiltonian.compile().to_qubo(feed_dict=feedDict) rawSolution = pyqubo.solve_qubo(qubo) decodeSolution, broken, energu = hamiltonian.compile().decode_solution( rawSolution, vartype="BINARY", feed_dict=feedDict) orderList = dict2AnsList(solutionsDict=decodeSolution, citiesSize=cities) orderList = list(map(lambda x: x + 1, orderList)) orderList.append(0) plotMap(citiesLocation=citiesLocation, orderList=orderList) sys.exit()
distance += d_ij * x[k, i] * x[(k+1)%n_city, j] # Construct hamiltonian A = Placeholder("A") H = distance + A * (time_const + city_const) # Compile model model = H.compile() # Generate QUBO feed_dict = {'A': 4.0} qubo, offset = model.to_qubo(feed_dict=feed_dict) # solve QUBO with Simulated Annealing (SA) provided by neal. sol = solve_qubo(qubo) # decode solution, constraints that are broken and energy value solution_sim, broken, energy = model.decode_solution(sol, vartype="BINARY", feed_dict=feed_dict) plot_city(cities, solution_sim["c"]) plt.savefig(path + '/venv/results/test/test_simulator.png') plt.close() ############################################################################################################################################################################################### # solve TSP problem on D-Wave machine ############################################################################################################################################################################################### from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite
def solve(numbers): qbits = pyqubo.Array.create('x', len(numbers), vartype='BINARY') H = sum([(2 * q - 1) * n for n, q in zip(numbers, qbits)])**2 model = H.compile() qubo, offset = model.to_qubo() return pyqubo.solve_qubo(qubo)
def solve(self, file_name, all_jobs, job_num, all_machines, machine_num, job_ids, request_times, due_times, process_intervals, processing_cost): solved = False k = 0 milp_model, assign, start_time = _create_milp_model( job_num, machine_num, job_ids, request_times, due_times, process_intervals, processing_cost) """ Write a log file, cannot call in main() function """ output_file = os.getcwd( ) + "/logs/hybrid/2nd/hybrid-jss-" + file_name + ".log" milp_model.setParam(grb.GRB.Param.LogFile, output_file) """ Hybrid strategy """ try: while not solved: print( "-----------------------------------------ITERATION:--------------------------------", k + 1) # milp_model.update() # milp_model.tune() milp_model.optimize(callbackTerminate) print("start time after MILP: {}".format(start_time)) if k > 0: print("After getting integer cuts %i:" % (k + 1)) if milp_model.status == grb.GRB.Status.OPTIMAL: """ Check the feasibility subproblem by MILP or CP model """ model, next_sequence, next_ts, job_pairs_apos, z_apos, U = self._feasi_by_milp( job_num, machine_num, job_ids, request_times, due_times, process_intervals, assign, start_time) qubo, offset = model.to_qubo() bqm = dimod.BinaryQuadraticModel.from_qubo(qubo, offset) # sampler = EmbeddingComposite(DWaveSampler({"qpu": True})) # response = sampler.sample(bqm) # next_sequence = response.first.sample next_sequence = pyqubo.solve_qubo(qubo) print("y result: {}".format(next_sequence)) print("next ts: {}".format(next_ts)) # # do IIS (test conflict contraints) # print('The model is infeasible; computing IIS') # milp2_model.computeIIS() # if milp2_model.IISMinimal: # print('IIS is minimal\n') # else: # print('IIS is not minimal\n') # print('\nThe following constraint(s) cannot be satisfied:') # for c in milp2_model.getConstrs(): # if c.IISConstr: # print('%s' % c.constrName) # Infeasible schedule print(z_apos, job_pairs_apos) next_start_time = milp_model.getAttr("X", start_time) print(next_start_time) check_feasible = True for (i, j) in job_pairs_apos: if z_apos[j] == z_apos[i] and next_sequence[ 'y_(%d,%d)' % (i, j)] == 1: next_start_time[j] = next_start_time[ i] + process_intervals[i][z_apos[i]] print("new: {}".format(next_start_time)) # Case: same machine, same start time --> not feasible solution for (i, j) in job_pairs_apos: if z_apos[j] == z_apos[i] and next_start_time[ i] == next_start_time[j]: check_feasible = False print("check feasible: {}".format(check_feasible)) # feasible_schedule = {} # for (i,j) in job_pairs_apos: # feasible_schedule[(i,j)] = 0 # if z_apos[j] == z_apos[i] and next_sequence['y_(%d,%d)' % (i,j)] == 1 and next_sequence['y_(%d,%d)' % (i,j)] + next_sequence['y_(%d,%d)' % (j,i)] == 1: # print(i,j, process_intervals[i][z_apos[i]]) # condition = next_start_time[j] < next_start_time[i] + process_intervals[i][z_apos[i]] - U*(1 - next_sequence['y_(%d,%d)' % (i,j)]) # print("here: {}".format(condition)) # if condition: # continue # else: # feasible_schedule[(i,j)] = 1 # # print(feasible_schedule) # print(next_start_time) # if any(value==1 for key,value in feasible_schedule.items()): # check_feasible = 1 # print(check_feasible) # print(next_start_time) if not check_feasible: # status2_str = StatusDict[milp2_model.status] # print("Feasibility was stopped with status %s" %status2_str) """ Infeasible """ k += 1 """ Adding integer cuts """ # 1. Creation of set of elements x[i,m] == 1 set_xim = [ i for i in range(job_num) for m in range(machine_num) if assign[(i, m)].x == 1 ] print(set_xim) # 2. Add constraint to MILP model milp_model.addConstr(lhs=grb.quicksum([ assign[(i, m)] for i in set_xim for m in range(machine_num) if assign[(i, m)].x == 1 ]), sense=grb.GRB.LESS_EQUAL, rhs=len(set_xim) - 1, name="integer cut") # # do IIS (test conflict contraints) # print('The model is infeasible; computing IIS') # milp_model.computeIIS() # if milp_model.IISMinimal: # print('IIS is minimal\n') # else: # print('IIS is not minimal\n') # print('\nThe following constraint(s) cannot be satisfied:') # for c in milp_model.getConstrs(): # if c.IISConstr: # print('%s' % c.constrName) else: """ Feasible """ solved = True print("Optimal Schedule Cost: %i" % (milp_model.objVal)) milp_model.printStats() self._formulate_schedules(all_machines, job_ids, request_times, due_times, process_intervals, assign, next_start_time) else: status_str = StatusDict[milp_model.status] print("Optimization was stopped with status %s" % status_str) milp_model.params.DualReductions = 0 milp_model._vars = assign, start_time milp_model.Params.lazyConstraints = 1 solved = True except grb.GurobiError as e: print("Error code " + str(e.errno) + ": " + str(e)) return solved