From 4c3a08322dd63da056f7018762ef8d2a65f43209 Mon Sep 17 00:00:00 2001 From: Rahul Shrestha Date: Sun, 4 Aug 2024 07:05:42 +0200 Subject: [PATCH] Fix incorrect edges in `adjacency_matrix_to_graph` (#1202) * Fix matrix bug Signed-off-by: rahulbshrestha * Fixed graphviz import Signed-off-by: rahulbshrestha --------- Signed-off-by: rahulbshrestha --- dowhy/utils/graph_operations.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/dowhy/utils/graph_operations.py b/dowhy/utils/graph_operations.py index 577f1d1265..030a0fd10a 100644 --- a/dowhy/utils/graph_operations.py +++ b/dowhy/utils/graph_operations.py @@ -37,17 +37,29 @@ def adjacency_matrix_to_graph(adjacency_matrix, labels=None): :param labels: List of labels. :returns: Graph in DOT format. """ + import graphviz + + if adjacency_matrix.ndim != 2: + raise ValueError("Adjacency matrix must have a dimension of 2.") + + if isinstance(adjacency_matrix, np.matrix): + adjacency_matrix = np.asarray(adjacency_matrix) + # Only consider edges have absolute edge weight > 0.01 idx = np.abs(adjacency_matrix) > 0.01 dirs = np.where(idx) - import graphviz d = graphviz.Digraph(engine="dot") - names = labels if labels else [f"x{i}" for i in range(len(adjacency_matrix))] - for name in names: - d.node(name) + + if labels is None: + labels = [f"x{i}" for i in range(len(adjacency_matrix))] + + for label in labels: + d.node(label) + for to, from_, coef in zip(dirs[0], dirs[1], adjacency_matrix[idx]): - d.edge(names[from_], names[to], label=str(coef)) + d.edge(labels[from_], labels[to], label=str(coef)) + return d