In this series: Part IV, Surfaces. Chapter 8 made a raster from shapes. This chapter makes a table from a raster, and draws mountains with it
You will build: The mountains of Java drawn with lines alone, its skyline in eight layers, the same drawing with the number of people, and the heights of a volcano by direction from its summit
You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 5 explains lag and over
Time to run: The commands took less than two minutes when tested, including 23 MB of downloads. The copies in the folder make it work without a connection, apart from section 4
Level: Intermediate; a raster becomes a table, and SQL does the rest
Mountains on a map are usually drawn with shading, with contour lines, or with colours for the height. This chapter uses none of these. It draws the mountains of Java with seventy lines from west to east.
The method treats the raster in a different way. For most programs a raster is a picture. But it is also a table: one row for each cell, with a place and a value. In a table, SQL can sort, group and join the cells, and make drawings for which raster tools have no command.
NoteLearning objectives
By the end of this chapter you will be able to:
turn a raster into a table, with a row and a column number for each cell;
draw a relief with lines alone, and hide what lies behind a mountain;
build a skyline from the highest cell in each column;
use the same lines for a completely different number, such as people;
draw a section through a wide strip of land: highest, mean and lowest;
read a raster along any curve with a join, and draw the heights around a volcano by direction.
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/ch09. 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("09")print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT /"sample-data/ch09").iterdir()))
A few short commands first, in the form of Chapter 0. The folder has the relief of Java and the sea around it. -z 4 makes all heights four times as large, so that the shade is strong enough for such a wide view:
That is the usual way to draw a relief: every cell becomes a grey spot. But what is in the file? Make it very small, 6 columns and 2 rows, and print it:
Look before moving on. Twelve cells are twelve rows, and each row has three numbers: east, north and height. A raster is a table. The second row of the grid starts with the seventh row of the table, and it lies deeper, because it covers the ocean in the south.
A table contains no light and no shade, but it can be sorted, grouped and joined. This chapter draws Java from such a table, with lines alone.
1. A raster is a table
The relief comes from ETOPO 2022 (ledger L58), with a cell every 30 arc-seconds, or about 900 m. The first line fetches Java from the global file. The second one makes a raster of 70 rows and 1000 columns out of it:
gdal_translate-q-projwin 104.5 -5.5 115 -9.2 /vsicurl/https://www.ngdc.noaa.gov/mgg/global/relief/ETOPO2022/data/30s/30s_surface_elev_gtif/ETOPO_2022_v1_30s_N90W180_surface.tif java.tifgdalwarp-q-overwrite-te 104.9 -9 114.7 -5.7-ts 1000 70 -r max java.tif rows.tifgdal raster as-features rows.tif java.gpkg --output-layer cell --geometry-type none --include-xy--include-row-col--overwriteogr2ogr-f CSV /vsistdout/ java.gpkg -sql"select * from cell where row=35 and col between 380 and 383"
-r max keeps the highest value inside each new cell. With the mean, the narrow summits would be much too low.
The third line is the step from picture to table. as-features writes a row for each cell, with its row and column number, the place of its middle and its value, here in band_1. --geometry-type none leaves out the shapes, because the two coordinates are enough.
If the server cannot be reached, use the copies in the folder: offline_java.tif for java.tif here, offline_swath.tif for swath.tif in section 7, and offline_semeru.tif for semeru.tif in section 8.
2. Seventy lines
For each of the 70 rows, join its cells to a line from west to east. But move each point up by its height. One metre becomes 0.00017 degrees:
gdal pipeline read java.gpkg ! sql "select 9 v, st_buffer(makeline(makepoint(center_x, center_y+0.00017*max(band_1,0))),0.005,2) geom from (select * from cell order by row, col) group by row" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5880,2280"--extent"104.9,-9.15,114.7,-5.35" ! edit --nodata none ! color-map --color-map ridge.txt ! materialize ! resize --size"1960,760"-r average ! write simple.png --overwrite
A query of two rows is enough to show the mountains. max(band_1,0) puts the sea floor at zero.
Look before moving on. One thing is wrong. The lines cross. The front of a mountain does not hide what is behind it.
The solution is to draw from back to front, so that each new part covers what lies behind it. The northern rows come first. Under each line, draw a surface in the colour of the background, down to below the next line. It covers everything that was drawn there before. And if each line is cut into short pieces, every piece can have the colour of its height:
gdal pipeline read java.gpkg ! sql "with c as materialized (select row, col, center_x x, center_y y, max(band_1,0) h from cell) select v, geom from (select row, 0 k, 0 v, makepolygon(makeline(g)) geom from (select * from (select row, col, makepoint(x,y+h*0.00017) g from c union all select row, 99998, makepoint(max(x),y-0.3) from c group by row union all select row, 99999, makepoint(min(x),y-0.3) from c group by row union all select row, -1, makepoint(min(x),y-0.3) from c group by row) order by row, col) group by row union all select row, 1, case when h0+h=0 then 1 else min(9,2+cast(max(h0,h)/400 as integer)) end, st_buffer(makeline(makepoint(x0,y+h0*0.00017),makepoint(x,y+h*0.00017)),0.0062,2) from (select *, lag(h) over (partition by row order by col) h0, lag(x) over (partition by row order by col) x0 from c) where x0 is not null) order by row, k" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5880,2280"--extent"104.9,-9.15,114.7,-5.35" ! edit --nodata none ! color-map --color-map ridge.txt ! materialize ! resize --size"1960,760"-r average ! write ridge.png --overwrite
Part
Meaning
order by row, k
the order of drawing: from north to south, and in each row first the surface (k is 0) and then the line (k is 1)
makepolygon(makeline(g))
the surface: the line, and then three corners 0.3 degrees further down, with the numbers 99998, 99999 and -1
lag(h), lag(x)
the neighbour to the left. Two neighbours make one short piece of line, as in Chapter 5
min(9, 2+h/400)
a new colour every 400 m. Class 1 is the sea
Such a drawing became famous on a record cover of 1979, Unknown Pleasures by Joy Division. It showed the radio pulses of a star, printed by a computer, from a doctoral thesis of 1970 (ledger L78). There, each line was a moment. Here, it is a strip of Java.
3. The skyline in eight layers
From a ship in the Indian Ocean, with the view to the north, only the highest point in each direction is visible. In the table, this is a group by: the highest cell in each column.
One skyline for the whole island would show few details. So cut Java into eight strips from north to south, take the skyline of each, and fill it. The far strips are pale, and the near ones dark, as mountains often look in haze:
gdalwarp-q-overwrite-te 104.9 -9 114.7 -5.7-ts 1176 396 -r max java.tif fine.tifgdal raster as-features fine.tif sky.gpkg --output-layer cell --geometry-type none --include-xy--include-row-col--overwritegdal pipeline read sky.gpkg ! sql "with t as materialized (select row/50 b, col, center_x x, max(0,max(band_1))/1000-0.32*(row/50) h, -9 base from cell group by 1,2) select b+1 v, makepolygon(makeline(g)) geom from (select * from (select b, col, makepoint(x,h) g from t union all select b, 99998, makepoint(max(x),base) from t group by b union all select b, 99999, makepoint(min(x),base) from t group by b union all select b, -1, makepoint(min(x),base) from t group by b) order by b, col) group by b order by b" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5880,2160"--extent"104.9,-3.2,114.7,4" ! edit --nodata none ! color-map --color-map mist.txt ! materialize ! resize --size"1960,720"-r average ! write mist.png --overwrite
row/50 divides whole numbers, and gives 0 for the first 50 rows, 1 for the next 50, and so on. This is the strip. -0.32*(row/50) sets each strip a little lower than the one behind it.
Look before moving on. This is no view from a real place. Java is about a thousand kilometres long, and from no ship could one see all of it. It is a drawing with real heights, and for many purposes that is enough. Chapter 12 calculates what is really visible from a place.
4. How high are the peaks, really?
The heights in a drawing can be wrong, so check some of them. Natural Earth has a list of mountains with names and heights, and four of them lie in our window. For each one, take the highest cell within 0.03 degrees:
ogr2ogr-update-overwrite sky.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/10m/physical/ne_10m_geography_regions_elevation_points.zip -nln peak -dialect SQLite -sql"select name, elevation, geometry geom from ne_10m_geography_regions_elevation_points where name<>'' and st_x(geometry) between 105 and 114 and st_y(geometry) between -9 and -6"ogr2ogr-f CSV /vsistdout/ sky.gpkg -sql"select name, elevation in_the_list, round(max(band_1)) in_our_relief, round(max(band_1))-elevation difference from peak join cell on center_x between st_x(geom)-0.03 and st_x(geom)+0.03 and center_y between st_y(geom)-0.03 and st_y(geom)+0.03 group by name order by 2 desc"
name,in_the_list,in_our_relief,difference
Gunung Semeru,3676,3433,-243
Gunung Ciremay,3077,2925,-152
Gunung Merapi,2968,2652,-316
Krakatau,813,99,-714
Look before moving on. Semeru, Ciremay and Merapi are 150 to 320 m too low. A cell of 900 m gives one height for a whole piece of mountain, and a summit is smaller than that. This is true for every relief: coarse cells make the peaks too low. For the drawing it does not matter. For a question about a height, use finer data, as in sections 7 and 8.
Krakatau is another case. It is 700 m too low, and no cell size explains that. The highest cell of this group of islands, with 428 m, lies 5.5 km to the south-east of the point in the list. So the name and the height in the list seem to belong to two different places. A check can find errors in both data sets.
5. The same drawing with the number of people
The query of section 2 does not need heights. It works with any number. people.tif has the number of people in each cell, estimated by WorldPop for the year 2025 (ledger L79). Make 70 rows again, but now with the sum:
gdalwarp-q-overwrite-te 104.9 -9 114.7 -5.7-ts 1000 70 -r sum people.tif people_rows.tifgdal raster as-features people_rows.tif people.gpkg --output-layer cell --geometry-type none --include-xy--include-row-col--overwriteogr2ogr-f CSV /vsistdout/ people.gpkg -sql"select round(sum(band_1)/1e6,1) million_people, round(max(band_1)) most_in_one_cell from cell"gdal pipeline read people.gpkg ! sql "with c as materialized (select row, col, center_x x, center_y y, max(band_1,0) h from cell) select v, geom from (select row, 0 k, 0 v, makepolygon(makeline(g)) geom from (select * from (select row, col, makepoint(x,y+h*0.0000046) g from c union all select row, 99998, makepoint(max(x),y-0.3) from c group by row union all select row, 99999, makepoint(min(x),y-0.3) from c group by row union all select row, -1, makepoint(min(x),y-0.3) from c group by row) order by row, col) group by row union all select row, 1, case when h0+h=0 then 1 else min(9,2+cast(max(h0,h)/6000 as integer)) end, st_buffer(makeline(makepoint(x0,y+h0*0.0000046),makepoint(x,y+h*0.0000046)),0.0062,2) from (select *, lag(h) over (partition by row order by col) h0, lag(x) over (partition by row order by col) x0 from c) where x0 is not null) order by row, k" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5880,2280"--extent"104.9,-9.15,114.7,-5.35" ! edit --nodata none ! color-map --color-map ridge.txt ! materialize ! resize --size"1960,760"-r average ! write people.png --overwrite
million_people,most_in_one_cell
160,159775
Look before moving on. The highest peak of this drawing is Jakarta. Compare the two pictures. Where the first one has its peaks, this one is mostly low, and the high numbers of people lie between the mountains and on the northern coast. And nearly nowhere on the island are the lines flat.
How the file was made. The estimate for Indonesia is a file of 6 MB, with cells of about 1 km. Its server does not let GDAL read a piece of a file, so it has to be downloaded as a whole (the file). This line cut out Java, and gave it the grid of section 3:
-r sum divides the people of each old cell among the new ones, and loses nobody. With -r average the total would be wrong. WorldPop calls this release an alpha version. It distributes the numbers of larger districts with the help of satellite images, so a single cell is an estimate and not a count.
6. Mountains above, people below
Both tables have the same 1176 columns. So bring them together, with the base line between them. Upwards, the highest point in each column, and downwards, all people in the same column:
gdal raster as-features people.tif people_fine.gpkg --output-layer people --geometry-type none --include-xy--include-row-col--overwriteogr2ogr-update-overwrite sky.gpkg people_fine.gpkg peoplegdal pipeline read sky.gpkg ! sql "with a as materialized (select 1 v, col, center_x x, max(0,max(band_1))/1000+0.04 h, 0.04 base from cell group by col), b as materialized (select 2 v, col, center_x x, -sum(band_1)/2.5e5-0.04 h, -0.04 base from people group by col), u as (select * from a union all select * from b) select v, makepolygon(makeline(g)) geom from (select * from (select v, col, makepoint(x,h) g from u union all select v, 99998, makepoint(max(x),base) from u group by v union all select v, 99999, makepoint(min(x),base) from u group by v union all select v, -1, makepoint(min(x),base) from u group by v) order by v, col) group by v" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5880,2400"--extent"104.9,-4.2,114.7,3.8" ! edit --nodata none ! color-map --color-map mirror.txt ! materialize ! resize --size"1960,800"-r average ! write mirror.png --overwrite
The lower shape shows a different number than the upper one. Its deepest point is the column through Jakarta, with more than 900,000 people in a strip only 900 m wide. The second one in the east is Surabaya.
A drawing like this needs an explanation of its numbers. Upwards is a maximum, and downwards is a sum. One thousand metres up are as long as 250,000 people down.
7. A section through a strip of land
A line for everyday work. The usual height profile follows one line across the map, and everything beside the line is lost. A strip shows more. Take 110 km from west to east and 30 km from south to north, with the volcanoes Merapi and Merbabu at one end and Lawu at the other, and calculate three numbers for each column:
gdalwarp-q-overwrite-t_srs EPSG:32749 -tr 100 100 -te 425000 9150000 535000 9180000 -r max /vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_S08_00_E110_00_DEM/Copernicus_DSM_COG_10_S08_00_E110_00_DEM.tif /vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_S08_00_E111_00_DEM/Copernicus_DSM_COG_10_S08_00_E111_00_DEM.tif swath.tifgdal raster as-features swath.tif swath.gpkg --output-layer cell --geometry-type none --include-xy--include-row-col--overwritegdal pipeline read swath.gpkg ! sql "with t as materialized (select col, center_x/1000 x, max(band_1) a, avg(band_1) b, min(band_1) c from cell group by 1), u as materialized (select 1 v, col, x, a/100 h, 0 base from t union all select 2, col, x, b/100, 0 from t union all select 3, col, x, c/100, 0 from t) select v, makepolygon(makeline(g)) geom from (select * from (select v, col, makepoint(x,h) g from u union all select v, 99998, makepoint(max(x),base) from u group by v union all select v, 99999, makepoint(min(x),base) from u group by v union all select v, -1, makepoint(min(x),base) from u group by v) order by v, col) group by v order by v" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5400,1800"--extent"425,0,535,36.6667" ! edit --nodata none ! color-map --color-map swath.txt ! materialize ! resize --size"1800,600"-r average ! write swath.png --overwriteogr2ogr-f CSV /vsistdout/ swath.gpkg -sql"select 'Merbabu' mountain, round(max(band_1)) metres, center_x, center_y from cell where center_x<450000 and center_y>9170000 union all select 'Merapi', round(max(band_1)), center_x, center_y from cell where center_x<450000 and center_y<9170000 union all select 'Lawu', round(max(band_1)), center_x, center_y from cell where center_x>500000"
The relief here is the Copernicus model with cells of 30 m (ledger L80). gdalwarp joins two tiles without an extra option.
Silhouette
Meaning
pale
the highest point in the 30 km from south to north
grey
the mean
dark
the lowest point
Look before moving on. At the two ends, the three are far apart: a steep mountain beside low land. In the middle they come together, and the land is flat from south to north. That is the plain around the city of Surakarta. A single line could not have shown this.
The pale peak on the left consists of two mountains. Merbabu and Merapi stand less than 10 km apart, one behind the other, and the strip keeps the higher one.
The list of section 4 gives 2,968 m for Merapi, and this relief 2,907. Here the cells are small enough, so they are not the reason. Merapi is an active volcano whose summit changes, and the list does not give the year of its number. We found no source that explains the difference.
8. The heights around a volcano
This drawing needs the table. Take a circle around Mount Semeru, the highest mountain of Java, 200 m from the summit, and read the height at each step. Then take a circle of 400 m, and so on, up to 8 km. Draw each circle as a line, with the direction on the x axis and the height on the y axis.
First the relief around the mountain, in cells of 20 m, and as a table:
3,672 m, and the list of section 4 has 3,676. With small cells, the summit has nearly the right height.
Now the circles. For each radius and each degree, sine and cosine give the place. The next step is the most important one of this chapter: to read a raster at a place, join the table by row and column. The row is the distance from the upper edge divided by 20 m, and the column the distance from the left edge:
ogr2ogr-update-overwrite semeru.gpkg semeru.gpkg -sql"with recursive r(r) as (select 200 union select r+200 from r where r<8000), a(a) as (select 0 union select a+1 from a where a<360), s as materialized (select center_x x0, center_y y0, max(band_1) from cell), p as materialized (select r, a, cast((x0+r*sin(radians(a))-703000)/20 as integer) c, cast((9112000-y0-r*cos(radians(a)))/20 as integer) w from r, a, s) select r, a, band_1 h from p join cell on row=w and col=c"-nln turngdal pipeline read semeru.gpkg ! sql "select 2+min(7,cast((8200-r)/1000 as integer)) v, st_buffer(makeline(makepoint(a,h/20)),0.22,3) geom from (select * from turn order by r desc, a) group by r order by r desc" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size"5400,2400"--extent"0,30,360,190" ! edit --nodata none ! color-map --color-map ridge.txt ! materialize ! resize --size"1800,800"-r average ! write turn.png --overwrite
How to read it. The x axis is the direction as on a compass: north is at both edges, east is at a quarter, south in the middle, and west at three quarters. The highest line is the circle nearest to the summit, and each next one is 200 m further out.
Look before moving on.
A perfect cone would give straight, level lines. In the south and south-east, Semeru is close to it.
The small dips that stand below each other are gullies. Each one begins somewhere on the slope, and the circles below it all cross it at the same direction.
In the north, the lines rise and cross. There is no slope down to a plain: the mountain is joined to the next ones. Where an outer circle lies higher than an inner one, the way from the summit goes up again.
How steep is the slope? The circles are 200 m apart, so the distance between the lines shows it:
ogr2ogr-f CSV /vsistdout/ semeru.gpkg -sql"select r metres_from_summit, round(avg(h)) mean_height_south, round(degrees(atan((lag(avg(h)) over (order by r)-avg(h))/(r-lag(r) over (order by r))))) slope_degrees from turn where a between 120 and 240 and r in (200,1000,2000,3000,4000,6000,8000) group by r"
The southern side is steepest between 1 and 2 km from the summit, with 32 degrees. From there it gets less steep with every step, down to 9 degrees at the foot. This gives the volcanoes in section 2 their form, with a pointed top and a wide foot.
Try it yourself
Forty lines, or two hundred. Change 70 in section 1, and the width of the lines in section 2.
The view from the north. Reverse the order of drawing, with order by -row, k, and move the points up in the same way. Which mountains are hidden now?
Your own island. Choose another window in section 1, and use its numbers for the extent of the picture, too.
Another number. Rain, light at night, or the price of rice: every raster can be drawn in seventy lines.
Another volcano. Tambora on Sumbawa has a large crater. Its first circles are lower than the next ones. You need the tiles of its place, the right UTM zone, and the corner numbers of your window.
Checkpoint
The cell below stops with an error if the results are not what this chapter expects.
import csvimport iodef rows(sql, dataset):"""The rows of a query, as dictionaries."""returnlist(csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -sql "{sql}"'))))assert rows("select count(*) n from cell", "java.gpkg")[0]["n"] =="70000", "70 rows and 1000 columns"# The sum of people must not change when the grid changesa, b = (float(rows(f"select sum(band_1) s from {t}", f)[0]["s"]) for t, f in (("cell", "people.gpkg"), ("people", "sky.gpkg")))assertabs(a / b -1) <0.001, "both tables of people should have the same total"top =float(rows("select max(band_1) h from cell", "semeru.gpkg")[0]["h"])assertabs(top -3676) <10, "Semeru should be about 3676 m high"assert rows("select count(*) n from turn", "semeru.gpkg")[0]["n"] ==str(40*361), "every step of the walk should have found its cell"pictures = ("simple.png", "ridge.png", "mist.png", "people.png", "mirror.png", "swath.png", "turn.png")assertall((WORK / f).stat().st_size >10_000for f in pictures)print(f"checkpoint passed: {a /1e6:.1f} million people in both grids; Semeru {top:,.0f} m; 40 circles complete")print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 160.0 million people in both grids; Semeru 3,672 m; 40 circles complete
time since the first cell: 106 s
Troubleshooting
Symptom
Cause
Fix
Lines that go back and forth through the whole picture
The cells were not sorted before makeline
order by row, col in an inner query
Range downloading not supported by this server
The server only gives whole files
Download the file with a browser first
Invalid value 'max' for string argument 'resampling'
resize in a pipeline does not support max and sum
gdalwarp -r max
A total of people that is far too small or too large
average in place of sum
-r sum
Gaps in the lines around the volcano
Some points of the circles lie outside the raster
A larger window, or one more tile
The shapes are filled in a strange way
The corners of the surface are not last
The large column numbers, and -1 for the first corner