Python networkx.relabel_nodes() Examples

The following are 30 code examples of networkx.relabel_nodes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_isomorphvf2.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_selfloop():
    # Simple test for graphs with selfloops
    edges = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 2), 
             (2, 4), (3, 1), (3, 2), (4, 2), (4, 5), (5, 4)]
    nodes = list(range(6))

    for g1 in [nx.Graph(), nx.DiGraph()]:
        g1.add_edges_from(edges)
        for _ in range(100):
            new_nodes = list(nodes)
            random.shuffle(new_nodes)
            d = dict(zip(nodes, new_nodes))
            g2 = nx.relabel_nodes(g1, d)
            if not g1.is_directed():
                gm = iso.GraphMatcher(g1,g2)
            else:
                gm = iso.DiGraphMatcher(g1,g2)
            assert_true(gm.is_isomorphic()) 
Example #2
Source File: synthetic_structsim.py    From gnn-model-explainer with Apache License 2.0 6 votes vote down vote up
def ba(start, width, role_start=0, m=5):
    """Builds a BA preferential attachment graph, with index of nodes starting at start
    and role_ids at role_start
    INPUT:
    -------------
    start       :    starting index for the shape
    width       :    int size of the graph
    role_start  :    starting index for the roles
    OUTPUT:
    -------------
    graph       :    a house shape graph, with ids beginning at start
    roles       :    list of the roles of the nodes (indexed starting at
                     role_start)
    """
    graph = nx.barabasi_albert_graph(width, m)
    graph.add_nodes_from(range(start, start + width))
    nids = sorted(graph)
    mapping = {nid: start + i for i, nid in enumerate(nids)}
    graph = nx.relabel_nodes(graph, mapping)
    roles = [role_start for i in range(width)]
    return graph, roles 
Example #3
Source File: initialization_test.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def test_initialization_reproducible_between_runs():
    seed = 45
    logical_graph = nx.erdos_renyi_graph(6, 0.5, seed=seed)
    logical_graph = nx.relabel_nodes(logical_graph, cirq.LineQubit)
    device_graph = ccr.get_grid_device_graph(2, 3)
    initial_mapping = ccr.initialization.get_initial_mapping(
        logical_graph, device_graph, seed)
    expected_mapping = {
        cirq.GridQubit(0, 0): cirq.LineQubit(5),
        cirq.GridQubit(0, 1): cirq.LineQubit(0),
        cirq.GridQubit(0, 2): cirq.LineQubit(2),
        cirq.GridQubit(1, 0): cirq.LineQubit(3),
        cirq.GridQubit(1, 1): cirq.LineQubit(4),
        cirq.GridQubit(1, 2): cirq.LineQubit(1),
    }
    assert initial_mapping == expected_mapping 
Example #4
Source File: gates.py    From circuit-fault-diagnosis with Apache License 2.0 6 votes vote down vote up
def gate_model(gate_type, fault=True):
    labels, configurations = GATES[gate_type]
    if fault:
        configurations = fault_gate(configurations, FAULT_GAP)
    num_variables = len(next(iter(configurations)))
    for size in range(num_variables, num_variables+4):  # reasonable margin
        G = nx.complete_graph(size)
        nx.relabel_nodes(G, dict(enumerate(labels)), copy=False)
        spec = pm.Specification(G, labels, configurations, dimod.SPIN)
        try:
            pmodel = pm.get_penalty_model(spec)
            if pmodel is not None:
                return pmodel
        except pm.ImpossiblePenaltyModel:
            pass

    raise ValueError("unable to get the penalty model from factories") 
Example #5
Source File: build.py    From stolos with Apache License 2.0 6 votes vote down vote up
def visualize_dag(dg=None, plot_nx=False, plot_graphviz=True, write_dot=True,
                  prog='dot'):
    """For interactive use"""
    import webbrowser
    if not dg:
        dg = build_dag()
    dg = nx.relabel_nodes(
        dg,
        {x: "%s\n%s" % (x, node.get_job_id_template(x)[0]) for x in dg.node})
    if plot_nx:
        nx.draw_graphviz(dg, prog=prog)
    if write_dot or plot_graphviz:
        tmpf = tempfile.mkstemp(suffix='.dot', prefix='stolos_dag_')[1]
        nx.write_dot(dg, tmpf)
        os.popen('{1} {0} -Tpng > {0}.png'.format(tmpf, prog))
        print("saved to %s.png" % tmpf)
        if plot_graphviz:
            webbrowser.open(tmpf + '.png') 
