Skip to content

Optimization for layered graph layouts

import pathlib
import sys

import networkx as nx
import numpy as np
from IPython.display import SVG
from matplotlib import patches as mpatches
from matplotlib import pyplot as plt

from vizopt.animation import SnapshotCallback, snapshots_to_animated_svg
from vizopt.base import OptimConfig
from vizopt.templates.layered_graph import (
    layered_graph_template,
    make_layered_graph_input_params,
)
# Build a simple DAG
dag = nx.DiGraph()
dag.add_edges_from(
    [
        ("A", "B"),
        ("A", "C"),
        ("B", "D"),
        ("B", "E"),
        ("C", "E"),
        ("C", "F"),
        ("D", "G"),
        ("E", "G"),
        ("F", "G"),
    ]
)

# dag = inclusion_tree

input_params = make_layered_graph_input_params(
    dag, min_distance=1.5, preferred_edge_vector=(1.0, 0.0)
)
problem = layered_graph_template.instantiate(
    input_params, weight_overrides={"edge_direction": 0.0}
)
optim_vars, history = problem.optimize(OptimConfig(n_iters=5000, learning_rate=1e-2))

problem.plot_configuration(optim_vars, input_params)
plt.title("Layered graph layout (standard direction → (1, 0))")
plt.show()

output

snapshot_cb = SnapshotCallback(every=50)
problem = layered_graph_template.instantiate(
    input_params, weight_overrides={"edge_direction": 0.0}
)
optim_vars_opt, history = problem.optimize(
    OptimConfig(n_iters=5000, learning_rate=3e-3), callback=snapshot_cb
)

svg = snapshots_to_animated_svg(
    problem, snapshot_cb.snapshots, fps=12, size=500, history=history
)
SVG(data=svg)

output