iTranslated by AI
I Built a Python Library for Converting Geospatial Data into Heterogeneous Graph Representations for GNNs, and It Blew Up
Introduction
Nice to meet you. My name is Sato, and I am a PhD student at the University of Liverpool in the UK.
Liverpool is famous for soccer and The Beatles, but that's not particularly why I came to the UK...
In the UK, a research field called Geographic Data Science, which combines human geography (urban economics, economic geography, urban planning, demography) and data science, is thriving. I am enrolled in a research institute specializing in this field.
My specialty is Urban Morphology, which understands society from the physical structure of cities. I am particularly interested in the topology of urban form and in the application of Graph Representation Learning, which has achieved results in nonlinear pattern classification. Besides classical models like spectral clustering and node2vec, Graph Neural Networks (GNNs), which can handle both node/edge/graph features and their relative topological positions, have gained attention in recent years. In particular, models for Heterogeneous Graphs that mix multiple node and edge types have been actively proposed, and their application implementations in various fields are progressing.
Challenges
Regarding geospatial data, various discrete relationships can be defined. The most intuitive example is the street network. OpenStreetMap data is well known for being convertible to NetworkX objects using OSMNx.
Urban space contains diverse spatial relationships beyond street networks: adjacency between buildings, connections between buildings and streets, travel times between public transit stops, population flows between regions, etc. Furthermore, for street networks, non-OSM data like Overture Maps, which has been actively developed in recent years, is gaining presence. Converting these diverse geographic discrete relationships from multiple sources into a unified (heterogeneous) graph representation and making them handleable in GNNs is highly useful for both urban research and practical implementations.
However, the process of constructing graphs from geospatial data is cumbersome. Transforming data across different libraries like GeoPandas, NetworkX, and PyTorch Geometric, and implementing domain-specific graph construction logic (e.g., generating public transit networks from GTFS data), requires a lot of time and code. Especially when dealing with heterogeneous graphs, managing multiple node and edge types increases complexity.
To address these challenges, I developed a Python library called city2graph.
Library Overview

city2graph is a Python library that converts geospatial data into graph representations for use in graph neural networks. It provides an integrated interface combining GeoPandas, NetworkX, and PyTorch Geometric, supporting multiple domains such as urban morphology, public transit, and mobility (including population movement).
Despite being such a niche library, it has started to gain traction among researchers and data scientists on LinkedIn, and in one year we have received 842 GitHub Stars from around the world!
Installation is available via pip and conda. The standard installation only includes dependencies that do not use PyTorch Geometric, but with pip, you can install all necessary libraries in an extended form according to your hardware specification. (For conda, since PyTorch has officially ended support on conda, manual installation from conda-forge is required.)
Basic Installation (without PyTorch)
# pip
pip install city2graph
# conda
conda install city2graph -c conda-forge
Installation including PyTorch Geometric features (pip)
# CPU version
pip install "city2graph[cpu]"
# GPU version (example for CUDA 12.8)
pip install "city2graph[cu128]"
Installation including PyTorch Geometric features (conda)
# Install city2graph
conda install city2graph -c conda-forge
# Install PyTorch and PyTorch Geometric (for CUDA 12.8)
conda install -c conda-forge pytorch=2.7.1=*cuda128*
conda install -c conda-forge pytorch_geometric
Basic Usage
The core functionality of city2graph is the ability to convert data between GeoPandas, NetworkX, and PyTorch Geometric. Here, we demonstrate the common interface of the library through an example of creating a k-nearest neighbor graph from 1,000 random points.
Data Preparation
First, generate 1,000 random points:
import geopandas as gpd
from shapely import Point
import numpy as np
import city2graph as c2g
# 1) Generate random points (EPSG:3857 for metric distance calculation)
np.random.seed(42) # for reproducibility
num_points = 1000
x_coords = np.random.rand(num_points) * 1000 # random x coordinates between 0 and 1000
y_coords = np.random.rand(num_points) * 1000 # random y coordinates between 0 and 1000
gdf = gpd.GeoDataFrame(
{"name": [f"Point_{i}" for i in range(num_points)]},
geometry=[Point(x, y) for x, y in zip(x_coords, y_coords)],
crs="EPSG:3857"
)
Creating a Proximity Graph
Next, create a KNN graph with k=10:
# 2) Create a proximity graph (KNN method)
nodes, edges = c2g.knn_graph(
gdf,
distance_metric="euclidean",
k=10,
as_nx=False
)

This yields two GeoDataFrames: nodes and edges. The MultiIndex of edges corresponds to the Index of nodes, and the original data columns (including geometry) are preserved.
Converting Between Formats
You can convert these GeoDataFrames to NetworkX or PyTorch Geometric:
# 3) Convert to your preferred framework
# NetworkX
nx_graph = c2g.gdf_to_nx(nodes, edges)
# PyTorch Geometric
pyg_graph = c2g.gdf_to_pyg(nodes, edges)
Thus, with city2graph, you can freely move between GeoPandas, NetworkX, and PyTorch Geometric. Leveraging the advantages of each format, you can seamlessly execute everything from data preprocessing to GNN model training and result visualization.
Building a Heterogeneous Graph
The examples so far have dealt with homogeneous graphs, where all nodes are of the same type. By using heterogeneous graphs with multiple node and edge types, you can represent more nuanced spatial relationships.
In heterogeneous graphs, nodes and edges are managed in dictionary form. For example, let's construct a heterogeneous graph from amenity and street segment data:
import city2graph as c2g
# 1. Create a proximity graph from amenity data
amenity_nodes, amenity_edges = c2g.knn_graph(amenity_gdf, k=5, as_nx=False)
# 2. Create a graph of street segments
segment_nodes, segment_edges = c2g.gdf_to_nx(segments_gdf)
segment_nodes, segment_edges = c2g.nx_to_gdf(segment_graph)
# 3. Connect amenities and street segments by proximity
amenity_segment_nodes, amenity_segment_edges = c2g.bridge_nodes(
{'amenity': amenity_nodes, 'segment': segment_nodes},
proximity_method='knn',
k=3
)
# 4. Build a heterogeneous graph (merge nodes and edges in dictionary form)
combined_nodes = {
'amenity': amenity_segment_nodes['amenity'],
'segment': amenity_segment_nodes['segment']
}
combined_edges = {
('segment', 'connects', 'segment'): segment_edges,
('amenity', 'is_nearby', 'segment'): amenity_segment_edges[('amenity', 'is_nearby', 'segment')]
}
# Convert to PyTorch Geometric HeteroData
hetero_data = c2g.gdf_to_pyg(combined_nodes, combined_edges)
Thus, city2graph allows you to integrate graphs from different domains in dictionary form, representing complex urban spatial relationships as a single heterogeneous graph. The heterogeneous graph constructed in this example forms the basis for the metapaths explained next.
Extending Heterogeneous Graphs with Metapaths
In heterogeneous graphs, there are multiple types of nodes and edges. For example, in urban space, there are two node types: "amenity" and "segment", and edge types like "is_nearby" and "connects" can be defined between them.
In city2graph, you can add new edges to a heterogeneous graph by defining metapaths. A metapath is a path that traverses multiple node types and edge types. For example, the metapath "amenity → segment → segment → amenity" represents relationships between amenities connected via the street network:
import city2graph as c2g
# Define metapath: amenity → segment → segment → amenity (3-hop path)
metapaths = [[("amenity", "is_nearby", "segment"),
("segment", "connects", "segment"),
("segment", "connects", "segment"),
("segment", "is_nearby", "amenity")]]
# Add edges connecting amenities via the street network based on the metapath
nodes_with_metapaths, edges_with_metapaths = c2g.add_metapaths(
(combined_nodes, combined_edges),
metapaths,
edge_attr="distance_m",
edge_attr_agg="sum"
)
In this example, we add edges between amenities that are connected via two street segments. By specifying edge_attr="distance_m" and edge_attr_agg="sum", the distances along the metapath are summed and used as the weight for the new edges.
Below is an animation of metapaths when incrementally adding the number of segment hops:

By leveraging metapaths, you can explicitly model indirect relationships between nodes that are not directly connected, thereby improving the representational power of GNNs.
Examples of Constructable Graphs
The types of graphs that can be constructed vary depending on the combination of data sources and domains. Here, we introduce some examples.
1. Morphological Graph
From data such as buildings, streets, and land use, you can construct a graph representing urban morphology. It supports open data such as OpenStreetMap (OSM) and Overture Maps, and can generate heterogeneous graphs including the following three types of edges:
- Private-to-private: adjacency relationships between buildings
- Public-to-public: connectivity in the street network
- Private-to-public: connections between buildings and streets
import city2graph as c2g
# Generate a morphological graph from building and street data
morph_g = c2g.morphological_graph(
buildings_gdf,
streets_gdf,
building_key="bid",
street_key="sid"
)

2. Transportation Network
From public transit data in GTFS (General Transit Feed Specification) format, you can generate a graph considering travel times and connectivity between stops. It supports multiple modes such as bus, tram, and train.
import city2graph as c2g
# Load GTFS data
gtfs = c2g.load_gtfs("./gtfs_feed/")
# Generate a transit network graph with travel time as weight
transit_g = c2g.travel_summary_graph(
gtfs,
weight="mean_travel_time"
)

3. Proximity Graph
From point data such as POIs (Points of Interest) or buildings, you can generate edges based on spatial proximity. Multiple methods are supported: k-nearest neighbors (KNN), Delaunay triangulation, Waxman model, etc. These can be computed not only with Euclidean distance but also with Manhattan distance or network distance based on specified network data.
import city2graph as c2g
# Waxman graph using Manhattan distance (L1 norm)
wax_l1_nodes, wax_l1_edges = c2g.waxman_graph(
poi_gdf,
distance_metric="manhattan",
r0=100,
beta=0.5
)
# Waxman graph using Euclidean distance (L2 norm)
wax_l2_nodes, wax_l2_edges = c2g.waxman_graph(
poi_gdf,
distance_metric="euclidean",
r0=100,
beta=0.5
)
# Waxman graph using network distance
wax_net_nodes, wax_net_edges = c2g.waxman_graph(
poi_gdf,
distance_metric="network",
r0=100,
beta=0.5,
network_gdf=segments_gdf.to_crs(epsg=6677)
)