Example #6
Source File: test_specification.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_relabel_typical(self):
        graph = nx.circular_ladder_graph(12)
        decision_variables = (0, 2, 5)
        feasible_configurations = {(1, 1, 1): 0.}
        spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        mapping = dict(enumerate('abcdefghijklmnopqrstuvwxyz'))

        new_spec = spec.relabel_variables(mapping, inplace=False)

        # create a test spec
        graph = nx.relabel_nodes(graph, mapping)
        decision_variables = (mapping[v] for v in decision_variables)
        test_spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        self.assertEqual(new_spec, test_spec)
        self.assertEqual(new_spec.ising_linear_ranges, test_spec.ising_linear_ranges)
        self.assertEqual(new_spec.ising_quadratic_ranges, test_spec.ising_quadratic_ranges) 
Example #7
Source File: test_specification.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_relabel_copy(self):
        graph = nx.circular_ladder_graph(12)
        decision_variables = (0, 2, 5)
        feasible_configurations = {(1, 1, 1): 0.}
        spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        mapping = dict(enumerate('abcdefghijklmnopqrstuvwxyz'))

        new_spec = spec.relabel_variables(mapping, inplace=False)

        # create a test spec
        graph = nx.relabel_nodes(graph, mapping)
        decision_variables = (mapping[v] for v in decision_variables)
        test_spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        self.assertEqual(new_spec, test_spec)
        self.assertEqual(new_spec.ising_linear_ranges, test_spec.ising_linear_ranges)
        self.assertEqual(new_spec.ising_quadratic_ranges, test_spec.ising_quadratic_ranges) 
Example #8
Source File: test_specification.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_relabel_inplace(self):
        graph = nx.circular_ladder_graph(12)
        decision_variables = (0, 2, 5)
        feasible_configurations = {(1, 1, 1): 0.}
        spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        mapping = {i: v for i, v in enumerate('abcdefghijklmnopqrstuvwxyz') if i in graph}

        new_spec = spec.relabel_variables(mapping, inplace=True)

        self.assertIs(new_spec, spec)  # should be the same object
        self.assertIs(new_spec.graph, spec.graph)

        # create a test spec
        graph = nx.relabel_nodes(graph, mapping)
        decision_variables = (mapping[v] for v in decision_variables)
        test_spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)

        self.assertEqual(new_spec, test_spec)
        self.assertEqual(new_spec.ising_linear_ranges, test_spec.ising_linear_ranges)
        self.assertEqual(new_spec.ising_quadratic_ranges, test_spec.ising_quadratic_ranges) 
Example #9
Source File: test_interface.py    From penaltymodel with Apache License 2.0 6 votes vote down vote up
def test_and_on_k44(self):
        graph = nx.Graph()
        for i in range(3):
            for j in range(3, 6):
                graph.add_edge(i, j)

        decision_variables = (0, 2, 3)
        feasible_configurations = AND(2)

        mapping = {0: '0', 1: '1', 2: '2', 3: '3'}
        graph = nx.relabel_nodes(graph, mapping)
        decision_variables = tuple(mapping[x] for x in decision_variables)

        spin_configurations = tuple([tuple([2 * i - 1 for i in b]) for b in feasible_configurations])
        spec = pm.Specification(graph, decision_variables, spin_configurations, vartype=dimod.SPIN)

        pm0 = mip.get_penalty_model(spec)

        self.check_generated_ising_model(pm0.feasible_configurations, pm0.decision_variables,
                                         pm0.model.linear, pm0.model.quadratic, pm0.ground_energy - pm0.model.offset,
                                         pm0.classical_gap) 
