Integration with graph-like classes
Arbitrary classes of which instances can be interpreted
as scipy
sparse matrices or 2D square numpy
arrays
can be registered as abstract subclasses of GraphABC
.
This way all main classes/functions implemented in pathcensus
can automatically interpret them as graph-like objects allowing
seemless integration with many different data formats and third-party
packages such as networkx
or igraph
.
In order to register a class a function for converting its instances to
scipy.sparse.spmatrix
(CRS format) needs to be defined.
The conversion is handled by the pathcensus.graph.adjacency()
function
which can be overloaded through the single dispatch mechanism. In particular,
it should be called on arrays/sparse matrices extracted from graph classes
to ensure standardized format. See the example below.
Graph classes defined by networkx
, igraph
and graph_tool
are registered automatically provided
the packages are installed.
Note
pathcensus
uses the A_{ij} = 1
convention to indicate
that a node i sends a tie to a node j. Functions converting
graph-like objects to arrays / sparse matrices need to be aware
of that.
Below is an example in which a custom conversion from a list of list
format is registered. Arguably, the below implementation is naive and
handles the conversion by simply converting to a numpy
array,
without checking wheter the array is really 2D and square, but it illustrates
the main logic of registering custom graph-like classes.
>>> import numpy as np
>>> from pathcensus import GraphABC, adjacency, PathCensus
>>> def _adj_list(graph: list) -> spmatrix:
... """Adjacency matrix from list of lists."""
... A = np.array(graph)
... return adjacency(A)
>>> GraphABC.register_type(list, _adj_list)
>>> # A triangle graph
>>> A = [[0, 1, 1], [1, 0, 1], [1, 1, 0]]
>>> # Calculate path census
>>> paths = PathCensus(A)
>>> paths.census("global")
t tw th q0 qw qh
0 1 3 3 0 0 0