def test_parse_dzn_types(self): obj = pymzn.dzn2dict(self.dzn, types={ 'x18': { 'type': 'int', 'enum_type': 'P' }, 'x19': { 'type': 'int', 'set': True, 'enum_type': 'P' }, 'P': { 'type': 'int', 'set': True, 'enum_type': 'P' }, }) self.assertIsInstance(obj['x18'], IntEnum) self.assertEqual(obj['x18'], 2) self.assertEqual(type(obj['x18']).__name__, 'P') self.assertEqual(obj['x19'], set({1, 2})) obj = pymzn.dzn2dict(self.dzn, types={ 'x18': { 'type': 'int', 'enum_type': 'P' }, 'x19': { 'type': 'int', 'set': True, 'enum_type': 'P' }, }) self.assertEqual(obj['x18'], 'B') self.assertEqual(obj['x19'], set(['A', 'B'])) self.assertIsInstance(obj['P'], set) self.assertEqual(obj['P'], set(['A', 'B', 'C'])) # If supply wrong type raise ValueError self.assertRaises(ValueError, pymzn.dzn2dict, self.dzn, types={'x2': { 'type': 'int' }})
def print_decision(decision): gr_list = [0] * len(decision) data = pm.dzn2dict('datafrompython.dzn') # print(data) graph = data['congestion_graph'] importance = data['importance'] for lst_in in range(len(decision)): for i in range(len(decision[lst_in])): if decision[lst_in][i] == 1: gr_list[lst_in] = i + 1 # print(gr_list) for i in range(len(adj_list)): print("") print("") print("for intersection " + str(i + 1) + " =============================>>>>>>>>>") for j in range(len(adj_list[i])): if adj_list[i][j][0] == gr_list[i]: print(" road towards intersection " + str(adj_list[i][j][0]) + " congestion:" + str(graph[i][adj_list[i][j][0] - 1]) + " importance: " + str(importance[i][adj_list[i][j][0] - 1]) + " decision :## GREEN ## ") else: print(" road towards intersection " + str(adj_list[i][j][0]) + " congestion:" + str(graph[i][adj_list[i][j][0] - 1]) + " importance: " + str(importance[i][adj_list[i][j][0] - 1]) + " decision :## RED ## ") print("-------------------")
def update_cost(solns, dzn, period): data = pm.dzn2dict('datafrompython.dzn') decision = solns[0]['decision'] gr = data['congestion_graph'] rate_dec = 2 for i in range(len(adj_list)): reduction = rate_dec * period for j in range(len(adj_list)): if decision[i][j] == 1: if reduction > gr[i][j]: reduction = gr[i][j] gr[i][j] -= reduction prev_queue.append([i, j]) if len(prev_queue) > 100: prev_queue.popleft() elif j in adj_list[i]: gr[j][i] += reduction // 3 # print("congestion_graph") # print(gr) data['congestion_graph'] = gr n = len(gr) prev = [[0] * n for i in range(n)] for pair in prev_queue: prev[pair[0]][pair[1]] += 1 data['prev'] = prev global iteration iteration += 1 file_name = 'test_data' + str(iteration) + '.dzn' dzn = pm.dict2dzn(data) return dzn
def test_eval_dzn(self): dzn = dedent('''\ % This is a comment; with a semicolon x1 = 1;x2 = 1.0; x3 = -1.5; x4 = {}; x4a = { }; x5 = {1, 3}; x6 = 1..3; x7 = []; x8 = array1d({}, []); x9 = [1, 2, 3]; % Another comment x10 = [{1, 2}, {3, 4}]; x11 = array1d(1..3, [1, 2, 3]); x12 = array2d(1..2, 1..3, [1, 2, 3, 4, 5, 6]);x13 = array2d(2..3, 2..4, [1, 2, 3, 4, 5, 6]); x14 = array2d(2..3, 1..3, [1, 2, 3, 4, 5, 6]); x15 = array2d(1..2, 2..4, [1, 2, 3, 4, 5, 6]) ;''') obj = pymzn.dzn2dict(dzn) for i in range(1, 11): self.assertIn('x{}'.format(i), obj) self.assertEqual(obj['x1'], 1) self.assertEqual(obj['x2'], 1.0) self.assertEqual(obj['x3'], -1.5) self.assertEqual(obj['x4'], set()) self.assertEqual(obj['x4a'], set()) self.assertEqual(obj['x5'], {1, 3}) self.assertEqual(obj['x6'], {1, 2, 3}) self.assertEqual(obj['x7'], []) self.assertEqual(obj['x8'], []) self.assertEqual(obj['x9'], [1, 2, 3]) self.assertEqual(obj['x10'], [{1, 2}, {3, 4}]) self.assertEqual(obj['x11'], [1, 2, 3]) self.assertEqual(obj['x12'], [[1, 2, 3], [4, 5, 6]]) self.assertEqual(obj['x13'], { 2: { 2: 1, 3: 2, 4: 3 }, 3: { 2: 4, 3: 5, 4: 6 } }) self.assertEqual(obj['x14'], {2: [1, 2, 3], 3: [4, 5, 6]}) self.assertEqual(obj['x15'], [{2: 1, 3: 2, 4: 3}, {2: 4, 3: 5, 4: 6}])
def update_cost(solns, dzn, period): data = pm.dzn2dict('datafrompython.dzn') decision = solns[0]['decision'] gr = data['congestion_graph'] #print("decision") #print(decision) rate_dec = 2 for i in range(len(adj_list)): reduction = 3 * period for j in range(len(adj_list)): if decision[i][j] == 1: if reduction > gr[i][j]: reduction = gr[i][j] gr[i][j] -= reduction prev_queue.append([i, j]) if len(prev_queue) > 100: prev_queue.popleft() elif j in adj_list[i]: gr[j][i] += reduction // 3 print("congestion_graph") print(gr) data['congestion_graph'] = gr n = len(gr) prev = [[0] * n for i in range(n)] #print("prev queue") #print(prev_queue) #(prev[0])[1]=-2 # print(prev) #exit() for pair in prev_queue: # print(pair) #print(pair[0]) #print(pair[1]) #prev[0][0]=1 prev[pair[0]][pair[1]] += 1 # print(prev) data['prev'] = prev # print("prev") #print(prev) dzn = pm.dict2dzn(data) return dzn
def test_parse_dzn(self): obj = pymzn.dzn2dict(self.dzn) for i in range(1, 11): self.assertIn('x{}'.format(i), obj) self.assertEqual(obj['x1'], 1) self.assertEqual(obj['x2'], 1.0) self.assertEqual(obj['x3'], -1.5) self.assertEqual(obj['x4'], set()) self.assertEqual(obj['x4a'], set()) self.assertEqual(obj['x5'], {1, 3}) self.assertEqual(obj['x6'], pymzn.IntSet(1, 3)) self.assertEqual(obj['x7'], []) self.assertEqual(obj['x8'], []) self.assertEqual(obj['x9'], [1, 2, 3]) self.assertEqual(obj['x10'], [{1, 2}, {3, 4}]) self.assertEqual(obj['x11'], [1, 2, 3]) self.assertEqual(obj['x12'], [[1, 2, 3], [4, 5, 6]]) self.assertEqual(obj['x13'], { 2: { 2: 1, 3: 2, 4: 3 }, 3: { 2: 4, 3: 5, 4: 6 } }) self.assertEqual(obj['x14'], {2: [1, 2, 3], 3: [4, 5, 6]}) self.assertEqual(obj['x15'], [{2: 1, 3: 2, 4: 3}, {2: 4, 3: 5, 4: 6}]) self.assertEqual(obj['x16'], [{1}, {2, 3}, set(), {4}]) self.assertEqual(obj['x17'], [set()]) self.assertEqual(obj['x18'], 'B') self.assertEqual(obj['x19'], set(['A', 'B']))
solutions = pymzn.minizinc( mzn=f"{MINIZINC_BASE}/camelot_minimize.mzn", data=dict(n_tracks=len(camelot_tracks), track_distance=camelot_distance), solver=pymzn.ORTools(), parallel=8, #output_objective=True, keep_solutions=True, #rebase_arrays=False, #pre_passes=1, #keep=True, timeout=60, #output_mode='raw' ) #print(solutions) solution_dict = dict() if isinstance(solutions, str): for s in solutions.splitlines(False): if not s.startswith("%"): solution_dict.update(**pymzn.dzn2dict(s)) else: solution_dict = solutions[-1] print(solution_dict) track_order = solution_dict['track_order'] track_solution = [camelot_tracks[i - 1] for i in track_order] print(f"Output: {track_solution}") #print(f"Max track distance: {solution_dict['max_distance']}")
def main(): k4 = pymzn.dzn2dict('knapsack-4.dzn') k19 = pymzn.dzn2dict('knapsack-19.dzn') k60 = pymzn.dzn2dict('knapsack-60.dzn') k100 = pymzn.dzn2dict('knapsack-100.dzn') k400 = pymzn.dzn2dict('knapsack-400.dzn') k10k = pymzn.dzn2dict('knapsack-10000.dzn') k = k10k class DFS(object): def __init__(self, ws, vs, mw): self.data = sorted(zip(ws, vs), reverse=True, key=lambda w_v: float(w_v[1]) / w_v[0]) self.max_weight = float(mw) self.lowerbound = 0 self.acc_val = 0 self.acc_weight = 0 def calculate_upperbound(self, index, max_weight): current_value = 0 current_weight = 0 for item in self.data[index:]: if current_weight + item[0] <= max_weight: current_weight += item[0] current_value += item[1] else: current_value += item[1] * (max_weight - current_weight) / item[0] break return current_value def dfs(self): # Initialize a stack of tuples <index, include_in_knapsack> stack = [(0, False), (0, True)] # Start DFSing while stack: node, include_in_knapsack = stack.pop() if include_in_knapsack: # We add the value to our accumulated value and the weight to accumulated weight self.acc_val += self.data[node][1] self.acc_weight += self.data[node][0] # If it's not too much weight we continue DFSing and update the lowerbound. if self.acc_weight <= self.max_weight: # We then check if the new accumulated value is bigger than what we ever saw if self.lowerbound < self.acc_val: self.lowerbound = self.acc_val # If yes, we update # And now if we are not at the end of the list, we DFS to the next node if (node + 1 < len(self.data)) \ and (self.acc_val + self.calculate_upperbound(node + 1, self.max_weight - self.acc_weight) >= self.lowerbound): stack.append((node + 1, False)) stack.append((node + 1, True)) else: # We remove the node impact on the parameters self.acc_val -= self.data[node][1] self.acc_weight -= self.data[node][0] # And now if we are not at the end of the list, we DFS to the next node if (node + 1 < len(self.data)) and ( self.acc_val + self.calculate_upperbound( node + 1, self.max_weight - self.acc_weight) >= self.lowerbound): stack.append((node + 1, False)) stack.append((node + 1, True)) d = DFS(k['weight'], k['value'], k['weight_limit']) print(datetime.datetime.now()) d.dfs() print(d.lowerbound) print(datetime.datetime.now())