Example #10
Source File: PC.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def orient_undirected_graph(self, data, graph, **kwargs):
        """Run PC on an undirected graph.

        Args:
            data (pandas.DataFrame): DataFrame containing the data
            graph (networkx.Graph): Skeleton of the graph to orient

        Returns:
            networkx.DiGraph: Solution given by PC on the given skeleton.
        """
        # Building setup w/ arguments.
        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]
        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.CI_test]
        self.arguments['{DIRECTED}'] = 'TRUE'
        self.arguments['{ALPHA}'] = str(self.alpha)
        self.arguments['{NJOBS}'] = str(self.njobs)
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()

        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())
        fg = DataFrame(1 - fe.values)

        results = self._run_pc(data, fixedEdges=fe, fixedGaps=fg, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #11
Source File: PC.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data, **kwargs):
        """Run the PC algorithm.

        Args:
            data (pandas.DataFrame): DataFrame containing the data

        Returns:
            networkx.DiGraph: Solution given by PC on the given data.
       """
        # Building setup w/ arguments.
        self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test]
        self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.CI_test]
        self.arguments['{DIRECTED}'] = 'TRUE'
        self.arguments['{ALPHA}'] = str(self.alpha)
        self.arguments['{NJOBS}'] = str(self.njobs)
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()

        results = self._run_pc(data, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #12
Source File: LiNGAM.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data):
        """Run the LiNGAM algorithm.

        Args:
            data (pandas.DataFrame): DataFrame containing the data

        Returns:
            networkx.DiGraph: Prediction given by the LiNGAM algorithm.

        """
        # Building setup w/ arguments.
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()
        results = self._run_LiNGAM(data, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #13
Source File: CAM.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data, **kwargs):
        """Apply causal discovery on observational data using CAM.

        Args:
            data (pandas.DataFrame): DataFrame containing the data

        Returns:
            networkx.DiGraph: Solution given by the CAM algorithm.
        """
        # Building setup w/ arguments.
        self.arguments['{SCORE}'] = self.scores[self.score]
        self.arguments['{CUTOFF}'] = str(self.cutoff)
        self.arguments['{VARSEL}'] = str(self.variablesel).upper()
        self.arguments['{SELMETHOD}'] = self.var_selection[self.selmethod]
        self.arguments['{PRUNING}'] = str(self.pruning).upper()
        self.arguments['{PRUNMETHOD}'] = self.var_selection[self.prunmethod]
        self.arguments['{NJOBS}'] = str(self.njobs)
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()
        results = self._run_cam(data, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #14
Source File: gnn_explainer.py    From pytorch_geometric with MIT License 6 votes vote down vote up
def __subgraph__(self, node_idx, x, edge_index, **kwargs):
        num_nodes, num_edges = x.size(0), edge_index.size(1)

        subset, edge_index, mapping, edge_mask = k_hop_subgraph(
            node_idx, self.__num_hops__(), edge_index, relabel_nodes=True,
            num_nodes=num_nodes, flow=self.__flow__())

        x = x[subset]
        for key, item in kwargs:
            if torch.is_tensor(item) and item.size(0) == num_nodes:
                item = item[subset]
            elif torch.is_tensor(item) and item.size(0) == num_edges:
                item = item[edge_mask]
            kwargs[key] = item

        return x, edge_index, mapping, edge_mask, kwargs 
Example #15
Source File: test_isomorphvf2.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_multiedge():
    # Simple test for multigraphs
    # Need something much more rigorous
    edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), 
             (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), 
             (10, 11), (10, 11), (11, 12), (11, 12), 
             (12, 13), (12, 13), (13, 14), (13, 14), 
             (14, 15), (14, 15), (15, 16), (15, 16), 
             (16, 17), (16, 17), (17, 18), (17, 18), 
             (18, 19), (18, 19), (19, 0), (19, 0)]
    nodes = list(range(20))

    for g1 in [nx.MultiGraph(), nx.MultiDiGraph()]:
        g1.add_edges_from(edges)
        for _ in range(10):
            new_nodes = list(nodes)
            random.shuffle(new_nodes)
            d = dict(zip(nodes, new_nodes))
            g2 = nx.relabel_nodes(g1, d)
            if not g1.is_directed():
                gm = iso.GraphMatcher(g1,g2)
            else:
                gm = iso.DiGraphMatcher(g1,g2)
            assert_true(gm.is_isomorphic()) 
Example #16
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __from_graph_tool_to_nx(graph, node_map=None, directed=None):

    if directed is None:
        directed = graph.is_directed()

    if directed:
        tp = nx.DiGraph()
    else:
        tp = nx.Graph()

    tp.add_nodes_from([int(v) for v in graph.vertices()])
    tp.add_edges_from([(int(e.source()), int(e.target()))
                       for e in graph.edges()])
    if node_map:
        nx.relabel_nodes(tp, node_map, copy=False)

    return tp 
Example #17
Source File: test_Network.py    From pathpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_import_from_networkx():
    # TODO: add test for weighted networks
    from pathpy.classes.network import network_from_networkx
    import networkx as nx

    g = nx.generators.barabasi_albert_graph(20, 10)
    relabeling = {i: str(i) for i in g}
    nx.relabel_nodes(g, relabeling, copy=False)
    for i, edge in enumerate(g.edges):
        g.edges[edge]['custom'] = i

    net = network_from_networkx(g)
    assert net.ncount() == len(g)
    assert net.ecount() == len(g.edges)
    for edge in net.edges:
        assert net.edges[edge]['custom'] == g.edges[edge]['custom'] 
