nkde

Network kernel density estimation (NKDE, TNKDE) along street networks in Python: simple, discontinuous and continuous kernels on lixels, adaptive bandwidths, network K-function and crash or crime hot spots.

Version 0.1.2 · Python >=3.9 · MIT licence
pip install nkde
PyPISourceIssuesChangelogCite (DOI)

nkde

PyPI version Python versions pipeline status License: MIT DOI Downloads

Network kernel density estimation along street networks, in Python.

Crashes, crimes, shops and bus stops happen on streets. A planar (2D) kernel density spreads every event over a disc, so it puts density on the street behind a block that is 100 m away as the crow flies but 300 m away on foot or by car. It also counts every parallel street that the disc touches. Network kernel density estimation (NKDE) spreads each event along the network using shortest-path or branch distances, so the result is a density per metre of street.

nkde provides:

The only required dependency is numpy. scipy (optional) speeds up the planar KDE.

Installation

pip install nkde              # numpy only
pip install "nkde[fast]"      # + scipy (planar KDE through a KD-tree)
pip install "nkde[geo]"       # + scipy, shapely, geopandas, networkx

Python 3.9 to 3.13.

Quick start

Command line

nkde run roads.geojson events.geojson --bw 300 --lixel 10 --method continuous -o density.geojson

Inputs are GeoJSON LineString/MultiLineString roads and Point/MultiPoint events in projected metres. With --lonlat, WGS84 inputs are projected to their UTM zone and the output is written back in lon/lat. Other options:

option meaning
--kernel quartic|triangular|epanechnikov|gaussian|uniform kernel (default quartic)
--method simple|discontinuous|continuous estimator (default continuous)
--adaptive, --trim-bw M Abramson adaptive bandwidth, capped at M (default 3 x bw)
--weight-field F event weights, for example casualties
--time-field F --times 0:365:7 --time-bw 30 TNKDE (numbers or ISO dates; ISO dates become days)
--max-snap M drop events farther than M metres from any road
--split-crossings add junctions where roads cross without a shared vertex
--max-depth N limit branch enumeration to N junctions
--top N print the N highest-density lixels

nkde kfunction roads.geojson events.geojson --tmax 1000 --step 50 --nsim 99 -o k.csv writes the network K-function with its simulation envelope.

The output is one LineString per lixel with properties lixel, edge, source_id, length, density (per metre, integrates to 1 over the network) and intensity (events per metre, integrates to the number of events or the total weight). TNKDE output has density_t<j> / intensity_t<j> columns, and the times are stored in the collection's nkde member.

Python

import nkde

net = nkde.network_from_geojson("roads.geojson")             # projected metres
events = nkde.events_from_geojson("crashes.geojson", net, max_distance=25)

res = nkde.nkde(net, events, bw=300, lixel_length=10, method="continuous")
res.to_geojson("density.geojson")

top = nkde.rank_hotspots(res, top=20)                         # highest-density lixels
clusters = nkde.hotspot_clusters(res.lixels, res.density >= 0.002)

Lon/lat data:

lines, _ = nkde.read_lines("roads_wgs84.geojson")
import numpy as np
allc = np.vstack(lines)
fwd, inv, zone = nkde.utm_transformers(allc[:, 0], allc[:, 1])  # zone.epsg -> 326xx
net = nkde.network_from_geojson("roads_wgs84.geojson", transform=fwd)
events = nkde.events_from_geojson("events_wgs84.geojson", net, transform=fwd)
res = nkde.nkde(net, events, 300, lixel_length=10)
res.to_geojson("density_wgs84.geojson", inverse_transform=inv)

Spatio-temporal density, comparison with a planar KDE, and K-function:

ev = net.snap(xy, times=days)                                 # times in any unit
tres = nkde.nkde(net, ev, 300, lixel_length=10, times=range(0, 365, 7), time_bw=30)
tres.density.shape                                            # (n_lixels, n_times)

planar = nkde.planar_kde(res.lixels, events, 300)             # per square metre

k = nkde.network_k_function(net, events, distances=range(50, 1001, 50), n_simulations=99)
k.clustered()                                                 # observed K above the envelope

examples/quickstart.py builds a small network and writes GeoJSON outputs. examples/benchmark.py reproduces the timings below.

Methods

Lixels and events

Each edge of length l is cut into ceil(l / L) equal lixels, so no lixel is longer than L. The density is evaluated at lixel mid points. Each event is snapped to the nearest point on the nearest edge and is stored as (edge, offset), where the offset is the distance in metres from the start of the edge. Junctions are the end points of lines and the vertices shared by several lines. split_at_intersections=True (--split-crossings) also adds junctions where lines cross without a shared vertex.

Kernels

All kernels have support [-h, h] and unit mass in 1D (u = d / h):

