Skip to main content

Chapter 16: Repeating and sharing the work

Chapter 16: Repeating and sharing the work

TipAt a glance
  • In this series: Part VII, Repeating and sharing. The result of Chapter 15 is needed again next month, for many files, and on the computers of other people. This chapter shows how to repeat and share the work
  • You will build: A map of the earthquakes of the last 30 days that is always up to date; all of Indonesia in a file of 260 kB; a sheet with 72 volcanoes, made by a line that writes lines; a calendar made from a thousand files; and one file with all the results of Chapter 15, with a test of what changes in other formats
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 15 made the results that go into the package; copies of them are in the folder
  • Time to run: The commands took about four minutes when tested. The downloads are about 500 MB, nearly all for section 4, which has a copy of 2 MB for readers with a slow connection. About 150 MB of free space
  • Level: Easy to intermediate; the longer queries are in files, with comments

The table of Chapter 15 may be needed again next month, with new numbers.

Until now, each line had to work once, on this computer, while you were looking at it. If other people use the result, the lines must do more. They must work again next month, work for a thousand files, and work for other people, on other computers.

This chapter has no new kind of analysis. It shows how to save, repeat and share the lines that you already have.

NoteLearning objectives

By the end of this chapter you will be able to:

  • save a command in place of a result, so that the result is always up to date;
  • let the computer make a map each morning, and keep the old map if there is an error;
  • use hundreds of files on a server as one file;
  • let one line write a hundred other lines, and run them eight at a time;
  • split a table into a thousand files and join them again, without a loop;
  • put rasters and tables into one file, or into a small website;
  • test what changes when your data are converted into another format;
  • name the tasks that GDAL does not do, and the programs that do them.

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/ch16. In this notebook, the next cell does that.

import sys
import time
from pathlib import Path

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
sys.path.insert(0, str(ROOT / "src"))
import oneline

T0 = time.perf_counter()
WORK = oneline.start("16")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch16").iterdir()))
working folder: ch16 | files copied there: ['calendar.sql', 'calendar.txt', 'check.sql', 'drops.txt', 'light.txt', 'marks.txt', 'minutes.tif', 'morning.bat', 'morning.sh', 'night.txt', 'offline_november.geojson', 'offline_volcanoes.csv', 'offline_wall.tif', 'quakes.csv', 'relief.tif', 'rings.sql', 'shelters.csv', 'villages.gpkg', 'volcano.txt']

Warm-up: a file that contains a command

relief.tif is the land and the sea floor around Indonesia. Make a hillshade of it, twice. The difference between the two lines is the name of the output (-z 2 draws all heights twice as high):

gdal raster hillshade relief.tif shade.tif -z 2 --overwrite

gdal raster hillshade relief.tif shade.gdalg.json -z 2 --overwrite
shade.tif           1,726,471 bytes
shade.gdalg.json          182 bytes

The second file is more than 9,000 times smaller. It is too small for a picture. Look into the file:

gdal vsi copy shade.gdalg.json /vsistdout/
{
  "type":"gdal_streamed_alg",
  "command_line":"gdal raster hillshade --input relief.tif --zfactor 2 --output-format stream --output streamed_dataset",
  "gdal_version":"3120300"
}

There is no picture. The file contains the command. (/vsistdout/ is the screen, so gdal vsi copy can show any text file, in any shell.)

Every program that uses GDAL 3.11 or later can open this file in the same way as a TIFF (ledger L155). At that moment, the command runs, and only for the part that is needed. Here is the result:

The shaded relief of land and sea floor around Indonesia, in grey, read from a file of 182 bytes

Look before moving on. A TIFF contains a result. A .gdalg.json file contains the command that makes the result. This chapter calls it a command file. (In the printed outputs, it is called a recipe.) A result opens at once, but it becomes old. A command file needs some time at each opening, but its result is always new. It also needs its input: without relief.tif in the same folder, this command file does not work.

a result (.tif) a command file (.gdalg.json)
size all cells a few hundred bytes
when the input changes it is wrong, without a message it is right
speed fast the calculation is done again each time
you can send it alone yes only with its inputs, or if they are on a server

1. A map that is always up to date

The earthquake service of the USGS answers a request in the form of an address (Chapter 1). The map of this section shows each earthquake of a month as a group of rings on a dark sea. Strong earthquakes have more and larger rings. New ones are bright, and older ones are darker.

It is made only from command files. First the background. One command file gives the colours, one the shading, and one puts the shading on the colours:

gdal raster color-map relief.tif colour.gdalg.json --color-map night.txt --overwrite

gdal raster pipeline read relief.tif ! hillshade -z 2 ! color-map --color-map light.txt --add-alpha ! write light.gdalg.json --overwrite

gdal raster blend colour.gdalg.json --overlay light.gdalg.json ground.gdalg.json --overwrite

light.txt turns the hillshade into a layer that is partly transparent: black and nearly opaque in the shade, and a warm colour and nearly transparent on the sunny side. Look at the last line. Its inputs are command files, and its output is a command file, too. Command files can use other command files.

Next, the earthquakes of November 2026, and their rings:

gdal vector sql "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&minlatitude=-13&maxlatitude=9&minlongitude=93&maxlongitude=142&minmagnitude=4&starttime=2026-11-01&endtime=2026-12-01" quakes.gdalg.json --dialect SQLite --sql "select mag, time, geometry from OGRGeoJSON" --output-layer quakes --overwrite

gdal vector sql quakes.gdalg.json rings.gdalg.json --dialect SQLite --sql "@rings.sql" --overwrite

Without a connection, write offline_november.geojson in place of the address in quotes.

The first command file does one small thing: it takes three columns and gives the table the name quakes. All the others read quakes, and do not contain the address of the data. This is important for the next steps.

rings.sql draws the rings:

select
  -- 31 for the newest earthquake, and one less for each day before it
  31 - (last - time) / 86400000.0 fresh,
  -- a ring: the edge of a circle, made 0.024 degrees wide, and wider for the strong ones
  st_buffer(st_exteriorring(st_buffer(geometry, value * size, 16)), 0.012 + 0.004 * (mag - 4)) geom
from
  (select mag, time, geometry, max(time) over () last, 0.22 * pow(1.75, mag - 4) size from quakes),
  json_each(json_array(0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6))
-- magnitude 4 has two rings, and each magnitude more has about two more
where value <= 0.4 + (mag - 4) * 0.45
order by time, value

Last, two command files that draw the rings and put them on the background. Then the only line that really makes a picture:

gdal pipeline read rings.gdalg.json ! rasterize --attribute-name fresh --extent 93,-13,142,9 --size 3920,1760 --ot Float32 --nodata 0 ! color-map --color-map drops.txt --add-alpha ! resize --size 1960,880 -r average ! write drops.gdalg.json --overwrite

gdal raster blend ground.gdalg.json --overlay drops.gdalg.json today.gdalg.json --overwrite
Warning 1: pipeline: Step rasterize is not natively streaming compatible, and may cause significant processing time at opening
gdal raster convert today.gdalg.json november.jpg --co QUALITY=85 --overwrite

The warning says that rasterize can not work in small pieces, so it does all its work when the command file is opened. For a picture of this size, this is no problem.

rasterize draws twice as large as needed, and resize makes the result smaller again. This gives the thin rings smooth edges.

Dark map of Indonesia and the seas around it. The earthquakes of one month are drawn as groups of rings: pale blue for the first days, bright gold for the last. The largest rings are near Timor and in the Banda Sea, and a bright cluster lies between Sulawesi and the Philippines

7 recipes, 2,148 bytes together
earthquakes, strongest: 147,6.8

Look before moving on. Most earthquakes of this month were in the east: from Sumbawa to the Banda Sea, and between Sulawesi and Halmahera. The dark line in the sea floor south of the islands is the trench. The diagram shows how the files depend on each other. Each name without a point is a command file of a few hundred bytes:

relief.tif --+--> colour --+
             |             +--> ground --+
             +--> light ---+             |
                                         +--> today --> a picture
the server ----> quakes --> rings --> drops

Another address, another map

Only the first command file of the lower row contains the address. So write this one again, with the weeks around 26 December 2004, and make the picture. You do not change the other six:

gdal vector sql "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&minlatitude=-13&maxlatitude=9&minlongitude=93&maxlongitude=142&minmagnitude=4&starttime=2004-12-21&endtime=2005-01-20" quakes.gdalg.json --dialect SQLite --sql "select mag, time, geometry from OGRGeoJSON" --output-layer quakes --overwrite

gdal raster convert today.gdalg.json december2004.jpg --co QUALITY=85 --overwrite

The same map for the weeks around 26 December 2004. Eight very large rings around the north of Sumatra reach to the Malay Peninsula. West and north of Aceh, hundreds of smaller rings cover each other completely

The large rings are the earthquake of magnitude 9.1 off Sumatra. In the 25 days after it, more than 600 others of magnitude 4 and more followed in the north-west of this map alone (ledger L158).

Leave out the date

The next step makes a map that is always up to date. If the address contains no dates, the service gives the last 30 days (ledger L29). These are different days every morning, so the answer is always new:

gdal vector sql "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&minlatitude=-13&maxlatitude=9&minlongitude=93&maxlongitude=142&minmagnitude=4" quakes.gdalg.json --dialect SQLite --sql "select mag, time, geometry from OGRGeoJSON" --output-layer quakes --overwrite

gdal raster convert today.gdalg.json today.jpg --co QUALITY=85 --overwrite

The same map with the earthquakes of the 30 days before this page was made

This picture shows the 30 days before this page was made. If you run the two lines, you get the last 30 days before today. After that, you do not need the first line again. today.gdalg.json is the map of the last 30 days, today, next month and next year. Drag it into QGIS: if your QGIS has GDAL 3.11 or later, it should open like any raster.

The data of November can still change. The picture of November changed between two runs on the morning of 4 December. The USGS had revised an earthquake south of Java, and one group of rings was a little different. In that one night, it revised twelve earthquakes of November in the box of this map (ledger L163). A command file gives the corrected data, without any work.

The limits of this method. A live map depends on its server. And it does not store the past: a month later, you can not show the map of today. If you need to prove what it showed, keep the result as well, with the date in its name.

2. A new picture every morning at six

A command file gives a new result when somebody opens it. But most people need a normal picture. So a computer should make the picture each morning. Every system has a program for that, and it needs one small file.

The most important question is: what happens if there is an error? The server may not answer, or the disk may be full. If your line writes directly into today.jpg, the result is then half a picture, and the good one from yesterday is gone. So the file does this in two steps: first it makes a new picture with another name, and only if that worked, it replaces the old one.

How does the file check that it worked? Each program gives back a number when it ends, the exit code: 0 means that there was no error. These two files are in the folder:

@echo off
rem go to the folder of this file
cd /d "%~dp0"
rem make a new picture; the old one stays until the new one is complete
gdal raster convert today.gdalg.json new.jpg --overwrite --quiet
if errorlevel 1 (
  echo %date% %time% FAILED, the old picture stays >> morning.log
  exit /b 1
)
move /y new.jpg today.jpg >nul
echo %date% %time% new picture >> morning.log

if errorlevel 1 means: if the exit code is 1 or more. %~dp0 is the folder of the file.

#!/bin/sh
# go to the folder of this file
cd "$(dirname "$0")" || exit 1
# make a new picture; the old one stays until the new one is complete
if gdal raster convert today.gdalg.json new.jpg --overwrite --quiet
then
  mv new.jpg today.jpg
  echo "$(date) new picture" >> morning.log
else
  echo "$(date) FAILED, the old picture stays" >> morning.log
  exit 1
fi

if checks the exit code by itself.

Start the file once by hand, with .\morning.bat or sh morning.sh. Then test an error: write a wrong address into the command file quakes, and start it again. The old picture must still be there, and morning.log must have a line about the error. Both files were tested in this way.

If that works, add it to the schedule of the system. These lines change settings of your computer, so this notebook does not run them:

