def get_condensation_graph(graph, parent_mapping): cond_graph = GraphCore(False) for src, edges in graph.get_all_edges().items(): parent_src = parent_mapping[src] for dst in edges: parent_dst = parent_mapping[dst] if parent_src == parent_dst: continue else: cond_graph.add_edge(parent_src, parent_dst) # For all the vertices which are disconnected from the rest of the graph. for src in graph.vertices: if parent_mapping[src] == src: cond_graph.add_vertex(src) return cond_graph
def main(): graph = GraphCore(False) num_vertices = 4 edges_input = [] edges_input.append((1, 2)) edges_input.append((3, 2)) edges_input.append((4, 3)) edges_input.append((2, 1)) for edge in edges_input: # Reverse edges. graph.add_edge(edge[1], edge[0]) for vert in range(num_vertices): graph.add_vertex(vert + 1) ans = get_first_component_nodes(graph) print(ans)
def simplify_debt_graph(debt_graph: GraphCore): credit_flow = {} for vert in debt_graph.vertices: credit_flow[vert] = 0 for src, edges in debt_graph.get_all_edges().items(): for neigh, edge in edges.items(): wt = edge["weight"] credit_flow[src] -= wt credit_flow[neigh] += wt debtors = [] creditors = [] for vert, flow in credit_flow.items(): if flow < 0: debtors.append([vert, -flow]) else: creditors.append([vert, flow]) assert sum(map(lambda item: item[1], debtors)) == sum(map(lambda item: item[1], creditors)) simplified_graph = GraphCore() for vert in debt_graph.vertices: simplified_graph.add_vertex(vert) debtors_idx = 0 creditors_idx = 0 while debtors_idx < len(debtors) and creditors_idx < len(creditors): debtor = debtors[debtors_idx] creditor = creditors[creditors_idx] min_flow = min(debtor[1], creditor[1]) simplified_graph.add_edge(debtor[0], creditor[0], min_flow) debtor[1] -= min_flow creditor[1] -= min_flow if debtor[1] == 0: debtors_idx += 1 if creditor[1] == 0: creditors_idx += 1 assert debtors_idx == len(debtors) assert creditors_idx == len(creditors) return simplified_graph