### Install graphlay Source: https://github.com/aarkue/graphlay/blob/main/bindings/python/README.md Install the prebuilt graphlay package using pip. ```sh pip install graphlay ``` -------------------------------- ### Install and run graphlay layout Source: https://github.com/aarkue/graphlay/blob/main/cli/README.md Installs the CLI tool via cargo and demonstrates a basic layout operation using a JSON input piped to the command. ```sh cargo install graphlay-cli echo '{"nodes": [{"size": {"width": 80, "height": 40}}, {"size": {"width": 80, "height": 40}}], "edges": [{"source": 0, "target": 1}]}' | graphlay layout --preset process_map --pretty ``` -------------------------------- ### Install CLI tool Source: https://github.com/aarkue/graphlay/blob/main/README.md Command to install the graphlay command line interface. ```bash cargo install graphlay-cli ``` -------------------------------- ### Run the eval example with all flags Source: https://github.com/aarkue/graphlay/blob/main/docs/quality.md Shows the basic invocation of the eval example and lists all available flags. Use --filter to select fixtures, --svg-out to render SVGs, --baseline/--save-baseline for comparisons, --repeat for median durations, --effort for speed/quality, and other flags for additional metrics. ```sh cargo run -p graphlay --release --features fixtures --example eval -- [args] # --filter only fixtures whose name or kind contains # --svg-out render one SVG per fixture into # --baseline compare against saved metrics, print deltas and mark regressions # --save-baseline write this run's metrics as a new baseline # --repeat lay each fixture out n times and take the median duration # --effort fast, balanced (default) or thorough # --wide print a second table with the metrics the main table leaves out # --phase-profile the staircase steps of the long edges after each pipeline phase # --stability lay each fixture out again without its lightest 10% of edges and # report how far the drawing moved ``` -------------------------------- ### Install npm package Source: https://github.com/aarkue/graphlay/blob/main/README.md Command to install the graphlay WASM package via npm. ```bash npm install graphlay ``` -------------------------------- ### Build and layout a graph in Rust Source: https://github.com/aarkue/graphlay/blob/main/README.md Example showing how to build a graph using GraphBuilder, apply a layered layout, and iterate over the resulting node placements and edge routes. ```rust use graphlay::{layout, GraphBuilder, LayoutOptions, Node, Size}; let mut b = GraphBuilder::new(); let a = b.add_node(Node { size: Size::new(120.0, 52.0), ..Node::default() }); let c = b.add_node(Node { size: Size::new(120.0, 52.0), ..Node::default() }); b.connect(a, c); let drawing = layout(&b.build(), &LayoutOptions::layered_default()).expect("a valid graph"); for placement in &drawing.nodes { println!("({:.0}, {:.0}) in layer {:?}", placement.center.x, placement.center.y, placement.rank); } for route in &drawing.edges { println!("{:?}: {} points", route.kind, route.points.len()); } ``` -------------------------------- ### Install Rust crate Source: https://github.com/aarkue/graphlay/blob/main/README.md Command to add the graphlay crate to a Rust project. ```bash cargo add graphlay ``` -------------------------------- ### Define an order-to-cash Petri net Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md This example shows how to construct a complex Petri net using the Net API, defining places and transitions, and connecting them with arcs to model an order-to-cash process. ```rust /// An order process: receive the order, check stock and credit in parallel, then ship or /// reject, and send reminders until the payment arrives. fn order_to_cash() -> Panel { let mut n = Net::default(); let start = n.place(None); let receive = n.transition("Receive order"); let p1 = n.place(None); let split = n.silent(); let (stock_in, credit_in) = (n.place(None), n.place(None)); let check_stock = n.transition("Check stock"); let check_credit = n.transition("Check credit"); let (stock_ok, credit_ok) = (n.place(None), n.place(None)); let approve = n.transition("Approve order"); let reject = n.transition("Reject order"); let decided = n.place(None); let ship = n.transition("Ship goods"); let shipped = n.place(None); let invoice = n.transition("Send invoice"); let open = n.place(None); let remind = n.transition("Send reminder"); let pay = n.transition("Receive payment"); let done = n.place(None); for (a, b) in [ (start, receive), (receive, p1), (p1, split), (split, stock_in), (split, credit_in), (stock_in, check_stock), (credit_in, check_credit), (check_stock, stock_ok), (check_credit, credit_ok), (stock_ok, approve), (credit_ok, approve), (stock_ok, reject), (credit_ok, reject), (approve, decided), (decided, ship), (ship, shipped), (shipped, invoice), (invoice, open), (open, remind), (remind, open), (open, pay), (pay, done), (reject, done), ] { n.arc(a, b); } n.draw("a Petri net: order to cash") } ``` -------------------------------- ### Build nested subprocesses graph and layout in both directions (tests/gallery/compounds.rs) Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Rust example from tests/gallery/compounds.rs that builds a graph with nested nodes using Node::parent, sets Spacing::compound_header to 16.0, and lays out the graph in both Direction::LeftRight and Direction::TopBottom. The resulting layouts are returned as two panels. ```rust use graphlay::{layout, Direction, GraphBuilder, LayoutOptions, Node, NodeId, Size}; use super::Panel; pub fn panels() -> Vec { let mut b = GraphBuilder::new(); let mut node = |name: &str, parent: Option| { b.add_node(Node { size: Size::new(110.0, 36.0), key: Some(name.to_string()), parent, ..Node::default() }) }; let order_in = node("Order in", None); let fulfilment = node("Fulfilment", None); let check = node("Check stock", Some(fulfilment)); let backorder = node("Backorder", Some(fulfilment)); let packaging = node("Packaging", Some(fulfilment)); let pick = node("Pick", Some(packaging)); let pack = node("Pack", Some(packaging)); let label = node("Label", Some(fulfilment)); let billing = node("Billing", None); let invoice = node("Invoice", Some(billing)); let collect = node("Collect payment", Some(billing)); let done = node("Done", None); for (s, t) in [ (order_in, check), (check, pick), (check, backorder), (backorder, pick), (pick, pack), (pack, label), (label, done), (order_in, invoice), (invoice, collect), (collect, done), ] { b.connect(s, t); } let graph = b.build(); let mut options = LayoutOptions::default(); options.spacing.compound_header = 16.0; let across_options = options; let across = layout(&graph, &across_options).expect("lays out"); options.direction = Direction::TopBottom; let down = layout(&graph, &options).expect("lays out"); vec![ Panel::new( "Direction::LeftRight", graph.clone(), &across_options, across, ), Panel::new("Direction::TopBottom", graph, &options, down), ] } ``` -------------------------------- ### tree::layout example with TreeOptions (tests/gallery/tree.rs) Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Builds a company hierarchy graph and lays it out with tree::layout using three TreeOptions variants: elbow edges top-to-bottom, straight edges, and left-to-right. The code uses GraphBuilder to add nodes and connect them, then creates a Panel for each option. Note the comment that the metrics check takes layered options, so LayoutOptions::layered_default() is used as a stand-in. ```rust use graphlay::tree::{self, TreeEdgeStyle, TreeOptions}; use graphlay::{Direction, GraphBuilder, LayoutOptions, Node, Size}; use super::Panel; pub fn panels() -> Vec { let mut b = GraphBuilder::new(); let mut unit = |name: &str| { b.add_node(Node { size: Size::new(92.0, 36.0), key: Some(name.to_string()), ..Node::default() }) }; let company = unit("Company"); let (sales, product, finance) = (unit("Sales"), unit("Product"), unit("Finance")); let teams = [ (sales, "Inbound"), (sales, "Accounts"), (product, "Design"), (product, "Platform"), (product, "Mobile"), (finance, "Payroll"), ]; let teams: Vec<_> = teams .into_iter() .map(|(parent, name)| (parent, unit(name))) .collect(); for (parent, team) in teams { b.connect(parent, team); } for child in [sales, product, finance] { b.connect(company, child); } let graph = b.build(); let elbow = TreeOptions { direction: Direction::TopBottom, edge_style: TreeEdgeStyle::Elbow, ..TreeOptions::default() }; let straight = TreeOptions { edge_style: TreeEdgeStyle::Straight, ..elbow }; let sideways = TreeOptions { direction: Direction::LeftRight, ..elbow }; // The metrics check takes layered options. A tree has none, so the default stands in. let measured = LayoutOptions::layered_default(); [ ("elbow edges, top to bottom", elbow), ("straight edges", straight), ("left to right", sideways), ] .into_iter() .map(|(caption, options)| { let drawing = tree::layout(&graph, &options).expect("lays out"); Panel::new(caption, graph.clone(), &measured, drawing) }) .collect() } ``` -------------------------------- ### Perform graph layout with layout() Source: https://github.com/aarkue/graphlay/blob/main/bindings/wasm/js/README.md Example of using the layout function to compute a graph layout with specific nodes, edges, and routing styles. ```ts import { layout } from "graphlay"; const box = { size: { width: 120, height: 50 } }; const drawing = await layout({ graph: { nodes: [box, box, box], edges: [{ source: 0, target: 1 }, { source: 1, target: 2 }] }, preset: "process_map", options: { routing: { style: "diagonal" } }, }); drawing.nodes[0].center; // { x, y } drawing.edges[0].points; // the polyline, border to border ``` -------------------------------- ### Configure viewport_aspect in tests/gallery/wrapping.rs Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md This example demonstrates setting wrap.viewport_aspect to 16.0 / 9.0 to organize a sequential process graph into rows. ```rust use graphlay::{layout, GraphBuilder, LayoutOptions, Node, Size}; use super::Panel; pub fn panels() -> Vec { let mut b = GraphBuilder::new(); let steps = [ "Lead", "Qualify", "Demo", "Offer", "Negotiate", "Contract", "Onboard", "Kick-off", "Deliver", "Invoice", "Renew", ]; let n: Vec<_> = steps .iter() .map(|name| { b.add_node(Node { size: Size::new(100.0, 36.0), key: Some(name.to_string()), ..Node::default() }) }) .collect(); for w in n.windows(2) { b.connect(w[0], w[1]); } // Two shortcuts and a loop back. b.connect(n[1], n[5]); b.connect(n[4], n[3]); b.connect(n[8], n[10]); let graph = b.build(); let mut options = LayoutOptions::default(); options.wrap.viewport_aspect = 16.0 / 9.0; let wrapped = layout(&graph, &options).expect("lays out"); vec![Panel::new( "wrap.viewport_aspect = 16 / 9", graph, &options, wrapped, )] } ``` -------------------------------- ### Build swimlanes graph with GroupLanes::Soft and Strict (Rust) Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Rust example from tests/gallery/swimlanes.rs. It creates a graph with nodes assigned to lanes via Node::group, connects them, and lays out the graph twice: once with default GroupLanes::Soft and once with GroupLanes::Strict. The resulting panels are labeled 'group_lanes: Soft (default)' and 'group_lanes: Strict', with the strict panel including lane names. ```rust use graphlay::{layout, GraphBuilder, GroupId, GroupLanes, LayoutOptions, Node, Size}; use super::Panel; /// Lane names, by group id. pub const LANES: &[&str] = &["Customer", "Sales", "Warehouse", "Finance"]; pub fn panels() -> Vec { let mut b = GraphBuilder::new(); let steps = [ ("Place order", 0), ("Receive order", 1), ("Check credit", 3), ("Confirm order", 1), ("Pick items", 2), ("Pack", 2), ("Ship", 2), ("Send invoice", 3), ("Receive goods", 0), ("Pay invoice", 0), ("Book payment", 3), ]; let n: Vec<_> = steps .iter() .map(|&(name, lane)| { b.add_node(Node { size: Size::new(120.0, 40.0), key: Some(name.to_string()), group: Some(GroupId(lane)), ..Node::default() }) }) .collect(); for (s, t) in [ (0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (3, 7), (6, 8), (7, 9), (8, 9), (9, 10), ] { b.connect(n[s], n[t]); } let graph = b.build(); let mut options = LayoutOptions::default(); let plain = options; let soft = layout(&graph, &plain).expect("lays out"); options.order.group_lanes = GroupLanes::Strict; let strict = layout(&graph, &options).expect("lays out"); vec![ Panel::new("group_lanes: Soft (default)", graph.clone(), &plain, soft), Panel::new("group_lanes: Strict", graph, &options, strict).with_lanes(LANES), ] } ``` -------------------------------- ### Create a first drawing with default options in tests/gallery/quick_start.rs Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Demonstrates the basic usage of GraphBuilder to define nodes with sizes and keys, connect them with edges, and apply default layout options. ```rust use graphlay::{layout, GraphBuilder, LayoutOptions, Node, Size}; use super::Panel; pub fn panels() -> Vec { let mut b = GraphBuilder::new(); let mut task = |name: &str| { b.add_node(Node { size: Size::new(120.0, 40.0), key: Some(name.to_string()), ..Node::default() }) }; let (register, check, approve, reject, notify) = ( task("Register"), task("Check"), task("Approve"), task("Reject"), task("Notify"), ); for (s, t) in [ (register, check), (check, approve), (check, reject), (approve, notify), (reject, notify), ] { b.connect(s, t); } let graph = b.build(); let options = LayoutOptions::default(); let drawing = layout(&graph, &options).expect("lays out"); vec![Panel::new("default options", graph, &options, drawing)] } ``` -------------------------------- ### Rust test file for presets gallery (tests/gallery/presets.rs) Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Builds an order process graph and a type graph, then renders panels for each preset and direction/routing variation. Uses graphlay's layout, GraphBuilder, LayoutOptions, Direction, RoutingStyle, and Size. The order process graph uses edge weights and thicknesses derived from case counts; the type graph connects a central Order node to several other types with alternating edges. ```rust use graphlay::{layout, Direction, Edge, GraphBuilder, LayoutOptions, Node, RoutingStyle, Size}; use super::Panel; /// An order process with a rework loop and a skip, with edge weights from case counts. fn order_process() -> graphlay::Graph { let mut b = GraphBuilder::new(); let mut step = |name: &str| { b.add_node(Node { size: Size::new(110.0, 40.0), key: Some(name.to_string()), ..Node::default() }) }; let (receive, check, reserve, pick, ship, invoice, close, reject) = ( step("Receive"), step("Check"), step("Reserve"), step("Pick"), step("Ship"), step("Invoice"), step("Close"), step("Reject"), ); for (s, t, count) in [ (receive, check, 400.0), (check, reserve, 360.0), (check, reject, 40.0), (reserve, pick, 360.0), (pick, ship, 350.0), (ship, invoice, 350.0), (invoice, close, 350.0), (reject, close, 40.0), (reserve, invoice, 10.0), (pick, check, 25.0), ] { let mut e = Edge::new(s, t); e.weight = 1.0 + f64::ln(count); e.thickness = (1.0 + f64::ln(count) / 2.0).min(5.0); b.add_edge(e); } b.build() } /// Four object types around one central type, as a data model's type graph looks. fn type_graph() -> graphlay::Graph { let mut b = GraphBuilder::new(); let mut kind = |name: &str| { b.add_node(Node { size: Size::new(96.0, 40.0), key: Some(name.to_string()), ..Node::default() }) }; let order = kind("Order"); let others: Vec<_> = ["Item", "Customer", "Invoice", "Package", "Payment", "Route"] .into_iter() .map(&mut kind) .collect(); for (i, &other) in others.iter().enumerate() { b.connect(order, other); if i % 2 == 0 { b.connect(other, order); } if i + 1 < others.len() && i % 3 == 0 { b.connect(other, others[i + 1]); } } b.build() } pub fn panels() -> Vec { let mut out = Vec::new(); let process = order_process(); let mut draw = |caption: &str, options: LayoutOptions| { let drawing = layout(&process, &options).expect("lays out"); out.push(Panel::new(caption, process.clone(), &options, drawing)); }; draw( "layered, left to right: the default", LayoutOptions::layered_default(), ); draw( "process map: top to bottom, orthogonal", LayoutOptions::process_map(), ); let mut diagonal = LayoutOptions::process_map(); diagonal.routing.style = RoutingStyle::Diagonal; draw("process map, diagonal routing", diagonal); let mut across = LayoutOptions::process_map(); across.direction = Direction::LeftRight; draw("process map, left to right", across); let types = type_graph(); for (caption, options) in [ ("hub and spoke", LayoutOptions::hub_and_spoke()), ( "hub and spoke with a flow", LayoutOptions::hub_and_spoke_flow(), ), ] { let drawing = layout(&types, &options).expect("lays out"); out.push(Panel::new(caption, types.clone(), &options, drawing)); } out } ``` -------------------------------- ### Run test suite Source: https://github.com/aarkue/graphlay/blob/main/RELEASING.md Execute the full test suite across Rust, JavaScript, and Python components before releasing. ```sh cargo test --release --all-features cargo test -p graphlay-cli -p graphlay-wasm pnpm install && pnpm --filter graphlay build && pnpm --filter graphlay test pip install ./bindings/python && pytest bindings/python/tests ``` -------------------------------- ### Typical change check with baseline comparison Source: https://github.com/aarkue/graphlay/blob/main/docs/quality.md Shows a typical workflow for checking a change: first run with --save-baseline to record metrics, then after changing the engine run with --baseline to compare. The exit code is 1 when a fixture fails to lay out. Timings vary between runs, so use --repeat 3 or more before interpreting small differences. ```sh cargo run -p graphlay --release --features fixtures --example eval -- \ --svg-out /tmp/before --save-baseline /tmp/before.json # change the engine cargo run -p graphlay --release --features fixtures --example eval -- \ --svg-out /tmp/after --baseline /tmp/before.json ``` -------------------------------- ### Define Petri net discovery from log Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Constructs a Petri net from a JSON fixture file by mapping nodes to places, silent transitions, or labeled transitions and drawing the resulting network. ```rust fn fines_net() -> Panel { let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/petri/pn-rtfm-imf02-reference.json"); let f = fixture::load_file(&path).expect("the fixture loads"); let mut n = Net::default(); let ids: Vec = f .nodes .iter() .map(|node| { if node.shape.eq_ignore_ascii_case("ellipse") { n.place(None) } else if node.label.is_empty() { n.silent() } else { n.transition(&node.label) } }) .collect(); for e in &f.edges { n.arc(ids[e.from], ids[e.to]); } n.draw("the Petri net discovered from the same log") } ``` -------------------------------- ### json::sketch Source: https://github.com/aarkue/graphlay/blob/main/docs/svg.md Does both sketch_scene and render_scene in one step. ```APIDOC ## json::sketch ### Description Does both sketch_scene and render_scene in one step. ``` -------------------------------- ### Sketch a scene from a graph layout Source: https://github.com/aarkue/graphlay/blob/main/docs/svg.md Demonstrates building a graph, calculating its layout, and customizing the resulting scene before rendering it to SVG. ```rust use graphlay::{layout, svg, GraphBuilder, LayoutOptions, Size}; let mut b = GraphBuilder::new(); let a = b.add_box(Size::new(120.0, 50.0)); let c = b.add_box(Size::new(120.0, 50.0)); b.connect(a, c); let g = b.build(); let l = layout(&g, &LayoutOptions::layered_default()).expect("a valid graph"); let mut scene = svg::sketch_scene(&g, &l, &svg::SketchOptions::default()); scene.background = Some("#f8fafc".into()); let node = &mut scene.nodes[0]; node.fill = Some("#dbeafe".into()); node.content.push(svg::NodeContent::Glyphs(svg::GlyphRow::dots(1, 5.0, "#1e3a8a"))); if let Some(label) = node.label_mut() { label.weight = Some(600.0); } let edge = &mut scene.edges[0]; edge.marker_end = svg::MarkerRef::builtin(svg::BuiltinMarker::Arrow).colored("#2563eb"); edge.labels.push(svg::EdgeLabel::new("42", l.edges[0].label_anchor).chip()); let svg = svg::render(&scene, &svg::Theme::default(), &svg::HeuristicMeasurer::new()); ``` -------------------------------- ### Customize process model rendering Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md This snippet demonstrates how to configure SketchOptions and iterate through scene nodes and edges to apply custom shapes, colors, and decorations based on node kinds and edge variables. ```rust let sketch = SketchOptions { labels: self.labels.clone(), ..SketchOptions::default() }; let mut scene = sketch_scene(&graph, &drawing, &sketch); for (i, node) in scene.nodes.iter_mut().enumerate() { match self.kinds[i] { Kind::Place => { let c = colour(self.types[i]); node.shape = svg::Shape::Circle; node.fill = Some(self.types[i].map_or("#ffffff", |t| TYPES[t].2).to_string()); node.stroke = Some(Stroke::new(c, 1.5)); if !has_in(i) { node.content .push(NodeContent::Glyphs(GlyphRow::dots(1, 5.5, c))); } if !has_out(i) { let ring = Ring { color: c.to_string(), width: 1.5, inset: 3.5, }; node.content.push(NodeContent::Rings { rings: vec![ring] }); } } Kind::Transition => { node.shape = svg::Shape::Rect { corner_radius: 2.0 }; node.stroke = Some(Stroke::new(INK, 1.5)); if let Some(text) = node.label_mut() { text.color = Some(INK.to_string()); text.size = Some(11.5); } } Kind::Silent => { node.shape = svg::Shape::Rect { corner_radius: 0.0 }; node.fill = Some(INK.to_string()); node.stroke = Some(Stroke::new(INK, 1.6)); } } } for (edge, &(ty, variable)) in scene.edges.iter_mut().zip(&self.arcs) { let c = colour(ty); edge.corner_radius = 6.0; if variable { // A double line: a wide band in the type's colour under a white core. let band = Stroke { linecap: LineCap::Round, ..Stroke::new(c, 6.5) }; edge.decorations.push(Decoration::band(edge, band)); edge.stroke = Stroke::new("#ffffff", 2.5); edge.marker_end = MarkerRef::builtin(BuiltinMarker::Arrow).colored(c); } else { edge.stroke = Stroke::new(c, 1.6); } } if self.types.iter().any(Option::is_some) { let items = TYPES .iter() .enumerate() .filter(|(t, _)| self.types.contains(&Some(*t))) .map(|(_, (name, c, _))| LegendItem::new(Swatch::color(*c), *name)); let origin = Point::new(drawing.bounds.max.x + 24.0, drawing.bounds.min.y); let legend = svg::Panel::legend(origin, "Object types", items); scene.overlays.push(Overlay::panel(legend)); } Panel::new(caption, graph, &options, drawing).scene(scene, Palette::default()) } } ``` -------------------------------- ### Create and layout a graph Source: https://github.com/aarkue/graphlay/blob/main/bindings/python/README.md Define a graph with nodes and edges, apply a layout preset, and save the result as an SVG. ```python import graphlay g = graphlay.Graph() g.node("start", width=60, height=30, shape="ellipse") g.node("work", label="Do the work") g.node("end", width=60, height=30, shape="ellipse") g.edge("start", "work") g.edge("work", "end") drawing = graphlay.layout(g, preset="process_map", options={"routing": {"style": "diagonal"}}) drawing.positions() # {"start": (x, y), ...} drawing.edges[0]["points"] # the polyline, border to border drawing # in a notebook: the drawing itself drawing.sketch().save("drawing.svg") ``` -------------------------------- ### Register process model panels Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Collects various process model visualizations into a vector of panels for display. ```rust pub fn panels() -> Vec { vec![ order_to_cash(), object_centric_net(), object_centric_dfg(), fines_dfg(), fines_net(), ] } ``` -------------------------------- ### SketchOptions Source: https://github.com/aarkue/graphlay/blob/main/docs/svg.md Sets the labels, lane names, background, and padding for the sketch scene. ```APIDOC ## SketchOptions ### Description Sets the labels, lane names, background, and padding for the sketch scene. ``` -------------------------------- ### Create an object-centric directly-follows graph Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md Constructs a DFG representing an online shop's workflow, visualizing object types in different colors and edge weights based on occurrence frequency. ```rust fn object_centric_dfg() -> Panel { const ACTIVITIES: [(&str, usize, u64); 10] = [ ("place order", 0, 2000), ("confirm order", 0, 1950), ("payment reminder", 0, 550), ("pay order", 0, 1930), ("item out of stock", 1, 300), ("pick item", 1, 7390), ("create package", 2, 2400), ("send package", 2, 2400), ("failed delivery", 2, 170), ("package delivered", 2, 2390), ]; let mut b = GraphBuilder::new(); let activity: Vec = ACTIVITIES .iter() .map(|(name, ty, _)| { b.add_node(Node { size: Size::new((7.0 * name.len() as f64 + 30.0).max(120.0), 46.0), group: Some(GroupId(*ty as u32)), ..Node::default() }) }) .collect(); let mut ends = |rank: RankConstraint, size: Size| -> Vec { (0..TYPES.len()) .map(|ty| { b.add_node(Node { size, rank, group: Some(GroupId(ty as u32)), ..Node::default() }) }) .collect() }; let start = ends(RankConstraint::First, Size::new(92.0, 30.0)); let end = ends(RankConstraint::Last, Size::new(24.0, 24.0)); let a = |name: &str| activity[ACTIVITIES.iter().position(|x| x.0 == name).expect("known")]; let flows: Vec<(NodeId, NodeId, usize, u64)> = vec![ (start[0], a("place order"), 0, 2000), (a("place order"), a("confirm order"), 0, 1950), (a("confirm order"), a("pay order"), 0, 1520), (a("confirm order"), a("payment reminder"), 0, 430), (a("payment reminder"), a("payment reminder"), 0, 120), (a("payment reminder"), a("pay order"), 0, 410), (a("pay order"), end[0], 0, 1930), (start[1], a("place order"), 1, 7600), (a("place order"), a("confirm order"), 1, 7400), (a("confirm order"), a("pick item"), 1, 7100), (a("confirm order"), a("item out of stock"), 1, 300), (a("item out of stock"), a("pick item"), 1, 290), (a("pick item"), a("create package"), 1, 7300), (a("create package"), end[1], 1, 7300), (start[2], a("create package"), 2, 2400), (a("create package"), a("send package"), 2, 2400), (a("send package"), a("package delivered"), 2, 2230), (a("send package"), a("failed delivery"), 2, 170), (a("failed delivery"), a("package delivered"), 2, 160), (a("package delivered"), end[2], 2, 2390), ]; for &(s, t, ty, n) in &flows { let mut e = Edge::new(s, t); e.group = Some(GroupId(ty as u32)); e.weight = 1.0 + (n as f64).ln(); e.thickness = 1.4 + 3.0 * (n as f64).ln() / 7600f64.ln(); e.label_size = Some(label_size(&count(n))); b.add_edge(e); } let graph = b.build(); let options = LayoutOptions::process_map(); let drawing = layout(&graph, &options).expect("lays out"); } ``` -------------------------------- ### Construct a finite automaton visualization Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md This snippet shows how to build a finite automaton using GraphBuilder. It defines states, transitions with symbols, and custom node styling including double rings for accepting states. ```rust /// A finite automaton: circles for states, a double ring for the accepting ones, self-loops /// for the transitions that stay, and the symbol read on every edge. fn automaton() -> Panel { let mut b = GraphBuilder::new(); let mut state = |name: &str| { b.add_node(Node { size: Size::new(44.0, 44.0), shape: Shape::Ellipse, key: Some(name.to_string()), ..Node::default() }) }; let q: Vec<_> = (0..5).map(|i| state(&format!("q{i}"))).collect(); // The arrow into the initial state comes from a point-sized node nothing draws. let start = b.add_node(Node { size: Size::new(2.0, 2.0), ..Node::default() }); let transitions = [ (start, q[0], ""), (q[0], q[1], "a"), (q[0], q[0], "b"), (q[1], q[1], "a"), (q[1], q[2], "b"), (q[2], q[3], "a"), (q[2], q[0], "b"), (q[3], q[4], "b"), (q[3], q[3], "a"), (q[4], q[4], "a, b"), ]; for (s, t, symbol) in transitions { let mut e = Edge::new(s, t); if !symbol.is_empty() { e.label_size = Some(Size::new(8.0 * symbol.len() as f64 + 8.0, 14.0)); } b.add_edge(e); } let g = b.build(); let mut options = LayoutOptions::layered_default(); options.self_loops.side = LoopSide::CrossNegative; let drawing = layout(&g, &options).expect("lays out"); let accepting = [q[2].index(), q[4].index()]; let mut scene = sketch_scene(&g, &drawing, &SketchOptions::default()); for (i, node) in scene.nodes.iter_mut().enumerate() { if i == start.index() { node.fill = Some("none".to_string()); node.stroke = Some(Stroke::new("none", 1.6)); continue; } node.shape = svg::Shape::Circle; node.stroke = Some(Stroke::new(INK, 1.75)); if accepting.contains(&i) { let ring = Ring { color: INK.to_string(), width: 1.5, inset: 4.0, }; node.content.push(NodeContent::Rings { rings: vec![ring] }); } } for (i, edge) in scene.edges.iter_mut().enumerate() { edge.stroke = Stroke::new(INK, 1.6); let symbol = transitions[i].2; if !symbol.is_empty() { edge.labels.push(chip(&drawing, i, symbol, INK)); } } Panel::new("a finite automaton", g, &options, drawing).scene(scene, Palette::default()) } ``` -------------------------------- ### Scene builder methods Source: https://github.com/aarkue/graphlay/blob/main/docs/svg.md Builder methods for restyling scenes: label_mut, GlyphRow::dots, NodeContent::symbol, EdgeLabel::new(..).chip(), MarkerRef::builtin(..).colored(..), Decoration::band, LegendItem::new, and Panel::legend. ```APIDOC ## Scene builder methods ### Description Builder methods for restyling scenes: label_mut, GlyphRow::dots, NodeContent::symbol, EdgeLabel::new(..).chip(), MarkerRef::builtin(..).colored(..), Decoration::band, LegendItem::new, and Panel::legend. ``` -------------------------------- ### Layout a networkx graph Source: https://github.com/aarkue/graphlay/blob/main/bindings/python/README.md Use graphlay to calculate positions for a networkx DiGraph and visualize it using networkx.draw. ```python import networkx as nx g = nx.DiGraph([("a", "b"), ("b", "c"), ("a", "c")]) pos = graphlay.layout(g).positions(flip_y=True) nx.draw(g, pos) ``` -------------------------------- ### Create a service map visualization Source: https://github.com/aarkue/graphlay/blob/main/docs/gallery.md This function constructs a service map with nodes organized by tiers, custom edge styling based on request rates, and a legend. It uses GraphBuilder to define nodes and edges, then applies layout options and custom scene styling. ```rust fn service_map() -> Panel { const TIER: [&str; 3] = ["#38bdf8", "#a78bfa", "#34d399"]; let services = [ ("Web app", 0), ("Mobile API", 0), ("Auth", 1), ("Orders", 1), ("Catalog", 1), ("Payments", 1), ("Notify", 1), ("Users DB", 2), ("Orders DB", 2), ("Cache", 2), ("Queue", 2), ]; let mut b = GraphBuilder::new(); let ids: Vec<_> = services .iter() .map(|(name, tier)| { b.add_node(Node { size: Size::new(if *tier == 2 { 96.0 } else { 104.0 }, 40.0), shape: if *tier == 2 { Shape::Ellipse } else { Shape::Box }, key: Some(name.to_string()), ..Node::default() }) }) .collect(); let calls = [ (0, 2, 120.0, "8 ms"), (0, 3, 300.0, "24 ms"), (0, 4, 900.0, "5 ms"), (1, 2, 200.0, "9 ms"), (1, 3, 150.0, "26 ms"), (3, 5, 140.0, "41 ms"), (3, 4, 300.0, "4 ms"), (3, 6, 100.0, "2 ms"), (5, 6, 90.0, "3 ms"), (2, 7, 320.0, "1 ms"), (3, 8, 450.0, "3 ms"), (4, 9, 1200.0, "<1 ms"), (4, 8, 60.0, "6 ms"), (6, 10, 190.0, "1 ms"), (5, 8, 140.0, "2 ms"), ]; for (s, t, _, _) in calls { let mut e = Edge::new(ids[s], ids[t]); e.label_size = Some(Size::new(38.0, 14.0)); b.add_edge(e); } let g = b.build(); let mut options = LayoutOptions::layered_default(); options.direction = Direction::LeftRight; options.spacing.layer_gap = 120.0; options.spacing.node_gap = 40.0; let drawing = layout(&g, &options).expect("lays out"); let mut scene = sketch_scene(&g, &drawing, &SketchOptions::default()); for (i, node) in scene.nodes.iter_mut().enumerate() { node.fill = Some("#1e293b".to_string()); node.stroke = Some(Stroke::new(TIER[services[i].1], 1.75)); if let Some(text) = node.label_mut() { text.color = Some("#e2e8f0".to_string()); text.weight = Some(600.0); } } for (i, edge) in scene.edges.iter_mut().enumerate() { let (s, t, rate, latency): (usize, usize, f64, &str) = calls[i]; let (from, to) = (TIER[services[s].1], TIER[services[t].1]); edge.stroke = Stroke::new(from, 1.2 + 2.6 * rate.ln() / 1200f64.ln()); if from != to { let stop = |offset, colour: &str| GradientStop { offset, color: colour.to_string(), }; edge.stroke.paint = Paint::Gradient(Gradient { from: edge.points[0], to: edge.points[edge.points.len() - 1], stops: vec![stop(0.0, from), stop(1.0, to)], }); edge.marker_end = MarkerRef::builtin(BuiltinMarker::Arrow).colored(to); } edge.labels.push(EdgeLabel { chip: Some(Chip { fill: "#0f172a".to_string(), ..Chip::default() }), ..chip(&drawing, i, latency, "#cbd5e1") }); } let tiers = ["clients", "services", "stores"] .into_iter() .zip(TIER) .map(|(text, colour)| LegendItem::new(Swatch::color(colour), text)); scene.overlays.push(legend(&drawing, "Tiers", tiers)); scene.background = Some("#0b1220".to_string()); // The legend's text takes the palette's text colour. let palette = Palette { node_text: "#e2e8f0".to_string(), ..Palette::default() }; Panel::new("a service map", g, &options, drawing).scene(scene, palette) } ``` -------------------------------- ### JSON request with preset and options patch Source: https://github.com/aarkue/graphlay/blob/main/docs/guide.md Shows the JSON structure for a layout request: a graph with empty nodes and edges, a preset name, and an options patch. The layout merges the patch into the preset and rejects unknown or invalid fields with an error that names the field. ```json { "graph": { "nodes": [], "edges": [] }, "preset": "process_map", "options": { "routing": { "merge_edges": "both" }, "effort": "thorough" } } ``` -------------------------------- ### Commit, tag and push release Source: https://github.com/aarkue/graphlay/blob/main/RELEASING.md Finalize the release by tagging the repository and pushing the changes to the main branch. ```sh git tag vX.Y.Z git push origin main vX.Y.Z ``` -------------------------------- ### json::sketch_scene Source: https://github.com/aarkue/graphlay/blob/main/docs/svg.md Returns the scene as JSON, similar to svg::sketch_scene. ```APIDOC ## json::sketch_scene ### Description Returns the scene as JSON, similar to svg::sketch_scene. ```