How to use the networkx.relabel_nodes function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Niemeyer-Research-Group / pyMARS / pymars / drg.py View on Github external
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
github maxplanck-ie / HiCAssembler / hicassembler / Scaffolds.py View on Github external
# add further edges if a high value count exist
            # that is higher than the expected power law decay
            elif ma.data[index] > neighbors[row][0]*POWER_LAW_DECAY and \
                    ma.data[index] > neighbors[col][0]*POWER_LAW_DECAY:
                if neighbors[row][1] < min_neigh:
                    neighbors[row] = (ma.data[index], neighbors[row][1]+1)

                if neighbors[col][1] < min_neigh:
                    neighbors[col] = (ma.data[index], neighbors[col][1]+1)
                net[row, col] = ma.data[index]

        G = nx.from_scipy_sparse_matrix(net, create_using=nx.Graph())
        if trans:
            # remap ids
            mapping = dict([(x,paths[x][0]) for x in range(len(paths))])
            G = nx.relabel_nodes(G, mapping)

        # remove all edges not connected to flanks
        # the idea is that if a path already exist
        # no edges should point to it unless
        # is they are the flanks
        """
        if self.iteration==2:
            import pdb;pdb.set_trace()
        if self.merged_paths:
            flanks = set(Scaffolds.flatten_list(
                    [[x[0],x[-1]] for x in self.merged_paths]))
            for edge in G.edges():
                if len(flanks.intersection(edge)) == 0:
                    G.remove_edge(*edge)
        """
        return G
