A complete k-Partite graph can be divided into "k" distinct sets of nodes, each of which is connected to all nodes not in its own set. This can be generated with code CompleteGraph[{an, bn, cn}] where "an", "bn", and "cn" are the number of nodes in k = 3 distinct set. I would like to generate a graph that is similar, but the subset "A" connects only to "B", and "B" connects only to "C" as seen below:
This occurs in artificial neural networks.
This can be done using:
LayeredGraph[{nnA_, nnB_, nnC_}] :=
Module[{graph1, graph2},
graph1 = CompleteGraph[{nnA, nnB}, DirectedEdges -> True];
graph2 = IndexGraph[#, nnA + 1] &@ CompleteGraph[{nnB, nnC}, DirectedEdges -> True];
GraphUnion[graph1, graph2]
]
or
LayeredGraph2[{nnA_, nnB_, nnC_}] :=
Module[{graph1, deletableEdges},
graph1 = CompleteGraph[{nnA, nnB, nnC}, DirectedEdges -> True];
Print["graph built"];
deletableEdges =
Apply[DirectedEdge[#1, #2] &, #, {1}] &@ Tuples[{Range[1, nnA], Range[nnA + nnB + 1, nnA + nnB + nnC]}];
Print["edges calculated"];
EdgeDelete[graph1, deletableEdges]
]
but both become very slow at the GraphUnion[]
and the EdgeDelete[]
functions for {nnA, nnB, nnC} = {400, 100, 400}
and I would like to create even larger graphs. In contrast, CompleteGraph[{400, 100, 400}]
with even more edges completes in a moment.