Example #18
Source File: test_io.py    From graspy with Apache License 2.0 6 votes vote down vote up
def setup_class(self, tmpdir):
        n = 10
        p = 0.5
        wt = np.random.exponential
        wtargs = dict(scale=4)

        np.random.seed(1)

        self.A = gs.simulations.er_np(n, p)
        self.B = gs.simulations.er_np(n, p, wt=wt, wtargs=wtargs)

        G_A = nx.from_numpy_array(self.A)
        G_B = nx.from_numpy_array(self.B)
        G_B = nx.relabel_nodes(G_B, lambda x: x + 10)  # relabel nodes to go from 10-19.

        self.A_path = str(tmpdir / "A_unweighted.edgelist")
        self.B_path = str(tmpdir / "B.edgelist")
        self.root = str(tmpdir)

        nx.write_edgelist(G_A, self.A_path, data=False)
        nx.write_weighted_edgelist(G_B, self.B_path) 
Example #19
Source File: Lasso.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def predict(self, data, alpha=0.01, max_iter=2000, **kwargs):
        """ Predict the graph skeleton.

        Args:
            data (pandas.DataFrame): observational data
            alpha (float): regularization parameter
            max_iter (int): maximum number of iterations

        Returns:
            networkx.Graph: Graph skeleton
        """
        edge_model = GraphicalLasso(alpha=alpha, max_iter=max_iter)
        edge_model.fit(data.values)

        return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #20
Source File: VARLiNGAM.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data):
        """ Run the VarLiNGAM algorithm on data.

        Args:
            data (pandas.DataFrame): time series data

        Returns:
            tuple :(networkx.Digraph, networkx.Digraph) Predictions given by
               the varLiNGAM algorithm: Instantaneous and Lagged causal Graphs
        """
        inst, lagged = self._run_varLiNGAM(data.values, verbose=self.verbose)
        return (nx.relabel_nodes(nx.DiGraph(inst),
                                 {idx: i for idx, i in enumerate(data.columns)}),
                nx.relabel_nodes(nx.DiGraph(lagged),
                                 {idx: i for idx, i in enumerate(data.columns)}),
                ) 
