No description
  • Python 98.8%
  • Shell 1.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
surdeus 4e4eeac1fb erosion: add 'Erode terrain', stream-power erosion with depression fill
The third way of changing a DEM, and the only one that reads the drainage.
Blending and diffusion work on elevation; neither makes a valley, because a
valley is what water leaves behind rather than a shape.

E = K * (A/Amax)^m * S, so ground comes off where water runs steeply and
almost nothing happens on flat ridges. Twenty iterations on the Vir map's
mountain window cut channels 167 m deep at the default strength while the
9647 m summit moved 1 m. Diffusion reached similar smoothness only by
removing 30% of that summit.

Two bugs found by testing, both of which had been reporting success:

  Accumulation was used as a raw cell count, which is not scale-invariant.
  A continental catchment reaches millions, A^0.5 reaches thousands, and one
  iteration removed kilometres of rock - the first full-map run flattened an
  entire continent to zero. Dividing by the largest catchment in the window
  makes strength mean "metres per iteration in the biggest channel", the same
  at any scale.

  Slope was divided by grid distance but not by pixel size, so a 78 m drop
  across one diagonal cell read as 55 m/m - a 89 degree face. That made every
  earlier calibration compensating for it, and it is why the first attempt
  flattened terrain.

Depressions are filled by priority flood before eroding: water cannot climb,
so a closed pit stops erosion and leaves a flat-bottomed hole.

The area mask is now honoured. It was accepted and ignored, and skipping
tiles outside it took a one-continent run from a quarter of an hour to four
minutes.

Deposition was prototyped and measured, then left out on purpose: 2.4x slower,
recovers only 58% of lost mass without an outlet trap, and reduces valley
formation by filling the channels it carves. erosion.erode_window accepts the
parameter and raises NotImplementedError rather than ignoring it, so the seam
is ready. The README records all of it.

16 new tests, 122 total.
2026-11-20 21:53:27 +05:00
qgis_smoothie erosion: add 'Erode terrain', stream-power erosion with depression fill 2026-11-20 21:53:27 +05:00
tests erosion: add 'Erode terrain', stream-power erosion with depression fill 2026-11-20 21:53:27 +05:00
.gitignore qgis-smoothie: smooth terrain from polygons 2026-11-20 01:39:11 +05:00
build.sh build: produce an installable ZIP instead of a symlink installer 2026-11-20 01:42:46 +05:00
README.md erosion: add 'Erode terrain', stream-power erosion with depression fill 2026-11-20 21:53:27 +05:00

qgis-smoothie

Two tools for DEM terrain: build it from polygons, or repair what polygon burning left behind.

  • Smooth terrain from polygons — give a polygon and one elevation value; the value ramps from the boundary to the centre along a chosen profile, so one polygon makes one hill — no stacking concentric rings, no thinking about the order of features.
  • Blend levels — the inverse. Takes a DEM that is a staircase of flat bands and grades each step into a slope, leaving the plate interiors alone.
  • Raise land from its coast — gives a landmass burned in as a flat polygon the natural rise from its shoreline inland, driven by distance from the coast so it follows the real outline.
  • Erode terrain — carves valleys by stream-power erosion: removes ground where water actually flows, so ridges survive while channels deepen.
  • Replace DEM file — the commit step. Pick the DEM layer you already have; it writes the new data over the file behind it — grid-checked, re-compressed, swapped atomically, stale statistics removed, and the layer reloaded so the map updates.

profile

Why

Rasterising polygons into a DEM is easy, but it produces flat plateaus with vertical walls. Getting a slope means drawing many polygons, each slightly smaller and slightly higher, in the right order. That is tedious and falls apart the moment two hills overlap.

The interpolation here is driven by distance from the polygon boundary, not by area or radius. That is what makes it work on a shape that is not a circle: an elongated valley ramps across its width and stays flat along its length, and a concave coastline still gets an inward gradient everywhere.

A DEM already built the hard way — by burning bands on top of each other — still carries the staircase. Blend levels is there for that, and it is the same machinery run backwards: both tools interpolate along a distance field, so the profile chosen for blending becomes the shape of the riser.

Profiles

Seven curves, all running from 0 at the edge to 1 at the centre, so switching between them changes the slope and never the summit. Every one is monotonic and hits both endpoints exactly — a profile choice is never a way to move the peak or tear the seam.

profile shape gradient
linear straight cone constant
smooth smoothstep 0 at both ends, peak mid
cosine gentlest shoulders 0 at both ends, peak mid
plateau mesa: flat top, steep flanks 0, then sudden
gaussian dome, slightly skewed 0 at rim, eased at crest
hillslope convex crest, straight face, concave foot 0 → 1.43 → 0
valley steep rim, flat floor 2.50 → 0
mountain talus apron, rock face, sharp peak 0 → 1.25, no easing

hillslope — for real hills

The one worth defaulting to for terrain. A real hillslope is not a symmetric S: it has three units, and they are not equal.

  • concave foot (0.35 of the radius) — the gradient builds from nothing as the slope leaves the surrounding ground
  • straight face (0.40) — a constant slope at roughly the angle of repose
  • convex crest (0.25) — the gradient eases to nothing at the summit

Two consequences fall out of that on purpose:

  • The gradient is continuous but its derivative is not, so there are two sharp breaks of slope. Real hillslopes break exactly there, where one process hands over to another — at the top of the free face and at the base of the debris slope.
  • The crest is shorter than the foot, because colluvium spreads out at the base over a longer distance than the summit rounds off. Symmetric curves cannot express this, which is the whole reason this profile exists.

Measured against an independently constructed three-unit reference — with foot and crest proportions deliberately different from the ones above, so it is not the curve compared with itself — RMSE is 0.010–0.015, against 0.026–0.031 for cosine and smooth. Roughly half the error.

valley — for valleys, basins and broad uplands

The gradient is steepest at the rim and eases to zero at the centre, so the middle becomes a flat floor. Give it a negative value for a valley or basin, or a positive value for a broad flat-topped upland with steep margins.

This is the useful difference from hillslope: with hillslope a valley keeps a rounded shoulder and gets its steepest gradient partway down the wall; with valley the walls are steep right at the shoulder and the floor is wide.

mountain — for real mountains

Steepness is not what separates a mountain from a hill. That is relief over radius — a matter of how big you draw it, not of shape. The difference that does show in a profile is what happens at the summit, and at the base.

  • Hills are soil-mantled and transport-limited. Their crests round off, so the gradient falls to zero at the top.
  • Mountains are rock and detachment-limited. The steep face persists to the summit, so the peak is sharp.
  • Mountains shed debris into a talus or alluvial apron, so the lowest slopes are noticeably gentler than the face above — a concave transition.

The profile is therefore: gradient rising from 0 across a talus apron (0.30 of the radius), then held at full value all the way to the summit, with no easing.

That combination is unique in this plugin, and there is a test that keeps it that way. Measured across all eight profiles:

profile gradual apron keeps gradient at the crest
linear no yes
plateau no yes
smooth, cosine, gaussian, hillslope, valley yes no
mountain yes yes

On a 70 km radius disc painted to 6000 m over 1 km cells:

hillslope summit and neighbours:  5998  5999  6000  5999  5998
mountain  summit and neighbours:  5831  5933  6000  5956  5855

The hillslope top is rounded to within 2 m; the mountain drops 44 m in one cell. A point, not a dome.

Ridges come for free

Paint an elongated polygon with mountain and the sharp crest becomes a ridge line. The distance transform's maximum runs along the middle of the shape, so a profile that stays steep at the summit turns that line into an arête rather than a rounded ridge.

Same footprint, painted to 5000 m — the drop from crest to the next cell:

profile crest to next cell form
hillslope 3 m rounded ridge
mountain 176 m sharp crest

So a mountain range is a long thin polygon, not a row of circles.

A note on what was measured, and what was not

The profiles were validated against geomorphological models, not fitted to the DEM in this map. That DEM is painted, not surveyed: 98.1% of adjacent land cells differ by exactly zero metres, and only 0.14% of steps exceed 500 m. There is no natural hillslope signal in it to learn from.

Against the linear-diffusion model of hillslope evolution — the standard physical account of soil creep relaxing a slope — cosine and smooth already score well (RMSE 0.037 and 0.044), because diffusion of a symmetric step yields a symmetric S. That model is symmetric, so it cannot justify hillslope; the three-unit description does.

Absolute or relative

  • Absolute — the centre becomes exactly the elevation you typed.
  • Relative — the value is added on top of what is already there, so a 500 m hill with a value of 1000 becomes a 1500 m hill and keeps its shape.

Negative values work in both modes: a basin is just a hill with a minus sign.

Anchoring

  • Blend into terrain (default) — each cell ramps from its own current elevation, so the painted area joins the surrounding ground with no visible step. The result reaches the target exactly at the centre and equals the original terrain at the rim.
  • Flat base — every cell ramps from one constant. This gives a cleaner geometric shape, but leaves a step wherever the boundary crosses a slope.

The step in the flat case is usually invisible: on the Vir map, natural terrain already changes by up to 470 m between adjacent 1 km cells, so a 128 m boundary step is inside the noise. Use it when the polygon edge sits on flat ground and you want a tidy cone.

Overlaps need no ordering

Where features overlap, the higher ground wins — but only once a cell has already been painted. The first feature to touch a cell sets its value; a later feature sharing that cell may only raise it.

That single rule gives both behaviours that matter:

  • two overlapping hills merge into a ridge, at a saddle where they meet;
  • a basin can still lower the ground, because it is the first writer there.

You never have to sort the attribute table or worry about which polygon comes first.

Memory

Each polygon is processed inside its own bounding box, so peak memory is set by the largest polygon, not by the size of the DEM. Painting three peaks into a 24,002 x 14,078 grid (338 million cells) takes about 3 seconds and 1 GB of RSS, because only a handful of small windows are ever held in memory.

The output is streamed from the input with CreateCopy, so the DEM is never loaded whole.

Blend levels — repairing a staircase DEM

A DEM built by burning polygons of increasing height is a staircase: flat plate, one-cell cliff, flat plate. Every cell is either perfectly level or jumping, so the gradient is zero almost everywhere and infinite at the band edges. A hillshade turns each edge into a hard line and the map reads as a stack of contours.

The slopes are not the problem. A 100 m step over a 1 km cell is 5.7 degrees, an ordinary hillside. The problem is that the gradient is discontinuous — it steps from 0 to that value and back to 0 within three cells, which no real terrain does.

Width: minimum first, slope cap second

half_width = max(min_width, |step| / (pixel_size * tan(max_slope))) / 2

The minimum width does the real work, and the slope cap is a second clause for genuinely large cliffs.

This combination is not arbitrary. Measured on the Vir map, a 25 degree cap alone left 97% of band edges untouched, because 93% of them are gentler than 15 degrees. A slope cap by itself would have looked like the tool did nothing.

Two methods

Method chooses what the pass actually does, and they are not equivalent.

  • Grade band edges (default) — widens each step between bands into a slope. Touches only a riser's width in from an edge, so a wide plateau keeps its flat middle. Peaks keep their height.
  • Diffuse everything — relaxes every interior cell toward its neighbours, the hillslope-diffusion model of soil creep. Reaches the inside of plateaus, which is the only way to remove them with this tool.

Diffusion is far more effective and it is destructive. On the Vir map's mountain window:

setting flat peak largest step mean
original 99.8% 9746 m 3864 m 217.3
diffuse, 10 passes 64.9% 6774 m 880 m 217.0
diffuse, 50 passes 42.2% 4774 m 880 m 216.7
diffuse, 200 passes 29.0% 3055 m 880 m 216.2

Ten passes already cut the plateau fraction and the largest step by more than three quarters. It also takes 30% off the highest summit, and fifty passes take half. That is real erosion, not a display artefact: the equation has no notion of a peak worth keeping, so it dissipates one like any other bump.

Mean elevation is preserved exactly in diffusion mode — verified to the last digit, because the scheme is written in flux form. Elevation that silently appears or vanishes would be invisible on screen and would corrupt any volume or hypsometric figure taken from the DEM later. The first implementation leaked 25% of the total over 200 passes; that is the bug this guards against.

Cells touching the coastline are held fixed, so the sea is a wall rather than a sink.

Passes

One pass only reaches cells within a riser width of a band edge, so a wide plateau keeps its flat middle. Passes re-grades what the last pass left, which is how flat ground is progressively broken up:

pass   flat%   max step   marginal change
   0   99.8%      3864 m
   1   80.6%      2212 m        1,950,060
   2   77.7%      2240 m          657,698
   3   76.0%      2593 m          506,189
   5   73.9%      3044 m          359,691
  10   69.9%      3044 m          236,011

Each pass moves the surface less than the one before — the sequence settles rather than drifting. It never stops completely, which is what makes the parameter useful rather than decorative.

There is a trade-off to watch: past two or three passes the plateau fraction keeps falling but the largest step starts climbing again, because repeated grading creates steeper joins between risers than it removes. On the Vir map's mountain window, one pass gave the best result on both counts.

Narrow bands

Bands two or three cells wide are common in steep terrain, and an earlier version of this tool skipped them: it required four of a cell's eight neighbours to agree before treating it as flat, which no narrow band can satisfy. Those cells stayed put while their neighbours were graded, which raised the largest step in the mountain area from 3864 m to 4051 m — the tool was making the worst terrain worse.

Treating a cell as flat when any neighbour matches fixes that. The same pass now gives 2212 m instead of 4051 m.

Riser shapes

riser continuity at the plateau effect
linear C0 visible crease where it meets flat ground
smooth C1 gradient continuous, curvature jumps
soft C2 gradient and curvature both continuous

soft is the default. It is smootherstep applied across the whole riser, so the join to untouched flat ground is invisible even under a hillshade. The measured slope at the join, as a fraction of the steepest slope in the riser: linear 0.50, smooth 0.06, soft 0.01.

What it will not do

  • Ordinary slopes are never shaved. A step is only graded if the ground on both sides of it is flat, judged over the whole 3x3 neighbourhood. A grader that accepts any difference treats every hillside as a terrace and erodes it a little more on each run.
  • Running it twice does not keep going. Because the risers it paints are no longer flat, a second pass finds no qualifying edges and changes nothing. Verified by test.
  • Narrow bands are not preserved. A band one or two cells thick between two others is thinner than the riser, so it gets reshaped, and the local maximum step can end up fractionally larger. Plateaus smaller than about 3x3 cells are treated as peaks rather than bands and are left alone — on the Vir map those are the 9746 m summit (6 cells) and the 8093 m one (12 cells), which are spikes, not bands.

Measured on the Vir map

24,002 x 14,078 grid, min_width=3, max_slope=35, riser soft:

                      before    after
edges steeper than 15 deg   6,471    4,726
edges steeper than 25 deg   2,921    1,726
edges steeper than 35 deg   2,675      781
curvature, 99.9th pct         692      316
cells with curvature > 100  15,110    7,548

Curvature halved is the number that matters: it is curvature, not step height, that makes band edges visible in a hillshade. Whole raster took 36 seconds and changed 4% of cells. Sea cells were untouched and the flat plate interiors byte-identical.

Wider settings grade further — on the same cross-section, min_width 3 leaves one intermediate value per step, 6 leaves two, 10 leaves three:

before:        130 130 ... 97 97 ... 57 57 ... 0
min_width  3:  121  98 ... 86 58 ... 56 16
min_width  6:  129 118 102 ... 96 82 63 ... 49 21 1
min_width 10:  126 116 105 100 ... 92 80 67 61 ... 52 42 24 7

Restricting it to polygons

Blending the whole DEM is not always what you want: some plateaus should stay crisp, and it is easier to fix one region at a time. Give a polygon layer and the tool works only there — or only outside it, which is how to protect areas you want left alone.

The polygons do not have to be saved. Scratch layers, memory layers and temporary outputs work, because the features are read from the QGIS feature source rather than by opening a file. A layer in a different CRS from the DEM is reprojected first, on the QGIS side.

The polygons choose which steps are graded, not which cells may change. That distinction is the whole design, and it was measured rather than assumed.

A step belongs to an edge, and the riser spans several cells either side. If the mask stopped the writes at its own boundary, the riser would be sliced in half and the result would be a fresh step exactly where the mask ends. On a synthetic stair of 0/400/800/1200 m bands with a mask ending mid-riser:

full blend      ... 809  858  947  1053  1142  1191  1200 ...
naive cell mask ... 809  858  947 | 1200                   seam of 253 m

The naive version replaces a 400 m step with a 253 m step and puts it somewhere new. Letting the selected riser run to completion instead gives the same seamless result as a full blend inside the area, and leaves everything else untouched. Verified on the Vir map: running inside a 400x400 km box changed 19,383 cells inside it and 97 just outside, where risers crossed the boundary — and the largest step across the box edge was 117 m before and 117 m after, so nothing new appeared there.

Nodata matters

Many DEMs use a sentinel such as -1 for sea without declaring it as nodata. The Vir map does: the raster declares no nodata value at all, so without telling the tool, the coastline is treated as a band edge and graded like any other step. Set the nodata value parameter to stop that; the tool then leaves those cells byte-identical.

Raise land from its coast

A continent burned in as a flat polygon sits at exactly one elevation. If that is 0 it is indistinguishable from sea level and reads as water someone forgot to colour blue. Nothing on Earth is like that: the flattest large lowland rises 100–150 m over 2,000 km, and every coastline has ground rising behind it.

This tool ramps elevation from the coast inland. Three things make it work on a real outline rather than a rectangle:

Distance from the coast, not radius. The ramp is driven by how far each cell is from the nearest shore, so bays, peninsulas and concave coasts get the gradient that belongs to them instead of a bulge out of the polygon's middle.

Proportional to each landmass. Every feature is measured against its own deepest interior point, so a small island does not get a ramp calibrated to a continent.

A beach. The first few kilometres stay at the coastal elevation. That is what stops the shore looking cut out with a knife.

Two modes, and neither lowers anything

mode raises
Fill only ground already at the coastal elevation
Surface anything lower than the ramp

Fill leaves mountains, plateaus and valleys exactly as they are, so it can be run over a part-finished map without disturbing work already done. Surface also raises ground below the ramp, which is how a bare draft continent gets a base shape in one pass.

Both take the higher of what was there and the ramp. Nothing is ever lowered — there is a test for it, and it is what makes the tool safe to run repeatedly.

Measured on a draft continent

9.8 million land cells, 1,224 km from coast to deepest interior:

distance inland     mean elevation
     1-5 cells           0.0 m      beach
    5-25 cells           0.0 m      beach
  25-100 cells           0.4 m
 100-300 cells          12.0 m
 300-600 cells          78.5 m
 600-1224 cells        210.5 m

The coast ring is exactly 0 and the deepest cells land exactly on the target. Whole run: 3 seconds.

Interior height: fixed, or scaled by landmass size

Interior height decides what a landmass's middle should reach.

Fixed gives every landmass the same elevation, whatever its size. Simple and predictable.

Scale with landmass size gives small islands less and large continents more, following how real landmasses behave. The exponent comes from a least squares fit of interior elevation against maximum distance-from-coast for six real landmasses:

landmass depth real interior model
Malta-scale island 20 km 50 m 75 m
Sicily 120 km 300 m 174 m
Iberia 700 km 600 m 396 m
Australia 1,500 km 350 m 566 m
North America 2,500 km 700 m 718 m
Eurasia 3,500 km 800 m 841 m

h = 18.5 · d^0.47, RMSE 133 m. Doubling a landmass's depth raises its interior by about 39%, not 100% — bigger continents are higher, but not dramatically so.

The parameter is stated as a reference: "interior elevation applies at this depth". Set 200 m at 1,000 km and everything scales from there. The exponent is exposed because the Earth fit is only a starting point for a fictional world.

On six real landmasses from this map, with 200 m at 1,000 km:

depth    fixed    scaled
1225 km   200 m    220 m
 911 km   200 m    191 m
 694 km   200 m    168 m
 578 km   200 m    155 m
 460 km   200 m    139 m

Climb distance, and why proportional can look like nothing

Climb distance caps how far inland the climb is spread. 0 means proportional — the ramp finishes at the deepest interior point, however far in that is.

Proportional is the geologically honest choice, and on a wide landmass it is close to invisible. Measured on Lacon, 460 km from coast to deepest interior:

distance inland proportional capped at 100 km
25 km 0.3 m 21.5 m
50 km 2.5 m 92.7 m
100 km 16.4 m 200 m

A 200 m climb spread over 460 km adds a third of a metre in the first 25 km, which rounds away in a 1 m DEM. That is not a bug, but it looks exactly like one. The default is 100 km so the coast visibly rises; set 0 when you want the real proportions and are willing to accept a nearly invisible result.

Fill mode does nothing to land that already has height

Fill mode raises only ground at the coastal elevation. Point it at a finished continent and it will correctly leave almost everything alone: Lacon is 90% above 0 m already, so only the 9.6% sitting at exactly sea level can move.

The algorithm now reports this:

raised 196,354 cell(s) of 2,076,649
91% of the selected area was already above the coastal elevation and was left
alone, which is what fill mode does. If the landmass already has terrain,
there is nothing for this tool to add - it is for flat polygons burned in at
one height.

If you want the whole surface lifted regardless, use Surface mode.

A note on the cross-section

Elevation depends on distance from the coast, so a straight line across a landmass with two lobes can rise, fall and rise again. That is correct: the middle of the line is close to water on both sides. Judge the result by the distance table above, not by one transect.

Erode terrain — carving valleys

The third way of changing a DEM, and the only one that reads the drainage. Blending and diffusion both work on elevation — how far a cell is from an edge, or from its neighbours. Neither produces a valley, because a valley is not a shape; it is what water leaves behind.

Material is removed in proportion to how much water crosses a cell and how steeply that water is falling:

E = K · (A/A_max)^m · S

Where a lot of water runs down a steep face, ground comes off. On a broad flat ridge, almost nothing happens. Repeated, valleys deepen while ridges and summits stay put — the opposite of what diffusion does to the same terrain.

Measured on the Vir map

Mountain window, 600 × 500 cells, 20 iterations:

strength deepest cut mean peak
0.1 59 m −0.1% −0.2%
0.3 (default) 167 m −0.4% −0.5%
1.0 502 m −1.3% −1.5%

Channels incised more than 5 m below their surroundings:

before erosion:   1 of 3,386   (0%)   ← no valleys at all
K = 0.3:        591 of 9,949   (6%)
K = 1.0:      3,447 of 11,698  (29%)

Contrast with Blend levels in diffusion mode, which reached a similar smoothness only by removing 30% of the summit. Erosion removes 0.5% of it.

Strength is scale-invariant

The accumulation is divided by the largest catchment in the window before the power is applied, so strength means metres cut per iteration in the largest channel — the same on an island as on a continent.

This matters because it was not always so. Using raw cell counts, a continental catchment reaches millions, A^0.5 reaches thousands, and a single iteration removed kilometres of rock: the first full-map run flattened an entire continent to zero in twenty passes. Divide by the maximum and the parameter behaves the same at every scale.

Depressions are filled first

Water cannot climb. A cell with no lower neighbour traps everything that reaches it, and erosion stalls there leaving a flat-bottomed hole. Priority flood raises each closed depression to its lowest outlet — the smallest change that lets water leave — and the number of cells raised is reported, because it also measures how much the DEM disagrees with itself.

The area polygon really restricts it

Give a polygon and only the land inside is eroded. Tiles whose core has no mask are skipped entirely, which is what made a one-continent run take four minutes instead of a quarter of an hour across the whole raster.

Deposition: not implemented, and why

Real erosion moves material. What comes off a slope is carried downstream and dropped where the water slows. This does not — what is removed is gone, and mean elevation falls about 1% over twenty passes.

It was prototyped and measured before being left out:

erosion only with deposition
code 23 lines 48 lines (+25)
speed, 600×600 window 1.05 s 2.75 s (2.6× slower)
mass lost 2.30M cell-metres 0.97M (−58%)
channels incised 8% 5%