4. Mobility Graph
From an Origin-Destination (OD) matrix, you can construct a graph representing movement flows between regions. It supports data such as bike-sharing, population movement, and pedestrian flows.
import city2graph as c2g
# Generate a graph from OD data in edgelist format
nodes_gdf, edges_gdf = c2g.od_matrix_to_graph(
od_edges_df,
zones_gdf,
zone_id_col="zone_id",
matrix_type="edgelist",
source_col="origin",
target_col="destination",
weight_cols=["flow"]
)

5. Conversion to PyTorch Geometric
As mentioned earlier, the generated graph can be easily converted to the Data or HeteroData format of the GNN framework PyTorch Geometric. Additionally, reverse conversion (PyG → GeoDataFrame) is also supported, allowing you to visualize prediction results on a map.
import city2graph as c2g
# Convert GeoDataFrame to PyTorch Geometric
data = c2g.gdf_to_pyg(buildings_gdf, edges_gdf)
# Run predictions with a model (omitted)
# Convert prediction results back to GeoDataFrame
pred_gdf = c2g.pyg_to_gdf(data)
End-to-End Example
import torch
from torch_geometric.nn import HeteroConv, GCNConv, Linear
import city2graph as c2g
# 1. Create a morphological graph from building data
morph_nodes, morph_edges = c2g.morphological_graph(
buildings_gdf,
streets_gdf,
building_key="bid",
street_key="sid"
)
# 2. Create a proximity graph from POI data
poi_nodes, poi_edges = c2g.knn_graph(poi_gdf, k=8, as_nx=False)
# 3. Build a heterogeneous graph (merge nodes and edges in dictionary form)
combined_nodes = {
'building': morph_nodes['building'],
'street': morph_nodes['street'],
'poi': poi_nodes
}
combined_edges = {
('building', 'adjacent_to', 'building'): morph_edges[('building', 'adjacent_to', 'building')],
('street', 'connects', 'street'): morph_edges[('street', 'connects', 'street')],
('building', 'faces', 'street'): morph_edges[('building', 'faces', 'street')],
('poi', 'near', 'poi'): poi_edges
}
# 4. Convert to PyTorch Geometric heterogeneous graph
hetero_data = c2g.gdf_to_pyg(combined_nodes, combined_edges)
# 5. Define a heterogeneous GNN model
class HeteroGNN(torch.nn.Module):
def __init__(self, hidden_dim=64, out_dim=1):
super().__init__()
# Input embeddings for each node type
self.lin_building = Linear(-1, hidden_dim)
self.lin_street = Linear(-1, hidden_dim)
self.lin_poi = Linear(-1, hidden_dim)
# Heterogeneous graph convolution layers
self.conv1 = HeteroConv({
('building', 'adjacent_to', 'building'): GCNConv(-1, hidden_dim),
('street', 'connects', 'street'): GCNConv(-1, hidden_dim),
('building', 'faces', 'street'): GCNConv((-1, -1), hidden_dim),
('poi', 'near', 'poi'): GCNConv(-1, hidden_dim),
}, aggr='sum')
self.conv2 = HeteroConv({
('building', 'adjacent_to', 'building'): GCNConv(-1, hidden_dim),
('street', 'connects', 'street'): GCNConv(-1, hidden_dim),
('building', 'faces', 'street'): GCNConv((-1, -1), hidden_dim),
('poi', 'near', 'poi'): GCNConv(-1, hidden_dim),
}, aggr='sum')
# Output layer (for building node prediction)
self.lin_out = Linear(hidden_dim, out_dim)
def forward(self, x_dict, edge_index_dict):
# Input embeddings
x_dict = {
'building': self.lin_building(x_dict['building']).relu(),
'street': self.lin_street(x_dict['street']).relu(),
'poi': self.lin_poi(x_dict['poi']).relu(),
}
# Heterogeneous graph convolution
x_dict = self.conv1(x_dict, edge_index_dict)
x_dict = {key: x.relu() for key, x in x_dict.items()}
x_dict = self.conv2(x_dict, edge_index_dict)
# Output for building nodes
return self.lin_out(x_dict['building'])
# 6. Model training
model = HeteroGNN(hidden_dim=64, out_dim=1)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
for epoch in range(100):
model.train()
optimizer.zero_grad()
# Forward pass
out = model(hetero_data.x_dict, hetero_data.edge_index_dict)
# Loss calculation (e.g., building price prediction)
loss = torch.nn.functional.mse_loss(out, hetero_data['building'].y)
# Backward pass
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(f'Epoch {epoch}, Loss: {loss.item():.4f}')
Conclusion
If you find this interesting, please give us a Star ⭐️ on the GitHub repository!
Also, since this is OSS development, pull requests and contributions are very welcome!
Discussion