diff --git a/backend/tests/test_chart_rendering.py b/backend/tests/test_chart_rendering.py index 72ccd4e17..3acd42ce7 100644 --- a/backend/tests/test_chart_rendering.py +++ b/backend/tests/test_chart_rendering.py @@ -11,7 +11,10 @@ import pytest -from graphlink_chart_rendering import render_chart_png +from matplotlib.figure import Figure +from matplotlib.patches import FancyBboxPatch, PathPatch + +from graphlink_chart_rendering import _build_theme, _render_sankey_chart, render_chart_png _PNG_MAGIC = b"\x89PNG\r\n\x1a\n" @@ -75,3 +78,87 @@ def test_render_chart_png_covers_the_remaining_three_chart_types(chart_type): png_bytes = render_chart_png(chart_type, data, 680.0, 500.0) assert png_bytes.startswith(_PNG_MAGIC) + + +# Match the live SVG regression cases in sankeyLayout.test.ts and inspect +# the actual Matplotlib patch geometry, not merely whether a PNG was returned. +@pytest.mark.parametrize("flows", [ + [{"source": f"A{i}", "target": f"B{i}", "value": 1.0} for i in range(count)] + for count in (30, 150, 300) +] + [ + [ + {"source": "A", "target": "B", "value": 1000.0}, + {"source": "A", "target": "C", "value": 1.0}, + {"source": "B", "target": "D", "value": 1000.0}, + {"source": "C", "target": "D", "value": 1.0}, + {"source": "X", "target": "Y", "value": 0.1}, + ], + [ + {"source": "A", "target": "B", "value": 0.01}, + {"source": "A", "target": "C", "value": 0.03}, + ], + [ + {"source": "A", "target": "B", "value": 1e308}, + {"source": "A", "target": "C", "value": 1e308}, + ], +], ids=["dense-30", "dense-150", "dense-300", "skewed", "fractional", "overflow"]) +def test_sankey_nodes_and_ribbons_fit_and_preserve_flow_proportions(flows): + figure = Figure() + ax = figure.add_subplot() + _render_sankey_chart(figure, ax, {"flows": flows}, _build_theme()) + + nodes = [patch for patch in ax.patches if isinstance(patch, FancyBboxPatch)] + ribbons = [patch for patch in ax.patches if isinstance(patch, PathPatch)] + by_name = {label.get_text(): node for label, node in zip(ax.texts, nodes)} + assert len(nodes) == len({flow[key] for flow in flows for key in ("source", "target")}) + assert len(ribbons) == len(flows) + + # The renderer orders ribbons by source column, source y, and target y. + ordered = sorted(flows, key=lambda flow: ( + by_name[flow["source"]].get_x(), + by_name[flow["source"]].get_y(), + by_name[flow["target"]].get_y(), + )) + max_value = max(flow["value"] for flow in flows) + scale = max(path.get_path().vertices[7, 1] - path.get_path().vertices[0, 1] + for path in ribbons) + assert scale > 0 + epsilon = 1e-10 + ports = {name: {"in": [], "out": []} for name in by_name} + for flow, ribbon in zip(ordered, ribbons): + vertices = ribbon.get_path().vertices + source, target = by_name[flow["source"]], by_name[flow["target"]] + start, end = (vertices[0, 1], vertices[7, 1]), (vertices[3, 1], vertices[4, 1]) + assert vertices[0, 0] == pytest.approx(source.get_x() + source.get_width(), abs=epsilon) + assert vertices[3, 0] == pytest.approx(target.get_x(), abs=epsilon) + expected = flow["value"] / max_value * scale + assert start[1] - start[0] == pytest.approx(expected, abs=epsilon) + assert end[1] - end[0] == pytest.approx(expected, abs=epsilon) + ports[flow["source"]]["out"].append(start) + ports[flow["target"]]["in"].append(end) + + for name, node in by_name.items(): + bounds = node.get_path().get_extents() + assert bounds.xmin >= 0 + assert bounds.xmax <= 1 + assert bounds.ymin >= 0.09 - epsilon + assert bounds.ymax <= 0.91 + epsilon + weight = max( + sum(flow["value"] / max_value for flow in flows if flow["source"] == name), + sum(flow["value"] / max_value for flow in flows if flow["target"] == name), + ) + assert node.get_height() > 0 + assert node.get_height() == pytest.approx(weight * scale, abs=epsilon) + for side in ports[name].values(): + cursor = node.get_y() + for start, end in sorted(side): + assert start == pytest.approx(cursor, abs=epsilon) + assert end > start + assert end <= node.get_y() + node.get_height() + epsilon + cursor = end + + columns = {node.get_x() for node in nodes} + for x in columns: + column = sorted((node for node in nodes if node.get_x() == x), key=lambda node: node.get_y()) + for previous, current in zip(column, column[1:]): + assert current.get_y() >= previous.get_y() + previous.get_height() - epsilon diff --git a/graphlink_chart_rendering.py b/graphlink_chart_rendering.py index 107c01dc9..a7b43b555 100644 --- a/graphlink_chart_rendering.py +++ b/graphlink_chart_rendering.py @@ -795,18 +795,22 @@ def _render_sankey_chart(figure, ax, chart_data: dict[str, Any], theme: dict[str if node not in levels: levels[node] = max((levels.get(flow["source"], 0) + 1 for flow in incoming[node]), default=0) + # Normalize before summing to avoid overflowing finite flow values. + # Keep these geometry rules in sync with sankeyLayout.ts. + max_flow_value = max((flow["value"] for flow in flows), default=1.0) or 1.0 column_map = defaultdict(list) node_weights = {} for node in nodes: node_weights[node] = max( - sum(flow["value"] for flow in outgoing[node]), - sum(flow["value"] for flow in incoming[node]), - 1.0, + sum(flow["value"] / max_flow_value for flow in outgoing[node]), + sum(flow["value"] / max_flow_value for flow in incoming[node]), ) column_map[levels[node]].append(node) - column_gap = 0.03 chart_height = 0.82 + # Keep at least half the height available for nodes in the densest column. + largest_column = max((len(column) for column in column_map.values()), default=1) + column_gap = min(0.03, chart_height / (2 * max(1, largest_column - 1))) available_columns = max(column_map.keys()) + 1 if column_map else 1 global_scale = None for column_nodes in column_map.values(): @@ -816,7 +820,7 @@ def _render_sankey_chart(figure, ax, chart_data: dict[str, Any], theme: dict[str continue column_scale = available_height / total_weight global_scale = column_scale if global_scale is None else min(global_scale, column_scale) - scale = global_scale or 0.04 + scale = global_scale if global_scale is not None else 0.0 x_start = 0.08 x_end = 0.92 @@ -862,7 +866,8 @@ def _render_sankey_chart(figure, ax, chart_data: dict[str, Any], theme: dict[str for flow in sorted_flows: source_layout = node_layout[flow["source"]] target_layout = node_layout[flow["target"]] - thickness = max(flow["value"] * scale, 0.008) + # The stroke can aid visibility without inflating the filled area. + thickness = (flow["value"] / max_flow_value) * scale start_y0 = outgoing_cursor[flow["source"]] start_y1 = start_y0 + thickness @@ -920,7 +925,7 @@ def _render_sankey_chart(figure, ax, chart_data: dict[str, Any], theme: dict[str (layout["x"], layout["y"]), layout["width"], layout["height"], - boxstyle="round,pad=0.003,rounding_size=0.01", + boxstyle=f"round,pad=0,rounding_size={min(0.01, layout['width'] / 2, layout['height'] / 2)}", facecolor=node_color, edgecolor=_mpl_rgba(theme["text"], 70 / 255), linewidth=1.0, diff --git a/web_ui/src/app/canvas/charts/SankeyChartMarks.tsx b/web_ui/src/app/canvas/charts/SankeyChartMarks.tsx index 83a771f06..aad096430 100644 --- a/web_ui/src/app/canvas/charts/SankeyChartMarks.tsx +++ b/web_ui/src/app/canvas/charts/SankeyChartMarks.tsx @@ -90,7 +90,7 @@ export function SankeyChartMarks({ chartData, theme, width, height, onHover, wra x={node.x} y={node.y} width={node.width} - height={Math.max(1, node.height)} + height={node.height} fill={colorByNode.get(node.name)} stroke={theme.text} strokeOpacity={0.28} diff --git a/web_ui/src/app/canvas/charts/sankeyLayout.test.ts b/web_ui/src/app/canvas/charts/sankeyLayout.test.ts index 68da011f7..f25b89a0a 100644 --- a/web_ui/src/app/canvas/charts/sankeyLayout.test.ts +++ b/web_ui/src/app/canvas/charts/sankeyLayout.test.ts @@ -72,6 +72,88 @@ describe("computeSankeyLayout", () => { }); }); +describe("bounded Sankey geometry", () => { + const cases = [ + ...[30, 150, 300].map((count) => ({ + name: `${count} disconnected flows`, + flows: Array.from({ length: count }, (_, i) => ({ source: `A${i}`, target: `B${i}`, value: 1 })), + })), + { + name: "skewed fan-out and fan-in with a disconnected fractional flow", + flows: [ + { source: "A", target: "B", value: 1000 }, + { source: "A", target: "C", value: 1 }, + { source: "B", target: "D", value: 1000 }, + { source: "C", target: "D", value: 1 }, + { source: "X", target: "Y", value: 0.1 }, + ], + }, + { + name: "fractional flows", + flows: [ + { source: "A", target: "B", value: 0.01 }, + { source: "A", target: "C", value: 0.03 }, + ], + }, + { + name: "finite flows with an overflowing raw total", + flows: [ + { source: "A", target: "B", value: 1e308 }, + { source: "A", target: "C", value: 1e308 }, + ], + }, + ]; + + it.each(cases)("fits all nodes and conserves proportional ports: $name", ({ flows }) => { + const layout = computeSankeyLayout(flows); + const byName = new Map(layout.nodes.map((node) => [node.name, node])); + const maxValue = Math.max(...flows.map((flow) => flow.value)); + const scale = Math.max(...layout.flows.map((flow) => flow.startY1 - flow.startY0)); + const epsilon = 1e-10; + expect(layout.flows).toHaveLength(flows.length); + expect(scale).toBeGreaterThan(0); + for (const node of layout.nodes) { + expect(node.x).toBeGreaterThanOrEqual(0); + expect(node.x + node.width).toBeLessThanOrEqual(1); + expect(node.y).toBeGreaterThanOrEqual(0.09 - epsilon); + expect(node.y + node.height).toBeLessThanOrEqual(0.91 + epsilon); + expect(node.height).toBeGreaterThan(0); + const outgoing = layout.flows.filter((flow) => flow.source === node.name); + const incoming = layout.flows.filter((flow) => flow.target === node.name); + const weight = Math.max( + outgoing.reduce((sum, flow) => sum + flow.value / maxValue, 0), + incoming.reduce((sum, flow) => sum + flow.value / maxValue, 0), + ); + expect(node.height).toBeCloseTo(weight * scale, 10); + for (const ports of [ + outgoing.map((flow) => [flow.startY0, flow.startY1]), + incoming.map((flow) => [flow.endY0, flow.endY1]), + ]) { + let cursor = node.y; + for (const [start, end] of ports.sort((a, b) => a[0] - b[0])) { + expect(start).toBeCloseTo(cursor, 10); + expect(end).toBeGreaterThan(start); + expect(end).toBeLessThanOrEqual(node.y + node.height + epsilon); + cursor = end; + } + } + } + for (const flow of layout.flows) { + const expected = (flow.value / maxValue) * scale; + expect(flow.startY1 - flow.startY0).toBeCloseTo(expected, 10); + expect(flow.endY1 - flow.endY0).toBeCloseTo(expected, 10); + expect(flow.x0).toBeCloseTo(byName.get(flow.source)!.x + byName.get(flow.source)!.width, 10); + expect(flow.x1).toBeCloseTo(byName.get(flow.target)!.x, 10); + } + for (let level = 0; level <= layout.maxLevel; level += 1) { + const column = layout.nodes.filter((node) => node.level === level).sort((a, b) => a.y - b.y); + for (let i = 1; i < column.length; i += 1) { + expect(column[i].y).toBeGreaterThanOrEqual(column[i - 1].y + column[i - 1].height - epsilon); + } + } + }); +}); + describe("sankeyFlowPath", () => { it("builds a closed SVG ribbon path from the flow's geometry", () => { const layout = computeSankeyLayout([{ source: "A", target: "B", value: 5 }]); diff --git a/web_ui/src/app/canvas/charts/sankeyLayout.ts b/web_ui/src/app/canvas/charts/sankeyLayout.ts index a43c443a1..b320de175 100644 --- a/web_ui/src/app/canvas/charts/sankeyLayout.ts +++ b/web_ui/src/app/canvas/charts/sankeyLayout.ts @@ -44,8 +44,6 @@ const COLUMN_GAP = 0.03; const CHART_HEIGHT = 0.82; const X_START = 0.08; const X_END = 0.92; -const FALLBACK_SCALE = 0.04; -const MIN_FLOW_THICKNESS = 0.008; export function computeSankeyLayout(flows: ChartFlowRow[]): SankeyLayout { const outgoing = new Map(); @@ -87,27 +85,34 @@ export function computeSankeyLayout(flows: ChartFlowRow[]): SankeyLayout { } } + // Normalize before summing: even individually finite flow values can + // overflow a node or column total. Use the same unit for every port. + const maxFlowValue = flows.reduce((max, flow) => Math.max(max, flow.value), 0) || 1; const nodeWeights = new Map(); const columnMap = new Map(); for (const node of nodes) { - const outWeight = (outgoing.get(node) ?? []).reduce((sum, flow) => sum + flow.value, 0); - const inWeight = (incoming.get(node) ?? []).reduce((sum, flow) => sum + flow.value, 0); - nodeWeights.set(node, Math.max(outWeight, inWeight, 1.0)); + const outWeight = (outgoing.get(node) ?? []).reduce((sum, flow) => sum + flow.value / maxFlowValue, 0); + const inWeight = (incoming.get(node) ?? []).reduce((sum, flow) => sum + flow.value / maxFlowValue, 0); + nodeWeights.set(node, Math.max(outWeight, inWeight)); const level = levels.get(node) ?? 0; if (!columnMap.has(level)) columnMap.set(level, []); columnMap.get(level)!.push(node); } const availableColumns = columnMap.size ? Math.max(...columnMap.keys()) + 1 : 1; + // Preserve ordinary spacing, but reserve at least half the chart height + // for nodes even in the densest column. + const largestColumn = Math.max(1, ...[...columnMap.values()].map((column) => column.length)); + const columnGap = Math.min(COLUMN_GAP, CHART_HEIGHT / (2 * Math.max(1, largestColumn - 1))); let globalScale: number | null = null; for (const columnNodes of columnMap.values()) { const totalWeight = columnNodes.reduce((sum, node) => sum + (nodeWeights.get(node) ?? 0), 0); - const availableHeight = CHART_HEIGHT - COLUMN_GAP * Math.max(0, columnNodes.length - 1); + const availableHeight = CHART_HEIGHT - columnGap * Math.max(0, columnNodes.length - 1); if (totalWeight <= 0 || availableHeight <= 0) continue; const columnScale = availableHeight / totalWeight; globalScale = globalScale === null ? columnScale : Math.min(globalScale, columnScale); } - const scale = globalScale ?? FALLBACK_SCALE; + const scale = globalScale ?? 0; const step = (X_END - X_START) / Math.max(1, availableColumns - 1); const nodeWidth = Math.min(0.05, step * 0.28); @@ -120,12 +125,12 @@ export function computeSankeyLayout(flows: ChartFlowRow[]): SankeyLayout { }); const totalHeight = columnNodes.reduce((sum, node) => sum + (nodeWeights.get(node) ?? 0) * scale, 0) + - COLUMN_GAP * Math.max(0, columnNodes.length - 1); + columnGap * Math.max(0, columnNodes.length - 1); let currentY = 0.5 - totalHeight / 2; for (const node of columnNodes) { const height = (nodeWeights.get(node) ?? 0) * scale; nodeLayout.set(node, { name: node, x: X_START + level * step, y: currentY, width: nodeWidth, height, level }); - currentY += height + COLUMN_GAP; + currentY += height + columnGap; } } @@ -148,7 +153,9 @@ export function computeSankeyLayout(flows: ChartFlowRow[]): SankeyLayout { const flowLayouts: SankeyFlowLayout[] = sortedFlows.map((flow) => { const sourceLayout = nodeLayout.get(flow.source)!; const targetLayout = nodeLayout.get(flow.target)!; - const thickness = Math.max(flow.value * scale, MIN_FLOW_THICKNESS); + // A minimum filled width would misstate the value and overflow ports. + // The renderer's stroke is independent of the quantitative ribbon area. + const thickness = (flow.value / maxFlowValue) * scale; const startY0 = outgoingCursor.get(flow.source)!; const startY1 = startY0 + thickness;