schtasks /create /tn "Earthquake map" /tr "C:\maps\morning.bat" /sc daily /st 06:00

To stop it again: schtasks /delete /tn "Earthquake map"

Write crontab -e, and add this row. The first five fields are the minute, the hour, the day of the month, the month, and the day of the week:

0 6 * * * sh "$HOME/maps/morning.sh"

To stop it again, delete the row.

(The forms are from the manuals of Microsoft and of cron, ledger L160.)

A common error. Your terminal can find GDAL, because its environment is active. The scheduled program starts without this environment. If morning.log says FAILED every day, but the file works by hand, this is the reason. With conda, add a line before gdal:

System Line
Windows call "%USERPROFILE%\miniforge3\Scripts\activate.bat" gdal-oneliners
macOS, Linux . "$HOME/miniforge3/bin/activate" gdal-oneliners

The computer must also be on at six, and not in sleep mode.

3. All of Indonesia in one small file

The second task is to work with many files. This section begins with files that are not on your computer.

The relief that is used since Chapter 0, Copernicus GLO-30, is on a server in tiles of one degree. In many chapters, the names of the tiles were typed by hand. Chapter 14 had a better method: a table of files, with one row for each file, its name, and the box that it covers. GDAL reads such a table as one raster. The driver has the name GTI.

For a few files, GDAL can write the table (gdal driver gti create). It opens each file and reads its position. For all of Indonesia, it is not necessary to open the files. The server has a list of all its tiles, and the names of the tiles contain their positions. So SQL can write the table:

ogr2ogr -overwrite cloud.gpkg "CSV:/vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/tileList.txt" -oo HEADERS=NO -dialect SQLite -sql "select '/vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/'||n||'/'||n||'.tif' location, buildmbr(x,y,x+1,y+1) geom from (select field_1 n, substr(field_1,31,3)*(case substr(field_1,30,1) when 'E' then 1 else -1 end)-0.5/3600 x, substr(field_1,24,2)*(case substr(field_1,23,1) when 'N' then 1 else -1 end)+0.5/3600 y from tileList) where x between 94 and 140 and y between -11 and 6" -nln cloud -nlt POLYGON -a_srs EPSG:4326

ogr2ogr -f CSV /vsistdout/ cloud.gpkg -sql "select count(*) tiles, min(location) the_first_name from cloud"
tiles,the_first_name
467,/vsicurl/https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_N00_00_E097_00_DEM/Copernicus_DSM_COG_10_N00_00_E097_00_DEM.tif
Part What it does
CSV:/vsicurl/...tileList.txt the list on the server, read as a table with one column, field_1
substr(field_1,31,3) three letters from position 31: the longitude. In ..._S01_00_E100_00_DEM it is 100
case ... when 'E' then 1 else -1 end west and south get a minus
-0.5/3600, +0.5/3600 half a cell to the west, and half a cell to the north. See below
buildmbr(x,y,x+1,y+1) the box of the tile, one degree wide
location the name of the column that GDAL reads in such a table

Why half a cell? The tile E118 does not begin at 118 degrees. gdalinfo says 117.99986, because in this relief the middle of the first cell lies on the full degree. The first version of this line had whole degrees. The map looked right. But the cells along each border then belonged to two tiles, and GDAL sometimes used the one and sometimes the other. When the same line ran in four shells, two of them gave another column of heights at 118 degrees, up to 49 m different. So open one file of a collection with gdalinfo, and compare its corner with your table.

Now read the size of this raster:

