IO & interoperability¶
Going in and out of AnnNet. Three native formats and two backend
bridges.
import tempfile
from pathlib import Path
from annnet import AnnNet
G = AnnNet(directed=True)
G.add_vertices(['A', 'B', 'C'])
G.add_edges('A', 'B', edge_id='e1', weight=1.0)
G.add_edges('B', 'C', edge_id='e2', weight=2.0)
G.attrs.set_vertex_attrs('A', label='alpha')
G.attrs.set_edge_attrs('e1', confidence=0.9)
tmp = Path(tempfile.mkdtemp(prefix='annnet_tuto_io_'))
print('temp dir:', tmp)
temp dir: /tmp/annnet_tuto_io_3r0vbcwm
Native .annnet format¶
Lossless, manifest-aware, fastest for AnnNet round-trip.
from annnet import read, write
write(G, tmp / 'g.annnet')
G_native = read(tmp / 'g.annnet')
print('round-trip nv/ne:', G_native.shape)
round-trip nv/ne: (3, 2)
Parquet¶
Column-stored, language-agnostic. Good when you want to inspect the graph tables outside Python.
from annnet import to_parquet, from_parquet
to_parquet(G, tmp / 'g_parquet')
G_parquet = from_parquet(tmp / 'g_parquet')
print('round-trip nv/ne:', G_parquet.shape)
round-trip nv/ne: (3, 2)
JSON¶
Human-readable. Useful for tiny graphs and debugging.
from annnet import to_json, from_json
to_json(G, tmp / 'g.json')
G_json = from_json(tmp / 'g.json')
print('round-trip nv/ne:', G_json.shape)
round-trip nv/ne: (3, 2)
NetworkX bridge¶
G.nx.backend() returns the cached underlying networkx.MultiDiGraph
(or MultiGraph for undirected). Use it with any networkx algorithm.
import networkx as nx
nxG = G.nx.backend()
print('nx type:', type(nxG).__name__)
print('nodes:', sorted(nxG.nodes()))
print('shortest_path A→C:', nx.shortest_path(nxG, 'A', 'C'))
nx type: MultiDiGraph nodes: ['A', 'B', 'C'] shortest_path A→C: ['A', 'B', 'C']
igraph bridge¶
G.ig.backend() returns the cached underlying igraph.Graph.
to_igraph(G) additionally returns a manifest dict; round-trip via
from_igraph(igG, manifest) is lossless.
from annnet import to_igraph, from_igraph
igG, manifest = to_igraph(G)
print('ig vcount/ecount:', igG.vcount(), igG.ecount())
G_via_ig = from_igraph(igG, manifest)
print('round-trip nv/ne:', G_via_ig.shape)
ig vcount/ecount: 3 2 round-trip nv/ne: (3, 2)
scverse bridge (AnnData)¶
For single-cell workflows there's to_anndata / from_anndata. The
edge attribute table becomes obs, the vertex attribute table becomes
var, the incidence matrix becomes a sparse X.
from annnet import to_anndata, from_anndata
adata = to_anndata(G)
G_back = from_anndata(adata)
See the use-case notebooks for end-to-end examples with a real AnnData
(Kang 2018 PBMC).
Next: 04 — Slices.