github entropicalabs / entropica_qaoa / entropica_qaoa / utilities.py View on Github external
biases:
        Whether or not the graph nodes should be assigned a weight.
        If true, the weight is set to a random number drawn from the uniform
        distribution in the interval 0 to 1.

    Returns
    -------
    nx.Graph:
        A graph with the properties as specified.

    """
    np.random.seed(seed=seed)

    # create a random regular graph on the nodes
    G = nx.random_regular_graph(degree, len(nodes), seed)
    nx.relabel_nodes(G, {i: n for i, n in enumerate(nodes)})

    for edge in G.edges():
        if not weighted:
            G[edge[0]][edge[1]]['weight'] = 1
        else:
            G[edge[0]][edge[1]]['weight'] = np.random.rand()

    if biases:
        for node in G.nodes():
            G.node[node]['weight'] = np.random.rand()

    return G
github networkx / networkx / networkx / readwrite / gexf.py View on Github external
mapping = [(u, G.nodes[u]["label"]) for u in G]
    except KeyError:
        raise nx.NetworkXError(
            "Failed to relabel nodes: "
            "missing node labels found. "
            "Use relabel=False."
        )
    x, y = zip(*mapping)
    if len(set(y)) != len(G):
        raise nx.NetworkXError(
            "Failed to relabel nodes: "
            "duplicate node labels found. "
            "Use relabel=False."
        )
    mapping = dict(mapping)
    H = nx.relabel_nodes(G, mapping)
    # relabel attributes
    for n in G:
        m = mapping[n]
        H.nodes[m]["id"] = n
        H.nodes[m].pop("label")
        if "pid" in H.nodes[m]:
            H.nodes[m]["pid"] = mapping[G.nodes[n]["pid"]]
        if "parents" in H.nodes[m]:
            H.nodes[m]["parents"] = [mapping[p] for p in G.nodes[n]["parents"]]
    return H
github hklarner / PyBoolNet / PyBoolNet / Commitment.py View on Github external
for x in AttrJson:
			diagram.graph[x] = PyBoolNet.Utility.Misc.copy_json_data(AttrJson[x])


		nodes_sum = 0
		for x in diagram.nodes():
			projection = diagram.node[x]["attractors"]
			diagram.node[x]["attractors"] = lift_attractors(Subspaces, projection)
			nodes_sum+= diagram.node[x]["size"]

		if not nodes_sum==size_total:
			print("WARNING: commitment diagram does not partition the state space, this may be due to rounding of large numbers.")

		sorted_ids = sorted(diagram, key=lambda x: diagram.node[x]["formula"])
		mapping = {x:str(sorted_ids.index(x)) for x in diagram}
		networkx.relabel_nodes(diagram,mapping,copy=False)

	if not Silent:
		print(" total executions of NuSMV: %i"%counter_mc)


	if FnameImage:
		diagram2image(diagram, FnameImage=FnameImage, StyleInputs=True, StyleSplines="curved", StyleEdges=EdgeData, StyleRanks=True, FirstIndex=1)

	if FnameJson:
		save_diagram(diagram, FnameJson)

	return diagram
github biolab / orange3-network / orangecontrib / network / readwrite.py View on Github external
# Construct x-y-label table (added in OWNxFile.readDataFile())
    table = None
    vars = [ContinuousVariable('x'), ContinuousVariable('y')] if rows else []
    meta_vars = [StringVariable('label ' + str(i)) for i in range(len(metas[0]) if metas else 0)]
    if rows or metas:
        domain = Domain(vars, metas=meta_vars)
        table = Table.from_numpy(domain,
                                 np.array(rows, dtype=float).reshape(len(metas),
                                                                     len(rows[0]) if rows else 0),
                                 metas=np.array(metas, dtype=str))
    if table is not None and auto_table:
        G.set_items(table)
    # Relabel nodes to integers, sorted by appearance
    for node in G.node:
        G.node[node]['label'] = node
    nx.relabel_nodes(G, remapping, copy=False)
    if table is not None and len(table) != G.number_of_nodes():
        raise PajekBug("There is a bug in your version of NetworkX reading Pajek files. "
                       "Please update your NetworkX installation.")
    return G
github cogeorg / BlackRhino / networkx / algorithms / operators / binary.py View on Github external
def add_prefix(graph, prefix):
        if prefix is None:
            return graph

        def label(x):
            if is_string_like(x):
                name = prefix + x
            else:
                name = prefix + repr(x)
            return name
        return nx.relabel_nodes(graph, label)
    G = add_prefix(G, rename[0])
github sk2 / autonetkit / autonetkit / load / graphml.py View on Github external
if key not in graph[src][dst]:
                    graph[src][dst][key] = val

# apply defaults
# relabel nodes
# other handling... split this into seperate module!
# relabel based on label: assume unique by now!
    # if graph.graph.get("Network") == "European NRENs":
        # TODO: test if non-unique labels, if so then warn and proceed with this logic
        # we need to map node ids to contain network to ensure unique labels
        # mapping = dict( (n, "%s__%s" % (d['label'], d['asn'])) for n, d in graph.nodes(data=True))


    mapping = dict((n, d['label']) for (n, d) in graph.nodes(data=True))  # TODO: use dict comprehension
    if not all(key == val for (key, val) in mapping.items()):
        nx.relabel_nodes(graph, mapping, copy=False)  # Networkx wipes data if remap with same labels

    graph.graph['file_type'] = 'graphml'

    selfloop_count = graph.number_of_selfloops()
    if selfloop_count > 0:
        log.warning("Self loops present: do multiple nodes have the same label?")
        selfloops = ", ".join(str(e) for e in graph.selfloop_edges())
        log.warning("Removing selfloops: %s" % selfloops)
        graph.remove_edges_from(edge for edge in graph.selfloop_edges())


    return graph
github LTS5 / connectomeviewer / cviewer / plugins / cff / cfile.py View on Github external
if like_network is None:
            create_graph_info = True
        else:
            # matrix has N rows and columns which is equal to the number of nodes
            assert matrix.shape[0] == matrix.shape[1] == len(like_network.graph.nodes())

        # add graph 
        import networkx as nx
        test_G = nx.from_numpy_matrix(matrix)
        
        # relabeling function
        addn = lambda nmod:'n'+str(nmod+1)
        
        # relabel graph
        test_G_corrected = nx.relabel_nodes(test_G, addn)
        
        nodes_ids = test_G_corrected.nodes()
        
        # create node positions with springlayout if create_graph_info
        if create_graph_info:
            npos = nx.spring_layout(test_G_corrected, dim = 3, weighted = True, scale = 100)
        
        # add node properties
        if not create_graph_info:
            for k, v in like_network.graph.nodes(data=True):
                if not k in nodes_ids:
                    logger.error('Node id %s is not like_network.graph' % str(k))
                # add node properties
                test_G_corrected.node[k] = v
        else:
            for k in test_G_corrected.nodes():
github KyleBenson / ride / topology_manager / network_topology.py View on Github external
log.basicConfig(format='%(levelname)s:%(message)s', level=log.DEBUG)

    if from_file:
        net = NetworkTopology()
        source = "s0"
        net.load_from_file('campus_topo.json')
        # dest = ["h1-b4", "h2-b7", "h3-b0", "h2-b0", "h4-b2", "h5-b21", "h6-b45", "h7-b71"]
        dest = ["h1-b4", "h2-b5", "h3-b0"]
    else:
        g = nx.complete_graph(4)
        g.add_edge(0, "s")
        g.add_edge(3, "d1")
        g.add_edge(2, "d1")
        g.add_edge(1, "d2")
        # Need to relabel to strings since we assume nodes are strings
        nx.relabel_nodes(g, {i: str(i) for i in g.nodes()}, copy=False)
        net = NetworkTopology(g)

        dest = ["d1", "d2"]
        source = "s"

    # First, test out our added path functions
    p1 = net.get_path(source, dest[0])
    p2 = net.get_path(dest[0], dest[1])
    pm = net.merge_paths(p1, p2)

    # Verify it by ensuring each edge is in the topo as well as one of the first paths
    pm_edges = net.get_edges_for_path(pm)
    p1_edges = net.get_edges_for_path(p1)
    p2_edges = net.get_edges_for_path(p2)
    assert len(pm) > 1, "merged path is too small for meaningful tests!"
    assert len(pm_edges) == len(pm) - 1  # right # edges?