I have a simple adjacency list representation of a graph like this
{
1: [2, 3, 4],
2: [5],
3: [6, 9],
4: [3],
5: [3],
6: [7, 8],
7: [],
8: [],
9: []
}
which looks like this
But each node also has a "type ancestry" which tells us what "type" of node it is, and this is completely different from the hierarchy present in the adjacency list above. For example, it would tell us that "node 6 is of type 'BA', and all type 'BA' nodes are type 'B'".
For example, consider this ancestry:
{
1: [], # no ancestry
2: ['AA', 'A'], # Read this as "2 is a type AA node, and all type AA nodes are type A nodes"
3: ['B'], # 3 is directly under type B
4: [],
5: ['AA', 'A'],
6: ['BA', 'B'],
7: ['BA', 'B'],
8: ['BA', 'B'],
9: ['BB', 'B']
}
which when visualized would look like this
However, instead of connecting nodes directly as per the adjacency list, we must use their "representative types" when available, where the representative types of the nodes would be the nodes just below the lowest common ancestor of their type ancestries. When visualized with this adjustment, it would look like this
So what I want to produce programmatically is a "hierarchical/nested" adjacency list for such a visualization, which would look like below. The main idea is to introduce a subtree for each key in the adjacency list (along with the edges field), which would in turn contain its own adjacency list and so forth (recursively).
{1: {'edges': ['A', 'B', 4], 'subgraphs': {}},
4: {'edges': ['B'], 'subgraphs': {}},
'A': {'edges': ['B'],
'subgraphs': {'AA': {'edges': [],
'subgraphs': {2: {'edges': [5], 'subgraphs': {}},
5: {'edges': [], 'subgraphs': {}}}}}},
'B': {'edges': [],
'subgraphs': {3: {'edges': ['BA', 'BB'], 'subgraphs': {}},
'BA': {'edges': [],
'subgraphs': {6: {'edges': [7, 8], 'subgraphs': {}},
7: {'edges': [], 'subgraphs': {}},
8: {'edges': [], 'subgraphs': {}}}},
'BB': {'edges': [],
'subgraphs': {9: {'edges': [], 'subgraphs': {}}}}}}}
What is an elegant way of transforming the original adjacency list + the separate "ancestry" map to produce such a data structure?



5: ['B']instead of5: ['AA','A']? Which process has created that input? I would redesign the source that produced that data. Do you have a more primitive source for it, that does not have duplication like here?5: ['B']instead of5: ['AA', 'A']then node 5 would exist in the box for 'B' and the edge would be drawn from box 'A' to 'B'. There would be no direct edge from 2 to 5.