def test_incidence_graph(self): m = make_degenerate_solid_phase_model() variables = list(m.component_data_objects(pyo.Var)) constraints = list(m.component_data_objects(pyo.Constraint)) graph = get_incidence_graph(variables, constraints) matrix = get_structural_incidence_matrix(variables, constraints) from_matrix = from_biadjacency_matrix(matrix) self.assertEqual(graph.nodes, from_matrix.nodes) self.assertEqual(graph.edges, from_matrix.edges)
def plot_graph(graph: Graph, layout=None, bipartite=False, labels=None, *args, **kwargs): import networkx as nx from networkx.algorithms.bipartite.matrix import from_biadjacency_matrix nx_layout = { None: nx.random_layout, 'circular': nx.circular_layout, 'kamada_kawai': nx.kamada_kawai_layout, 'random': nx.random_layout, 'shell': nx.shell_layout, 'spectral': nx.spectral_layout, 'spring': nx.spring_layout, 'bipartite': nx.bipartite_layout } nrow, ncol = graph.sm.shape if bipartite: g = from_biadjacency_matrix(graph.sm) # bipartite graph can use other layout, but default is bipartite layout = 'bipartite' if layout is None else layout else: g = nx.from_scipy_sparse_matrix(graph.sm) if layout == 'bipartite': pos = nx.bipartite_layout(g, nodes=range(nrow)) else: pos = nx_layout[layout](g) fig = plt.figure() if bipartite: nx.draw_networkx(g, pos=pos, node_color=('r' * nrow + 'b' * ncol), alpha=0.8) else: nx.draw_networkx(g, pos=pos, node_color='r', alpha=0.8) if labels is not None: if isinstance(labels, dict): nx.draw_networkx_labels(g, pos=pos, labels=labels) else: ldict = dict(zip(range(len(labels)), labels)) nx.draw_networkx_labels(g, pos=pos, labels=ldict) return fig
def get_max_weight_match(sim: np.ndarray) -> np.ndarray: if nx is None: raise ValueError("networkx must be installed to use match algorithm.") def permute(edge): if edge[0] < sim.shape[0]: return edge[0], edge[1] - sim.shape[0] else: return edge[1], edge[0] - sim.shape[0] G = from_biadjacency_matrix(csr_matrix(sim)) matching = nx.max_weight_matching(G, maxcardinality=True) matching = [permute(x) for x in matching] matching = sorted(matching, key=lambda x: x[0]) res_matrix = np.zeros_like(sim) for edge in matching: res_matrix[edge[0], edge[1]] = 1 return res_matrix