How to use the networkx.get_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 USEPA / WNTR / wntr / network / WaterNetworkModel.py View on Github external
def scale_node_coordinates(self, scale):
        """
        Scale node coordinates, using 1:scale.  Scale should be in meters.
        
        Parameters
        -----------
        scale : float
            Coordinate scale multiplier
        """
        pos = nx.get_node_attributes(self._graph, 'pos')
        
        for name, node in self._nodes.iteritems():
            self.set_node_coordinates(name, (pos[name][0]*scale, pos[name][1]*scale))
github HexHive / BOPC / source / path.py View on Github external
dbg_prnt(DBG_LVL_4, '%32s: %2d (%s)' % (func.name, depth, pretty_list(path)))


        # print path(s) to the user (DBG_LVL_3 and DBG_LVL_4 only)
        for final, path in zip(finals, paths):

            if path[0] != INFINITY:
                dbg_prnt(DBG_LVL_3, "\tShortest Path (%x -> %x) found (%d): %s" % 
                                    (root.addr, final.addr, path[0], pretty_list(path[1], ' -> ')))

            else:
                dbg_prnt(DBG_LVL_4, "\tNo Shortest Path (%x -> %x) found!" % 
                                    (root.addr, final.addr))

        # clean up clobbering nodes
        for node, _ in nx.get_node_attributes(self.__G, 'clobbering').items(): 
            del self.__G.node[ node ]['clobbering']                  


        return paths                                # return shortest paths (1 for each final node)
github kimhc6028 / pathnet-pytorch / visualize.py View on Github external
for fixed in fixed_pair:
            for f_1 in fixed[0]:
                for f_2 in fixed[1]:
                    if (not f_1 == None) and (not f_2 == None):
                        self.graph.add_edge(f_1, f_2, color = self.fixed_color, weight = self.fixed_weight)

        nodes = self.graph.nodes(data = True)
        node_color = 'g'
        node_size = [node[1]['size'] for node in nodes]
        node_shape = 's'

        edges = self.graph.edges()
        edge_color = [self.graph[u][v]['color'] for u,v in edges]
        weights = [self.graph[u][v]['weight'] for u,v in edges]
        nx.draw_networkx_nodes(self.graph, nodes = nodes, pos=nx.get_node_attributes(self.graph,'Position'), node_color = node_color, node_size = node_size, node_shape = node_shape)
        nx.draw_networkx_edges(self.graph, edges = edges, pos=nx.get_node_attributes(self.graph,'Position'), edge_color = edge_color, width = weights)
github sorgerlab / indra / indra / explanation / model_checker / pysb.py View on Github external
elif isinstance(stmt, Influence):
                obs_list = add_obs_for_agent(stmt.obj.concept)
                self.stmt_to_obs[stmt] = obs_list
        # Add observables for each agent
        for ag in self.agent_obs:
            obs_list = add_obs_for_agent(ag)
            self.agent_to_obs[ag] = obs_list

        logger.info("Generating influence map")
        self._im = self.generate_im(self.model)
        # self._im.is_multigraph = lambda: False
        # Now, for every rule in the model, check if there are any observables
        # downstream; alternatively, for every observable in the model, get a
        # list of rules.
        # We'll need the dictionary to check if nodes are observables
        node_attributes = nx.get_node_attributes(self._im, 'node_type')
        for rule in self.model.rules:
            obs_list = []
            # Get successors of the rule node
            for neighb in self._im.neighbors(rule.name):
                # Check if the node is an observable
                if node_attributes[neighb] != 'variable':
                    continue
                # Get the edge and check the polarity
                edge_sign = _get_edge_sign(self._im, (rule.name, neighb))
                obs_list.append((neighb, edge_sign))
            self.rule_obs_dict[rule.name] = obs_list
        return self._im
github SkBlaz / Py3plex / py3plex / visualization / multilayer.py View on Github external
all_positions = []
        for node in network.nodes(data=True):
            if 'pos' not in node[1]:
                no_position.append(node[0])
                cntr+=1
            else:
                all_positions.append(node[1]['pos'])
                cntr_all+=1

        if len(no_position) > 0:
            network = network.copy()
            network.remove_nodes_from(no_position)
            
       # print("No position for {}. Found position for {}.".format(cntr,cntr_all))
        
        positions = nx.get_node_attributes(network, 'pos')
        cntr = 0

        for position in positions:
            if np.abs(positions[position][0]) > 0.5 or np.abs(positions[position][1]) > 0.5:
                positions[position] = positions[position]/np.linalg.norm(positions[position])
            try:
                positions[position][0] = positions[position][0] + 0.5 + start_location_network
                positions[position][1] = positions[position][1] + 0.5 + start_location_network
            except Exception as es:
                print(es,"err")

        ## this is the default delay for matplotlib canvas
        if labels != False:
            try:
                shape_subplot.text(start_location_network+label_position,start_location_network-label_position, labels[color])
            except Exception as es:
github idekerlab / heat-diffusion / ndex / networkn.py View on Github external
def get_node_attribute_value_by_id(self, node_id, query_key='name', error=False):
        """Get the value of a particular node attribute based on the id.

        :param node_id: A node id.
        :type node_id: int
        :param query_key: The name of the attribute whose value we desire.
        :type query_key: str
        :return: The attribute value.
        :rtype: any

        """
        if node_id not in self.node:
            raise ValueError("Your ID is not in the network")
        node_attributes = nx.get_node_attributes(self, query_key)
        if error and len(node_attributes) == 0:
            raise ValueError("That node attribute name does not exist ANYWHERE in the network.")
        return self.node[node_id][query_key] if query_key in self.node[node_id] else None
github springer-math / Mathematics-of-Epidemics-on-Networks / EoN / simulation.py View on Github external
spontaneous_transitions = list(spontaneous_transition_graph.edges())
    induced_transitions = list(nbr_induced_transition_graph.edges())
    potential_transitions = {}
    rate = {}# intrensic rate of a transition
    #weight_sum = defaultdict(lambda: 0)
    #weights = defaultdict(lambda: None)
    #max_weight = defaultdict(lambda: 0)
    get_weight = defaultdict(lambda: defaultdict(lambda:None))


    for transition in spontaneous_transitions:
        rate[transition] = spontaneous_transition_graph.edges[transition[0],transition[1]]['rate']
        if 'weight_label' in spontaneous_transition_graph.edges[transition[0],transition[1]]:
            wl = spontaneous_transition_graph.edges[transition[0],transition[1]]['weight_label']
            get_weight[transition] = nx.get_node_attributes(G, wl)
            potential_transitions[transition] = _ListDict_(weighted=True)#max_weight[transition] = max(get_weight[transition].values())
        else:
            potential_transitions[transition] = _ListDict_()#max_weight[transition]=1
            
    for transition in induced_transitions:
        if transition[0][0] != transition[1][0]:
            raise EoN.EoNError("transition {} -> {} not allowed: first node must keep same status".format(transition[0],transition[1]))
        rate[transition] = nbr_induced_transition_graph.edges[transition[0],transition[1]]['rate']

        if 'weight_label' in nbr_induced_transition_graph.edges[transition[0],transition[1]]:
            wl = nbr_induced_transition_graph.edges[transition[0],transition[1]]['weight_label']
            get_weight[transition] = nx.get_edge_attributes(G, wl)
            potential_transitions[transition] = _ListDict_(weighted=True)
        else:
            potential_transitions[transition] = _ListDict_()
github CellProfiler / CellProfiler-Analyst / cpa / timelapsetool.py View on Github external
# Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v:
        
        sorted_nodes = sorted(self.directed_graph[self.selected_dataset][self.selected_dataset_track])
        temp_full_graph_dict = dict.fromkeys(self.directed_graph[self.selected_dataset][self.selected_dataset_track].nodes(),0.0)
        for key,subgraph in self.connected_nodes[self.selected_dataset][self.selected_dataset_track].items():
            attr = dict.fromkeys(subgraph.nodes(), 0.0)
            betweenness_centrality = nx.betweenness_centrality(subgraph, normalized=True)
            for (node,value) in betweenness_centrality.items():
                temp_full_graph_dict[node] = value
                attr[node] = value
            # Set identity attributes
            nx.set_node_attributes(subgraph, METRIC_BC, attr)
            # Set visibility attribute 
            # TODO: Come up with a heuristic to determine which branch to prune based on this value 
            attr = dict.fromkeys(subgraph.nodes(), True)
            branch_nodes = [_[0] for _ in nx.get_node_attributes(subgraph,BRANCH_NODES).items() if _[1]]
            for bn in branch_nodes:
                successors = subgraph.successors(bn)
                bc_vals = [betweenness_centrality[_] for _ in successors]
                cutoff = 1.0/len(bc_vals)/2.0 # Set to ????
                idx = np.argwhere(np.array(bc_vals)/sum(bc_vals) < cutoff)
                # Find all downstream nodes for branches that failed the cutoff
                for i in idx:
                    nodes = nx.single_source_shortest_path(subgraph,successors[i]).keys()
                    for _ in nodes:
                        attr[_] = False
            nx.set_node_attributes(subgraph, METRIC_BC_VISIBLE, attr)
        
        return np.array([temp_full_graph_dict[node] for node in sorted_nodes ]).astype(float)
github IBM / AMLSim / scripts / validation / network_analytics.py View on Github external
def __init__(self, _conf_json):
        super(ResultGraphLoader, self).__init__(_conf_json)

        # Create a transaction graph from output files
        output_dir = os.path.join(self.output_conf["directory"], self.sim_name)
        acct_file = self.output_conf["accounts"]
        tx_file = self.output_conf["transactions"]
        alert_acct_file = self.output_conf["alert_members"]
        alert_tx_file = self.output_conf["alert_transactions"]

        acct_path = os.path.join(output_dir, acct_file)
        tx_path = os.path.join(output_dir, tx_file)
        self.g = load_result_csv(acct_path, tx_path, self.schema)
        self.num_normal_accts = len([n for n, flag in nx.get_node_attributes(self.g, ACCT_SAR).items() if not flag])
        self.num_sar_accts = len([n for n, flag in nx.get_node_attributes(self.g, ACCT_SAR).items() if flag])