Skip to content

pydsa.graphs

draw_graph

draw_graph(G: dict[Any, dict | Any]) -> None

Utility function to draw a graph (stored as dict of dicts, dict of lists, or dict with (row, col) tuples as keys) in the terminal as a colored adjacency matrix. Requires 'tabulate' library: pip install tabulate For colors, requires 'colorama': pip install colorama Colors edges based on values (e.g., 1 in red, 0 in blue). Assumes nodes are comparable for sorting.

Source code in pydsa/graphs.mu
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def draw_graph(G: {Any: dict | Any}) -> none
  """
  Utility function to draw a graph (stored as dict of dicts, dict of lists, or dict with (row, col) tuples as keys) in the terminal as a colored adjacency matrix.
  Requires 'tabulate' library: pip install tabulate
  For colors, requires 'colorama': pip install colorama
  Colors edges based on values (e.g., 1 in red, 0 in blue).
  Assumes nodes are comparable for sorting.
  """
  G = as_dict_of_dicts(is_edge_list(G) ? build_graph_from_edge_list(G) : G)
  try
    from tabulate import tabulate
  except ImportError
    print "Please install tabulate: pip install tabulate"
    return
  try
    import colorama
  except ImportError
    print "Please install colorama: pip install colorama"
    return
  if not G
    print "Empty graph"
    return
  print "\n"
  first_key = next(iter(G))
  is_tuple_key = isinstance(first_key, tuple) and len(first_key) == 2
  if is_tuple_key
    all_nodes = {node for src, dst in G for node in (src, dst)}
  else
    all_nodes = set(G.keys())
    for neighbors in G.values()
      all_nodes.update(neighbors.keys())
  nodes = sort(all_nodes)
  headers = [str(node) for node in nodes]
  table = []
  for src in nodes
    row = []
    for dst in nodes
      if is_tuple_key
        val = (src, dst) in G ? G[(src, dst)] : none
      else
        val = src in G and dst in G[src] ? G[src][dst] : none
      row <- val is none ? "" : _cell(val)
    table <- row
  print(tabulate(table, headers=headers, tablefmt="grid", showindex=headers,
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def draw_graph(G: dict[Any, dict | Any]) -> None:
    """
    Utility function to draw a graph (stored as dict of dicts, dict of lists, or dict with (row, col) tuples as keys) in the terminal as a colored adjacency matrix.
    Requires 'tabulate' library: pip install tabulate
    For colors, requires 'colorama': pip install colorama
    Colors edges based on values (e.g., 1 in red, 0 in blue).
    Assumes nodes are comparable for sorting.
    """
    G = as_dict_of_dicts(build_graph_from_edge_list(G) if is_edge_list(G) else G)
    try:
        from tabulate import tabulate
    except ImportError:
        print("Please install tabulate: pip install tabulate")
        return
    try:
        import colorama
    except ImportError:
        print("Please install colorama: pip install colorama")
        return
    if not G:
        print("Empty graph")
        return
    print("\n")
    first_key = next(iter(G))
    is_tuple_key = isinstance(first_key, tuple) and len(first_key) == 2
    if is_tuple_key:
        all_nodes = {node for src, dst in G for node in (src, dst)}
    else:
        all_nodes = set(G.keys())
        for neighbors in G.values():
            all_nodes.update(neighbors.keys())
    nodes = sorted(all_nodes)
    headers = [str(node) for node in nodes]
    table = []
    for src in nodes:
        row = []
        for dst in nodes:
            if is_tuple_key:
                val = G[(src, dst)] if (src, dst) in G else None
            else:
                val = G[src][dst] if src in G and dst in G[src] else None
            row.append("" if val is None else _cell(val))
        table.append(row)
    print(tabulate(table, headers=headers, tablefmt="grid", showindex=headers, numalign="center", stralign="center"))

build_graph_from_edge_list

build_graph_from_edge_list(edges, directed: bool = False)

A dict of dicts from an edge list, every edge weighted 0. directed adds each edge one way only, as adjacency does.

Source code in pydsa/graphs.mu
56
57
58
59
60
61
62
63
def build_graph_from_edge_list(edges, directed: bool=false)
  """A dict of dicts from an edge list, every edge weighted 0. directed
  adds each edge one way only, as adjacency does."""
  ret G = {:dict}
  for u, v in edges
    G[u][v] = 0
    if not directed
      G[v][u] = 0
77
78
79
80
81
82
83
84
85
def build_graph_from_edge_list(edges, directed: bool = False):
    """A dict of dicts from an edge list, every edge weighted 0. directed
    adds each edge one way only, as adjacency does."""
    G = defaultdict(dict)
    for u, v in edges:
        G[u][v] = 0
        if not directed:
            G[v][u] = 0
    return G

as_dict_of_dicts

as_dict_of_dicts(G)

Accept a dict of lists (or tuples or sets) as well as a dict of dicts.

Also accept a dict of scalars (each key has one neighbor, its value) and a list of ints (a parent array: index i has one neighbor parent[i]). A self loop, parent[i] == i, draws as a node with no outgoing edge.

Source code in pydsa/graphs.mu
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def as_dict_of_dicts(G)
  """Accept a dict of lists (or tuples or sets) as well as a dict of dicts.

  Also accept a dict of scalars (each key has one neighbor, its value)
  and a list of ints (a parent array: index i has one neighbor
  parent[i]). A self loop, parent[i] == i, draws as a node with no
  outgoing edge."""
  if isinstance(G, list) and all(isinstance(v, int) for v in G)
    G = dict(enumerate(G))
  if not isinstance(G, dict)
    return G
  ret out = {}
  for k, v in G.items()
    if isinstance(v, dict)
      out[k] = v
    elif isinstance(v, (list, tuple, set))
      out[k] = _labelled_neighbors(v)
    else
      out[k] = v == k ? {} : {v: 1}
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def as_dict_of_dicts(G):
    """Accept a dict of lists (or tuples or sets) as well as a dict of dicts.

    Also accept a dict of scalars (each key has one neighbor, its value)
    and a list of ints (a parent array: index i has one neighbor
    parent[i]). A self loop, parent[i] == i, draws as a node with no
    outgoing edge."""
    if isinstance(G, list) and all(isinstance(v, int) for v in G):
        G = Rec(enumerate(G))
    if not isinstance(G, dict):
        return G
    out = Rec()
    for k, v in G.items():
        if isinstance(v, dict):
            out[k] = v
        elif isinstance(v, (list, tuple, set)):
            out[k] = _labelled_neighbors(v)
        else:
            out[k] = Rec() if v == k else Rec({v: 1})
    return out

is_edge_list

is_edge_list(edges)
Source code in pydsa/graphs.mu
118
119
def is_edge_list(edges)
  type(edges) is list and all(len(x) == 2 and type(x) is list for x in edges)
148
149
def is_edge_list(edges):
    return type(edges) is list and all(len(x) == 2 and type(x) is list for x in edges)

draw_graphviz

draw_graphviz(
    G: dict[Any, dict | list],
    png_filename: Optional[str] = None,
    n=None,
    directed: bool = False,
    show_weights: bool = False,
    colours: dict[Any, str]
    | list[str]
    | Optional[str] = None,
    labels: dict[Any, Any]
    | list[Any]
    | Optional[str] = None,
) -> None

Draw G as a picture in the terminal.

colours fills node i with colours[i]: a colour name, or one of the letters RGBYWMCK as a LeetCode colours string spells them. labels writes labels[i] under the name of node i. Both take a dict, a list or a string, indexed by node.

Source code in pydsa/graphs.mu
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def draw_graphviz(
  G: {Any: dict | list}, png_filename: str?=none, n=none, directed: bool=false,
  show_weights: bool=false, colours: {Any: str} | [str] | str?=none,
  labels: {Any: Any} | [Any] | str?=none
) -> none
  """Draw G as a picture in the terminal.

  `colours` fills node i with colours[i]: a colour name, or one of the
  letters RGBYWMCK as a LeetCode colours string spells them.
  `labels` writes labels[i] under the name of node i.
  Both take a dict, a list or a string, indexed by node."""
  if os.environ.get("RUNNING_TESTS") == "True"
    return
  G = as_dict_of_dicts(is_edge_list(G) ? build_graph_from_edge_list(G, directed) : G)
  if png_filename is none
    # Compute deterministic hash for caching; shorten hash for filename
    sorted_G = {
      str(k): sort([(str(dst), weight) for dst, weight in _items(v)], by=x -> x[0])
      for k, v in sort(G.items(), by=x -> str(x[0]))
    }
    serialized = json.dumps({"G": sorted_G, "n": n, "colours": colours,
      "labels": labels}, sort_keys=true, default=str).encode()
    png_filename = f"/tmp/graph_{hashlib.sha256(serialized).hexdigest()[:16]}.png"
  try
    from graphviz import Digraph, Graph
  except ImportError
    print "Please install graphviz: pip install graphviz"
    return
  if not G
    print "Empty graph"
    return
  print "\n"
  all_nodes = set(G.keys())
  edges = [(src, dst, weight) for src in G for dst, weight in _items(G[src])]
  if not directed
    # an undirected adjacency lists each edge from both ends: draw it once
    edges = [(src, dst, w) for src, dst, w in edges
      if str(src) <= str(dst) or src not in G.get(dst, {})]
  all_nodes.update(dst for _, dst, _ in edges)
  if n is not none
    all_nodes.update(range(n))
  for spec in (colours, labels)
    if isinstance(spec, (list, str))
      all_nodes.update(range(len(spec)))
  dot = (directed ? Digraph : Graph)(comment="The Graph")
  dot.attr(rankdir="TB")
  dot.attr(bgcolor="transparent")
  dot.node_attr.update(style="filled", fillcolor="transparent", color="white",
    fontcolor="white")
  dot.edge_attr.update(color="blue", fontcolor="white")
  for node in sort(all_nodes, by=str)  # Sort for consistent order
    dot.node(str(node), **_node_attrs(_per_node(colours, node), _per_node(labels, node)))
  for src, dst, weight in edges
    for one in (isinstance(weight, list) ? weight : [weight])
      dot.edge(str(src), str(dst), **_edge_attrs(one, show_weights))
  try
    print dot.pipe(format="ascii", encoding="utf-8")
  except Exception
    try
      base_name = png_filename[:-4]
      if not os.path.exists(png_filename)
        dot.render(base_name, format="png", cleanup=true, view=false)
      if os.system(f"timg {png_filename}") != 0
        raise RuntimeError("timg failed to run (is it installed?)")
    except Exception as e
      print f"Failed to render/display PNG: {e}"
      print f"\nDOT source:\n\n{dot.source}"
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def draw_graphviz(G: dict[Any, dict | list], png_filename: Optional[str] = None, n=None, directed: bool = False, show_weights: bool = False, colours: dict[Any, str] | list[str] | Optional[str] = None, labels: dict[Any, Any] | list[Any] | Optional[str] = None) -> None:
    """Draw G as a picture in the terminal.

    `colours` fills node i with colours[i]: a colour name, or one of the
    letters RGBYWMCK as a LeetCode colours string spells them.
    `labels` writes labels[i] under the name of node i.
    Both take a dict, a list or a string, indexed by node."""
    if os.environ.get("RUNNING_TESTS") == "True":
        return
    G = as_dict_of_dicts(build_graph_from_edge_list(G, directed) if is_edge_list(G) else G)
    if png_filename is None:
        sorted_G = Rec({str(k): sorted([(str(dst), weight) for dst, weight in _items(v)], key=lambda x: x[0]) for k, v in sorted(G.items(), key=lambda x: str(x[0]))})
        serialized = json.dumps(Rec({"G": sorted_G, "n": n, "colours": colours, "labels": labels}), sort_keys=True, default=str).encode()
        png_filename = f"/tmp/graph_{hashlib.sha256(serialized).hexdigest()[:16]}.png"
    try:
        from graphviz import Digraph, Graph
    except ImportError:
        print("Please install graphviz: pip install graphviz")
        return
    if not G:
        print("Empty graph")
        return
    print("\n")
    all_nodes = set(G.keys())
    edges = [(src, dst, weight) for src in G for dst, weight in _items(G[src])]
    if not directed:
        edges = [(src, dst, w) for src, dst, w in edges if str(src) <= str(dst) or src not in G.get(dst, Rec())]
    all_nodes.update(dst for _, dst, _ in edges)
    if n is not None:
        all_nodes.update(range(n))
    for spec in (colours, labels):
        if isinstance(spec, (list, str)):
            all_nodes.update(range(len(spec)))
    dot = (Digraph if directed else Graph)(comment="The Graph")
    dot.attr(rankdir="TB")
    dot.attr(bgcolor="transparent")
    dot.node_attr.update(style="filled", fillcolor="transparent", color="white", fontcolor="white")
    dot.edge_attr.update(color="blue", fontcolor="white")
    for node in sorted(all_nodes, key=str):
        dot.node(str(node), **_node_attrs(_per_node(colours, node), _per_node(labels, node)))
    for src, dst, weight in edges:
        for one in (weight if isinstance(weight, list) else [weight]):
            dot.edge(str(src), str(dst), **_edge_attrs(one, show_weights))
    try:
        print(dot.pipe(format="ascii", encoding="utf-8"))
    except Exception:
        try:
            base_name = png_filename[:-4]
            if not os.path.exists(png_filename):
                dot.render(base_name, format="png", cleanup=True, view=False)
            if os.system(f"timg {png_filename}") != 0:
                raise RuntimeError("timg failed to run (is it installed?)")
        except Exception as e:
            print(f"Failed to render/display PNG: {e}")
            print(f"\nDOT source:\n\n{dot.source}")

draw_ascii_graph

draw_ascii_graph(graph: dict[Any, dict | list]) -> None

Utility function to draw a graph (stored as dict of dicts or dict of lists) in the terminal using PHART for ASCII rendering. Requires 'networkx' and 'phart' libraries: pip install networkx phart Supports directed graphs. Edge weights (like 0/1) are ignored in rendering but structure is shown.

Source code in pydsa/graphs.mu
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def draw_ascii_graph(graph: {Any: dict | list}) -> none
  """
  Utility function to draw a graph (stored as dict of dicts or dict of lists) in the terminal using PHART for ASCII rendering.
  Requires 'networkx' and 'phart' libraries: pip install networkx phart
  Supports directed graphs. Edge weights (like 0/1) are ignored in rendering but structure is shown.
  """
  G: {Any: dict} = as_dict_of_dicts(graph)
  if not G
    print "Empty graph"
    return
  # An image terminal gets a graphviz layout: phart puts every node on
  # one row and routes edges through the others, which is unreadable
  # past a handful of edges.
  if _image_terminal()
    draw_graphviz(graph, directed=not _symmetric(G))
    return
  # imported here: networkx costs ~50ms and every interpreter start pays
  # for sitecustomize's imports
  try
    import networkx as nx
    from phart import ASCIIRenderer
  except ImportError
    print "Please install networkx and phart: pip install networkx phart"
    return
  print "\n"
  nx_graph = nx.DiGraph()
  all_nodes = set(G.keys())
  for neighbors in G.values()
    all_nodes.update(neighbors.keys())
  nx_graph.add_nodes_from(all_nodes)
  # Add edges, ignoring weights for now (PHART doesn't support labels)
  nx_graph.add_edges_from((src, dst) for src in G for dst in G[src])
  try
    print _colorize_ascii_graph(ASCIIRenderer(nx_graph).render())
  except Exception as e
    print f"Failed to render with PHART: {e}"
    print "Fallback: Adjacency list"
    for src in sort(G)
      shown = [f"{dst}({G[src][dst]})" for dst in sort(G[src])]
      print f"{src}: {', '.join(shown)}"
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def draw_ascii_graph(graph: dict[Any, dict | list]) -> None:
    """
    Utility function to draw a graph (stored as dict of dicts or dict of lists) in the terminal using PHART for ASCII rendering.
    Requires 'networkx' and 'phart' libraries: pip install networkx phart
    Supports directed graphs. Edge weights (like 0/1) are ignored in rendering but structure is shown.
    """
    G: dict[Any, dict] = as_dict_of_dicts(graph)
    if not G:
        print("Empty graph")
        return
    if _image_terminal():
        draw_graphviz(graph, directed=not _symmetric(G))
        return
    try:
        import networkx as nx
        from phart import ASCIIRenderer
    except ImportError:
        print("Please install networkx and phart: pip install networkx phart")
        return
    print("\n")
    nx_graph = nx.DiGraph()
    all_nodes = set(G.keys())
    for neighbors in G.values():
        all_nodes.update(neighbors.keys())
    nx_graph.add_nodes_from(all_nodes)
    nx_graph.add_edges_from((src, dst) for src in G for dst in G[src])
    try:
        print(_colorize_ascii_graph(ASCIIRenderer(nx_graph).render()))
    except Exception as e:
        print(f"Failed to render with PHART: {e}")
        print("Fallback: Adjacency list")
        for src in sorted(G):
            shown = [f"{dst}({G[src][dst]})" for dst in sorted(G[src])]
            print(f"{src}: {', '.join(shown)}")

build_graph

build_graph(adj: List[List[int]]) -> Optional[GraphNode]
Source code in pydsa/graphs.mu
306
307
308
309
310
311
312
313
def build_graph(adj: List[List[int]]) -> GraphNode?
  if not adj
    return none
  nodes = [GraphNode(i) for i in 1..len adj]
  for >i in adj
    for nb in adj[i]
      nodes[i].neighbors <- nodes[nb - 1]
  nodes[0]
327
328
329
330
331
332
333
334
def build_graph(adj: List[List[int]]) -> Optional[GraphNode]:
    if not adj:
        return None
    nodes = [GraphNode(i) for i in range(1, len(adj) + 1)]
    for i in range(len(adj)):
        for nb in adj[i]:
            nodes[i].neighbors.append(nodes[nb - 1])
    return nodes[0]

get_adj_list

get_adj_list(node: Optional[GraphNode]) -> list[list[int]]
Source code in pydsa/graphs.mu
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def get_adj_list(node: GraphNode?) -> [[int]]
  if not node
    return []
  node_map, max_val = {}, 0
  queue, visited = deque([node]), {node}
  while queue
    cur = queue.popleft()
    node_map[cur.val] = cur
    max_val = max(max_val, cur.val)
    for nb in cur.neighbors
      if nb not in visited
        visited.add(nb)
        queue <- nb
  nodes = map(node_map.get, 1..max_val)
  [sort([nb.val for nb in cur.neighbors]) for cur in nodes if cur]
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def get_adj_list(node: Optional[GraphNode]) -> list[list[int]]:
    if not node:
        return []
    node_map, max_val = Rec(), 0
    queue, visited = deque([node]), {node}
    while queue:
        cur = queue.popleft()
        node_map[cur.val] = cur
        max_val = max(max_val, cur.val)
        for nb in cur.neighbors:
            if nb not in visited:
                visited.add(nb)
                queue.append(nb)
    nodes = map(node_map.get, range(1, max_val + 1))
    return [sorted([nb.val for nb in cur.neighbors]) for cur in nodes if cur]