In this series: Part IV, Surfaces. Chapters 9 and 10 drew mountains in two ways. This chapter uses the commands for mountains on other data: distance, temperature, rain, and the photograph of a piece of cloth
You will build: A batik as a relief, the distance to the sea on Sulawesi and its direction, the middle line of an island, the areas around the airports, errors in a rain map, and the cold fronts in the sea south of Java
You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 8 explains a raster of distances
Time to run: The commands took about a minute when tested, including 2 MB of downloads, or none with the copies in the folder
Level: Intermediate; the commands are short, and their use is new
GDAL has commands for mountains: hillshade, slope, aspect, roughness. They take a grid of heights, and compare each cell with its eight neighbours. They do not check whether the numbers are metres above the sea.
So they also work with other numbers. A distance can be used as a height: the coast is at zero, and the land rises towards its middle. A temperature can be used as a height, and so can the rain of a year, or the brightness of a piece of cloth. The same commands then answer other questions. In which direction is the nearest sea? Where are two coasts equally far? Where does the sea change from warm to cold?
NoteLearning objectives
By the end of this chapter you will be able to:
use any grid of numbers as a surface;
read aspect as a direction to a target, and colour it with a circle of colours;
put a colour key into the data itself;
find the lines where two coasts are equally far, with slope;
use shading to find errors in data that a colour map hides;
give a slope a unit with a meaning;
choose colours that change at one important value.
Before running this chapter, do section 1 of Chapter 0 and section 5 of Chapter 1. In a terminal, make a new empty folder and copy into it the files of sample-data/ch11. In this notebook, the next cell does that.
import sysimport timefrom pathlib import Path# The repository root, whether the notebook runs from en/, id/ or the root itselfROOT = Path.cwd() if (Path.cwd() /"tutorial.yml").exists() else Path.cwd().parentsys.path.insert(0, str(ROOT /"src"))import onelineT0 = time.perf_counter()WORK = oneline.start("11")print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT /"sample-data/ch11").iterdir()))
A few short commands first, in the form of Chapter 0. The file alas.jpg is a photograph of a batik from before 1891. The pattern is called Alas-alasan, and shows the animals of the forest (ledger L99):
A photograph is a grid of numbers, like a relief. Bright places are high, and dark places are low. So apply shading to it:
Look before moving on. One command has turned a cloth into a relief. The blue ground is low, and the brown animals are high. The weave of the cloth is visible, too. -z 0.05 makes the heights twenty times smaller, because a step from 20 to 200 from one pixel to the next would be extremely steep.
Another command for mountains makes a drawing with thin lines. roughness is large where neighbours are different, which is at every line:
The second line exchanges black and white: 0 becomes 255, and 160 becomes 0. At the right border of the cloth, in the middle, there is a line of handwriting that is hard to see in the photograph. These commands were not made for photographs. They calculate the same as for a relief.
1. Distance as height
Take Sulawesi, the island with four long peninsulas, and calculate for every place how far it is from the sea. Chapter 8 did that. But now draw the result as a relief: the coast is at 0 m, and a place 10 km from the sea is 10 km high.
Look before moving on. The surface has the form of a roof. Every face goes down to the coast that is nearest to it, and every ridge is a place where the nearest coast changes. Small bays make small valleys in the faces. The real mountains of Sulawesi are not in this picture at all.
A house with this ground plan, and with the same steepness everywhere, would have exactly this roof.
2. In which direction is the sea?
aspect gives the direction in which a slope goes down. On this surface, “down” is the way to the nearest sea. So the command answers a different question here: in which direction is the nearest coast?
The answer is a direction, and directions form a circle. 359 degrees and 1 degree are neighbours. The colours must do the same, so the file way.txt goes once around the colour circle. All its colours are equally bright (L* is 66 everywhere), because north is not more than south.
A map with such colours needs a key. It can be made from a shape that slopes in all directions at once: a cone. So add an invented round island in the sea, and the same commands turn it into the key. The title of the map can be made from land in the same way:
ogr2ogr-update-append ground.gpkg letters.gpkg.zip -dialect SQLite -sql"with recursive c(i) as (select 1 union all select i+1 from c where i<8), t as (select i, geom, sum(advance) over (order by i)-advance x from c join letter on code=unicode(substr('SULAWESI',i,1))) select st_buffer(shiftcoords(scalecoords(geom,50000,50000),570000+50000*x,9470000),900) geom from t"-nln ground -a_srs EPSG:32751ogr2ogr-update-append ground.gpkg ground.gpkg -dialect SQLite -sql"select st_buffer(makepoint(660000,9950000,32751),50000,60) geom"-nln ground
sets the word letter by letter, as Chapter 17 explains, makes the letters 50 km high, and moves them into the sea in the south-east
st_buffer(makepoint(...),50000,60)
the round island, with a radius of 50 km
aspect
0 is north, 90 east, 180 south and 270 west. Where it is flat, on the water, there is no direction
Look before moving on. Find the disc in the sea, and then a place on the island. Pink means that the nearest coast is in the west, and green that it is in the east. Where two colours meet, two coasts are equally far. The disc was not drawn separately. It was made by the same three lines as the island, so its colours match the map. The letters have the same colours, for the direction to their own edges.
Is it right? Calculate the direction a second time with geometry. Take the airports of Sulawesi that lie more than 2 km inland, draw the shortest line from each to the coast, and compare its direction with the number in the raster:
gdal raster as-features way.tif way.gpkg --output-layer way --geometry-type none --include-row-col--overwriteogr2ogr-update-overwrite ground.gpkg way.gpkg wayogr2ogr-update-overwrite ground.gpkg airports.csv -oo X_POSSIBLE_NAMES=lon -oo Y_POSSIBLE_NAMES=lat -s_srs EPSG:4326 -t_srs EPSG:32751 -nln airportogr2ogr-f CSV /vsistdout/ ground.gpkg -sql"select iata, town, round(km,1) km_to_sea, round(case when a<0 then a+360 else a end) by_geometry, round(band_1) by_raster from (select p.iata, p.town, st_length(s)/1000 km, degrees(atan2(st_x(st_endpoint(s))-st_x(st_startpoint(s)),st_y(st_endpoint(s))-st_y(st_startpoint(s)))) a, w.band_1 from (select p.*, st_shortestline(p.geom, st_boundary(g.geom)) s from airport p join ground g on st_contains(g.geom, p.geom)) p join way w on w.row=cast((10240000-st_y(p.geom))/500 as integer) and w.col=cast((st_x(p.geom)-30000)/500 as integer)) where km>2 order by km desc"
The last two columns are directions on a compass, calculated in two different ways. For Makale in the mountains, 41.5 km from the sea, both are 79 degrees, which is nearly east. The largest difference is 6 degrees, at Raha. In the raster the coast consists of small steps of 500 m, so it cannot be more exact near the shore.
3. The middle line of an island
A place one kilometre farther from the nearest sea is one kilometre higher on this surface. So the surface is equally steep everywhere: its slope is 100 percent, on every face of every island. It can only be less in one kind of place, on the ridge, where the two sides meet and the differences to the neighbours cancel each other.
So calculate the slope, and show only where it is not 100:
The second line removes the sea, because the sea is flat, too.
Look before moving on. The bright lines are the places where two coasts are equally far, and the branches go to every cape. Where three lines meet, three coasts are equally far, like the three places on the coast in Chapter 8. A round island has only one such place, its centre. Each letter of the title has a line along the middle of its strokes.
Mathematicians call this line the medial axis. It is used to find the middle line of rivers and roads from their two banks.
4. Distances to the airports with shading
The opposite calculation starts from points. Let the zero be a few points, and the distance grow around them. The points are the 243 airports of Chapter 8:
Look before moving on. Around each airport the surface has the form of a funnel, with the airport at the deepest point, and where two funnels meet there is a sharp line. Every such line is the border between the areas of two airports, and all of them are straight. These are the borders of Chapter 8, where st_voronojdiagram calculated them. Here the shading shows them without that calculation.
On Java the funnels are small. In the mountains of Papua there are many of them close together. A possible reason is that few roads lead there, so people fly.
5. Shading shows errors in data
The same shading is also a tool for checking data. Here is the rain of the year 2023 on Borneo, from CHIRPS3, a data set made from satellite pictures and rain gauges (ledger L94):
Without a connection, use offline_borneo.tif as borneo.tif. The colours show no sharp changes: much rain in the middle, and less at the east coast. Now the same numbers with shading:
Look before moving on. There is a straight line from north to south through the west of the island, and to the left of it are fine stripes. Rain does not have straight borders like this. These lines are in the data. In the colours they are barely visible, even if you look for them, because they are small compared with the range of the map. Shading does not depend on the range. It only compares neighbours.
How large is the step? Make a table of the cells, and compare each one with its eastern neighbour. At a natural border between two columns, the rain goes up in about half of the rows, and down in the other half:
gdal raster as-features borneo.tif borneo.gpkg --output-layer cell --geometry-type none --include-xy--include-row-col--overwriteogr2ogr-f CSV /vsistdout/ borneo.gpkg -sql"select round(x+0.025,2) line_at, count(*) pairs, round(avg(d)) mean_step, round(avg(abs(d))) mean_size, round(100*avg(d<0)) percent_down from (select center_x x, col, case when band_1>=0 and n>=0 then n-band_1 end d from (select center_x, center_y, col, band_1, lead(band_1) over (partition by row order by col) n from cell) where center_y between -2 and 2.5) where d is not null group by col having count(*)>80 order by abs(avg(d<0)-0.5) desc limit 4"
At 111.10 degrees east, the rain is 226 mm lower in the next cell, on average over 85 rows, and it is lower in 93 percent of them. The usual size of a step in this area is 74 mm. The other columns in the list change in one direction as well, but by much less.
We do not know the reason. The annual files of 2010 and 2024 have a step at the same place, and another one lies in Papua at 137.85 degrees (ledger L98). This does not make the data bad: 226 mm are 6 percent of the rain there. But it matters if you count events, or compare two districts on both sides of this line. Before you use a new data set, look at it with shading.
6. Where the sea changes from warm to cold
Temperature can be used as a height as well. sst.tif has the temperature of the sea on 1 September 2019, in cells of 5 km (ledger L96). It was cut from a file of 12 MB, in the way Chapter 0 shows for netCDF.
In the middle of the year, the south-east wind blows along the south coast of Java, pushes the warm water away, and cold water rises from below. In 2019 this was unusually strong (ledger L100). First a map, with colours that change at an important value:
About the colours. Most colour maps change evenly from one end to the other. This one has a break at 27 degrees. Below it, all colours are blue, and above it, they are orange. The value has a meaning: tropical storms need water of at least 27 degrees (ledger L100), so the map shows where the water is warm enough for one. (Close to the equator, other conditions prevent them, as Chapter 5 shows.)
But the break is in the hue only. The brightness goes up evenly from 21 degrees to 30.5. So cold water is always darker than warm water, also on both sides of the break, and a black and white print remains correct. tools/check_colours.py measures this.
The use of gdaldem for things that are not heights is not a new idea. Robert Simmon’s series on GDAL uses color-relief for such maps, and thanks Joshua Stevens for describing it (ledger L101). This chapter adds the other commands of the same group.
Now the terrain commands. Where the temperature changes quickly, there is a front. In this surface, a front is a steep slope:
What is the unit? Slope is height divided by length. The map has kilometres (+units=km in the line before), and the height is in degrees Celsius. So the slope is degrees per kilometre, and in percent it is degrees per 100 kilometres. --xscale 1 --yscale 1 prevents GDAL from converting the numbers into metres.
Look before moving on. The first map shows where the water is cold. This one shows where the cold water ends. Two long bright lines leave the coast of Java. They are the edges of cold water that flows out into the ocean. The rest of the sea is full of thin lines and eddies that are not visible in the colour map.
print(next(t for t in oneline.run("gdalinfo -stats front.tif").splitlines() if"Minimum"in t).strip())
On average, the sea changes by 0.7 degrees in 100 km. At the strongest front the value is 13.5 degrees in 100 km. The real difference is smaller, because the front is much narrower than 100 km.
7. Outlines without drawing lines
The last command uses a different kind of number. A map of land cover has classes: 10 is trees, 40 is cropland, 50 is buildings, 80 is water (ledger L102). Such numbers are only names. It makes no sense to add them, and there is no class 45.
But it is possible to test whether neighbours are different. roughness is the largest difference between a cell and its neighbours. Zero means that all nine cells have the same class, and anything else means a border:
Without a connection, use offline_cover.tif as cover.tif. The place is the area around Ubud in Bali. The third line writes a 0 wherever there is a border, and the colour file gives 0 a dark colour.
Look before moving on. Everything here runs from north to south, down from the mountains to the sea. The villages are long red strips. Between them lie fields, and the green lines between the fields are trees. No polygon was made for these outlines, and it took less than a second.
Why not use the value of the roughness itself? Because it has no meaning here. Between trees (10) and buildings (50) it is 40, and between cropland (40) and buildings it is 10, but the second border is not weaker. With classes, only “zero or not” has a meaning.
Try it yourself
Your own photograph. Take any JPEG of a wall, a face or a leaf, and apply shading to it. Change -z until the form is clearly visible.
Another island. Change the window in section 1 to Halmahera, or to your own island. Do not forget the round one.
The nearest lake. In which direction is the nearest lake? Only the cells with the value zero are different, and the rest stays.
Rain with shading for all of Indonesia. Use -projwin 94 7 142 -11.5. Find the second step.
The front on other days. Make section 6 for another day of 2019. When does the cold water appear?
Direction of a front.aspect of the temperature gives the direction in which it gets colder. Use the colour circle.
Checkpoint
The cell below stops with an error if the results are not what this chapter expects.
import csvimport iodef rows(sql, dataset="ground.gpkg"):"""The rows of a query, as dictionaries."""returnlist(csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -sql "{sql}"'))))def value(name, x, y):"""One cell of a raster, at a place in its own coordinates."""returnfloat(oneline.run(f"gdallocationinfo -valonly -geoloc {name}{x}{y}"))# The round island is the key: 30 km north, east, south and west of its centre, the way to the sea must be 0, 90, 180 and 270for (dx, dy), want in {(0, 30000): 0, (30000, 0): 90, (0, -30000): 180, (-30000, 0): 270}.items(): got = value("way.tif", 660000+ dx, 9950000+ dy)assertabs((got - want +180) %360-180) <3, f"the key is wrong: {got} instead of {want}"assertabs(value("dist.tif", 660000, 9950000) -50000) <1000, "the centre of a round island of 50 km is 50 km from the sea"# The roof is equally steep on every faceassert95< value("steep.tif", 675000, 9950000) <105, "a face of the roof should have a slope of 100 percent"# Cold water south of Java, warm water north of itcold, warm = value("sea.tif", -220, -905), value("sea.tif", 0, -600)assert cold <25<27< warm, "the sea should be colder south of Java than north of it"step = rows("select avg(n-band_1) s from (select band_1, center_x x, center_y y, lead(band_1) over (partition by row order by col) n from cell) where round(x+0.025,2)=111.1 and y between -2 and 2.5 and band_1>=0 and n>=0", "borneo.gpkg")[0]["s"]assert-260<float(step) <-190, "the seam in the rain should be about 226 mm"pictures = ("stone.png", "pencil.png", "roof.png", "way.png", "spine.png", "folds.png", "rain_colour.png", "rain_lamp.png", "sea.png", "front.png", "cover.png")assertall((WORK / f).stat().st_size >10_000for f in pictures)print(f"checkpoint passed: the round island points to all sides; the sea has {cold:.1f} degrees south of Java and {warm:.1f} north of it; the seam in the rain is {float(step):.0f} mm")print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: the round island points to all sides; the sea has 22.8 degrees south of Java and 27.1 north of it; the seam in the rain is -226 mm
time since the first cell: 86 s
Troubleshooting
Symptom
Cause
Fix
The relief is only black and white
The heights are too large for the cells
A smaller -z
proximity gives the same number everywhere
It found no target
edit --nodata none before it, and the right --target-values
Pixels not square, distances will be inaccurate
Width and height of the cells differ
--resolution with two equal numbers in place of --size
The slope of the temperature is nearly 0
GDAL treats the coordinates as metres
--xscale 1 --yscale 1, and a projection in kilometres
A dark edge around every coast
“No data” was taken as a depth of -9999
-a_nodata -9999, or gdal raster edit --nodata -9999
Two opposite directions have the same colour
The colour file does not go around the circle
The first and the last row must have the same colour
What comes next
In this chapter, each cell was compared with its eight neighbours. From a mountain, much more distant places are visible. Chapter 12: What is visible from a summit calculates the lines of sight from the top of a volcano, and shows which places are hidden.