Example #21
Source File: GIES.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data):
        """Run the GIES algorithm.

        Args:
            data (pandas.DataFrame): DataFrame containing the data

        Returns:
            networkx.DiGraph: Solution given by the GIES algorithm.
        """
        # Building setup w/ arguments.
        self.arguments['{SCORE}'] = self.scores[self.score]
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()

        results = self._run_gies(data, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #22
Source File: GIES.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def orient_undirected_graph(self, data, graph):
        """Run GIES on an undirected graph.

        Args:
            data (pandas.DataFrame): DataFrame containing the data
            graph (networkx.Graph): Skeleton of the graph to orient

        Returns:
            networkx.DiGraph: Solution given by the GIES algorithm.

        """
        # Building setup w/ arguments.
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()
        self.arguments['{SCORE}'] = self.scores[self.score]

        fe = DataFrame(nx.adj_matrix(graph, weight=None).todense())
        fg = DataFrame(1 - fe.values)

        results = self._run_gies(data, fixedGaps=fg, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #23
Source File: GES.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def create_graph_from_data(self, data):
        """Run the GES algorithm.

        Args:
            data (pandas.DataFrame): DataFrame containing the data

        Returns:
            networkx.DiGraph: Solution given by the GES algorithm.

        """
        # Building setup w/ arguments.
        self.arguments['{SCORE}'] = self.scores[self.score]
        self.arguments['{VERBOSE}'] = str(self.verbose).upper()

        results = self._run_ges(data, verbose=self.verbose)

        return nx.relabel_nodes(nx.DiGraph(results),
                                {idx: i for idx, i in enumerate(data.columns)}) 
Example #24
Source File: drg.py    From pyMARS with MIT License 5 votes vote down vote up
def trim_drg(matrix, species_names, species_targets, threshold):
    """

    Parameters
    ----------
    matrix : np.ndarray
        Adjacency matrix representing graph
    species_names : list of str
        List of all species names
    species_targets : list of str
        List of target species names
    threshold : float
        DRG threshold for trimming graph
    
    Returns
    ------
    species_reached : list of str
        Names of species reached in graph search

    """
    name_mapping = {i: sp for i, sp in enumerate(species_names)}
    graph = networkx.DiGraph(np.where(matrix >= threshold, matrix, 0.0))
    networkx.relabel_nodes(graph, name_mapping, copy=False)
    species_reached = graph_search(graph, species_targets)

    return species_reached 
Example #25
Source File: utils.py    From cdlib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def nx_node_integer_mapping(graph):
    """Maps node labels from strings to integers.

    :param graph: networkx graph
    :return: if the node labels are string: networkx graph, dictionary <numeric_id, original_node_label>, false otherwise
    """

    convert = False
    for nid in graph.nodes():
        if isinstance(nid, str):
            convert = True
            break

    if convert:
        node_map = {}
        label_map = {}
        if isinstance(graph, nx.Graph):
            for nid, name in enumerate(graph.nodes()):
                node_map[nid] = name
                label_map[name] = nid

            nx.relabel_nodes(graph, label_map, copy=False)
            return graph, node_map
        else:
            raise ValueError("graph must be a networkx Graph object")

    return graph, None 
Example #26
Source File: test_sample.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_graph_mapped(self, graph):
        """Test if function returns correctly processed subgraphs given input samples of the list
        ``quantum_samples``. Note that graph nodes are numbered in this test as [0, 1, 4, 9,
        ...] (i.e., squares of the usual list) as a simple mapping to explore that the optimised
        subgraph returned is still a valid subgraph."""
        graph = nx.relabel_nodes(graph, lambda x: x ** 2)
        graph_nodes = list(graph.nodes)
        subgraphs_mapped = [
            sorted([graph_nodes[i] for i in subgraph]) for subgraph in self.subgraphs
        ]

        assert sample.to_subgraphs(self.quantum_samples, graph) == subgraphs_mapped 
Example #27
Source File: gui.py    From DROP-IDA-plugin with GNU General Public License v3.0 5 votes vote down vote up
def btn_show_angr_graph_clicked(self):
        # Assume angr is loaded
        def mapping(node):
            b = self.plugin.angr_proj.factory.block(node.addr)
            return str(b.capstone)

        try:
            graph = self.plugin.cfg.functions[self.current_function].graph
            graph2 = networkx.relabel_nodes(graph, mapping)
            viewer = sark.ui.NXGraph(graph2, title="angr graph", padding=0)
            viewer.Show()
        except:
            print("ERROR: {}".format(sys.exc_info())) 
Example #28
Source File: pfa.py    From pyMARS with MIT License 5 votes vote down vote up
def trim_pfa(matrix, species_names, species_targets, threshold):
    """

    Parameters
    ----------
    matrix : np.ndarray
        Adjacency matrix representing graph
    species_names : list of str
        List of all species names
    species_targets : list of str
        List of target species names
    threshold : float
        PFA threshold for trimming graph
    
    Returns
    ------
    species_reached : list of str
        Names of species reached in graph search

    """
    name_mapping = {i: sp for i, sp in enumerate(species_names)}
    graph = networkx.DiGraph(np.where(matrix >= threshold, matrix, 0.0))
    networkx.relabel_nodes(graph, name_mapping, copy=False)
    species_reached = graph_search(graph, species_targets)

    return species_reached 
Example #29
Source File: drgep.py    From pyMARS with MIT License 5 votes vote down vote up
def get_importance_coeffs(species_names, target_species, matrices):
    """Calculate importance coefficients for all species

    Parameters
    ----------
    species_names : list of str
        Species names
    target_species : list of str
        List of target species
    matrices : list of numpy.ndarray
        List of adjacency matrices

    Returns
    -------
    importance_coefficients : dict
        Maximum coefficients over all sampled states

    """
    importance_coefficients = {sp:0.0 for sp in species_names}
    name_mapping = {i: sp for i, sp in enumerate(species_names)}
    for matrix in matrices:
        graph = networkx.DiGraph(matrix)
        networkx.relabel_nodes(graph, name_mapping, copy=False)
        coefficients = graph_search_drgep(graph, target_species)
        
        importance_coefficients = {
            sp:max(coefficients.get(sp, 0.0), importance_coefficients[sp]) 
            for sp in importance_coefficients
        }
    
    return importance_coefficients 
Example #30
Source File: graph_util.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_lcc_undirected(G):
    G2 = max(nx.connected_component_subgraphs(G), key=len)
    tdl_nodes = G2.nodes()
    nodeListMap = dict(zip(tdl_nodes, range(len(tdl_nodes))))
    G2 = nx.relabel_nodes(G2, nodeListMap, copy=True)
    return G2, nodeListMap