It is roughly 25 lines and one parameter away, but it costs two and a half times the runtime — it cannot vectorise, because sediment must be routed downstream in elevation order, one cell at a time — and it reduces valley formation by filling the channels it carves. Mass is not fully conserved either, because sediment still exits at the domain boundary; true conservation needs an outlet trap, which is a modelling decision rather than a bug fix.

erode_window(..., deposition=...) exists and raises NotImplementedError rather than ignoring the argument, so the seam is ready if it is ever wanted.

Replace DEM file — committing the result

The other two algorithms produce a new raster. This one makes it the real dem.tif.

It looks like it should be two lines of shutil.copy, and it is not, because four things go wrong quietly:

The grid. A DEM with a shifted extent or a different pixel size looks fine on its own and breaks everything around it — draped layers sit wrong, the hillshade is offset, the project's default view no longer matches it. So the source is checked against the target's size, geotransform and CRS before anything is written, and a mismatch is refused. Nothing is resampled, because resampling invents data.

The size. QGIS writes GeoTIFFs uncompressed by default: the same 24,002 × 14,078 int16 grid is 3 MB compressed and 675 MB raw. Swapping a tuned DEM for a raw temporary layer makes the repository 200× larger with no warning anywhere. The replacement is therefore re-encoded with DEFLATE, a predictor and tiling rather than copied byte for byte.

The write. gdal.Create() over a file that is already open truncates it while the open handle still points at the old data — a half-written DEM and a reader showing stale values. The new data goes to a temporary file in the same folder and is renamed over the target, which is atomic.

The sidecar. GDAL caches statistics in <name>.aux.xml. A stale one outlives the data it describes and reports the old elevation range in layer Properties, which then looks authoritative.

Choosing the target

DEM layer to replace is a layer picker, so you pick the dem layer that is already in the project rather than typing a path. The tool replaces the file behind it and reloads it, so the map updates in place.

A layer can be in memory, in which case there is no file to replace — the tool says so instead of failing inside GDAL. Picking the same raster for both inputs is refused too.

Scripting still works: the parameter accepts a plain path string as well as a layer object, so processing.run(..., {'TARGET': '/path/dem.tif'}) is fine.

What it reports

Two counts, because they answer different questions:

  • verify_changed — does the new file hold exactly the source? Must be 0. A non-zero figure means the write did not land and the run failed.
  • changed — how much of the map actually moved, measured against the backup. On the Vir DEM a global blend reports 250,530 of 337,900,156 cells.

Plus the elevation range before and after, and the file size either side, so a wrong raster that slipped onto the file is visible rather than plausible.

The reload is the part people forget

After an atomic swap the file on disk is correct and the layer keeps showing the old values — it still holds a handle on the replaced inode. Nothing indicates this. The algorithm reloads every project layer whose source is the replaced path, and reports which ones it reloaded. Verified end to end: a layer showing 0.0 before the replacement showed 15.0 afterwards, with its renderer, opacity and layer identity intact.

Cost per iteration

Measured against git, since the DEM is tracked:

operation cells changed commit cost
local hill edit 2,601 ~20 KB
global blend 327,772 ~190 KB

Tiled DEFLATE changes only the affected tiles, so git's delta compression does well. Fifty local edits add about a megabyte; keeping the DEM tracked is fine and there is no need for LFS or external storage.

Requirements

  • QGIS 3.40 or newer (tested on QGIS 4.2.2)
  • Python numpy (already required by QGIS)
  • GDAL with OGR vector support (bundled with QGIS)

No external Python packages, no compilation.

Build and install

./build.sh                 # -> dist/qgis_smoothie-<version>.zip
./build.sh --clean         # discard dist/ first

Then in QGIS:

  1. Plugins -> Manage and Install Plugins -> Install from ZIP
  2. Select dist/qgis_smoothie-0.1.0.zip
  3. Enable it under the Installed tab

It appears in the Processing toolbox as Smoothie -> Smooth terrain from polygons.

Why the archive layout is checked

