Building (and working with) bipartite graphs

Hi,
I'm trying to build a bipartite graph from a MxN array. So far I've been able to do this:

# adjacency is the original np.array

S = []
E = []
W = []
for x in range(adjacency.shape[0]):
    for y in np.where(adjacency[x] > 0)[0]:
        S.append(x)
        E.append(y + adjacency.shape[0]) # so that node index starts with an offset)
        W.append(adjacency[x, y])

g = gt.Graph(directed=True)

g.add_edge_list(np.hstack([np.array(S)[:, None], np.array(E)[:, None]]))

ew = g.new_edge_property("double")
ew.a = W
g.ep['weight'] = ew

recs = [g.ep.weight]
rec_types = ['real-exponential']

state = gt.NestedBlockState(g, state_args=dict(recs=recs,
                                    rec_types=rec_types))

[…]

I'm pretty sure this is not the most efficient way to go, but gt.is_bipartite(g) returns True. Can anybody suggest a more straightforward approach? Also, is it necessary to specify a VertexPropertyMap with node type (i.e. M or N)?
Anyhow, after I had the graph and the final model, I tried to draw:

gt.draw_hierarchy(state, layout='bipartite')

but I get this error

IndexError
                                Traceback (most recent call last)

<ipython-input-67-d7655416181e> in <module>
----> 1 gt.draw_hierarchy(state, layout='bipartite')

~/anaconda3/envs/schist/lib/python3.8/site-packages/graph_tool/draw/cairo_draw.py in draw_hierarchy(state, pos, layout, beta, node_weight, vprops, eprops, hvprops, heprops, subsample_edges, rel_order, deg_size, vsize_scale, hsize_scale, hshortcuts, hide, bip_aspect, empty_branches, **kwargs)
   1773
                                   rel_order_leaf=True)

   1774 elif layout == "bipartite":
-> 1775
         tpos = get_bip_hierachy_pos(state, aspect=bip_aspect,

   1776
                                     node_weight=node_weight)

   1777 tpos = t.own_property(tpos)

~/anaconda3/envs/schist/lib/python3.8/site-packages/graph_tool/draw/cairo_draw.py in get_bip_hierachy_pos(state, aspect, node_weight)
   2145 t.add_edge(root, p2)
   2146 for p in ps:
-> 2147 if bc.a[tb[p]] == 0:
   2148 t.add_edge(p2, p)
   2149 else:

IndexError
: index 1 is out of bounds for axis 0 with size 1

Any help is appreciated

d

not the most efficient way to go, but gt.is_bipartite(g) returns True.
Can anybody suggest a more straightforward approach? Also, is it
necessary to specify a VertexPropertyMap with node type (i.e. M or N)?
You're probably better off with doing something like:

   idx = adjacency.nonzero()
   edges = array([idx[0], idx[1], adjacency[idx]]).T
   edges[:,1] += edges[:,0].max() + 1 # offset bipartition
   g.add_edge_list(edges, eprops=[weight])

Anyhow, after I had the graph and the final model, I tried to draw:

gt.draw_hierarchy(state, layout='bipartite')

but I get this error

In order for us to investigate further you need to provide us with a
minimal working example, not only the error message.

Best,
Tiago

Hi Tiago,
thanks for the answer