iterate neighbors along with attributes - python

In networkx
gr.nodes(data=True)
returns the list of nodes along with the attributes present on each node. Is it possible to get all the neighbors along with attributes of a given node in the graph.
Neighbors function doesn't accept any optional boolean parameter.

Use the adjacency_iter if you want to iterate over them or adjacency_list if you want them as a list.
Edit
I should add that neither of those will give you the attributes of node. But you can get them easily with g.node[n].

Related

Extracting random nodes in a graph using an attributes

I have a networkX graph where every node has an attribute.
I need to extract nodes based on a numerical attribute made in the range [0,inf] to create edges.
I tried using random.choice(G.nodes(), p) with p=attribute/(sum of the attributes in the graph).
The problem is that everytime i extract a node to create the edge my attribute change (for example let's say the attribute+=1) so I need to update all the probabilities because also the sum increases by 1.
For example I could have a graph with G.nodes(data=True)={1:{att=10},2:{att=5}, 3:{att=2}}
So p=[10/17, 5/17, 2/17].
If I extract for example 1 at the first extraction my graph will be G.nodes(data=True)={1:{att=11},2:{att=5}, 3:{att=2}} and p=[11/18, 5/18, 2/18].
Now, because i have more than a thousand graph and for every one of them I need to do a 50000 for clause that create edges, it's not computationally feasible to update all the probability every time i create an edge.
Is there a way to just use the node's attribute or to not calculate my probability every time?
By using numpy array I have done this:
G=nx.Graph()
G.add_nodes_from([1,2,3])
G.nodes[1]["att"]=10
G.nodes[2]["att"]=5
G.nodes[3]["att"]=2
dict={}
for i in G.nodes():
dict[i]=G.nodes[i]["att"]
extracted=random.chance(G.nodes(),p=np.fromiter(dict.values(),dtype="float")/np.sum(np.fromiter(dict.values(),dtype="float")))
When extracted (for example node 1) G.nodes[1]["att"]+=1 and nothing else need to be updated

Find all nodes with defined attribute in networkx graph

I looking for a elegant way to find all nodes with a defined attribute. E.g. let's say I create a new network with two nodes
G.add_node('A', attr1='alpha')
G.add_node('B', attr1='beta')
Now, I would like to have a function that returns all nodes where the attribute "attr1" that matches "beta" something like
THX
Lazloo
Try
L = [node for node in G.nodes() if G.node[node]['attr1']=='beta']
to create a list (look at list comprehensions). You can also create other data types that contain all of these nodes.

Get a sub-graph from one node in NetworkX

Context
This is the first time I have to work with NetworkX so either I can't read correctly the documentation, or I simply do not use the right vocabulary.
Problem
I am working with a DiGraph, and I want to get a list of every nodes accessible starting from a specified node.
I thought of making a sub-graph containing the nodes I just described, and I would siply have to iterate over that specific sub-graph. Unfortunately, I didn't find a way to create automatically a sub-graph with the condition I mentioned.
It feels like an obvious feature. What am I missing ?
You are looking for the nx.descendants method:
descendants(G, source)
Return all nodes reachable from
(source) in G.
Parameters : G : NetworkX DiGraph
source : node in G
Returns : des : set()
The descendants of source in G

When using python networkx is it possible to add multiple labels to a single node (i.e. a main label and then a sub label)?

When using python networkx is is possible to add multiple labels to a single node (i.e. a main label and then a sub label in each node)?
If you mean 'attribute' for 'label', then you can do this in (at least) 2 ways
For example:
import networkx as nx
G = nx.Graph()
G.add_node('Bob', {'age':45, 'gender':'male'})
G.node['Bob']['age']
> 45
G.add_node('Sara', age=40, gender = 'female')
G.node['Sara']['age']
> 40
G.node['Sara']['gender']
> 'female'
Notice that in the assignment for 'Sara' I didn't need to make the attribute names into strings, but when I accessed them, I did.
If on the other hand you mean that you want to have two different names for the node when you reference it, that's a different matter. For example say you want to use G.neighbors(node_name) to access the neighbors of a given node, you won't be able to use 'Robert' and 'Bob' interchangeably for the node name (unless there's something I'm unaware of).
Nodes can be any hashable Python object. You could use a tuple of multiple labels if you want.
From the documentation: https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.Graph.add_node.html#networkx.Graph.add_node
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be careful that the hash doesn’t change on mutables.

Accessing networkx nodes and attributes

I have this GraphML file that I've read into Networkx.
So I access all the nodes by:
g.nodes()
It gives me a list of strings. Say one of them is "123".
I then try to access a node as:
g["123"]
and it gives me a dictionary.
I then try to access the nodes using the nodes function as follows:
for n in g.nodes( data = True ):
print n
It then gives me a 2-tuple with the string node name as first element and a dictionary as a second element.
The thing is, it is a different dictionary from the first one. And it's confusing the heck out of me, so any help here is appreciated.
Are they supposed to be different? If so, why? If not, then what am I doing wrong? :)
I can post the actual data if it would help.
Have you considered reading the various pages of documentation?
nlist : list
A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary).
and...
adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
"Node data dictionary" and "adjacendy dictionary" are not the same thing.

Categories

Resources