kernel k(d)
quartic 15/16 (1 - u^2)^2 / h
triangular `(1 -
Epanechnikov 3/4 (1 - u^2) / h
Gaussian exp(-u^2 / (2 (1/3)^2)), truncated at h and renormalised (sigma = h/3)
uniform 1 / (2h)

The planar KDE uses the 2D versions of these kernels, which have unit mass over the disc of radius h. Note that spNetwork's Gaussian kernel uses sigma = h without truncation, so Gaussian results differ from spNetwork by construction.

The three estimators

Take an event e and a point x on the network.

As in spNetwork, the discontinuous and continuous kernels follow every walk shorter than h, not only shortest paths, so a branch can go around a block and come back. The number of walks grows exponentially with h / block length. nkde merges branches that enter the same directed edge at the same distance, because their future contributions are identical. On regular street grids this keeps the cost polynomial. max_depth (number of junctions crossed) and min_weight truncate the enumeration if needed. Both default to the exact estimator.

Implementation: each event produces a list of traversals (edge, entry end, start distance, weight) with a priority queue ordered by distance (the bounded Dijkstra for simple). The traversals of thousands of events are then expanded into (lixel, value) pairs in one vectorised numpy pass and summed with bincount. Only lixels within h are touched. Events are processed in chunks (chunk_size), which bounds memory use.

Adaptive bandwidth

With adaptive=True, a fixed-bandwidth pilot f~ is evaluated at the lixel of each event, and h_i = h0 * sqrt(g / f~(x_i)), where g is the geometric mean of the pilot values (Abramson 1982). h_i is capped at trim_bw (default 3 h0), as with spNetwork's trim_bw.

TNKDE

f(x, t) = (1 / W) sum_i w_i k_net(x; e_i) k_time(t - t_i), where both kernels have unit mass. It is evaluated at the lixels for each requested time. NKDEResult.integral() integrates over space and time.

K-function and hot spots

The global network K-function (Okabe & Yamada 2001) is K(t) = L / (n (n - 1)) * #{ordered pairs i != j : d(i, j) <= t}, where L is the network length. The envelope comes from n_simulations patterns of n uniform random points on the network (CSR on the network). Pointwise min/max or quantiles are available. rank_hotspots orders lixels by density and flags those above a quantile. monte_carlo_pvalues reruns the estimator on CSR patterns to give a p-value per lixel. hotspot_clusters labels connected groups of hot lixels.

Validation

The test suite (126 tests) checks:

Cross-check against spNetwork. No numeric comparison with published spNetwork outputs was made, because no reference values were available that could be reproduced reliably. The estimators follow the definitions in Okabe & Sugihara (2012) and in the spNetwork documentation (Gelb 2021): equal split by n - 1, continuous factors 2/n and 2/n - 1, and enumeration of all walks within the bandwidth. The hand-checkable cases above test those definitions directly. The known difference is the Gaussian kernel convention (see Kernels). spNetwork may also place lixel sample points or handle the last, shorter lixel of each edge differently.

Performance

These timings come from python examples/benchmark.py on a laptop (AMD Ryzen 5 4600H, Python 3.12, numpy 2.5, single thread). The network is a jittered 80 x 80 street grid with 100 m blocks: 6,400 nodes, 12,640 edges and 1,272 km of street, cut into 133,462 lixels of 10 m. There are 10,000 random events, the bandwidth is 300 m and the kernel is quartic.

step time mass per event
snap 10,000 points 1.3 s
simple NKDE 1.5 s 3.57
discontinuous NKDE 2.6 s 1.000000
continuous NKDE 5.9 s 1.000000
continuous, adaptive (pilot + final) 12.2 s
planar KDE at lixel mid points (scipy) 1.1 s
K-function, 1,000 events, 20 distances, 19 simulations 3.6 s

API overview

object purpose
Network.from_lines, Network.from_edges, network_from_geojson build the network
Network.lixelize(L) -> Lixels lixels (edge, start, end, mid, length, midpoints_xy(), locate())
Network.snap(xy, times=, weights=, max_distance=) -> Events snap points; events_on_edges, random_events
nkde(network_or_lixels, events, bw, ...) -> NKDEResult NKDE / TNKDE (intensity, density, bandwidths, integral(), to_geojson())
event_kernel, abramson_bandwidths one event's kernel; adaptive bandwidths
planar_kde(targets, events, bw) Euclidean KDE
network_k_function, pairwise_network_distances K-function and envelopes
rank_hotspots, monte_carlo_pvalues, hotspot_clusters hot spots
read_lines, read_points, events_from_geojson, result_to_geojson GeoJSON I/O
lonlat_to_utm, utm_to_lonlat, utm_transformers, UTMZone projection
nkde.interop network_from_geodataframe, events_from_geodataframe, result_to_geodataframe, network_from_networkx, network_to_networkx

References

Citation

@software{eminoglu_nkde,
  author  = {Eminoğlu, Yusuf},
  title   = {nkde: network kernel density estimation along street networks},
  year    = {2026},
  version = {0.1.2},
  doi     = {10.5281/zenodo.24065166},
  url     = {https://doi.org/10.5281/zenodo.24065166}
}

See CITATION.cff.

Related Geophilo SDKs

License

MIT (c) 2026 Yusuf Eminoğlu. See LICENSE.

Other Geophilo SDKs