A table of 9 plots stores 0 facts about who touches whom. Typed as a graph, the same block holds 20 touches, 6 frontages and 5 street joins, and a model can learn a different rule for each.
Step through the four builds of one toy block. Watch the node types, the edge types and the relation count grow. Then we build each layer from zero: cells, streets, transit, flows, composed paths, tensors and one GNN layer worked by hand.
You need a little Python and what a matrix multiply is. We build graphs, node types and message passing from zero.
The code follows the open source city2graph library (version 1.1.0, BSD 3-Clause), described in Sato, Pietrostefani, Mahabir and Arribas-Bel, Computers, Environment and Urban Systems 130, 102492 (2026). Docs at city2graph.net.
An illustrative toy block. Edge names are the library's own: touched_to, connected_to and faced_to come from morphological_graph; is_nearby from bridge_nodes. We made up the bus line and the metapath name.
Chapter 0
Count the facts a table cannot hold, and see what a raster throws away
A planner hands you a file of 2,000 buildings and asks which streets lack shops. You load it. It is a table: one row per building, columns for area, height and use. It looks like every other dataset.
A table assumes its rows are independent: knowing one row tells you nothing about another. A city breaks that rule. A corner shop tells you a lot about the three houses beside it. They share a street, a bus stop and a wall.
Every fact like "these two touch" or "these two face the same street" is about a pair. How many pairs can 12 buildings form? Call the number of buildings n.
Pairs equals n times n minus one, all over two.
Give each of the n buildings its n − 1 partners. Halve the total, because you counted every pair from both ends.
With n = 12: 12 × 11 / 2 = 66 pairs. The table has 12 × 6 = 72 cells and none of them means "row 3 and row 7". With n = 2,000 there are 1,999,000 pairs against 2,000 rows.
Each dot is a building. Each faint line is one pair a relation could fill. Slide the count and watch the pairs grow faster than the rows.
The pair count is exact. Which pairs hold a real relation depends on the rule you choose, which is the subject of Chapters 2 to 6.
The usual escape is a raster: burn the map into a pixel grid and give it to a convolutional network. A raster keeps where things are. It drops what is joined to what. A crossroads and a bridge both burn in as an X of road pixels. At one you can turn. At the other you cannot.
A graph is a set of nodes (the things) and a set of edges (pairs of things in some relation). A spatial graph also gives each node a geometry: a point, a line or a polygon. city2graph builds these from GeoPandas tables and hands the same graph to NetworkX or PyTorch Geometric.
Failure. The symptom is a model that ignores neighbourhood: two identical shops score the same, one on a high street and one behind a warehouse. To measure it, shuffle the row order of the neighbours' features; if the score does not move, the model never saw them. The fix is to store the relations as edges.
Chapter 1
Give every node a type and every edge a typed triple, so cells and streets keep their own features and rules
You have a graph of plots that touch. Now you add the streets, because the street a plot faces decides its customers. Where do the streets go?
Put them in the same node list and you get a homogeneous graph: one node type, one edge type. Two things break. A plot has an area in square metres; a street has a speed limit in km/h. One feature matrix forces them into the same column, so a mean over neighbours averages 340 m² with 30 km/h. And one weight matrix must serve both "a plot I touch" and "the street I face".
Plot p1 has one plot neighbour and one street neighbour. Choose flat or typed, then slide the hidden size of the layer.
Illustrative features. The weight count assumes one d by d matrix per edge type plus one self matrix per node type, for 3 node types and 5 edge types.
The fix is a heterogeneous graph: one graph where every node has a type and every edge has a type. Each node type keeps its own feature table, so plots may have 23 columns and streets 7. Each edge type gets its own weight matrix.
city2graph and PyTorch Geometric name an edge type as (source type, relation, target type), for example ("place", "faced_to", "movement"). The relation name alone is not enough: is_nearby can join a stop to a street or a plot to a stop. The triple picks the source feature table, the weight matrix and the target table.
pythonnodes = { # one GeoDataFrame per node type "place": place_gdf, # index = place_id, geometry = polygon "movement": movement_gdf, # index = movement_id, geometry = linestring } edges = { # one GeoDataFrame per edge triple ("place", "touched_to", "place"): p2p_gdf, # MultiIndex (place_id, place_id) ("movement", "connected_to", "movement"): m2m_gdf, ("place", "faced_to", "movement"): p2m_gdf, # MultiIndex (place_id, movement_id) }
Two rules in that snippet cause most first-day bugs. Node ids come from the GeoDataFrame index, not from a column. Edge endpoints come from a two-level MultiIndex: source id, then target id.
Worked number, with d = 64, 3 node types and 5 edge types. A homogeneous layer has 64 × 64 = 4,096 weights. A typed layer has (5 + 3) × 4,096 = 32,768. Eight times more, and still tiny.
Failure. Types cost data, not memory. Each edge type needs enough edges to fit its matrix. Measure it before training: count the rows of every edge table. A relation with 40 edges in the whole city fits noise; merge it or drop it.
Chapter 2
Tessellate the space around buildings, join it to the streets, and choose between the queen and rook rules
Make buildings the nodes and join the ones that touch. On a terraced street the row houses share walls, so you get a chain. One street over, the houses stand apart. The graph has 300 nodes and 0 edges. You measured walls, but the space between the houses holds the suburb together.
The fix is a morphological tessellation: cut the ground into one cell per building, where each cell holds the land closer to that building than to any other. The cells tile the ground, so neighbours always touch. city2graph calls these cells place nodes and the street segments movement nodes. The street network also cuts the ground into blocks first, so a cell never spills across a road.
| Edge triple | Means |
|---|---|
(place, touched_to, place) | the two cells share a boundary |
(movement, connected_to, movement) | the two segments meet at a junction |
(place, faced_to, movement) | the cell fronts onto that segment |
What counts as "touching"? The rook rule joins cells that share an edge. The queen rule also joins cells that share only a corner. The library default is queen. Take an n by n grid of cells. Call the rook edge count Erook and the queen count Equeen.
E-queen equals two n times n minus one, plus two times n minus one squared.
Count the side-by-side pairs along rows and columns: that is E-rook. Add two diagonals for every 2 by 2 block: that is E-queen.
With n = 3: E-rook = 2 × 3 × 2 = 12, and E-queen = 12 + 2 × 4 = 20. Check with degrees under rook: 4 corners of degree 2, 4 sides of degree 3, 1 centre of degree 4 give 8 + 12 + 4 = 24 = 2 × 12.
Warm squares are tessellation cells. Choose a rule and drag the grid size. Corner edges are the dashed ones.
A perfect grid is a toy. Real tessellation cells are irregular polygons, so real counts vary cell by cell.
Which rule is right depends on what the edge means. Shared walls and fences: rook. "You can see each other": queen. On real footprints an exact corner touch is fragile; a coordinate rounded in the seventh decimal flips a queen edge.
pythonimport city2graph as c2g nodes, edges = c2g.morphological_graph( buildings_gdf, segments_gdf, center_point=centre, distance=500, # 500 m along the street network, not a circle contiguity="queen", keep_buildings=True, )
Failure. A railway with no crossing still lets cells on both sides look close. The symptom is cells joined across tracks. Check it by mapping the faced_to and touched_to edges near barriers. The fix is non_movement_barrier_col: rows flagged there cut the tessellation but never become walkable movement nodes.
Chapter 3
Pick the primal or the dual street graph, and turn a GTFS timetable into weighted stop-to-stop edges
Streets are already a network. But which one? In the primal graph, junctions are nodes and segments are edges: the road map, good for routing. In the dual graph, segments are nodes, joined when they meet: good when the street itself is what you predict. The movement nodes of Chapter 2 are a dual.
One junction where k segments meet becomes k(k − 1)/2 dual edges, the pair count from Chapter 0. A four-way crossroads gives 6. The dual says "these streets meet", not "you may turn here".
pythonjunctions, segs = c2g.segments_to_graph(segments_gdf) # primal dual_nodes, dual_edges = c2g.dual_graph((junctions, segs), keep_original_geom=True)
GTFS (the General Transit Feed Specification) is a zip of CSV files: stops, routes, trips and stop times. It has no edges. load_gtfs reads it into an in-memory DuckDB database. travel_summary_graph then adds up the service between consecutive stops over a time window you choose. Each edge gets a frequency (traversals in the window) and a travel_time_sec.
Two routes serve stops X and Y. How long is the X to Y leg? Call route r's traversal count fr and its mean time tr.
T-bar equals the sum over r of f-r times t-r, divided by the sum over r of f-r.
Multiply each route's time t-r by how often it runs, f-r. Add those up. Divide by the total number of runs. T-bar is the time of a random trip on this leg.
With made-up numbers: route 12 runs 40 times at 180 s, route 45 runs 10 times at 300 s. T-bar = (40 × 180 + 10 × 300) / 50 = 10,200 / 50 = 204 s, and the frequency is 50. The plain mean of the two routes, 240 s, is 36 s too slow.
Each dot is one scheduled run of the leg. Slide how often each route runs and watch the weighted time move while the plain mean stays put.
Illustrative routes. The library's documented definition of travel_time_sec is the service-weighted average across all trips on the stop pair.
Some feeds give a headway instead of every trip: "every 10 minutes from 07:00 to 08:00". With use_frequencies=True (the default) that row counts as 60 / 10 = 6 traversals per active service day. Over 5 service days it adds 30.
Failure. A graph with no time window mixes the 03:00 city with the 08:30 city. The symptom is odd centrality ranks. Measure by rebuilding with a narrow window and comparing ranks. The fix: always set start_time, end_time, calendar_start and calendar_end, and report them like a sample size.
Chapter 4
Invent edges between bare points with five rules, and see how each rule states a different hypothesis
Most urban files are bare points: shops, schools, sensors, bike docks. Nothing says which are linked. A proximity graph invents edges from distance. It is a hypothesis: "things this close affect each other". Each rule is a different hypothesis.
Take five points in metres: A (0, 0), B (30, 10), C (60, 0), D (20, 50), E (70, 45). By Pythagoras, A to B is the square root of 30² + 10² = 31.62 m, and D to E is 50.25 m.
| Rule (function) | Edge when | On the five points |
|---|---|---|
k nearest (knn_graph) | v is among u's k closest | k = 2: 10 picks, 6 edges |
fixed radius (fixed_radius_graph) | distance ≤ radius | 50 m: 4 edges; 55 m: 7 |
Gabriel (gabriel_graph) | no point inside the circle on u–v as diameter | 6 edges |
relative neighbourhood (relative_neighborhood_graph) | no w closer to both u and v than they are to each other | 5 edges |
Waxman (waxman_graph) | a coin flip with a chance that falls with distance | 3.02 edges expected |
Pick a rule. The slider sets that rule's knob: k, the radius, or Waxman's r0. Gabriel and RNG take no knob. Press Draw to flip new Waxman coins.
Points from the worked example. kNN shows the library's undirected result: the union of each point's picks. Waxman uses β = 0.5 and a seeded random draw.
kNN is not mutual. A picks D, but D picks B and E. Inside one GeoDataFrame, knn_graph returns an undirected graph, the union of the picks: 10 picks collapse to 6 edges. Pass target_gdf and you get directed edges instead.
The radius knob is quadratic. At density λ points per km², a point expects λ × πr² neighbours. At 400 per km², r = 0.3 km gives 113; r = 0.6 km gives 452. Double the radius, four times the edges.
People mostly shop nearby and sometimes go far. The Waxman rule gives each pair a chance of an edge. Call the distance between u and v d, an overall scale β, and a decay length r0.
P of u, v equals beta times e to the minus d over r-zero.
Divide the distance d by r-zero. Take e to the minus that. Multiply by beta. Flip a coin with that chance for every pair.
With β = 0.5 and r0 = 100 m: A–B at 31.62 m gives 0.5 × 0.729 = 0.364; A–E at 83.22 m gives 0.5 × 0.435 = 0.218. Summed over all ten pairs, about 3.02 edges appear per draw.
Polygons get the same treatment: contiguity_graph(gdf, contiguity="queen") joins shared boundaries, and every proximity function accepts distance_metric="network" with a network_gdf.
Failure. Coordinates in latitude and longitude are degrees, not metres. At latitude 53.4° one degree east is about 66 km and one degree north about 111 km, so kNN picks the wrong neighbours with no error. Check gdf.crs.axis_info[0].unit_name; if it says degree, reproject first, for example to_crs(27700) in Britain.
Chapter 5
Turn counted flows into edges, and see how the threshold order changes which zones are linked
Someone counted how many people commute from each zone to each other zone. That count is the edge. This is origin–destination (OD) data: census migration, travel surveys, bike-share trips. A proximity edge is a guess. An OD edge is a measurement.
Four zones, daily commuters. Rows are origins, columns destinations:
| from / to | Z1 | Z2 | Z3 | Z4 |
|---|---|---|---|---|
| Z1 | – | 120 | 45 | 8 |
| Z2 | 95 | – | 210 | 30 |
| Z3 | 40 | 180 | – | 12 |
| Z4 | 5 | 25 | 15 | – |
od_matrix_to_graph drops the diagonal by default and is directed by default. With a threshold, it keeps a flow when the flow is at least the threshold. At threshold 20, four of the twelve flows fail (8, 12, 5, 15), so 8 directed edges survive.
With directed=False the library first adds both directions, then applies the threshold. Call the flow from u to v wuv and the threshold τ.
Keep the pair u, v if w-u-v plus w-v-u is at least tau.
Add w-u-v and w-v-u into one weight for the pair. Keep the undirected edge only if that sum reaches tau. In directed mode, each of w-u-v and w-v-u must reach tau alone.
Z3 and Z4: w = 12 one way and 15 the other, τ = 20. Directed, both fail and the pair vanishes. Undirected, 12 + 15 = 27 ≥ 20, so the edge survives. Five of the six pairs survive; only Z1–Z4 at 8 + 5 = 13 fails.
Each line is a flow between zones, thicker for more people. Choose a mode and drag the threshold. Watch the Z3 and Z4 pair.
Illustrative counts. The rules (directed by default, threshold as at least, undirected sums both directions before the threshold) are from the od_matrix_to_graph docstring.
Directed-then-threshold asks "is there a big flow this way?" Sum-then-threshold asks "do these places interact?" Both are right answers to different questions.
Failure. An OD table with several weight columns (total, by bike, by car) is ambiguous: at least 20 of what? The library makes you name threshold_col when weight_cols has more than one column. Write the reason for the threshold in a comment.
Chapter 6
Compose stored relations into a new one with two matrix multiplies, and budget the edges it creates
"Which neighbourhoods does public transport link?" Your graph has (area, near, stop) and (stop, connects, stop). No edge joins area to area. The answer is three hops deep: area, stop, stop, area. A named sequence of edge types like that is a metapath. add_metapaths walks it and stores the result as a new edge type.
Toy: three areas a1, a2, a3 and three stops s1, s2, s3 on one line s1–s2–s3. Area a1 is near s1, a2 near s2, a3 near s2 and s3. Write the near relation as a 0/1 table A (rows areas, columns stops) and the line as S (rows and columns stops).
M equals A times S times A-transpose.
Multiply A by S: for each area, which stops one ride reaches. Multiply that by A-transpose: which areas sit by those stops. Each entry of M is a path count.
A·S has row a3 = [1, 1, 1]: a3 touches s2 and s3, so one ride reaches all three stops. The full product is M = [[0,1,1],[1,0,1],[1,1,2]]. M[a3][a3] = 2 counts a3→s2→s3→a3 and a3→s3→s2→a3.
Areas on the left and right, stops in the middle. Toggle a link and watch M and the pink area-to-area edges change.
We checked the toy and its matrices with numpy. The library's docstring describes the operation the same way: it multiplies typed adjacency tables.
Off the diagonal, M has three undirected pairs: every area is now linked by transit, from an input with no area-to-area edges. The diagonal holds self-loops; a GNN already includes each node in its own update.
Why not a three-layer GNN? It mixes every three-hop path: area→stop→area→stop and area→street→street→area too. A metapath isolates one composition, gives it its own weight matrix, and reaches three hops in a one-layer model.
pythonnodes, edges = c2g.add_metapaths( (nodes, edges), sequence=[("area", "is_nearby", "stop"), ("stop", "connects", "stop"), ("stop", "is_nearby", "area")], new_relation_name="transit_accessible", # else it is named metapath_0 edge_attr="travel_time_sec", edge_attr_agg="sum", )
Failure. Metapaths densify. If each area is near p stops and each stop links to q others, one area reaches about p × q × p areas. With p = 3, q = 4: 36 per area, 180,000 edges over 5,000 areas. With p = 10, q = 8 downtown: 800 per area. The symptom is out-of-memory on the densest tile. Measure p and q there first. Fix: cap p with bridge_nodes(..., k=1) and drop composed edges over a travel-time cap.
Chapter 7
Convert typed GeoDataFrames into a HeteroData object, and count every edge the conversion adds
A neural network cannot read a GeoDataFrame. It wants float tensors and integer indices. gdf_to_pyg does the conversion. Pass single frames and you get a PyTorch Geometric Data; pass dictionaries and you get a HeteroData.
| Field | Shape | Holds |
|---|---|---|
data["place"].x | [N, F] | one float32 feature row per node |
data[et].edge_index | [2, E] | row 0 sources, row 1 targets, as int64 positions |
data[et].edge_attr | [E, Fe] | one feature row per edge |
edge_index is 2 rows by E columns, so x[edge_index[0]] gathers every source in one step. The indices are positions, not your ids. Each node type counts from 0 on its own: place 0 and movement 0 are different nodes.
Message passing needs a direction. With directed=False (the default), each stored row (u, v) gains its reverse (v, u). A cross-type edge cannot store its reverse in the same triple, because the source type differs. So reverse_edge_types="auto" adds a new triple such as ("movement", "rev_faced_to", "place"). Set it to None and an undirected cross-type edge raises an error.
The input has 620 touched_to, 480 connected_to and 390 faced_to rows. Choose the two settings and read each edge type's width.
Illustrative row counts. The symmetrize, rev_ and raise rules are from the gdf_to_pyg docstring in city2graph 1.1.0.
Worked count, undirected and auto. touched_to: 620 × 2 = 1,240 columns. connected_to: 480 × 2 = 960. faced_to keeps 390 and rev_faced_to adds 390. Total 2,980 edges, stored as 2 int64 each: 2,980 × 2 × 8 = 47,680 bytes. Features for 240 places and 310 streets at 23 float32 columns add 50,600 bytes. The whole block is under 100 KB.
pythondata = c2g.gdf_to_pyg(nodes, edges, node_feature_cols={"place": ["area", "height"], "movement": ["length"]}, directed=False, reverse_edge_types="auto", keep_geom=True) assert data["place", "touched_to", "place"].edge_index.shape[1] == 2 * len(p2p_gdf) nodes2, edges2 = c2g.pyg_to_gdf(data) # the round trip back to the map
Failure. If you stored both directions yourself, undirected mode rejects the input. If the width equals the row count, the edges went in as directed and half the messages are missing. The assert above catches both. Features must be numeric: one-hot encode land-use strings first.
Chapter 8
Run one round of message passing by hand, typed and type-blind, and see what the blind layer cannot learn
A message-passing layer does three things for every node at once. Each neighbour sends a message. The node aggregates them, here with a mean. It then updates its own vector. A typed layer does the first two once per edge type, each with its own weight matrix.
Toy: places p1 = [1, 0], p2 = [0, 1], p3 = [0.5, 0.5]; streets m1 = [2, 0], m2 = [0, 2]. p1 touches p2 and p2 touches p3. p1 and p2 face m1; p3 faces m2. Call node v's vector hv, its neighbours under relation r Nr(v), and relation r's weight matrix Wr.
H-prime-v equals ReLU of: h-v, plus the sum over r of W-r times the mean of h-u over u in N-r of v.
For each relation r, average the neighbours h-u it gives node v and multiply by W-r. Add those to h-v. Clip negatives with ReLU. That is h-prime-v.
For p1: self [1, 0]. Touch: mean of p2 = [0, 1], times W-touch gives [0, 0.5]. Face: m1 = [2, 0], times W-face gives [1, 0]. Sum: h′p1 = [2, 0.5]. Likewise p2 = [1.375, 1.125] and p3 = [0.5, 1.5].
Bars show each place's two numbers after one layer. Choose typed or blind. In typed mode, slide how much the street signal counts in the second entry.
We made up the weights so you can check them by hand; every number matches a numpy check. A trained layer learns its weights.
Now go blind: one W = W-touch for every neighbour. p1's neighbours {p2, m1} average to [1, 0.5], times W gives [0.5, 0.25], so h′p1 = [1.5, 0.25]. Two things went wrong. The mean blended a place vector with a street vector as if their columns meant the same thing. And one W cannot weigh streets and neighbours apart. Move the slider in blind mode: nothing changes, because the blind layer has no such knob.
The case study published with the library goes one step further. Its HANGAE model runs a HAN encoder (heterogeneous graph attention) over several metapaths and learns one attention weight per metapath. It trains without labels as a graph autoencoder: it learns to predict which pairs are edges, with a DistMult decoder. It ran on an Apple M2 laptop CPU.
pythonfrom torch_geometric.nn import HeteroConv, SAGEConv conv = HeteroConv({et: SAGEConv((-1, -1), 16) for et in data.edge_types}, aggr="sum") z = conv(data.x_dict, data.edge_index_dict)["place"] # [num_places, 16]
Failure. An embedding you never mapped is an embedding you never checked. If its first dimensions trace your study-area boundary, the model learned the edge of the data, not the city. Map them with pyg_to_gdf and a plot.
Chapter 9
Measure a walking catchment on the network, and name the places where an urban graph misleads
"How many people live within a 15-minute walk of a pharmacy?" The quick answer draws a circle. At 4.8 km/h, 15 minutes is 1,200 m, so the circle has radius 1.2 km. But you cannot walk through buildings.
The ratio of walking distance to straight-line distance is the circuity, often about 1.3 to 1.4 on street grids. Call the walk budget R and the circuity c. A walk of R metres covers only R / c of straight line.
The overstatement equals pi R squared over pi times R over c, squared, which equals c squared.
Divide the circle area by the reachable area. The radius shrinks by c, so the area shrinks by c times c. The circle is c-squared times too big.
With R = 1.2 km and c = 1.35: the circle is 4.52 km², the reach is π × 0.889² = 2.48 km², and 4.52 / 2.48 = 1.82 = 1.35². The buffer claims 82% more catchment than exists.
The faint circle is the buffer. The filled disc is what you reach on foot. Drag the circuity and the walk time.
A disc is a simplification. A real network catchment is a jagged shape, and circuity varies street by street.
The graph walks the real network. filter_graph_by_distance(graph, center_point, threshold) keeps the nodes within the path budget, summing edge_attr="length" by default. create_isochrone turns the reached nodes into a polygon. Its default method is "concave_hull_knn".
That isochrone errs the other way. It keeps whole nodes, so it stops at the last junction inside the budget. With junctions every 350 m, the last one is at 1,050 m, and (1,050 / 1,200)² = 0.77: about 23% of the area is lost. Both errors grow where blocks are long.
| Limit | Symptom | What to do |
|---|---|---|
| Zones change answers | results move when you swap census units | run at two or three scales; report all |
| Edges are assumptions | a finding holds only at k = 5 | sweep k, radius and rule; report the spread |
| Correlation, not cause | "build a street and shops will follow" | a causal design around a real change |
| Uneven data | poor areas look empty in OSM and Overture | check coverage per area before comparing |
| Boundary effects | edge nodes have low degree and centrality | build with a buffer, then clip |
Failure. GTFS holds only scheduled service. Where informal minibuses carry most trips, a GTFS graph calls a served area unreachable. Compare against a survey before you trust the map.
Chapter 10
Install the library, look up each constructor, and keep the defaults that are usually right
A city graph has typed nodes (cells, streets, stops, zones) and typed edges (touch, join, face, near, flow, composed). Build each family with one constructor, compose with metapaths, convert with gdf_to_pyg, train, and map the result back with pyg_to_gdf.
city2graph 1.1.0 supports Python 3.12 to 3.14. pip install city2graph gives graph building without PyTorch. pip install "city2graph[cpu]" adds PyTorch and PyTorch Geometric; the CUDA extras are cu126, cu128, cu130 and cu132. The README says to install the matching PyTorch wheel from its own index first.
| Function | Takes | Gives |
|---|---|---|
load_overture_data | area or place_name, types, release | GeoDataFrames per Overture type |
process_overture_segments | raw segments | segments split at connectors, with barriers |
morphological_graph | buildings, segments | place and movement nodes, 3 edge types |
segments_to_graph, dual_graph | LineStrings; a primal graph | primal graph; segments as nodes |
load_gtfs, travel_summary_graph | GTFS zip; DuckDB connection and window | stop nodes, frequency and travel_time_sec edges |
od_matrix_to_graph | edge list or square matrix, zones | zone nodes, flow edges |
knn_graph, fixed_radius_graph, gabriel_graph, relative_neighborhood_graph, delaunay_graph, waxman_graph | points and the rule's knob | proximity edges |
contiguity_graph, group_nodes, bridge_nodes | polygons; polygons and points; several layers | boundary, containment and is_nearby edges |
add_metapaths | hetero graph, sequence of triples | one new composed edge type |
gdf_to_pyg, pyg_to_gdf, gdf_to_nx, nx_to_rx | one graph format | another, with ids kept |
filter_graph_by_distance, create_isochrone | graph, centre, threshold | reachable subgraph; reach polygon |
| Term | One line | Number from this page |
|---|---|---|
| pairs | relation slots among n things | 12 buildings: 66 |
| queen vs rook | corner touches count, or not | 3 by 3: 20 vs 12 |
| travel_time_sec | service-weighted mean leg time | 204 s, not 240 |
| Waxman | edge chance β e−d/r0 | 3.02 expected edges |
| OD threshold | undirected sums before thresholding | 12 + 15 = 27 kept |
| metapath | M = A·S·AT path counts | M[a3][a3] = 2 |
| symmetrize | undirected rows become two edges | 2,980 edge columns |
| circuity | buffer is c² too big | 1.35 gives 1.82 |
gdf_to_pyg.pythonimport city2graph as c2g ov = c2g.load_overture_data(place_name="Liverpool, UK", types=["building", "segment", "connector"]) buildings = ov["building"].to_crs(27700) # metric CRS first segments = c2g.process_overture_segments(ov["segment"]).to_crs(27700) nodes, edges = c2g.morphological_graph(buildings, segments, center_point=centre, distance=1000) gtfs = c2g.load_gtfs("north_west_gtfs.zip") stops, legs = c2g.travel_summary_graph(gtfs, start_time="07:00:00", end_time="10:00:00", calendar_start="20250603", calendar_end="20250603") nodes["stop"] = stops.to_crs(27700) edges[("stop", "connects", "stop")] = legs.to_crs(27700) _, near = c2g.bridge_nodes(nodes, proximity_method="knn", k=2, source_node_types=["place"], target_node_types=["stop"]) edges.update(near) # adds ("place", "is_nearby", "stop") data = c2g.gdf_to_pyg(nodes, edges, node_feature_cols=feat_cols) c2g.validate_pyg(data) # ... train a HeteroConv model, then nodes_out, edges_out = c2g.pyg_to_gdf(data)
Now press Present or Teach and explain from memory: why cells beat buildings, how a timetable becomes edges, why the OD threshold order matters, and how M = A·S·AT creates a new relation. Then go back to the hero and build the block again, naming the function behind each layer.
The library is city2graph by Yuta Sato and the Geographic Data Science Lab at the University of Liverpool. Cite Sato, Y., Pietrostefani, E., Mahabir, R. and Arribas-Bel, D. (2026), "City2Graph: A Python library for Heterogeneous Graph Neural Networks and spatial analysis in urban systems", Computers, Environment and Urban Systems 130, 102492. We checked the function names and defaults on this page against the 1.1.0 source; the toy numbers are ours.