A QGIS plugin ZIP is not just "the folder zipped". QGIS looks inside for a single directory whose name becomes the Python module name, and requires metadata.txt at that directory's root. An archive with files at the top level, or a folder named qgis-smoothie with a hyphen, installs without error and then silently never appears.

build.sh therefore asserts the shape after writing, and deletes the archive and fails if anything is off:

  • every entry lives under qgis_smoothie/
  • metadata.txt and the four modules are present at that level
  • __pycache__ and *.pyc are excluded — a .pyc compiled on the build machine will be loaded on another and fail in confusing ways
  • -X strips uid, gid and timestamps, so the same sources produce the same bytes

The version in the filename is read from metadata.txt, so bumping the plugin version is one edit and the archive name follows.

Use

  1. Draw a polygon wherever you want the land to rise.
  2. Add a numeric field for its height, e.g. elev.
  3. Processing toolbox -> Smoothie -> Smooth terrain from polygons.
  4. Pick the DEM, the polygon layer, the field, a profile, and run.

For an existing staircase DEM, run Smoothie -> Blend levels instead. Both algorithms write a new raster; neither overwrites its input, and neither accepts its own output path as input (GDAL would truncate the file while still reading it). To replace the DEM, write to a new name and swap.

The result is a new raster. Compare it against the original before replacing anything.

Any layer works, saved or not

The polygons do not have to exist on disk. Scratch layers, memory layers and temporary outputs of other algorithms all work, because the features are read straight from the QGIS feature source rather than by opening a file.

That matters for the obvious workflow: draw a shape, try a profile, look at it, adjust, try again. Nothing has to be saved between attempts, and nothing has to be cleaned up afterwards.

The only thing that must be a real file is the input DEM, because GDAL reads it as a raster. The output is written by the algorithm's own output parameter, so a TEMPORARY_OUTPUT works there too.

If the polygon layer is in a different CRS from the DEM, its features are reprojected on the fly and the algorithm reports which CRSs it used.

Tests

Both cores are free of QGIS imports, so they can be tested directly:

python3 tests/test_interpolation.py       # 26 tests
python3 tests/test_blend.py               # 22 tests
python3 tests/test_coast.py               # 18 tests
python3 tests/test_erosion.py             # 16 tests
python3 tests/test_replace.py             # 18 tests

test_interpolation.py covers: exact distance transform against brute force, profile endpoints and monotonicity, hillslope curvature signs and asymmetry, mountain's apron-plus-sharp-peak signature and its uniqueness among the profiles, a peak landing exactly on target, no step at the seam, basins lowering ground, overlap merging, elongated shapes not turning circular, sparse overlap bookkeeping, and the full driver path.

test_replace.py covers: the grid refusals (size, origin, pixel size, CRS, each naming the field), compression applied on write, the target's projection kept, backup made and skippable, no staged file left behind, a mismatch leaving the target byte-identical, stale sidecar removal, and changed-cell and elevation-range reporting.

test_blend.py covers: riser continuity at the plateau, the two width clauses, coastlines not being treated as band edges, flat interiors untouched, sea preserved exactly, cliffs turning into ramps, gradient vanishing at the join, idempotence on a second run, mean elevation holding steady, mask selecting edges rather than cells, no seam where a mask ends, an empty mask changing nothing, and band edges on the raster rim still getting graded.

Known limits

  • Distance is measured in cells, in the pixel's own units. Anisotropic pixels (different x and y size) would make the ramp slightly elliptical. The tool still uses the exact Euclidean transform on the cell grid; it does not rescale by pixel size, because doing so approximately would be worse than not doing it. Use square pixels.
  • Only the first band is read. Multi-band rasters are copied as they are, with band 1 repainted.
  • A polygon thinner than about three cells has no room to ramp and is set flat at its value.
  • No feather outside the polygon. The ramp ends at the boundary. With blend into terrain that is seamless; with flat base on a slope it is not.
  • The output always rewrites the whole raster as DEFLATE-compressed GeoTIFF, so it can be much smaller than the input — or larger, if the input was already well compressed.

Licence

GPL-3.0, matching QGIS.