gdalinfo GTI:cloud.gpkg -nomd -norat --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR
Driver: GTI/GDAL Raster Tile Index
Files: none associated
Size is 165600, 61200
Coordinate System is:
GEOGCRS["WGS 84",
    ENSEMBLE["World Geodetic System 1984 ensemble",
        MEMBER["World Geodetic System 1984 (Transit)"],
        MEMBER["World Geodetic System 1984 (G730)"],
        MEMBER["World Geodetic System 1984 (G873)"],
        MEMBER["World Geodetic System 1984 (G1150)"],
        MEMBER["World Geodetic System 1984 (G1674)"],
        MEMBER["World Geodetic System 1984 (G1762)"],
        MEMBER["World Geodetic System 1984 (G2139)"],
        MEMBER["World Geodetic System 1984 (G2296)"],
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ENSEMBLEACCURACY[2.0]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["geodetic latitude (Lat)",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["geodetic longitude (Lon)",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    USAGE[
        SCOPE["Horizontal component of 3D system."],
        AREA["World."],
        BBOX[-90,-180,90,180]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
Origin = (94.999861111111116,6.000138888888888)
Pixel Size = (0.000277777777778,-0.000277777777778)
Corner Coordinates:
Upper Left  (  94.9998611,   6.0001389) ( 94d59'59.50"E,  6d 0' 0.50"N)
Lower Left  (  94.9998611, -10.9998611) ( 94d59'59.50"E, 10d59'59.50"S)
Upper Right ( 140.9998611,   6.0001389) (140d59'59.50"E,  6d 0' 0.50"N)
Lower Right ( 140.9998611, -10.9998611) (140d59'59.50"E, 10d59'59.50"S)
Center      ( 117.9998611,  -2.4998611) (117d59'59.50"E,  2d29'59.50"S)
Band 1 Block=256x256 Type=Float32, ColorInterp=Gray
cloud.gpkg: 262,144 bytes
165,600 x 61,200 = 10,134,720,000 cells, or 41 GB if they were here

The raster has ten billion heights, from the west of Sumatra to Papua, in a file that is small enough for an e-mail. None of them are on your computer yet. But you can cut out a piece, and you do not need to find the right tile first. This is Tambora, on Sumbawa:

gdal raster clip GTI:cloud.gpkg tambora.tif --bbox 117.8,-8.4,118.2,-8.1 --config GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR --overwrite

gdal pipeline read tambora.tif ! color-map --color-map volcano.txt ! blend --overlay [ read tambora.tif ! hillshade -z 1.3 ! color-map --color-map light.txt --add-alpha ! materialize ] ! write tambora.jpg --co QUALITY=85 --overwrite

The volcano Tambora from above: a wide cone with hundreds of fine valleys running down to the dark sea, and in its middle a round crater several kilometres wide with steep walls and a flat floor

The second line has brackets. [ ... ] is a pipeline inside another pipeline. It makes the shading layer of section 1, and blend puts it on the colours. materialize makes GDAL finish this part first.

Keep the order: clip first, and then the hillshade. A command file “hillshade of all Indonesia” is easy to write. But GDAL makes a hillshade row by row, and a row here is 46 degrees long. For a small window, it would open tiles from Aceh to Papua.

4. A line that writes lines

Tambora is one volcano. How many are there? The Smithsonian Institution keeps the list of the world, with all volcanoes that were active in the Holocene, the time since the last ice age. Its server gives us those of Indonesia:

ogr2ogr -overwrite volcanoes.csv "https://webservices.volcano.si.edu/geoserver/GVP-VOTW/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=GVP-VOTW:Smithsonian_VOTW_Holocene_Volcanoes&outputFormat=application/json&CQL_FILTER=Country='Indonesia'" -dialect SQLite -sql "select Volcano_Number number, Volcano_Name name, Last_Eruption_Year year, Elevation height, round(Longitude,4) x, round(Latitude,4) y from OGRGeoJSON order by 1"

ogr2ogr -f CSV /vsistdout/ volcanoes.csv -oo AUTODETECT_TYPE=YES -dialect SQLite -sql "select count(*) volcanoes, count(nullif(year,'')) with_a_known_year, count(distinct name) different_names, max(height) highest from volcanoes"
volcanoes,with_a_known_year,different_names,highest
101,75,100,3800

Without a connection, rename offline_volcanoes.csv to volcanoes.csv.

The aim is one relief file for each of them. This needs 101 lines, which are all the same except for the numbers. It is not practical to type them. There are three ways:

  1. A loop, in the language of your shell. Chapter 0 shows this for a few files.
  2. One GDAL line that takes many files at once. This is the next section.
  3. One line that writes the other lines. This is the most useful way, and it is not well known.

For SQL, a line of text is only a value in a table. So SQL can make it, with ||, which joins texts:

gdal vector sql volcanoes.csv jobs.csv --dialect SQLite --sql "select 'gdal_translate -q --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR -co COMPRESS=DEFLATE -projwin '||round(x-0.08,4)||' '||round(y+0.08,4)||' '||round(x+0.08,4)||' '||round(y-0.08,4)||' GTI:cloud.gpkg crater-'||number||'.tif' line from volcanoes" --lco HEADER=NO --lco SEPARATOR=TAB --lco LINEFORMAT=LF --overwrite
gdal_translate -q --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR -co COMPRESS=DEFLATE -projwin 96.209 4.983 96.369 4.823 GTI:cloud.gpkg crater-261030.tif
gdal_translate -q --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR -co COMPRESS=DEFLATE -projwin 96.741 4.849 96.901 4.689 GTI:cloud.gpkg crater-261050.tif
gdal_translate -q --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR -co COMPRESS=DEFLATE -projwin 98.4327 3.3179 98.5927 3.1579 GTI:cloud.gpkg crater-261070.tif
...
gdal_translate -q --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR -co COMPRESS=DEFLATE -projwin 127.32 0.4 127.48 0.24 GTI:cloud.gpkg crater-268070.tif

101 lines

Look before moving on. You can read the lines before you run them. Take the first one, and try it alone. If it is right, the others are right, too. If it is wrong, you correct one query, and not 101 lines.

Part What it does
x-0.08, y+0.08 the corners of a square around the volcano, 0.16 degrees wide, about 18 km
crater-'||number||'.tif the name of the result has the number of the volcano. See below
--lco HEADER=NO, SEPARATOR=TAB only the lines, with no title, and with no quotes around them
--lco LINEFORMAT=LF the ends of the lines as in macOS and Linux. Windows reads both

Why the number, and not the name? The first version used the name, and it made 100 files from 101 volcanoes. Look at the answer above: there are 100 different names. Two volcanoes are called Sumbing, one in Java and one in Sumatra, and the second file replaced the first one. For the programs, this is no error. Use a value for the file name that can not occur twice, and count the files at the end.

Run them, eight at a time

Now run the lines. The simple way is one after the other. But each of them waits for a server most of the time, and during this time, others can run. So run eight at the same time:

xargs -P 8 -I{} sh -c "{}" < jobs.csv

xargs takes the lines, -P 8 runs eight at a time. One after the other: sh jobs.csv.

Get-Content jobs.csv | ForEach-Object -Parallel { Invoke-Expression $_ } -ThrottleLimit 8
Get-Content jobs.csv | ForEach-Object { Invoke-Expression $_ }

This is the older PowerShell 5.1, with the blue window. It has no -Parallel, so this runs one after the other.

for /f "delims=" %i in (jobs.csv) do @%i

This runs one after the other, too. In a .bat file, write %%i in place of %i.

oneline.jobs("jobs.csv")
101 lines, 8 at a time: 54 seconds

In the notebook, a small Python function does the same as these loops. All four loops were tested, too, and the files are the same. One after the other took 6 minutes, and eight at a time 52 seconds (ledger L158). With your connection, the numbers will be different. Do not run many more than eight at a time, because this is a high load for a public server.

Now 101 files are in the folder. Make one picture of the 72 volcanoes that erupted last. The table of files is useful for this, too. Each row gets a place on the sheet in place of its place on the Earth:

ogr2ogr -overwrite wall.gpkg volcanoes.csv -oo AUTODETECT_TYPE=YES -dialect SQLite -sql "select 'vrt://crater-'||number||'.tif?outsize=240,240&r=average&a_ullr='||c||','||r||','||(c+240)||','||(r-240) location, buildmbr(c,r-240,c+240,r) geom, name, year from (select *, 250*(n-n/12*12) c, -250*(n/12) r from (select *, row_number() over (order by cast(year as int) desc, name)-1 n from volcanoes where year<>'') where n<72)" -nln wall -nlt POLYGON

gdal raster convert GTI:wall.gpkg wall.tif --overwrite
gdal pipeline read wall.tif ! color-map --color-map volcano.txt ! blend --overlay [ read wall.tif ! hillshade -z 0.015 ! color-map --color-map light.txt --add-alpha ! materialize ] ! write wall.jpg --co QUALITY=80 --overwrite

With a slow connection, skip all of this section and begin here: gdal raster convert offline_wall.tif wall.tif --overwrite, and then the last line.

A sheet with 72 square reliefs in six rows, each with one volcano in the middle and all at the same scale: sharp cones with white tops, wide craters, craters with lakes, and small round islands in a black sea

Look before moving on. Every square is the same size on the ground, and the colours mean the same height everywhere. The volcanoes that erupted last are in the top row, from the left, and the others follow from left to right and from top to bottom. If the year is the same, they are in the order of the alphabet. Read the names in the same order:

ogr2ogr -f CSV /vsistdout/ wall.gpkg -dialect SQLite -sql "select cast(1-r/250 as int) row, group_concat(name,', ') volcanoes, min(year) oldest from (select name, cast(year as int) year, st_maxy(geom) r from wall order by fid) group by 1"
row,volcanoes,oldest
1,"Dempo, Dukono, Ibu, Karangetang, Krakatau, Lewotobi, Lewotolok, Marapi, Merapi, Semeru, Sinabung, Dieng Volcanic Complex",2025
2,"Raung, Kerinci, Ruang, Suoh, Tengger Caldera, Agung, Sangeang Api, Iliwerung, Sirung, Soputan, Tangkuban Parahu, Gamalama",2018
3,"Rinjani, Lokon-Empung, Tara, Batu, Kelud, Slamet, Paluweh, Egon, Gamkonora, Talang, Ambang, Awu, Papandayan",2002
4,"Inielika, Batur, Kaba, Peuet Sague, Ijen, Iliboleng, Ranakah, Banda Api, Kie Besi, Sorikmarapi, Galunggung, Colo",1983
5,"Mahawu, Sundoro, Ebulobo, Iya, Kelimutu, Nila, Tambora, Gede-Pangrango, Arjuno-Welirang, Ciremai, Perbakti-Gagak, Salak",1938
6,"Telong, Bur ni, Tandikat-Singgalang, Serua, Sumbing, Banua Wuhu, Teon, Lamongan, Wurlali, Singkut, Tangkoko-Duasudara, Guntur, Merbabu",1797
Part What it does
vrt://file?outsize=240,240 the file, made smaller while it is read (Chapter 14)
a_ullr=... gives the file new corners: the place on the sheet. A square has 240 cells, and the next one begins after 250
n-n/12*12, n/12 the column and the row: 12 in each row. (% would be shorter, but some shells change it)
row_number() over (order by ...) 1 for the latest eruption, 2 for the one before

After the next eruption, the list of the Smithsonian will be updated. Run the lines of this section again, and the order of the pictures changes.

5. A thousand files, without a loop

The files of the last section came from a loop. Often you do not need one, because GDAL itself takes many files at once.

Many archives have one file for each day. This section first makes such an archive, and then uses it. quakes.csv has three years of earthquakes of magnitude 4.5 and more, in the same box as in section 1. One line writes a file for each day:

gdal vector partition quakes.csv days --field day --format CSV --scheme flat --overwrite
999 files in the folder days: quakes_2023-12-01_0000000001.csv, quakes_2023-12-02_0000000001.csv, ..., quakes_2026-11-29_0000000001.csv
Part What it does
partition ... --field day one file for each value of the column day
--scheme flat all files in one folder. The other scheme, hive, makes a folder for each value, with names such as day=2026-11-01. Some large databases use this form

Why are there 999 files, when three years have 1,096 days? The picture at the end of this section shows the reason.

Now the opposite: join all the files of this folder into one table again:

gdal vector concat "days/*.csv" back.csv --mode single --output-layer back --source-layer-field-name file --source-layer-field-content "{DS_BASENAME}" --overwrite

ogr2ogr -f CSV /vsistdout/ back.csv -sql "select * from back limit 3"

ogr2ogr -f CSV /vsistdout/ back.csv -dialect SQLite -sql "select count(*) earthquakes, count(distinct file) files, max(mag) strongest from back"
file,day,hour,x,y,depth,mag
quakes_2023-12-01_0000000001,2023-12-01,17:58,"129.4178","-2.7223","19.414","5"
quakes_2023-12-01_0000000001,2023-12-01,18:50,"129.4745","-2.7647","10.594","4.7"
quakes_2023-12-02_0000000001,2023-12-02,"05:37","112.511","-9.7881","43.519","5.2"
earthquakes,files,strongest
4070,999,"7.8"
Part What it does
"days/*.csv" all files of the folder. Keep the quotes. With them, GDAL replaces the star by the names of the files. Without them, bash and zsh do it, and the line can become too long for the system. This happened here with these 999 files, in Git Bash
--mode single all rows into one table
--source-layer-field-name file one more column: the name of the file from which the row comes

This needs no loop. It works for rasters, too: gdal raster mosaic "crater-*.tif" all.vrt puts files beside each other, and gdal raster stack puts them on top of each other. Keep the column with the name of the file. If there is an error in one of the thousand files, you need this column to find it.

One picture of a thousand files. Each day becomes a square, coloured by the number of earthquakes in its file. The query is in calendar.sql:

select n, buildmbr(week, row, week + 0.86, row + 0.86) geom
from (
  select n,
    -- the column: weeks since the Monday before the first day of the strip
    cast((julianday(day) - julianday(first, 'weekday 0', '-6 days')) / 7 as integer) week,
    -- the row: Monday is 0 and Sunday is 6; each year is 8.5 rows lower
    -((strftime('%w', day) + 6) % 7) - 8.5 * year row
  from (
    -- all days of three years, also those without a file
    with recursive calendar(day) as (
      select '2023-12-01' union all select date(day, '+1 day') from calendar where day < '2026-11-30')
    select calendar.day day, count(back.day) n,
      strftime('%Y', calendar.day, '+1 month') - 2024 year,
      (strftime('%Y', calendar.day, '+1 month') - 1) || '-12-01' first
    from calendar left join back on back.day = calendar.day group by calendar.day))
gdal vector sql back.csv calendar.gpkg --dialect SQLite --sql "@calendar.sql" --output-layer calendar --overwrite

gdal pipeline read calendar.gpkg ! rasterize --attribute-name n --extent -0.64,-23.5,53.5,1.36 --size 1949,895 --ot Int16 --init -1 ! color-map --color-map calendar.txt ! write calendar.png --overwrite

Three strips of small squares, one strip for each year from December to November, with a column for each week. Most squares are blue or green. After some bright squares, the colours fade downwards and to the right over days and weeks. A few places are empty

Look before moving on. Each strip is a year, from December to November. Each column is a week, with Monday at the top. The bright squares are the days with the most earthquakes. Look at the days after them, down the column, and then in the next one: the squares become darker slowly. These are the aftershocks. They are visible without any formula.

The picture also shows the missing files. The empty places are days without an earthquake of magnitude 4.5 in this box, so no file was written. There are 97 of them, and 999 + 97 = 1,096. In a folder, a day without an event and a lost file look the same. The query can show the difference only because it contains a list of all days.

A command file contains the names of the files, and not the star. You can write back.gdalg.json in place of back.csv. But GDAL replaces the star when it writes the command file, and puts 999 names into it. A file that is added tomorrow is not in the command file. For a folder that grows, run the line again each time.

6. One file for the mayor

The third task is to share the results with other people. The office of the mayor should get the map of minutes, the table of villages and the list of shelters, all from Chapter 15. (Copies are in the folder.) These are three files, with a fourth to explain them, and one of them can easily be lost.

A GeoPackage can contain all of them. This tutorial uses it for tables since Chapter 1. It can contain pictures, too:

gdal raster convert minutes.tif padang.gpkg --co RASTER_TABLE=minutes --co TILE_FORMAT=WEBP --co QUALITY=85 --overwrite

gdal raster overview add padang.gpkg

gdal vector convert villages.gpkg padang.gpkg --update --output-layer villages

gdal vector make-point shelters.csv padang.gpkg --x lon --y lat --dst-crs EPSG:4326 --update --output-layer shelters

gdal raster edit padang.gpkg --metadata "MADE_ON=2026-12-04" --metadata "MADE_FROM=Chapter 15 of One Line, One Map" --metadata "NOTE=An exercise and no evacuation plan"

ogrinfo -ro -q padang.gpkg
1: villages (Multi Polygon)
2: shelters (Point)
padang.gpkg: 536,576 bytes
Size is 1350, 1350
MADE_FROM=Chapter 15 of One Line, One Map
MADE_ON=2026-12-04
NOTE=An exercise and no evacuation plan
Part What it does
RASTER_TABLE=minutes the name of the picture inside the file
TILE_FORMAT=WEBP small, but with small errors. PNG is exact and larger. Section 7 measures these errors
overview add smaller versions of the picture, so that it opens fast
--update puts this into the file. --overwrite would begin a new one
edit --metadata who, when, from what, and what it must not be used for. A file is often passed on without your e-mail

Is everything inside? The best test is to make a map from this file alone:

gdal vector pipeline read padang.gpkg ! sql --dialect SQLite --sql "select 1 ink, st_buffer(st_boundary(geom), 9) geom from villages union all select 2, st_buffer(st_transform(geometry,32747), 130) from shelters" ! write marks.gdalg.json --overwrite

gdal pipeline read marks.gdalg.json ! rasterize --attribute-name ink --extent 642000,9885000,669000,9912000 --size 1350,1350 --ot Byte --init 0 ! color-map --color-map marks.txt --add-alpha ! write marks.tif --overwrite

gdal raster blend padang.gpkg --overlay marks.tif padang.jpg --co QUALITY=90 --overwrite

The dark map of Padang from Chapter 15, coloured from purple at the beach to light blue inland by the minutes to a safe place, with the thin grey borders of the villages and 23 white dots for the shelters

The white dots are the 23 shelters from a study of 2017 (Chapter 15).

A map for the browser

The office may not have QGIS. But everybody has a browser. One line cuts the picture into small tiles and writes a page that shows them on a map:

gdal raster tile minutes.tif web --min-zoom 10 --max-zoom 14 --format WEBP --skip-blank --webviewer leaflet --title "Padang: minutes to the nearest safe place" --copyright "WorldPop, DeltaDTM, Copernicus" --quiet

gdal vsi sozip create web web.zip --recursive --overwrite --quiet
web: 204 files, 0.3 MB | web.zip: 0.3 MB

Open web/leaflet.html with a double click. You can move and zoom, switch the picture off and on, and choose the map behind it. Put the folder web on any web server, and everybody can open it.

A web page with a street map of West Sumatra. The dark picture of Padang lies on it, half transparent, with its colours from purple to light blue. There are buttons to zoom, a title, and a list to choose the map behind

The page that GDAL wrote, in a browser. Map behind the picture: © OpenStreetMap contributors

The page loads its program and the street map behind your picture from the internet. So it needs a connection, even from your own disk.

gdal vsi sozip writes a normal zip file. Large files inside it are compressed in a special way, so that GDAL can read a part in the middle (ledger L157). So you can zip a big GeoPackage, and the other people can open padang.gpkg.zip without unpacking it.

7. What changes in another format?

Some people need a shapefile. Then your table is converted into another format, and you should check what is lost. This can be measured. Convert the villages into five formats. For the test, they get long column names, a remark that is empty for most of them, and a date:

gdal vector pipeline read villages.gpkg ! sql --dialect SQLite --sql "select name, district, lowest people_lowest, middle people_middle, highest people_highest, 'in the top ten of '||nullif(in_top_10,0)||' worlds' remark, '2026-12-04' counted, geom from mayor order by name" ! set-field-type --field-name counted --field-type Date ! write home.gpkg --output-layer home --overwrite

gdal vector convert home.gpkg shp.shp --overwrite

gdal vector convert home.gpkg geojson.geojson --lco RFC7946=YES --overwrite

gdal vector convert home.gpkg kml.kml --overwrite

gdal vector convert home.gpkg fgb.fgb --overwrite

gdal vector convert home.gpkg csv.csv --overwrite
Warning 6: Normalized/laundered field name: 'people_lowest' to 'people_low'
Warning 6: Normalized/laundered field name: 'people_middle' to 'people_mid'
Warning 6: Normalized/laundered field name: 'people_highest' to 'people_hig'
Warning 1: Several drivers matching kml extension. Using LIBKML

The shapefile gives a warning about its change: its column names can have only 10 characters (ledger L156). The other formats give no warning about changes in the table. Convert all of them back, into one file, each as a table with the name of its format. Then list their columns:

gdal vector concat home.gpkg shp.shp geojson.geojson kml.kml fgb.fgb back.gpkg --mode stack --output-layer "{DS_BASENAME}" --dst-crs EPSG:32747 --overwrite

ogr2ogr -f CSV /vsistdout/ back.gpkg -sql "select value file, count(*) columns, group_concat(p.name||' '||p.type,', ') names from json_each(json_array('home','shp','geojson','kml','fgb')), pragma_table_info(value) p group by value order by key"
Warning 1: A geometry of type MULTIPOLYGON is inserted into layer shp of geometry type POLYGON, which is not normally allowed by the GeoPackage specification, but the driver will however do it. To create a conformant GeoPackage, if using ogr2ogr, the -nlt option can be used to override the layer geometry type. This warning will no longer be emitted for this combination of layer and feature geometry type.
file,columns,names
home,9,"fid INTEGER, geom MULTIPOLYGON, name TEXT, district TEXT, people_lowest MEDIUMINT, people_middle MEDIUMINT, people_highest MEDIUMINT, remark TEXT, counted DATE"
shp,9,"fid INTEGER, geom POLYGON, name TEXT(80), district TEXT(80), people_low MEDIUMINT, people_mid MEDIUMINT, people_hig MEDIUMINT, remark TEXT(80), counted DATE"
geojson,9,"fid INTEGER, geom MULTIPOLYGON, name TEXT, district TEXT, people_lowest MEDIUMINT, people_middle MEDIUMINT, people_highest MEDIUMINT, remark TEXT, counted DATE"
kml,20,"fid INTEGER, geom GEOMETRY, id TEXT, Name TEXT, description TEXT, timestamp DATETIME, begin DATETIME, end DATETIME, altitudeMode TEXT, tessellate MEDIUMINT, extrude MEDIUMINT, visibility MEDIUMINT, drawOrder MEDIUMINT, icon TEXT, district TEXT, people_lowest MEDIUMINT, people_middle MEDIUMINT, people_highest MEDIUMINT, remark TEXT, counted TEXT"
fgb,9,"fid INTEGER, geom MULTIPOLYGON, name TEXT, district TEXT, people_lowest MEDIUMINT, people_middle MEDIUMINT, people_highest MEDIUMINT, remark TEXT, counted DATETIME"

Compare the lists. (The long warning is about the shapefile. It has no separate types for one area and for several areas, and GeoPackage has.) Then compare the shapes. check.sql compares each shape with the original one, and also the remarks:

select format, count(*) villages,
  max(1000 * hausdorffdistance(a.geom, b.geom)) moved_mm,
  sum(st_npoints(b.geom)) - sum(st_npoints(a.geom)) points_more,
  sum(a.remark is not b.remark) remarks_changed
from home a join (
  select 'fgb' format, name, remark, geom from fgb union all
  select 'geojson', name, remark, geom from geojson union all
  select 'kml', name, remark, geom from kml union all
  select 'shp', name, remark, geom from shp) b on a.name = b.name
group by format
ogr2ogr -f CSV /vsistdout/ back.gpkg -dialect SQLite -sql "@check.sql"

ogr2ogr -f CSV /vsistdout/ csv.csv -sql "select * from csv limit 2"
format,villages,moved_mm,points_more,remarks_changed
fgb,102,0,0,0
geojson,102,0.156875344626742,0,0
kml,102,4.42378222942352e-06,0,0
shp,102,0,0,0
name,district,people_lowest,people_middle,people_highest,remark,counted
Air Manis,Padang Selatan,"5","5","497",in the top ten of 2 worlds,2026/12/04
Air Pacah,Koto Tangah,"0","0","503",,2026/12/04

Look before moving on. The shapes have nearly no changes. The important changes are in the table:

Format What happened to the table What happened to the shapes
Shapefile .shp people_lowest became people_low, and people_highest became people_hig. Each text has space for 80 characters. It is several files: send all of them, or it does not work nothing
GeoJSON .geojson nothing they are stored in degrees with 7 decimals, as the standard says. This moved them by 0.2 mm here. (It can be up to about 8 mm. The original shapes already had 7 decimals)
KML .kml 11 new columns that belong to KML, name became Name, and the date became a text they are stored in degrees. The change is too small to be important
FlatGeobuf .fgb the date became a date with a time nothing
CSV .csv all columns became texts they are missing, without a warning. --lco GEOMETRY=AS_WKT would keep them as a text, but the coordinate system would still be missing

So if somebody needs a shapefile, send it together with a list of the column names. A GeoPackage is better, because the table is already in this format.

The same question for a picture

gdal raster compare compares two rasters. If it prints nothing, they are equal:

gdal raster convert minutes.tif exact.gpkg --co TILE_FORMAT=PNG --overwrite

gdal raster compare minutes.tif exact.gpkg --skip-binary --skip-metadata --quiet

It prints nothing. A GeoPackage with PNG tiles has exactly the same cells. (With --skip-binary and --skip-metadata, the files may be different, and only their contents are compared.)

With the WEBP of section 6, the same line reports differences in each band, of up to 26 steps out of 255. They are hard to see. But they change the results of calculations. So use WEBP and JPEG only for pictures that people look at, and never for heights, for classes, or for other data that you need for calculations.

compare also gives back the number of differences as its exit code. So the files of section 2 could use it, to do nothing if the new picture is the same as the old one.

8. What GDAL does not do

GDAL can do a lot, but not everything. Here are five common questions, and programs that are made for them. All of them are free (ledger L159).

Your question What GDAL can do Programs for this question
How long is the way by road? It calculates the straight line. In Chapter 15, this line was multiplied by 1.4 pgRouting in a PostGIS database, or OSRM
Where does the water of this slope flow? It calculates the slope of each cell, and not the path of the water GRASS (r.watershed), WhiteboxTools, TauDEM
What is the value between my measurements, and how certain is it? It has simple methods (Chapters 0 and 15), without the uncertainty kriging, with gstat in R or PyKrige in Python
I have a point cloud from a laser It reads the rasters that other programs make from it PDAL, which also works with pipelines
Where is this address? It has no list of streets Nominatim or Photon, both with data of OpenStreetMap

Use GDAL to convert the data for these programs, and to read their results again.

Try it yourself

  • Your own box. In section 1, use another country: change the four numbers of the address, and the same numbers in rasterize. You also need a relief for it (Chapter 2 has one for the whole world).
  • Only the strong ones. Write minmagnitude=5 in the address. Which command file did you change, and what about the others?
  • A picture for each day. In morning.sh, add cp today.jpg "$(date +%F).jpg" after mv. After a month, you have about 30 pictures that show the changes.
  • Another square. In section 4, write 0.16 in place of 0.08. Which volcanoes now have their neighbours in the picture?
  • Values that occur twice. Are there other columns in which two volcanoes are the same? Try height.
  • One file for each magnitude. partition needs a column. Make one with cast(mag as int), and write one file for each magnitude.
  • A longer text. Make the remark 300 characters long, and convert it to a shapefile. How much of it is left?

Checkpoint

The cell below stops with an error if the results are not what this chapter expects.

import csv

def ask(line):
    return list(csv.DictReader(oneline.run("ogr2ogr -f CSV /vsistdout/ " + line).splitlines()))

recipes = [f for f in WORK.glob("*.gdalg.json")]
assert len(recipes) >= 8 and sum(f.stat().st_size for f in recipes) < 5000, "the recipes should be tiny"
assert int(ask('quakes.gdalg.json -dialect SQLite -sql "select count(*) n from quakes"')[0]["n"]) > 20, "the last 30 days should have earthquakes"

tiles = int(ask('cloud.gpkg -sql "select count(*) n from cloud"')[0]["n"])
assert tiles == 467, "Indonesia should have 467 tiles"
craters = len(list(WORK.glob("crater-*.tif")))
assert craters == len((WORK / "jobs.csv").read_text().splitlines()) >= 101, "each line should have made its own file"

assert len(list((WORK / "days").glob("*.csv"))) == 999
assert int(ask('back.csv -dialect SQLite -sql "select count(*) n from back"')[0]["n"]) == 4070, "no earthquake should be lost"

trip = {r["format"]: r for r in ask('back.gpkg -dialect SQLite -sql "@check.sql"')}
assert all(int(r["villages"]) == 102 and float(r["moved_mm"]) < 10 for r in trip.values()), "the shapes should come home"

pictures = ("november.jpg", "december2004.jpg", "today.jpg", "tambora.jpg", "wall.jpg", "calendar.png", "padang.jpg")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: {len(recipes)} recipes, {tiles} tiles on a server, {craters} volcanoes, 999 days, {len(trip)} trips")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 9 recipes, 467 tiles on a server, 101 volcanoes, 999 days, 4 trips
time since the first cell: 191 s

Troubleshooting

Symptom Cause Fix
not recognized as being in a supported file format for a .gdalg.json file The program has a GDAL that is older than 3.11 Make a result for it: gdal raster convert recipe.gdalg.json result.tif
PowerShell says that the splatting operator @ can not be used, or the name of the .sql file is missing In PowerShell, a word that begins with @ has a special meaning Put quotes around it: --sql "@rings.sql"
A column or row of wrong heights where two tiles meet The boxes in the table of files are not exactly the boxes of the files Compare with the corners that gdalinfo gives. Here, it was half a cell
A command file can not find its inputs It reads them from its own folder Move the command file together with its inputs, or use whole paths or addresses
The GDALG driver does not support update access ogrinfo tries to open the file for writing, too It still works. With -ro, there is no message
The line has made its command file, but it does not end This happened on Windows with GDAL 3.12.3, when the input was a raster on a server and nothing was read from it Clip a piece to a TIFF, and write the command file for the piece
Field location is not of type string, or the files have wrong names, when SQL makes texts || is calculated before * and +: 'a'||2*3 is not a6 Put brackets around all calculations: 'a'||(2*3)
There are fewer files than lines in jobs.csv Two lines have the same name for the result Use a number that is different for each row
Argument list too long The shell replaced the star, and there are very many files Put quotes around "days/*.csv"
concat says has no spatial reference system One of the files, often a CSV file, has no coordinate system Leave it out, or convert it first, as with make-point in section 6
has both raster and vector content gdal info can not choose between the two contents of this GeoPackage gdal raster info or gdal vector info

What comes next

The lines now repeat themselves, the result is up to date, and other people can open it.

One topic is left: the design of a complete map. Chapter 17: A complete map sheet uses the data of the whole tutorial to make one large map for printing.

Earthquakes: U.S. Geological Survey, public domain. Relief of land and sea: ETOPO 2022, NOAA, CC0. Volcanoes: Global Volcanism Program, 2026. [Database] Volcanoes of the World (v. 5.4.0; 7 Aug 2026). Distributed by Smithsonian Institution, compiled by Venzke, E. doi:10.5479/si.GVP.VOTW5-2026.5.4. Their reliefs: Copernicus DEM GLO-30, produced using Copernicus WorldDEM-30 © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved. Padang: the sources of Chapter 15.