Skip to content

Instantly share code, notes, and snippets.

@aanastasiou
Created July 29, 2015 10:15
Show Gist options
  • Save aanastasiou/5474ba76db711971b6e8 to your computer and use it in GitHub Desktop.
Save aanastasiou/5474ba76db711971b6e8 to your computer and use it in GitHub Desktop.
Use pynq to query graph data from networkx.
#@author:Athanasios Anastasiou
#@date: Wed Jul 29 10:44:08 2015
import networkx #Graph module
import pynq #LINQ for Python module
from matplotlib import pyplot as plt #Fancy drawing stuff
import random #The standard oamdrn module
from collections import namedtuple #A named tuple to make pynq think it's going over a collection of classes.
#SETUP THE SCHEMA
#Notice the notion of references back to the original schema inspired by the property graph model (https://github.com/tinkerpop/blueprints/wiki/Property-Graph-Model)
# G, V, E have their usual meanings as in G(V,E)
#A named tuple stores the node schema...
V = namedtuple("nodeData",['nodeID','alpha'])
#...and another one stores the relationship schema
E = namedtuple("edgeData", ['edgeID', 'beta'])
#BUILD THE GRAPH
#Get a simple unordered graph of 100 nodes where each is connected to another by at most 8 edges.
G = networkx.random_graphs.random_regular_graph(8,100)
#Fix the layout which will later be used for drawing
pos = networkx.layout.spring_layout(G)
#Populate the graph with instances
for v in G.nodes():
G.node[v]['properties']=V(nodeID = v, alpha=random.randint(1,10))
for e in G.edges():
G.edge[e[0]][e[1]]['properties'] = E(edgeID = e, beta = random.random())
#Prior to querying the graph, grab its node and edge data
nodeData = map(lambda x:x[1]['properties'], G.nodes(data = True))
edgeData = map(lambda x:x[2]['properties'], G.edges(data = True))
#Now query stuff using pynq
#This works as expected...
sG = pynq.From(nodeData).where("item.alpha>4 and item.alpha<10").order_by("alpha").select_many()
#...the following breaks because of the -0.1
sE = pynq.From(edgeData).where("item.beta<0.05 and item.beta>-0.1").select_many()
#And now extract the subgraph
nodesInSubG = map(lambda x:x.nodeID, F)
subG = G.subgraph(nodesInSubG)
#Or doing it through the edges
nodesInSubE = set(reduce(lambda x,y:x+y.edgeID,sE,()))
subE = G.subgraph(nodesInSubE)
#Draw the selected nodes...
networkx.draw(subG, pos = pos, node_color = (0,1,0))
#...versus the whole graph...
networkx.draw(G, pos = pos, nodelist = list(set(G.nodes()).symmetric_difference(nodesInSubG)), node_color=(1,0,0))
#...and on a separate figure
plt.figure()
#...draw the selected edges...
networkx.draw(subE, pos = pos, edge_color = "g")
#...versus the whole graph
networkx.draw(G, pos = pos, edgelist = list(set(G.edges()).symmetric_difference(subE.edges())), edge_color="r")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment