Many algorithms on graphs require only local knowledge at each step, e.g. for BFS at any point we only need to know the AdjacencyList
of the vertex we are currently looking at. BFS is implemented in Mathematica in BreadthFirstScan
, but I see no way to use it on an implicit graph, i.e. not a Graph
object, but an object for which we can compute edges on-demand for any particular node.
More generally, is there any way to work with implicitly defined graphs in Mathematica? I've tried to trick it into accepting a "graph association", specifying the number of vertices and the function to use to compute neighbors of a vertex:
Unprotect@GraphQ;
GraphQ[Graph[a_Association]] := With[{}, Print@"call: GraphQ"; With[{}, Print@"call: GraphQ"; KeyExistsQ[a, "n"] && KeyExistsQ[a, "adj"]];
Protect@GraphQ;
Unprotect@VertexList;
VertexList[Graph[a_Association]] := With[{}, Print@"call: VertexList"; Range@a@"n"];
Protect@VertexList;
Unprotect@EdgeList;
EdgeList[Graph[a_Association]] := With[{}, Print@"call: EdgeList"; Flatten@Table[v \[DirectedEdge] # & /@ a["adj"]@v, {v, a@"n"}]];
Protect@EdgeList;
Unprotect@VertexCount;
VertexCount[Graph[a_Association]] := With[{}, Print@"call: VertexCount"; a@"n"];
Protect@VertexCount;
Unprotect@AdjacencyList;
AdjacencyList[Graph[a_Association], v_] := With[{}, Print@"call: AdjacencyList"; a["adj"]@v];
Protect@AdjacencyList;
Then, for example, the following would be an equivalent definition for CycleGraph@3
:
cycle3 = Graph[<|"n" -> 3, "adj" -> ({Mod[# + 1, 3, 1], Mod[# - 1, 3, 1]} &)|>];
However, I haven't got this graph to work for any built-in function: the furthest I've got is seeing NeighborhoodGraph
perform some calls to GraphQ
, VertexList
and EdgeList
(why would it do this?), but most functions just somehow detect this is not a native Graph
object... any ideas how to circumvent this?
PS: My use case involves a huge (~10^12 vertex) graph which I know has small connected components, which I'd like to explore.
Graph
. I see how this would be useful, but I am pretty sure this is not possible. $\endgroup$ImplicitGraph
function :-/ $\endgroup$