How to use the networkx.set_node_attributes 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 EI-CoreBioinformatics / mikado / Mikado / loci / abstractlocus.py View on Github external
def remove_path_from_graph(transcript: Transcript, graph: networkx.DiGraph):

        weights = networkx.get_node_attributes(graph, "weight")
        segments = sorted(list(transcript.exons) + list(transcript.introns), reverse=(transcript.strand == "-"))
        for segment in segments:
            if segment in weights:
                weights[segment] -= 1
            else:
                weights[segment] = 0

        nodes_to_remove = [interval for interval, weight in weights if weight == 0]
        graph.remove_nodes_from(nodes_to_remove)
        for node in nodes_to_remove:
            assert node not in graph.nodes()

        networkx.set_node_attributes(graph,
                                     name="weight",
                                     values=dict((k, v) for k, v in weights.items() if v > 0))
        return
github materialsproject / pymatgen / pymatgen / analysis / graphs.py View on Github external
MoleculeGraph.

        :return:
        """

        species = {}
        coords = {}
        properties = {}
        for node in self.graph.nodes():
            species[node] = self.molecule[node].specie.symbol
            coords[node] = self.molecule[node].coords
            properties[node] = self.molecule[node].properties

        nx.set_node_attributes(self.graph, species, "specie")
        nx.set_node_attributes(self.graph, coords, "coords")
        nx.set_node_attributes(self.graph, properties, "properties")
github JohnCoogan / twitter-graph-visualization / analysis.py View on Github external
def calculate_indegree(graph):
    # will only work on DiGraph (directed graph)
    print "Calculating indegree..."
    g = graph
    indeg = g.in_degree()
    nx.set_node_attributes(g, 'indegree', indeg)
    return g, indeg
github CellProfiler / CellProfiler-Analyst / cpa / timelapsetool.py View on Github external
ordering="default")
            mapping = dict(zip(G.nodes(),self.directed_graph[self.selected_dataset][self.selected_dataset_track].nodes()))
            glayout.layer_layout(G, level_attribute = "t")
            nx.relabel_nodes(G, mapping,copy=False) # Map back to original graph labels
            node_positions = dict(zip(G.nodes(),[[G.node[key]["t"],G.node[key]["y"]] for key in G.nodes()]))
            self.end_frame = end_frame = max(np.array(node_positions.values())[:,0])
            self.start_frame = start_frame = min(np.array(node_positions.values())[:,0])
            
            # Adjust the y-spacing between trajectories so it the plot is roughly square, to avoid nasty Mayavi axis scaling issues later
            # See: http://stackoverflow.com/questions/13015097/how-do-i-scale-the-x-and-y-axes-in-mayavi2
            xy = np.array([node_positions[key] for key in G.nodes()])
            scaling_y = 1.0/float(max(xy[:,1]) - min(xy[:,1]))*float(max(xy[:,0]) - min(xy[:,0]))
            for key in G.nodes(): node_positions[key][1] *= scaling_y
            
            self.lineage_node_positions = node_positions  
            nx.set_node_attributes(self.directed_graph[self.selected_dataset][self.selected_dataset_track],L_TCOORD,dict(zip(node_positions.keys(), [item[0] for item in node_positions.values()])))
            nx.set_node_attributes(self.directed_graph[self.selected_dataset][self.selected_dataset_track],L_YCOORD,dict(zip(node_positions.keys(), [item[1] for item in node_positions.values()])))         
            
            t2 = time.clock()
            logging.info("Computed lineage layout (%.2f sec)"%(t2-t1))
            
            # Each track gets its own indexed subgraph. Later operations to the graphs are referenced to this key.
            # According to http://stackoverflow.com/questions/18643789/how-to-find-subgraphs-in-a-directed-graph-without-converting-to-undirected-graph,
            #  weakly_connected_component_subgraphs maintains directionality
            connected_nodes = tuple(nx.weakly_connected_component_subgraphs(self.directed_graph[self.selected_dataset][self.selected_dataset_track]))
            self.connected_nodes[self.selected_dataset][self.selected_dataset_track] = dict(zip(range(1,len(connected_nodes)+1),connected_nodes))
            
            # Set graph attributes
            for key,subgraph in self.connected_nodes[self.selected_dataset][self.selected_dataset_track].items():
                # Set connect component ID in ful graph                
                nodes = subgraph.nodes()
                nx.set_node_attributes(self.directed_graph[self.selected_dataset][self.selected_dataset_track], SUBGRAPH_ID, dict(zip(nodes,[key]*len(nodes))))
github Patent2net / P2N / Patent2Net / P2N-PreNetworkssFam.py View on Github external
AtribDyn[noeud] = dict()
        AtribDyn[noeud]['id']= AtribDynLab.keys().index(noeud)
        AtribDyn[noeud]['start']= AtribDynLab[noeud]['label']['start']
        AtribDyn[noeud]['end']= AtribDynLab[noeud]['label']['end']
        AtribDyn[noeud]['label']= AtribDynLab[noeud]['label']['label']
 
#        if noeud in Patents:
#            AtribDyn[noeud]['pid']= AtribDynLab[noeud]['pid']
   #     Atrib[noeud] = AtribDynLab[noeud]['label']['label']
    nx.set_node_attributes(G1, 'id' , AtribDyn)

#    Atrib = OrderedDict()
#    for noeud in AtribDynLab.keys(): # ?????????
##        AtribDyn[noeud] = AtribDynLab[noeud]['weight']
#        Atrib [noeud] = AtribLab[noeud] ['pid']
    nx.set_node_attributes(G1,  'pid', AtribLab)
    for noeud in AtribDynLab.keys():
        AtribDyn[noeud] = AtribDynLab[noeud]['weight']
#        Atrib[noeud] = dict()
#        if noeud in Patents:
#            Atrib[noeud]['pid']= AtribDynLab[noeud]['pid']
#        else:
#            Atrib[noeud]['pid']= ""
#    nx.set_node_attributes(G1,  'pid', Atrib)
    nx.set_node_attributes(G1,  'weight', AtribDyn)

    nx.write_gpickle(G1, temporPath+network)
github braindynamicslab / dyneusr / dyneusr / visuals / annotation.py View on Github external
node_size=len(member_ids), 
                member_tooltips=members_html
            )
        else:
            node_tooltip += """<div>{}</div>""".format(members_html)
    
        # annote node
        annotation_map[n] = dict(
            tooltip=node_tooltip, 
            image=members_html,
            )

    # nx
    if verbose:
        print("Annotating Graph...")
    nx.set_node_attributes(G, annotation_map)
    return G, annotation_map
github Patent2net / Patent2Net--Old-stuff / Development / networkx_functs.py View on Github external
def add_partitions_to_digraph(graph, partitiondict):
    ''' Add the partition numbers to a graph - in this case, using this to update the digraph, with partitions calc'd off the undirected graph. Yes, it's a bad hack.
    '''
    g = graph
    nx.set_node_attributes(g, 'partition', partitiondict)
    nx.info(g)
    return
github prismmodelchecker / prism-games / prism-examples / smg / car / networkx / generators / bipartite.py View on Github external
def _add_nodes_with_bipartite_label(G, lena, lenb):
    G.add_nodes_from(range(0,lena+lenb))
    b=dict(zip(range(0,lena),[0]*lena))
    b.update(dict(zip(range(lena,lena+lenb),[1]*lenb)))
    nx.set_node_attributes(G,'bipartite',b)
    return G
github SkBlaz / Py3plex / examples / example3.py View on Github external
#### This is an example for the py3plex multiplex network visualization library
#### CUSTOM MULTIEDGE

import matplotlib.pyplot as plt
import networkx as nx
## REPRESENTATIVE py3plex usage example

from py3plex.multilayer import *

## read file from a simple edgelist
input_graph = nx.read_edgelist("testgraph/test.txt")

## generate arbitrary layout (can be done for individual networks also)
tmp_pos=nx.spring_layout(input_graph)
nx.set_node_attributes(input_graph,'pos',tmp_pos)

## generate some arbitrary networks from the parent network
subgraph1 = input_graph.subgraph(['n2','n4','n5','n6'])
subgraph2 = input_graph.subgraph(['n1','n3','n9'])
networks = [subgraph1,subgraph2]

## call first the multilayer method
draw_multilayer_default(networks,background_shape="circle",display=False,labels=['first network','second network'],networks_color="rainbow")

## assign some multiplex edges and draw them
multiplex_edges1 = [('n1','n4')]
draw_multiplex_default(networks,multiplex_edges1,alphachannel=0.2,linepoints="-.",linecolor="black",curve_height=2) ## curve height denotes how hight the maximal point in curve goes

multiplex_edges2 = [('n9','n5')]
draw_multiplex_default(networks,multiplex_edges2,alphachannel=0.5,linepoints="-",linecolor="orange")
github martinfleis / momepy / momepy / graph.py View on Github external
name : str (default 'degree')
        calculated attribute name

    Returns
    -------
    Graph
        networkx.Graph

    Examples
    --------
    >>> network_graph = mm.node_degree(network_graph)
    """
    netx = graph.copy()

    degree = dict(nx.degree(netx))
    nx.set_node_attributes(netx, degree, name)

    return netx