◆ How it works
How it works
An invented city goes through the whole pipeline, one step at a time. Every figure below was generated by the library, from its public functions; the numbers in the captions come from the same run.
The city has 36 places and 783 origin–destination flows (trips per working day from a gravity model; total volume 44,038). The data is in cidade.json; the run is the default one with grouping and the schematic layout:
milkflow cidade.json --group --schematic
In Rust, the same with the steps in view:
// The same as pipeline::run (Algorithm R), step by step;
// checked in site/tools/figuras/examples/etapas.rs
let problem = problem::build(&input, true)?; // (a) (b)
let design = filter::top_k(&problem, 3); // (c)
let start = skeleton::delaunay(&problem); // (d)
let scale = skeleton::reference_scale(&problem, &design, &start);
let prune = PruneOptions { mu: 4.0 * scale, max_stretch: None, keep_connected: true };
let corridor = skeleton::prune(&problem, &design, &start, &prune); // (e)
let all = filter::all(&problem);
let routing = route::route(&problem, &corridor, &all); // (f)
let spec = spec::build(&problem, &corridor, &routing, &all, input.nodes.len(), params); // (g) (h)
let turns = flowmodel::turns(&problem, &routing);
let esq = schematize::schematize(&spec, &turns, &SchematicOptions::default()); // (i)
let svg = svg::render(&spec, &Style::fitted(&spec, &Style::default())); // (j)
(a)Input: places and every pair
The input is a list of nodes (id, x, y in planar coordinates, y up) and a list of flows (origin, destination, value ≥ 0). Validation refuses unknown ids, non-finite or negative values and non-additive input; it sums repeated pairs, drops zeros and merges nodes on the same point (with a warning). Coordinates are rounded to 1/1024 of the unit before any decision.
svg::render_pairs). Flows from a place to itself (2,300) become the place's internal flow.(b)Aggregation by group
With group on, the nodes that share a group become one place, at the weighted centroid of the members (by each one's weight when all have one; otherwise by the volume that starts or ends at the node). Here: Centro (Centro, Matriz, Mercado, Estação); Porto (Cais, Porto, Canal); Serra (Alto da Serra, Floresta). Flow between members of the same group becomes internal flow: a ring around the symbol, never a segment.
Levels: the same file aggregated two ways
The city's nodes also carry their groups at two levels, in groups: bairro (the three groups above; a node with no group at that level stays alone) and regiao (five regions, which contain the bairros). With group: "bairro" comes the figure above; with group: "regiao", that of the regions. The same file, no other option: 30 places and 31% of the volume internal at the first level, 5 places and 49% internal at the second. Since the levels nest, the internal share can only grow; the accounting closes at both.
group: "bairro"37 segments · mean detour 1.16, max. 5.97 · 69% of the volume in corridors{"group": "bairro", "style": {"lang": "en"}}
milkflow cidade.json --title "" --group bairro --lang engroup: "regiao"4 segments · mean detour 1.11, max. 1.55 · 51% of the volume in corridors{"group": "regiao", "style": {"lang": "en"}}
milkflow cidade.json --title "" --group regiao --lang enA level that no node has is refused, rather than drawing every node alone. That the levels nest is the caller's promise; it is not checked. The input is in the reference.
Automatic aggregation: without given groups
Without groups, aggregate: {"to": 15} (--aggregate 15) merges neighbouring places until 15 remain. Neighbours are the Gabriel edges of the Delaunay triangulation up to 4 times their median, contracted after each merge. With the default method, ward, each step merges the neighbouring pair of least ma·mb/(ma+mb)·d² (d between the volume-weighted centroids): compact groups of similar weight, and Recife and Olinda, heavy and side by side, join early. With "method": "gravity", the group of smallest volume joins the neighbour of largest volume / distance², and heavy places hold out to the end. Each group sits at the position and takes the name of its heaviest place, and what runs inside it becomes its ring. Both methods are spatial and ignore who exchanges flow with whom. A place without a near neighbour (Fernando de Noronha, Natal, the capitals of other states) stays alone, off the frame, and does not count in the 15; the width classes fit the segments between the others.
{"k": 1, "style": {"frame_on_boundary": true, "max_labels": 40, "lang": "en"}}
milkflow regic_pe.json --title "" --k 1 --frame boundary --labels 40 --lang enaggregate: {"to": 15}23 segments · mean detour 1.32, max. 9.40 · 52% of the volume in corridors{"k": 1, "aggregate": {"to": 15}, "style": {"frame_on_boundary": true, "max_labels": 40, "lang": "en"}}
milkflow regic_pe.json --title "" --aggregate 15 --k 1 --frame boundary --labels 40 --lang en(c)Top-k filter: the design pairs
The filter decides which pairs design the skeleton (the design pairs). A pair is kept if it is among the k largest leaving its origin or among the k largest arriving at its destination (the union). Ties are broken by (value, origin, destination). With k = 3, 154 of the 468 pairs are design pairs, with 77% of the volume between places.
The other pairs do not vanish: by default (represent: "all") every pair is routed through the finished skeleton; they just have no say in it. The union guarantees a small place its own largest links, but no share of its volume; that is measured afterwards (coverage per place).
Seen from one place: Lagoa Azul
| destination | value | rank at origin | rank at destination | design? |
|---|---|---|---|---|
| Centro | 675 | 1 | 5 | yes |
| Porto | 131 | 2 | 8 | yes |
| Monte Alegre | 78 | 3 | 4 | yes |
| Ponte Seca | 64 | 4 | 4 | no |
| Ladeira | 59 | 5 | 5 | no |
| Rio Doce | 40 | 6 | 2 | yes |
| Vila Nova | 28 | 7 | 13 | no |
| Cajueiro | 27 | 8 | 4 | no |
The 8 largest of 23.
| origin | value | rank at origin | rank at destination | design? |
|---|---|---|---|---|
| Centro | 333 | 4 | 1 | yes |
| Porto | 92 | 8 | 2 | yes |
| Ponte Seca | 84 | 4 | 3 | yes |
| Ladeira | 77 | 3 | 4 | yes |
| Monte Alegre | 73 | 4 | 5 | no |
| Rio Doce | 57 | 2 | 6 | yes |
| Cajueiro | 39 | 4 | 7 | no |
| Serra | 37 | 10 | 8 | no |
The 8 largest of 23.
A pair is a design pair when its rank at the origin or at the destination is at most k. So a pair that is small for the place it leaves can stay because it is large for the place it reaches, and vice versa.
Top-k is the default filter. The filter option swaps it for another: dominant flow (Nystuen and Dacey), disparity backbone (Serrano et al.), the largest pairs up to a share of the volume, the n largest or a threshold. The same data under each one is in Filters.
(d)Delaunay triangulation: the starting skeleton
The candidate corridors are the edges of the Delaunay triangulation of the places: a planar graph, with no crossings, that joins each place to its near neighbours. Here there are 78 edges. With fewer than three places, or all of them on a line, the skeleton is the path along the line.
Not guaranteed: the Delaunay triangulation itself can stretch a path to more than 1.59 times the straight distance; its in-circle test is not exact, so for (nearly) cocircular places the diagonal chosen may differ from the exact Delaunay one (always the same one, though, for the same coordinates).
(e)Pruning, and what mu does
Pruning trades ink for detour. It minimizes
J(G) = Σ_{e ∈ G} len(e) + mu · Σ_{p design} f̂_p · d_G(o_p, d_p)
the sum of the edge lengths (the ink) plus mu times the mean path length of the design pairs, weighted by value (f̂, normalized to add up to 1). Starting from the whole Delaunay triangulation, each step removes the edge whose removal lowers J the most, with the exact change computed for every candidate, until no removal lowers J. An edge that would disconnect a design pair stays; a bridge never leaves (the skeleton stays connected and every routable pair stays routable).
mu is measured on a reference scale (the ink of the minimum spanning tree over the mean straight distance of the design pairs), so that the same value suits different data. Larger mu, more segments and less detour:
Detour of a pair = path length in the skeleton ÷ straight distance; the mean is weighted by the value of the routed pairs. Not guaranteed: pruning is greedy, with no approximation ratio (the gap to the optimum is measured on small instances, not bounded); the detour is bounded only with max_stretch, and only for design pairs; the number of segments is not necessarily monotone in mu.
(f)Routing: paths and loads
Every represented pair follows the shortest path of the skeleton, in Euclidean length. Among paths of equal length the neighbour with the smallest index wins, so the result does not depend on the order of iteration. The load of a segment is the sum of the values of the pairs that run through it, kept by direction (flow_ab, flow_ba).
- Serra – Barro Branco: load 1,494
- Barro Branco – Quinta: load 3,103
- Quinta – Centro: load 5,112
What a load does not say
The load of Quinta – Centro adds up every pair whose shortest path runs there, not only Serra → Centro. Once summed, the loads cannot be taken back to the pairs:
(g)Width classes and the legend
Width is not continuous: it comes in at most 5 classes, with breaks at round numbers of the series 1, 2, 5 × 10k between the smallest and the largest load (evenly spaced along the series when there are more candidates). The class of a load is the number of breaks not above it. Here the 37 loads fall like this:
| class | from | to | width (px) | segments |
|---|---|---|---|---|
| 0 | 89 | 100 | 1.5 | 1 |
| 1 | 100 | 200 | 3.0 | 2 |
| 2 | 200 | 1,000 | 5.5 | 13 |
| 3 | 1,000 | 2,000 | 9.0 | 11 |
| 4 | 2,000 | 5,112 | 14.0 | 10 |
In the final figure the legend shows the classes (“Width = volume”), the place symbol (origin and destination) and the internal-flow ring. The size of a place measures the routed volume that starts or ends there, never what passes through it. A single colour, the accent, carries the corridors; volume is never coded by colour.
Not guaranteed: the breaks depend on the figure's own data; two figures are comparable only if drawn with the same legend, and there is no option yet to fix the breaks. Classes hide differences within a class.
svg::render). The legend and the honesty line are written by the library, in the language of style.lang (here "en"; Portuguese by default).(h)Accounting: where every unit of volume went
Every pair falls in exactly one bucket: in corridors (represented and with a path), internal (inside a place or group), filtered (not represented) or without a path (represented, but the skeleton does not reach it). The four add up to the total, and that is checked. Coverage is in corridors ÷ total, each pair counted once: the sum of the segment loads is not a coverage, since a pair that runs through three segments would count three times.
- in corridors 30,337 · 68.9%
- internal 13,701 · 31.1%
- filtered 0 · 0.0%
- without a path 0 · 0.0%
- total 44,038
represent: "design")- in corridors 23,397 · 53.1%
- internal 13,701 · 31.1%
- filtered 6,940 · 15.8%
- without a path 0 · 0.0%
- total 44,038
skeleton: "input")- in corridors 30,140 · 68.4%
- internal 13,701 · 31.1%
- filtered 0 · 0.0%
- without a path 197 · 0.4%
- total 44,038
With the default pruned skeleton nothing is left without a path (pruning keeps bridges). With represent: "design", 314 pairs (15.8% of the volume) are filtered. With the user skeleton lacking the edges of Cerro and Mirante, 197 units (15 pairs) have no path. The figure sums this up in its honesty line (“69% of the volume in 37 segments · 31% internal to the groups”: 69% of the volume in 37 segments, 31% internal to the groups), and what was left out shows as a grey stub at the place of origin or destination.
(i)Schematic layout: from geographic to octilinear
The schematic mode redraws the same FlowSpec as a metro map: only the drawn positions (pos) and the paths (path) change; ids, geography, loads and classes stay. The method is routing on an octilinear grid (Bast, Brosi and Storandt, 2020) with Nöllenburg and Wolff's (2006) port constraints and bends weighted by the flow that continues:
- Targets. Very long bridges are shortened (far destinations stop dictating the frame) and the dense centre is opened by a proximity stress, keeping the frame and the direction of every segment.
- Grid and routing. On an octilinear grid the segments are routed one by one, heaviest first, by Dijkstra over (cell, direction of arrival, bends); occupied cells and crossing diagonals are forbidden. With no path the order changes and it restarts; then the grid grows.
- Degree-2 chains. A path of degree-2 places between two nodes of another degree (a metro line between two interchanges) is routed as one segment; then the places are set on the path by exact dynamic programming, each where its ports keep H6, on a bend when it can and evenly spaced. A chain that cannot hold its places is cut at its middle; with no layout at all the grid is laid out again without contraction, so contraction never makes a feasible case infeasible.
- Local search. Each node tries nearby cells and those that align its heaviest segment, and stays where the total cost drops.
- Independent check. The result comes out only with zero violations of the hard rules H1–H6; otherwise the geographic figure stands and the reason is recorded.
What contracting the chains changes
The same layout with and without contraction (option contract_chains of SchematicOptions, Rust only; on by default), measured by the independent check (schematize::check) when this site was built:
| data | places | chains contracted | bends inside segments | relative length | mean bend at nodes | H1–H6 violations |
|---|---|---|---|---|---|---|
| Synthetic city (grouped) | 30 | 7 | 6 → 4 | ×0.96 → ×0.96 | 0.83 → 0.84 | 0 / 0 |
REGIC (PE), k = 1 | 214 | 55 | 18 → 7 | ×2.15 → ×2.08 | 0.38 → 0.36 | 0 / 0 |
Without → with contraction. Contraction trades bends inside segments for bends at the places (C3 puts the place on the bend when it can): fewer drawn kinks and, on some data, a slightly higher flow-weighted mean bend at the nodes. The geographic figure does not change a byte.
Directions, sectors and bends
The hard rules
H1 · octilinear pieces, at most 3
H2 · the circular order of the neighbours
H3 · no crossings
H4 · least distances
min_node_gap · D apart and every segment is at least min_segment · D long (D: diagonal of the geographic box).H5 · degree at most 8
H6 · at most 45° from the real direction
sector_slack = 1). It is the “controlled deformation”.Not guaranteed: the result is a heuristic optimum, not the minimum cost; a layout may exist and not be found; widths and labels are not part of the computation (a path may pass one step from an unrelated node); the relative position of two non-adjacent nodes may change; the places of a contracted chain keep their order along it, not their distance to unrelated nodes; the boundary is not deformed (it is left out of the schematic figure).
(j)Styles
The same FlowSpec, drawn with other styles (Style). The SVG is a pure function of the spec and the style: changing the style redoes no computation.
theme: "light" (default): light paper, red corridors.theme: "dark": dark paper, coral corridors.theme: "print": greys only, for black-and-white printing.theme: "basemap": no background, land not filled, white halos, corridors at 0.85 opacity, to lay over a base map (here, over a checkerboard).stroke: "rails": class c becomes c + 1 thin parallel rails.directions: "split": one lane per direction, keeping right, each with the class of its own volume. Still weak in a dense centre.On the command line: --theme light|dark|print|basemap, --stroke solid|rails, --directions sum|split, --opacity X. Rails and split directions do not combine (the program refuses; the library draws the lanes solid). There are also palettes, mitred or smooth corners, square places, rails with parameters, one colour per direction and the language of the texts: Styles shows each one with the options that make it, and the reference lists them all.
(k)Lines by category (when the flows have a category)
This city has no categories. When the flows carry a category (and lines is "auto", the default), the pipeline takes five more steps, without changing the skeleton or the total loads:
problem::build_categorized: the categories in canonical order, at mostmax_categories; the smallest ones and the flows without a category become “other”.route::loads_by_category: each segment's load by category and direction, on the same paths as (f).spec::add_lines: the lines of each segment (segments[].lines) and the legend's categories; a segment's lines add up exactly to its load.flowmodel::category_turnsandlanes::connect: where each line continues at each node (next_a,next_b).lanes::apply: the order of the lines on each segment that minimizes the crossings at the nodes (by a heuristic), recorded inmeta.metrics.line_crossings.
The drawing then shows one coloured line per category, with connectors at the nodes. All of it is in Lines, with real data: the network of urban influence in Pernambuco, one line per regional network.