Fast, exact line-of-sight viewsheds for Python and Rust.
Most fast viewshed tools approximate line of sight; GDAL's, for example, wrongly hid 1–5% of visible ground in our tests. The exact ones are slow to call or hard to install. viewshed aims to be both exact and fast: a Rust core, NumPy in and out, pip install on any platform with no GDAL, GRASS or compiler, and first-class support for many observers (cumulative viewsheds, visibility index, wind-turbine ZTV).
0.6.1 on PyPI and crates.io (0.6.1 fixes a rare gap in the exact viewshed's error bounds and refuses inputs outside the limits its exact answers assume; 0.6.0 put every question on Terrain, exact on the bilinear surface by default, added hiding_height and a fast viewshed mode, and removed the old functions; see CHANGELOG.md). See BRIEF.md for the plan and conformance/ for how every result is checked.
- Exact, and checked. Everything a
Terrainanswers is exact on the bilinear surface (heights at cell centres, bilinear between them) and is checked against independent oracles in rational arithmetic (see Bilinear surface); float decisions are certified by rigorous rounding-error bounds, ties settled exactly.rviewshedis the model GRASSr.viewsheduses. It matches GRASS 8.4 on every cell of the conformance suite, with and without earth curvature and refraction, and an oracle written from the method's description backs that up; on large real rasters a few cells in a million can differ, apparently from rounding near ties. Accuracy against real geometry is measured on analytic scenes and continuous surfaces. - Fast. Rust on all cores: an exact viewshed over 2,001 × 2,001 cells takes 0.2–1.0 s on a 4-core desktop (table below).
rviewshed, a radial sweep, takes about 1 s and 100 MB for a 1,000-cell radius on a 4-core laptop, against 8–9 s forr.viewshed.Terrain.viewshedalso has an approximate fast mode. - Wind-farm ZTV. Counts how many turbine tips every cell can see, exactly, at the cost of one viewshed per tip.
- Hiding height: per cell, how tall a target can be and stay hidden from every watcher.
- Many observers: cumulative viewsheds and a visibility index, exact (see Many observers).
- Point-to-point line of sight, exact, for many pairs at once (radio links; see Line of sight between points).
- Reverse viewshed: from which cells a target (a mast, a roof) can be seen, exact for every cell (see Reverse viewshed).
- Exact shadow maps: every cell lit or in shadow for a given sun position, on the bilinear surface (see Shadow maps).
- Horizon maps: for every cell, the exact elevation angle of the skyline in a given direction (see Horizon maps).
- Sun hours: hours of direct sun per cell over a day, a season or a year, from exact shadow maps and the sun's computed position (see Sun hours).
- Earth curvature and refraction, on by default, as in GRASS
r.viewshed -c -r.
| Package | Install | Code |
|---|---|---|
| Python | pip install viewshed (abi3 wheels for Python ≥ 3.9) |
python/ |
| Rust | cargo add viewshed |
crates/viewshed/ |
import numpy as np
import viewshed
dem = np.zeros((41, 41)); dem[15, :] = 5.0 # flat ground with a 5 m wall
gt = (0.0, 1.0, 0.0, 41.0, 0.0, -1.0) # GDAL-style geotransform
terrain = viewshed.Terrain(dem, gt) # earth curvature and refraction are on
seen = terrain.viewshed((20.5, 20.5), height=1.6) # bool array
# zone of theoretical visibility: how many blade tips each cell can see from 2 m
tips = [(10.5, 30.5, 150.0), (30.5, 30.5, 150.0)]
counts = terrain.ztv(tips, observer_height=2.0) # uint32 array
# reverse viewshed: from which cells is the top of a 30 m mast visible?
seen_from = terrain.reverse_viewshed((20.5, 35.5), target_height=30.0) # bool array
# how tall can something be, per cell, and stay hidden from both watchers?
tall = terrain.hiding_height([(20.5, 20.5), (5.5, 30.5, 10.0)]) # float array
# exact shadow map for a sun in the south-east, 30 degrees up
lit = terrain.shadow(azimuth=135.0, elevation=30.0) # bool array
# hours of direct sun per cell over midsummer's day
from datetime import datetime, timezone
day = datetime(2026, 6, 21, tzinfo=timezone.utc), datetime(2026, 6, 22, tzinfo=timezone.utc)
hours = terrain.sun_hours(*day, lat=51.5, lon=-0.13) # float array
# the model GRASS r.viewshed uses
grass = viewshed.rviewshed(dem, gt, (20.5, 20.5), observer_height=1.6) # bool arrayTerrain(dem, transform, curvature=True, refraction=0.13, earth_radius=...) checks and copies the raster once (about 6 ms for 2,001 × 2,001 cells); the observer stands at its exact point. Terrain.viewshed takes height, target_height, max_distance, crop and mode: "exact" (the default), or "fast", which answers the same question in floats and from samples: some cells are wrong, mostly hidden ones shown, with no bound on how many. The other methods are exact only. The computation runs in Rust with the GIL released. viewshed.reference is the original pure-NumPy implementation, kept as an independent check.
min_distance, azimuth=(start, end) (clockwise from grid north) and elevation=(low, high) limit the field of view, in degrees. They only filter target cells, at the cell centre and ends included; ground outside them still blocks.
Terrain treats the DEM as heights at cell centres joined by bilinear interpolation, puts the observer at its exact point (not snapped to a cell centre) and decides line of sight to every cell exactly on that surface. Each decision is made in floating point only when rigorous rounding-error bounds prove it; the rare undecided sightlines are settled in rational arithmetic. So the output is identical, cell for cell, to the exact oracle in conformance/. The guarantee assumes sides of at most 100,000 cells, heights within ±1e7, a cell size between 1e-6 and 1e6, eye and target heights of at most 1e7 and an earth curvature drop of at most 1e7 across the raster (Terrain refuses anything else), cells taken as squares of side |transform[1]|, and a maths library whose sin, cos and atan2 are within 4 ulp (as on the usual platforms). No-data (NaN) never blocks and is never visible; a patch (the square between four cell centres) with a no-data corner has no surface. A sightline is blocked only where it passes strictly below the surface along a stretch of positive length, so touching a single grid vertex between two patches without surface (possible only on exact lattice directions at the edge of no-data areas) doesn't block it.
Large rasters (32,768 cells or more) are computed outward from the observer in rings, split into 64 angular sectors that run in parallel. Each sector keeps an analytic horizon of the terrain inserted so far. A cell certainly below that horizon is hidden without a sightline walk, whole 4×4 blocks of such cells are skipped together, and a cell certainly above it only has its last few cells walked. Small rasters walk each sightline with a max-height pyramid.
Speed on 2,001 × 2,001 windows of real terrain (wall time, best of three, 4 cores of an i5-8500T; observer 1.6 m above the ground, curvature and refraction on):
| Terrain | Observer | Visible | Exact bilinear | r.viewshed-model sweep (approximate) |
|---|---|---|---|---|
| Alps (Copernicus 30 m) | window centre | 0.6% | 0.21 s | 0.43 s |
| Alps | highest point | 11% | 0.42 s | 0.55 s |
| Iowa (USGS 3DEP 10 m) | window centre | 1% | 0.22 s | 0.43 s |
| Iowa | highest point | 6% | 0.34 s | 0.50 s |
| Kansas (USGS 3DEP 10 m) | window centre | 14% | 0.96 s | 0.53 s |
| Kansas | highest point | 37% | 0.89 s | 0.62 s |
| Wellington (1 m LiDAR) | window centre | 17% | 0.55 s | 0.51 s |
| Wellington | highest point | 48% | 0.85 s | 0.65 s |
The exact bilinear result is faster than this library's approximate r.viewshed-model sweep (same runs) on the Alps and Iowa windows, about level on the Wellington centre, and 1.3–1.8× slower where much of the terrain is visible (Kansas, the Wellington high point).
rviewshed is the model GRASS r.viewshed uses, so its results can be checked against GRASS. The observer stands at the centre of its cell. Every cell closer than the target is reduced to three height samples: its centre, and the two corners that bound it as seen from the observer, with each corner averaged from the four cells meeting there. A target (its cell centre plus target_height) is hidden when a closer cell's gradient, interpolated by angle at the target's direction, is steeper. With curvature on, every point is lowered by d²/(2R)·(1 − refraction) at horizontal distance d. No-data (NaN) never blocks and is never visible.
cumulative counts, for every cell, how many of a list of observers can see it (points along a walking route, a set of viewpoints, masts of different heights); visibility_index puts an observer on every n-th cell and gives each cell the fraction of them that can see it, a map of how exposed each place is.
route = [(10.5, 30.5), (20.5, 20.5), (30.5, 10.5, 10.0)] # (x, y) or (x, y, eye height)
counts = terrain.cumulative(route, height=1.6) # uint32 array
vi = terrain.visibility_index(stride=20, max_distance=3000.0) # 0..1 per cellBoth are exactly the sum of one viewshed per observer, spread over all cores, so they are exact in the same sense as viewshed, and the cost is one viewshed per observer. On 1,001 × 1,001 cells at 10 m with a 3 km range (Iowa and Kansas, 4 cores of an i5-8500T), 100 observers take about 2.7–5.8 s. Cells beyond max_distance of an observer count as not seen by it, so the index is lower near the raster's edge.
With a max_distance each observer only costs the window within it, in time and in memory: the counts are one array shared by all threads, and at most one viewshed per thread is in flight, so the number of observers and the size of the raster don't multiply the memory. The result is identical to summing whole-raster viewsheds, and doesn't depend on the number of cores.
Both take progress=, a function called as progress(done, total) while observers finish, on the calling thread. Returning False stops the run and raises viewshed.Cancelled; an exception stops it and propagates; Ctrl-C works too (the observers in flight are finished first):
counts = terrain.cumulative(route, progress=lambda done, total: print(f"{done}/{total}"))Terrain.line_of_sight decides exactly whether pairs of points can see each other: radio masts, sensors, any two points anywhere in the raster, each at a height above the ground.
masts = [(20.5, 20.5, 30.0)] # (x, y, height above ground)
sites = [(5.5, 30.5, 2.0), (35.5, 10.5, 2.0)]
ok = terrain.line_of_sight(masts, sites) # bool array, one per pairThe model is the bilinear surface: two points see each other when the segment between them is nowhere strictly below the surface along a stretch of positive length, with earth curvature and refraction as for viewsheds. The answer doesn't depend on which point is first, and for targets on cell centres it equals the bilinear viewshed. Most of each sightline is cleared by a bound (a bilinear patch never rises above its highest corner); stretches close to the ground are decided per patch in floating point with rigorous error margins, and the rare ones within the margin in exact rational arithmetic. On a 2,001 × 2,001 raster at 10 m, 20,000 links of up to 6 km take about 1 s on a 4-core laptop (about 50 µs per link).
fresnel_clearance gives the worst clearance of a radio link through the first Fresnel zone.
a, b = (5.5, 30.5, 10.0), (35.5, 10.5, 10.0)
ratio, t = terrain.fresnel_clearance(a, b, frequency=2.4e9, return_position=True)The link ends are (x, y, height above the surface) in metres. The result is the minimum, along the link, of the vertical clearance between the sightline and the terrain divided by the first-zone radius sqrt(lambda d1 d2 / D). A ratio of 1 means the whole first zone is clear, 0.6 is the usual planning target, 0 is grazing, and a negative ratio means the terrain blocks the line itself. t is the position of the worst point from a to b.
The calculation is exact on the bilinear surface, including curvature and refraction, and is certified to within 1e-9 + 1e-12 |ratio| of the exact rational-arithmetic value. Links run in parallel. Random links of up to 6 km between 30 m masts on 2,001 × 2,001 windows take about 7–8 µs each on farmland and plains (Iowa and Kansas, 10 m) and 360 µs on mountains (Alps, 30 m), averaged over 17,000–19,000 links on 4 cores of an i5-8500T.
Cells may differ from square by a relative 1e-9 and are then treated as square, so compared with the true transform, errors can slightly exceed the tolerances given here.
reverse_viewshed turns the question round: from which cells can a target at (x, y), target_height above the ground, be seen by an observer observer_height above each cell?
seen_from = terrain.reverse_viewshed((20.5, 35.5), target_height=30.0, observer_height=1.6) # bool arrayA cell is True when a viewshed from that cell would show the target, for every cell. That costs one exact viewshed: the sightline is the same segment both ways, the blocking rule (strictly below the surface along a stretch of positive length) doesn't depend on direction, and the curvature drop below the chord at a point is the same seen from either end, so it is the viewshed from the target with the two heights swapped (checked against the exact oracle run forwards from every cell). The target stays at its exact point; observers stand at cell centres. It takes about 2.3 s on 2,001 × 2,001 cells (4 cores).
shadow marks every cell lit or in shadow for a sun at a given azimuth (degrees clockwise from north) and elevation (degrees above the horizon), exactly, on the same bilinear surface as the exact viewshed.
lit = terrain.shadow(azimuth=135.0, elevation=30.0) # bool array, True = litA cell is in shadow when its ray towards the sun passes strictly below the surface along a stretch of positive length; rays that leave the raster are lit, and no-data cells are False and never cast shadow. The result is exact for the sun's direction vector as computed from the two angles in floating point (cardinal azimuths are exact): at 45°, for example, the ray rises by tan(45°) = 0.9999999999999999 per unit, not 1, which can move a shadow's edge by a cell on terrain built to tie. Most cells are certified lit by a running maximum along strips in the sun's direction; the rest are decided on their own ray with rigorous rounding-error bounds, and true ties in exact rational arithmetic. Earth curvature and refraction work as for viewsheds (refraction above 1 is rejected).
An exact shadow map takes about 0.5 s for 4 million cells (2,001 × 2,001 windows as above, 4 cores of an i5-8500T: 0.3–0.5 s with the sun 5–45° high). Approximate methods are faster or slower depending on the method, and differ from the exact map on a few percent of cells: a fast sampled sweep (Corripio 2003) is about 30–50 times faster and, on rough terrain at 2,001 × 2,001, differs on 0.5–1% of cells with the sun 15–30° high (missed shadow) and 1.5–2.5% at 5°; on 501 × 501 windows of rough terrain with the sun 5–30° high, GRASS r.sunmask differs on 1.6–4.9% of cells, mostly extra shadow within two cells of the shadow edge, and takes minutes.
horizon gives, for every cell, the elevation angle (degrees) of the highest terrain ahead in one direction: the input for sky view factor, terrain openness or a quick look at where the sun clears the skyline.
h = terrain.horizon(azimuth=135.0) # degrees, south-eastSame surface as shadow: heights at cell centres, bilinear between them, and the surface continues one cell beyond the outer cell centres, at the edge heights. Each value is the highest elevation angle of any point ahead on a stretch of positive length (no-data never counts), with earth curvature and refraction as for viewsheds. Cells with only no-data ahead get −90, no-data cells NaN. Negative horizons stay negative: GRASS r.horizon clamps at 0 (np.maximum(h, 0) to compare). A cell is shadowed by a sun at that azimuth exactly when the sun is below its horizon, so horizon maps and shadow agree. A horizon or shadow follows the floating-point direction of its azimuth, which is exact at multiples of 90°; at others (45° included) the rounding can make a ray touch a neighbouring patch that the ideal direction only meets at a corner.
Exact to within 10⁻⁹ in the tangent of the angle (certified for every cell), up to the final arctangent. Strips along the direction hold a tree of upper convex hulls of patch corners (with each strip's sideways tilt taken out), so most of the terrain ahead is ruled out without being looked at; the rest is evaluated in closed form with rigorous error bounds, and the rare cells that can't be bounded tightly enough are settled with their stretches decided in exact rational arithmetic. Speed depends on the terrain: one direction over 1,001 × 1,001 cells takes about 1.5 s on mountains (Alps, 30 m) and rolling farmland (Iowa, 10 m), 3–5 s on flat plains (Kansas, 10 m) and under 1 s on a smooth tilted plane (4 cores). The slowest case we know of is artificial: a tilted plane with centimetre noise, about 13 s, where many distant patches come within a hair of the horizon and can't be ruled out early. GRASS r.horizon agrees in grid-aligned directions, but in directions off the grid axes on rough terrain it is more than 0.5° off on 9–30% of cells (it samples along the ray), with 0.5–3.7% of cells flipping between lit and shadowed. It is also slower in wall time (3.5–8.8 s single-threaded against 0.8–2.0 s on 4 cores, 1,001 × 1,001, one direction), and about as fast per core. To compare, put the raster on its zone's central meridian or rotate the azimuth: r.horizon turns its directions to true north by the projection's grid convergence, while horizon uses grid north.
sky_view_factor and openness aggregate exact horizon maps over several directions. The horizons are exact on the bilinear surface; only the number of azimuths is a sampling approximation.
svf = terrain.sky_view_factor(kind="visible_sky", azimuths=32)
iso = terrain.sky_view_factor(kind="isotropic", azimuths=32)
opn = terrain.openness(kind="positive", azimuths=32)The visible-sky factor (Zakšek et al. 2011) is 1 - mean(sin(max(H, 0))) over the horizon elevations H. The isotropic factor is the diffuse sky view factor of Dozier & Frew (1990) for the local sloped surface, counting only sky above the horizontal and the slope's own plane: an open slope S gives (1 + cos S) / 2. Positive openness is the mean of 90° - H (Yokoyama et al. 2002); negative openness measures the terrain below the surface. The directions are evenly spaced clockwise from grid north, 32 by default. max_distance limits the terrain that counts.
At 32 directions, the azimuth-sampling error is about 5e-4 on rough mountains and 4e-5 on plains in our test windows. Exact horizons also remove the along-ray error of sampled tools: in the same study RVT's visible-sky factor was low by 0.0007–0.0094 and topocalc's by up to 0.01, mostly because those tools sample off the true ray. Computing 32 exact horizons is relatively costly (about 35 s for a 501 × 501 rough raster on 4 cores); fewer directions are faster.
With pip install viewshed[io] (rasterio), viewshed.io reads DEMs and writes results. No-data becomes NaN, the file's scale and offset are applied, and bounds reads only the cells needed.
from viewshed import io
dem = io.read_dem("dem.tif")
terrain = viewshed.Terrain(dem.z, dem.transform)
io.write_raster("seen.tif", terrain.viewshed((x, y)), dem)sun_hours adds up exact shadow maps over a time range: hours of direct sun per cell (float, NaN on no-data). sun_position gives the sun's azimuth and elevation at a place and time.
from datetime import datetime, timedelta, timezone
utc = timezone.utc
hours = terrain.sun_hours(datetime(2026, 6, 21, tzinfo=utc), datetime(2026, 6, 22, tzinfo=utc),
step=timedelta(minutes=15), crs="EPSG:32630") # float array, hours
sun = viewshed.sun_position(51.5, -0.13, datetime(2026, 6, 21, 12, tzinfo=utc)) # azimuth, elevation, elevation_trueTimes must carry a time zone (or be seconds since 1970-01-01 UTC). Each time step (default 15 minutes) uses the sun's position at the middle of the step and counts the whole step if the cell is lit; steps with the sun below the horizon count for nothing, and a last shorter step is sampled at its own middle. Each shadow map is exact for the sun position the package computes; the total over time is as fine as the step. The sun's position comes from the NOAA solar calculator equations (after Meeus), within about 0.02° of NREL's SPA for 1950–2050, and is computed once per step for the whole raster (across 50 km the sun's azimuth varies by about 0.3°). Two different refractions are involved: the sun's apparent elevation includes astronomical refraction (sunlight bending near the horizon), while refraction is the terrestrial coefficient used for the sightline over the curved earth, as for viewsheds.
Azimuths in the raster are measured from grid north, which differs from true north by the meridian convergence (a few degrees in UTM away from the central meridian). Pass it as grid_convergence (grid azimuth = true azimuth − convergence), or pass the raster's crs (anything pyproj accepts; needs pip install pyproj) and it is computed at the raster's centre, which also gives lat and lon if you leave them out. Without either, grid north is taken as true north.
A day at 15-minute steps on 2,001 × 2,001 cells takes 15–23 s on 4 cores (about 0.3–0.4 s per daylight step); a year at hourly steps, about half an hour.
How much exactness matters here: over a midsummer day, a fast sampled sweep (Corripio 2003) gave too few sun hours on average (0.01–0.09 h per cell), with 7.6% of cells on a 1 m lidar DEM and 2.6% on 30 m Alpine terrain off by an hour or more. That is 3–6 times the effect of realistic, spatially correlated DEM error on the same terrain; on flat 10 m farmland, DEM error matters more.
The version is written in four places (crates/viewshed/Cargo.toml, crates/viewshed-py/Cargo.toml, python/pyproject.toml, python/viewshed/__init__.py); python scripts/check_versions.py checks they agree. Add the release to CHANGELOG.md. Pushing a tag vX.Y.Z that matches runs the wheels workflow: it builds abi3 wheels for Linux (x86_64, aarch64), macOS (Intel, Apple) and Windows, installs and tests each one on Python 3.9 and 3.13, then publishes to PyPI (trusted publishing, pypi environment) and crates.io (CARGO_REGISTRY_TOKEN in the crates-io environment). Nothing is published if the versions and tag disagree or any test fails.
MIT OR Apache-2.0, at your option.