def main(): emergency, start_nodes, end_nodes, capacities = generate() num_emergency = len(emergency) num_solved_local = 0 # Instantiate a SimpleMaxFlow solver. max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) # Find the maximum flow between node 0 and node 4. if max_flow.Solve(0, 20) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) num_solved_local = max_flow.OptimalFlow() print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut:', max_flow.GetSourceSideMinCut()) print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.') print("There are " + str(num_emergency) + "emergencies.") print("There are " + str(num_solved_local) + " solved emergencies.") return num_emergency, num_solved_local
def create_graph_object(self): if np.issubdtype(self.flow_type, np.integer): self.graph = pywrapgraph.SimpleMaxFlow() else: raise ValueError( "Invalid flow_type '%s'. Only 'integer' allowed." % str(flow_type))
def exo4(): start_nodes = [0, 0, 1, 1, 2, 3, 3, 4] end_nodes = [1, 2, 2, 3, 4, 4, 5, 5] capacities = [3, 3, 2, 3, 2, 4, 2, 3] # Instantiate a SimpleMaxFlow solver. max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) # Find the maximum flow between node 0 and node 4. if max_flow.Solve(0, 5) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % ( max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut : ', max_flow.GetSourceSideMinCut()) print('Sink side min-cut : ', max_flow.GetSinkSideMinCut()) else: print("Il y a eu un problème avec l'entrée du flot maximum.")
def main(): """MaxFlow simple interface example.""" # [START data] # Define three parallel arrays: start_nodes, end_nodes, and the capacities # between each pair. For instance, the arc from node 0 to node 1 has a # capacity of 20. start_nodes = [0, 0, 0, 1, 1, 2, 2, 3, 3] end_nodes = [1, 2, 3, 2, 4, 3, 4, 2, 4] capacities = [20, 30, 10, 40, 30, 10, 20, 5, 20] # [END data] # Instantiate a SimpleMaxFlow solver. # [START constraints] max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for arc in zip(start_nodes, end_nodes, capacities): max_flow.AddArcWithCapacity(arc[0], arc[1], arc[2]) # [END constraints] # [START solve] # Find the maximum flow between node 0 and node 4. if max_flow.Solve(0, 4) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut:', max_flow.GetSourceSideMinCut()) print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.')
def main(): """MaxFlow simple interface example.""" # Define three parallel arrays: start_nodes, end_nodes, and the capacities # between each pair. For instance, the arc from node 0 to node 1 has a # capacity of 20. """ start_nodes = [0, 0, 0, 1, 1, 2, 2, 3, 3] end_nodes = [1, 2, 3, 2, 4, 3, 4, 2, 4] capacities = [20, 30, 10, 40, 30, 10, 20, 5, 20] """ # Instantiate a SimpleMaxFlow solver. max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) if max_flow.Solve(0, len(Z) - 1) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) else: print('There was an issue with the max flow input.')
def main(): # The problem data. A directed edge (u, v) has a capacity c. u = [0, 0, 0, 1, 1, 2, 2, 3, 3] v = [1, 2, 3, 2, 4, 3, 4, 2, 4] c = [20, 30, 10, 40, 30, 10, 20, 5, 20] assert len(u) == len(v) assert len(v) == len(c) max_flow = pywrapgraph.SimpleMaxFlow() for i in range(len(u)): max_flow.AddArcWithCapacity(u[i], v[i], c[i]) # Solve the problem, find max flow between nodes 0 and 1. status = max_flow.Solve(0, 4) if status == max_flow.OPTIMAL: print(f'Max flow: {max_flow.OptimalFlow()}') print() print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print( f'{max_flow.Tail(i)} -> {max_flow.Head(i)} {max_flow.Flow(i)} / {max_flow.Capacity(i)}' ) print(f'Source side min-cut: {max_flow.GetSourceSideMinCut()}') print(f'Sink side min-cut: {max_flow.GetSinkSideMinCut()}') else: print('Unable to compute max-flow.')
def main(): start_nodes = [0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 9] end_nodes = [1, 2, 3, 4, 5, 4, 5, 6, 5, 6, 7, 8, 7, 8, 9, 8, 9, 10, 10, 10] capacities = [ 245, 270, 260, 130, 115, 70, 90, 110, 140, 120, 110, 85, 130, 95, 85, 130, 160, 220, 330, 240 ] max_flow = pywrapgraph.SimpleMaxFlow() for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) if max_flow.Solve(0, 10) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut:', max_flow.GetSourceSideMinCut()) print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.')
def main(): #This code was based upon Maximum Flow section at Or-Tools guide provided by Google #Source: https://developers.google.com/optimization/flow/maxflow start_nodes = [0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 7, 8, 9] end_nodes = [1, 2, 3, 4, 5, 4, 5, 6, 5, 6, 7, 8, 7, 8, 9, 8, 9, 10, 10, 10] capacities = [ 245, 270, 260, 130, 115, 70, 90, 110, 140, 120, 110, 85, 130, 95, 85, 130, 160, 220, 330, 240 ] max_flow = pywrapgraph.SimpleMaxFlow() for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) if max_flow.Solve(0, 10) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut:', max_flow.GetSourceSideMinCut()) print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.')
def maximum_flows(request): """Solve maximum flow optimization problem. Args: data (dict): Input data as defined in the endpoint. References: https://developers.google.com/optimization/flow/maxflow """ # Get inputs print('Starting maximum flow optimization...') data = request.get_json()['data'] start_nodes = [arc['startNodeId'] for arc in data['arcs']] end_nodes = [arc['endNodeId'] for arc in data['arcs']] capacities = [arc['capacity'] for arc in data['arcs']] source_node = [n['id'] for n in data['nodes'] if n['type'] == 'Source'][0] sink_node = [n['id'] for n in data['nodes'] if n['type'] == 'Sink'][0] # Map nodes unique_nodes = set(start_nodes + end_nodes) node_map = dict((v, i) for i, v in enumerate(unique_nodes)) node_inv_map = dict((i, k) for k, i in node_map.items()) start_nodes = [node_map[n] for n in start_nodes] end_nodes = [node_map[n] for n in end_nodes] source_node = node_map[source_node] sink_node = node_map[sink_node] # Optimize max_flow = pywrapgraph.SimpleMaxFlow() for i in range(len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) solved = max_flow.Solve(source_node, sink_node) # Results status = 'success' message = None data = None if solved == max_flow.OPTIMAL: message = 'Optimal solution found successfully!' data = {} data['optimalFlow'] = max_flow.OptimalFlow() data['sourceMinCut'] = [node_inv_map[i] for i in max_flow.GetSourceSideMinCut()] data['sinkMinCut'] = [node_inv_map[i] for i in max_flow.GetSinkSideMinCut()] data['arcs'] = [] for i in range(max_flow.NumArcs()): data['arcs'].append({ 'startNodeId': node_inv_map[max_flow.Tail(i)], 'endNodeId': node_inv_map[max_flow.Head(i)], 'flow': max_flow.Flow(i), 'capacity': max_flow.Capacity(i) }) else: message = 'No solution found' return {'status': status, 'message': message, 'data': data}, 200
def MaxFlow_FeasibilityProblem(n_students_per_tutor, Affinity, min_val): T, S = Affinity.shape # build the min-cost transportation problem # nodes and edges ind = np.where(Affinity>=min_val) start_nodes = ind[0] # tutors end_nodes = ind[1] + T # students n_edges_inner = len(start_nodes) # add source [S+T] -> tutors and students -> destination [S+T+1] start_nodes = np.r_[start_nodes, [S+T] * T, T+np.arange(S)] end_nodes = np.r_[end_nodes, range(T), [S+T+1] * S] # capacities capacities = np.r_[np.ones(n_edges_inner), n_students_per_tutor, np.ones(S)] max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc for ii in range(len(start_nodes)): max_flow.AddArcWithCapacity(int(start_nodes[ii]), int(end_nodes[ii]), int(capacities[ii])) if max_flow.Solve(S+T, S+T+1) != max_flow.OPTIMAL: print('There was an issue with the max-flow input.') # compute the tutor-student resulting allocation allocation = np.zeros([T,S], dtype=int) for ii in range(n_edges_inner): allocation[start_nodes[ii], end_nodes[ii]-T] = int(max_flow.Flow(ii)) # students without a tutor unassigned_students = np.where(np.sum(allocation,axis=0)==0)[0] feasible_flag = (len(unassigned_students)==0) # minimum achieved affinity tmp = allocation * Affinity if feasible_flag==False: min_affinity = 0 else: min_affinity = np.min(tmp[tmp>0]) if np.sum(tmp)==0: tutor_student_assignment_low = [] tutor_student_assignment_high = [] else: if feasible_flag==False: tutor_student_assignment_low = [] tutor_student_assignment_high = np.where(tmp>min_affinity) else: tutor_student_assignment_low = np.where(tmp==min_affinity) tutor_student_assignment_high = np.where(tmp>min_affinity) return feasible_flag, unassigned_students, min_affinity, tutor_student_assignment_low, tutor_student_assignment_high
def main(): max_flow = pywrapgraph.SimpleMaxFlow() if len(sys.argv) >= 2: n = int(sys.argv[1]) else: print('Missing args: python generating.py n') pair = random.sample(range(n), 2) source = pair[0] sink = pair[1] # Parameters can be hardcoded if required density = 1 - random.random() maxcap = random.randint(n, n**2) mincap = int(maxcap * (1 - 1 / density)) edges = 0 test_filename = 'test_n{0}_mc{1}.txt'.format(n, maxcap) test_file = open(test_filename, 'w') test_file.write('{0}\n'.format(n)) test_file.write('{0} {1}\n'.format(source, sink)) for i in range(n): if i == sink: continue for j in range(n): if j == source or j == i: continue capacity = random.randint(mincap, maxcap) if capacity > 0: max_flow.AddArcWithCapacity(i, j, capacity) test_file.write('{0} {1} {2}\n'.format(i, j, capacity)) edges += 1 if max_flow.Solve(source, sink) == max_flow.OPTIMAL: # print('n:', n, 'd:', density) # print('Max flow:', max_flow.OptimalFlow()) # print('') # print(' Arc Flow / Capacity') # for i in range(max_flow.NumArcs()): # print('%1s -> %1s %3s / %3s' % ( # max_flow.Tail(i), # max_flow.Head(i), # max_flow.Flow(i), # max_flow.Capacity(i))) test_file.write('{0}'.format(max_flow.OptimalFlow())) else: print('There was an issue with the max flow input.') test_file.write('{0}'.format(-1)) print('Edge count:', edges) print('Max:', maxcap) test_file.close()
def max_flow(inp: WusnInput, max_num, rns): start_nodes = [] end_nodes = [] capacities = [] cost = [] supply = inp.num_of_relays + inp.num_of_sensors + len(rns) + 10000 demand = inp.num_of_relays + inp.num_of_sensors + len(rns) + 20000 for i in range(inp.num_of_sensors): start_nodes.append(supply) end_nodes.append(i) capacities.append(1) cost.append(0) for i in range(inp.num_of_sensors): for j in rns: if distance(inp.relays[j], inp.sensors[i]) <= 2 * inp.radius: start_nodes.append(i) end_nodes.append(j + inp.num_of_sensors) capacities.append(1) # cost.append() for i in rns: start_nodes.append(i + inp.num_of_sensors) end_nodes.append(i + inp.num_of_sensors + len(rns)) capacities.append(max_num[inp.relays[i]]) start_nodes.append(i + inp.num_of_sensors + len(rns)) end_nodes.append(demand) capacities.append(max_num[inp.relays[i]]) # cost.append(inp.static_relay_loss(inp.relays[i])) for i in range(len(start_nodes)): print(start_nodes[i], end_nodes[i], capacities[i]) mf = pywrapgraph.SimpleMaxFlow() for i in range(0, len(start_nodes)): mf.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) if mf.Solve(supply, demand) == mf.OPTIMAL: print('Max flow:', mf.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(mf.NumArcs()): if mf.Flow(i) != 0: print('%1s -> %1s %3s / %3s' % (mf.Tail(i), mf.Head(i), mf.Flow(i), mf.Capacity(i))) print('Source side min-cut:', mf.GetSourceSideMinCut()) print('Sink side min-cut:', mf.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.')
def main(): """MaxFlow simple interface example.""" # Define three parallel arrays: start_nodes, end_nodes, and the capacities # between each pair. For instance, the arc from node 0 to node 1 has a # capacity of 20. # start_nodes = [0, 0, 0, 1, 1, 2, 2, 3, 3] # end_nodes = [1, 2, 3, 2, 4, 3, 4, 2, 4] # capacities = [20, 30, 10, 40, 30, 10, 20, 5, 20] # Instantiate a SimpleMaxFlow solver. word_dict = parse.construct_word_dict('vocab.txt') parse.count_words("train.tsv", word_dict) start_nodes, end_nodes, capacities = parse.create_edge(word_dict) with open('./test.tsv', 'rb') as f: reader = csv.reader(f, delimiter='\t') next(reader, None) for row in reader: max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) tokens = parse.remove_punctuations(row[2].lower()).split(' ') label = row[1] lastvalidtoken = word_dict['[SOURCE]']['word_id'] for i, token1 in enumerate(tokens): if not (token1 in word_dict): continue else: max_flow.AddArcWithCapacity( word_dict['[SOURCE]']['word_id'], word_dict[token1]['word_id'], 99) lastvalidtoken = word_dict[token1]['word_id'] max_flow.AddArcWithCapacity(lastvalidtoken + len(word_dict) - 2, word_dict['[SINK]']['word_id'], 99) if max_flow.Solve( word_dict['[SOURCE]']['word_id'], word_dict['[SINK]']['word_id']) == max_flow.OPTIMAL: print('label:\t', label, '\tMax flow:\t', max_flow.OptimalFlow()) else: print('There was an issue with the max flow input.')
def MaxFlow(): """MaxFlow simple interface example.""" print 'MaxFlow on a simple network.' tails = [0, 0, 0, 0, 1, 2, 3, 3, 4] heads = [1, 2, 3, 4, 3, 4, 4, 5, 5] capacities = [5, 8, 5, 3, 4, 5, 6, 6, 4] expected_total_flow = 10 max_flow = pywrapgraph.SimpleMaxFlow() for i in range(0, len(tails)): max_flow.AddArcWithCapacity(tails[i], heads[i], capacities[i]) if max_flow.Solve(0, 5) == max_flow.OPTIMAL: print 'Total flow', max_flow.OptimalFlow(), '/', expected_total_flow for i in range(max_flow.NumArcs()): print 'From source %d to target %d: %d / %d' % (max_flow.Tail( i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i)) print 'Source side min-cut:', max_flow.GetSourceSideMinCut() print 'Sink side min-cut:', max_flow.GetSinkSideMinCut() else: print 'There was an issue with the max flow input.'
def maxFlow(start_nodes, end_nodes, capacities): '''求解最大流问题''' max_flow = pywrapgraph.SimpleMaxFlow() for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) # Find the maximum flow between node 0 and node 4. if max_flow.Solve(0, 4) == max_flow.OPTIMAL: print('Max flow:', max_flow.OptimalFlow()) print('') print(' Arc Flow / Capacity') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) print('Source side min-cut:', max_flow.GetSourceSideMinCut()) print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) else: print('There was an issue with the max flow input.')
def __init__(self, n, random_order=False, order=None, logger=None): self.n = n self.__order = [i for i in range(n)] self.__reverse_map = [i for i in range(n)] self.cap = [[0 for j in range(n)] for i in range(n)] self.__edges = [] self.__logger = logger if not logger is None else Logger("MaxFlow") if random_order: random.shuffle(self.__order) if not order is None: last = len(order) rest = [i for i in range(last, n)] if random_order: random.shuffle(rest) self.__order = [*order, *rest] iteration = 0 for i in self.__order: self.__reverse_map[i] = iteration iteration += 1 self.__maxflow = pywrapgraph.SimpleMaxFlow()
def max_flow(self): max_flow = pywrapgraph.SimpleMaxFlow() for edge in self.__graph.get_edges(): max_flow.AddArcWithCapacity(edge.start_node, edge.end_node, edge.capacity) if not max_flow.Solve(self.__source, self.__sink) == max_flow.OPTIMAL: # print('Max flow:', max_flow.OptimalFlow()) # print('') # print(' Arc Flow / Capacity') # for i in range(max_flow.NumArcs()): # print('%1s -> %1s %3s / %3s' % ( # max_flow.Tail(i), # max_flow.Head(i), # max_flow.Flow(i), # max_flow.Capacity(i))) # print('Source side min-cut:', max_flow.GetSourceSideMinCut()) # print('Sink side min-cut:', max_flow.GetSinkSideMinCut()) # else: print('There was an issue with the max flow input.') return max_flow.OptimalFlow()
def generate_test_case(n): max_flow = pywrapgraph.SimpleMaxFlow() pair = random.sample(range(n), 2) source = pair[0] sink = pair[1] # Parameters can be hardcoded if required density = 1 - random.random() maxcap = random.randint(n, n**2) mincap = int(maxcap * (1 - 1/density)) edges = 0 test_filename = 'test_n{0}_mc{1}.txt'.format(n, maxcap) test_file = open(test_filename, 'w') test_file.write('{0}\n'.format(n)) test_file.write('{0} {1}\n'.format(source, sink)) for i in range(n): if i == sink: continue for j in range(n): if j == source or j == i: continue capacity = random.randint(mincap, maxcap) if capacity > 0: max_flow.AddArcWithCapacity(i, j, capacity) test_file.write('{0} {1} {2}\n'.format(i, j, capacity)) edges += 1 if max_flow.Solve(source, sink) == max_flow.OPTIMAL: test_file.write('{0}'.format(max_flow.OptimalFlow())) else: print('There was an issue with the max flow input.') test_file.write('{0}'.format(-1)) test_file.close() return test_filename, edges
def solve_max_flow(self, sol, dist): max_flow = pywrapgraph.SimpleMaxFlow() sensors_arr = [k for k in self.inp.sensors] relays_arr = [k for k in self.inp.relays] N, M = self.inp.num_of_sensors, self.inp.num_of_relays for i in range(N): max_flow.AddArcWithCapacity(0, i + 1, 1) for i in range(N): for j in range(M): if distance(sensors_arr[i], relays_arr[j]) <= 2 * dist: max_flow.AddArcWithCapacity(i + 1, j + N + 1, 1) for j in range(M): max_flow.AddArcWithCapacity(j + N + 1, N + M + 1, sol[j]) if max_flow.Solve(0, N + M + 1) == max_flow.OPTIMAL: return max_flow else: return -1
from ortools.graph import pywrapgraph # 定义从 start->end 的弧的容量 # 即 start_node[i] -> end_node[i] = capacities[i] start_nodes = [1, 1, 1, 2, 4, 4, 3, 3, 5] end_nodes = [2, 4, 3, 6, 6, 5, 4, 5, 6] capacities = [70, 90, 100, 80, 100, 40, 40, 70, 90] # 创建简单流 max_flow = pywrapgraph.SimpleMaxFlow() # 添加节点和弧的约束 for i in range(len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) # 求解 1->6 的最大流 if max_flow.Solve(1, 6) == max_flow.OPTIMAL: print('最大流是:', max_flow.OptimalFlow()) print(' 边 流量 / 边的最大流量') for i in range(max_flow.NumArcs()): print('%1s -> %1s %3s / %3s' % (max_flow.Tail(i), max_flow.Head(i), max_flow.Flow(i), max_flow.Capacity(i))) # 结果如下: # 最大流是: 260 # 边 流量 / 边的最大流量 # 1 -> 2 70 / 70 # 1 -> 4 90 / 90 # 1 -> 3 100 / 100 # 2 -> 6 70 / 80 # 4 -> 6 100 / 100 # 4 -> 5 30 / 40
def solve_one_example_with_genetic_climber_max_flow(deadline_for_genetic, deadline_for_hill_climber): (B, L, D), book_values, book_counts, libraries = process_file() libraries_backup = copy.deepcopy(libraries) genetic_solver = GeneticSolver(B, L, D, book_values, book_counts, libraries, start_time, deadline=deadline_for_genetic) individual = genetic_solver.get_individual() check_solution(D, genetic_solver.get_solution(selected_lib_ids=individual)) hill_climber_solver = MutationHillClimbingSolver( B, L, D, book_values, book_counts, libraries, genetic_solver.individual_scores, start_time, deadline=deadline_for_hill_climber) # Creating new individual with hill_climber individual = hill_climber_solver.get_individual(individual) climbed_solution = hill_climber_solver.get_solution(individual) check_solution(D, climbed_solution) libraries = libraries_backup all_book_ids = set() for lib_id in individual: all_book_ids.update(libraries[lib_id].book_ids) book_to_node, node_to_book = generate_book_to_node_assignment( len(individual), all_book_ids) start_nodes = [] end_nodes = [] capacities = [] unit_costs = [] source = 0 sink = len(individual) + len(all_book_ids) + 1 day = 0 # from source to lib for i in range(len(individual)): day += libraries[individual[i]].signup_time start_nodes.append(source) end_nodes.append(lib_to_node(i)) capacities.append((D - day) * libraries[individual[i]].books_per_day) unit_costs.append(0) # from lib to book for i in range(len(individual)): for book_id in libraries[individual[i]].book_ids: start_nodes.append(lib_to_node(i)) end_nodes.append(book_to_node[book_id]) capacities.append(1) unit_costs.append(0) # from book to sink for book_id in all_book_ids: start_nodes.append(book_to_node[book_id]) end_nodes.append(sink) capacities.append(1) unit_costs.append(-book_values[book_id]) max_flow = pywrapgraph.SimpleMaxFlow() # Add each arc. for i in range(0, len(start_nodes)): max_flow.AddArcWithCapacity(start_nodes[i], end_nodes[i], capacities[i]) max_flow.Solve(0, sink) if max_flow.Solve(0, sink) != max_flow.OPTIMAL: raise Exception("Failed with max_flow", max_flow.OptimalFlow()) optimal_flow = max_flow.OptimalFlow() supplies = [0 for i in range(sink + 1)] supplies[0] = optimal_flow supplies[-1] = -optimal_flow min_cost_flow = pywrapgraph.SimpleMinCostFlow() # Add each arc. for i in range(0, len(start_nodes)): min_cost_flow.AddArcWithCapacityAndUnitCost(start_nodes[i], end_nodes[i], capacities[i], unit_costs[i]) for i in range(0, len(supplies)): min_cost_flow.SetNodeSupply(i, supplies[i]) if min_cost_flow.Solve() != min_cost_flow.OPTIMAL: raise Exception("Failed with min_cost_flow", max_flow.OptimalFlow()) solution = [] for lib_id in individual: lib2 = copy.deepcopy(libraries[lib_id]) lib2.book_ids = set() solution.append(lib2) for i in range(min_cost_flow.NumArcs()): from_node = min_cost_flow.Tail(i) to_node = min_cost_flow.Head(i) flow = min_cost_flow.Flow(i) if lib_to_node(0) <= from_node <= lib_to_node(len(individual) - 1) and flow == 1: lib_index = node_to_lib(from_node) book_id = node_to_book[to_node] solution[lib_index].book_ids.add(book_id) check_solution(D, solution) create_solution(solution)