Skip to content

Instantly share code, notes, and snippets.

@hagberg
Created November 25, 2014 14:26
Show Gist options
  • Save hagberg/456523d36af61109c9bd to your computer and use it in GitHub Desktop.
Save hagberg/456523d36af61109c9bd to your computer and use it in GitHub Desktop.
def from_biadjacency_matrix(A,create_using=None):
import numpy as np
kind_to_python_type={'f':float,
'i':int,
'u':int,
'b':bool,
'c':complex,
'S':str,
'V':'void'}
try: # Python 3.x
blurb = chr(1245) # just to trigger the exception
kind_to_python_type['U']=str
except ValueError: # Python 2.6+
kind_to_python_type['U']=unicode
G=_prep_create_using(create_using)
n,m=A.shape
dt=A.dtype
try:
python_type=kind_to_python_type[dt.kind]
except:
raise TypeError("Unknown numpy data type: %s"%dt)
# make sure we get isolated nodes
G.add_nodes_from(range(n),part=0)
G.add_nodes_from(range(n,n+m),part=1)
# get a list of edges
x,y=np.asarray(A).nonzero()
# handle numpy constructed data type
if python_type is 'void':
fields=sorted([(offset,dtype,name) for name,(dtype,offset) in
A.dtype.fields.items()])
for (u,v) in zip(x,y):
attr={}
for (offset,dtype,name),val in zip(fields,A[u,v]):
attr[name]=kind_to_python_type[dtype.kind](val)
G.add_edge(u,n+v,attr)
else: # basic data type
G.add_edges_from( ((u,n+v,{'weight':python_type(A[u,v])})
for (u,v) in zip(x,y)) )
return G
@JBPressac
Copy link

Hello,
Thank you again for this funtion. However, should'nt:

G.add_nodes_from(range(n),part=0)
G.add_nodes_from(range(n,n+m),part=1) 

rather be:

G.add_nodes_from(range(n),bipartite=0)
G.add_nodes_from(range(n,n+m),bipartite=1)

Thanks,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment