Skip to main content

Chapter 4: Earthquakes by depth

Chapter 4: Earthquakes by depth

TipAt a glance
  • In this series: Part I, Places. In the chapters before, the two axes of a map were angles. They can also be other quantities. This chapter puts the depth of earthquakes on one axis, and shows what lies below the surface
  • You will build: Side views of the plates under Java, Sumatra and the Banda Sea, the year after the 2004 earthquake with time on one axis, and a map with circles whose area shows the energy
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell
  • Time to run: The commands took about a minute when tested, including 11 MB of downloads
  • Level: Beginner; the longer queries are explained part by part

On most maps, the x axis points to the east and the y axis to the north. This is a convention, and GDAL can draw any two numbers. With the depth on the y axis, a map of earthquakes becomes a view from the side, which shows a plate that sinks under Java. With the time on the x axis, the picture shows how many earthquakes followed a large one, and for how long.

This chapter uses the earthquake catalogue of the US Geological Survey (USGS), which is updated all the time. It uses no geological map: every shape in the pictures is made of earthquakes alone.

NoteLearning objectives

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

  • read the answer of a web service like a file, and keep only what you need;
  • choose any two quantities as the axes of a drawing;
  • find values in a data set that were assumed and not measured;
  • rotate a map to any angle with a projection, so that a line at an angle becomes vertical;
  • draw a bar chart in the terminal with SQL;
  • distinguish between the number of events and their total energy.

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/ch04. 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("04")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch04").iterdir()))
working folder: ch04 | files copied there: ['deep.txt', 'heat.txt', 'quake.txt', 'usgs.gpkg.zip']

Warm-up

A few short commands first, in the form of Chapter 0. The folder has a copy of the earthquakes of section 1, as a GeoPackage inside a zip. GDAL reads the file inside the zip if you write /vsizip/ in front of the name:

gdal vector info /vsizip/usgs.gpkg.zip --summary

gdal vector grid count /vsizip/usgs.gpkg.zip crowd.tif --input-layer quakes --zfield mag --extent 90,-13,142,15 --size 1040,560 --radius 1 --overwrite

gdal raster color-map crowd.tif crowd.png --color-map heat.txt --overwrite
INFO: Open of `/vsizip/usgs.gpkg.zip'
      using driver `GPKG' successful.
1: java (Point)
2: quakes (Point)

A map of earthquake numbers on black. A bright arc runs along Sumatra and Java and turns north through the Philippines. No coast is drawn.

grid count counts the earthquakes within one degree of each cell. No coast is drawn, but the positions of Sumatra, Java and the Philippines are visible.

If you replace one word, the result is a different map. grid average takes the mean of a column, here of the depth:

gdal vector grid average /vsizip/usgs.gpkg.zip deep.tif --input-layer quakes --zfield depth --extent 90,-13,142,15 --size 1040,560 --radius 0.5 --overwrite

gdal raster color-map deep.tif deep.png --color-map deep.txt --overwrite

The same arc coloured by depth. The outer side is dark blue and shallow, and the inner side, north of Java and west of the southern Philippines, is yellow and deep.

Look before moving on. The outer side of the arc is shallow, and the inner side is deep: the yellow places lie more than 500 km below the surface. Between the two, the depth increases step by step, so the earthquakes form an inclined surface. A map from above does not show its shape well. This chapter draws the same earthquakes from the side.

1. A web address as a data source

The USGS has a web service for queries about earthquakes (ledger L29). The query is part of the web address, and the answer is GeoJSON, which GDAL reads directly. So you can write this address where you would usually write a file name:

ogr2ogr -overwrite quakes.gpkg "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&starttime=1990-01-01&endtime=2026-01-01&minmagnitude=5&minlatitude=-13&maxlatitude=15&minlongitude=90&maxlongitude=142" -dialect SQLite -sql "select mag, datetime(time/1000,'unixepoch') utc, st_z(geometry) depth, place, geometry geom from OGRGeoJSON" -nln quakes -dim XY -a_srs EPSG:4326

ogr2ogr -update -overwrite quakes.gpkg "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&starttime=1990-01-01&endtime=2026-01-01&minmagnitude=4.5&minlatitude=-13&maxlatitude=-4&minlongitude=108&maxlongitude=113" -dialect SQLite -sql "select mag, datetime(time/1000,'unixepoch') utc, st_z(geometry) depth, place, geometry geom from OGRGeoJSON" -nln java -dim XY -a_srs EPSG:4326

ogr2ogr -update -overwrite quakes.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/50m/physical/ne_50m_land.zip -nln land -nlt PROMOTE_TO_MULTI -clipsrc 85 -20 150 20

The first line requests every earthquake of magnitude 5 or more from 1990 to 2025, in a box from the Andaman Islands to New Guinea. The second requests a smaller box around Java, with magnitudes from 4.5. The third adds the land, from Natural Earth, as in Chapter 1.

Part Meaning
"https://...&..." the quotes are needed, because & has a meaning of its own in every shell
endtime=2026-01-01 keeps the answer about the same on every day you run this. Without it, the list would grow
minmagnitude and the box the server gives at most 20,000 events for one query (ledger L29), so a query needs limits
time/1000 the catalogue counts time in milliseconds since 1970, in UTC (ledger L30). SQLite needs seconds
st_z(geometry) depth the points have a third coordinate: the depth in kilometres, counted downwards. This copies it into a column
-dim XY then removes it from the points, which makes the later lines simpler

If the USGS server cannot be reached, use the copy in the chapter’s folder, made on 3 December 2026. This line replaces the first two: ogr2ogr -overwrite quakes.gpkg usgs.gpkg.zip

Check the result:

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select * from (select 'quakes' layer, count(*) events, min(mag) smallest, max(mag) largest, max(depth) deepest_km from quakes) union all select 'java', count(*), min(mag), max(mag), max(depth) from java"

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select mag, utc, depth, place from quakes order by mag desc limit 5"
layer,events,smallest,largest,deepest_km
quakes,11622,5,9.1,678
java,985,4.5,7.8,652.2
mag,utc,depth,place
9.1,2004-12-26 00:58:53,30,2004 Great Sumatra-Andaman Islands Earthquake
8.6,2012-04-11 08:38:36,20,2012 Wharton Basin Earthquake
8.6,2005-03-28 16:09:36,30,2005 Nias-Simeulue Earthquake
8.4,2007-09-12 11:10:26,34,2007 Bengkulu Earthquake
8.2,2012-04-11 10:43:10,25.1,2012 Wharton Basin Aftershock

The catalogue is corrected from time to time, also for past years, so your counts can differ a little from the ones printed here.

2. The earthquakes on an ordinary map

This map shows the earthquakes from above, with a colour for the depth. The limits are those of the USGS: shallow down to 70 km, intermediate down to 300 km, and deep below that (ledger L31).

gdal pipeline read quakes.gpkg ! sql "select 1 v, geom from land union all select * from (select case when depth<70 then 4 when depth<300 then 5 else 6 end, st_buffer(geom, 0.02+0.025*pow(1.6,mag-5)) from quakes order by depth)" ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,2520" --extent "90,-13,142,15" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,840" -r average ! write above.png --overwrite

Map from the Andaman Islands to New Guinea on dark blue, with thousands of dots. South of Java and along the west coast of Sumatra the dots are yellow. Next to them, towards Asia, comes a band of red dots, and north of Java and Flores a band of violet ones.

This is the pipeline of Chapter 3. The symbols are buffers, and a large picture is reduced to get smooth edges.

Look before moving on. Yellow is shallow, red is intermediate and violet is deep. From the Indian Ocean across Java towards Borneo, the dots are first yellow, then red under the island, and then violet in the sea to the north. Further east, the violet dots also lie north of the yellow ones. The depth follows a clear pattern, and a map from above cannot show it well.

3. Java from the side

The next picture shows Java from the east, looking west, so north is on the right. The x axis is the distance from south to north, and the y axis is the depth. This needs one change in the query: the position of a dot is no longer its point on the Earth, but a point made from latitude and depth.

makepoint(st_y(geom)*111.2, -depth)

One degree of latitude is about 111.2 km (the circumference of a sphere with a radius of 6,371 km, divided by 360). Because of the minus sign, deep earthquakes are at the bottom. Both axes are now in kilometres with the same scale, so angles in the picture are correct.

gdal pipeline read quakes.gpkg ! sql "select case when depth<70 then 4 when depth<300 then 5 else 6 end v, st_buffer(makepoint(st_y(geom)*111.2, -depth), 0.6+1.2*pow(1.6,mag-4.5)) geom from java order by mag" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "1560,1200" --extent "-1430,-690,-520,30" ! edit --nodata none ! color-map --color-map quake.txt ! write first.png --overwrite

Dots on dark blue, seen from the side. Yellow dots near the top are followed by red dots that go down towards the right, then an empty space, then a cluster of violet dots at the lower right. Two perfectly straight horizontal rows of yellow dots cross the top.

edit --crs none is new. The coordinates are no longer degrees, and this step removes the coordinate system, so that GDAL does not treat them as degrees.

Look before moving on. The earthquakes form a slope that goes down from left to right, from the ocean in the south to under the island and beyond. Two other things are unusual. There is a large empty space in the slope, and near the top there are two perfectly straight lines of dots. Such straight lines are not natural, so the next section examines them first.

4. What are the two straight lines?

Count the events that have exactly the same depth:

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select depth, count(*) events, round(100.0*count(*)/(select count(*) from java),1) percent from java group by depth order by events desc limit 6"
depth,events,percent
10,194,19.7
33,152,15.4
35,49,5
100,7,0.7
25,5,0.5
67,3,0.3

Hundreds of earthquakes have a depth of 10, 33 or 35 km, and after that almost no value is repeated often. The USGS explains this: if the data are not sufficient to calculate the depth, the program sets it to a fixed value. The text gives 33 km for shallow earthquakes, and 5 or 10 km in some regions (ledger L30). The value 35 is not in that text. When were the three values used?

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select depth, count(*) events, min(date(utc)) first, max(date(utc)) last from java where depth in (10,33,35) group by depth"
depth,events,first,last
10,194,2003-11-20,2025-07-07
33,152,1990-01-15,2003-11-28
35,49,2005-11-01,2025-12-03

Look before moving on. Under Java, the value 33 ends in November 2003, the month in which 10 begins, and 35 follows two years later. A plate does not change in one month, but a procedure can. So 35 is probably a fixed value too, and this chapter treats it as one.

Four in ten of these depths, then, most likely mean “shallow, not well known”. An assumed value looks exactly like a measured one in a table, and a drawing can show the difference. For any column of measurements, it is useful to count the most frequent values first.

Here is the picture again, with those events in grey and behind the others. It also gets a line for every 100 km, and a white bar at sea level for Java:

gdal pipeline read quakes.gpkg ! sql "with recursive k(d) as (select 0 union all select d+100 from k where d<600), cut as (select st_intersection(geom, makeline(makepoint(110.5,-12,4326),makepoint(110.5,-4,4326))) g from land) select 1 v, st_buffer(makeline(makepoint(-1430,-d),makepoint(-520,-d)),0.4) geom from k union all select 7, st_buffer(makeline(makepoint(st_miny(g)*111.2,6),makepoint(st_maxy(g)*111.2,6)),5) from cut where not st_isempty(g) union all select * from (select case when depth in (10,33,35) then 3 when depth<70 then 4 when depth<300 then 5 else 6 end, st_buffer(makepoint(st_y(geom)*111.2, -depth), 0.6+1.2*pow(1.6,mag-4.5)) from java order by depth in (10,33,35) desc, mag)" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,3600" --extent "-1430,-690,-520,30" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,1200" -r average ! write java.png --overwrite

The same side view, cleaner. A white bar at the top marks Java. Yellow dots start at the left, red dots go down under the white bar to 250 km, then nothing until about 450 km. Below that, violet dots form two steep clusters to the right of the island, down to 650 km. Grey dots mark the two straight rows.

The query has four parts, joined by union all. Later parts are drawn on top of earlier ones:

  1. k is a list of depths, 0, 100, 200 and so on to 600. Each becomes a thin line.
  2. cut is the land along one meridian, 110.5 degrees east, which passes through Salatiga in Central Java. Its southern and northern ends are the ends of the white bar.
  3. The grey dots come first, because order by depth in (10,33,35) desc sorts them to the beginning.
  4. The other dots follow, small ones before large ones.

Look before moving on. The dots show the Australia plate, which sinks under Java. According to the USGS it moves north-northeast under the Sunda plate at about 6 cm a year. It lies 100 to 200 km below Java and reaches 600 km north of the island (ledger L33). The picture shows the same, and it was drawn only from points in a table.

5. How many earthquakes are at each depth?

A simple bar chart can be made of text. zeroblob(n) makes n empty bytes, hex writes each of them as 00, and replace turns every 00 into a #. One # stands for up to ten earthquakes:

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "with recursive k(d) as (select 0 union all select d+50 from k where d<650) select d from_km, d+50 to_km, n events, replace(hex(zeroblob((n+9)/10)),'00','#') bar from (select d, (select count(*) from java where depth>=d and depth<d+50) n from k)"
from_km,to_km,events,bar
0,50,614,##############################################################
50,100,229,#######################
100,150,60,######
150,200,16,##
200,250,8,#
250,300,1,#
300,350,0,
350,400,0,
400,450,0,
450,500,1,#
500,550,12,##
550,600,26,###
600,650,15,##
650,700,3,#

Look before moving on. In 36 years there was not one earthquake of magnitude 4.5 or more between 300 and 450 km, and below that they begin again. The list of depths comes from the query and not from the data. This is why the empty classes are in the table. A plain group by would leave them out, and the gap would not be visible in the chart.

What does the gap mean? The earthquakes alone cannot show it. The plate can be there without earthquakes. A study of 1996, which used the speed of earthquake waves, described the same gap between 350 and 500 km, and found that the plate probably continues through it, perhaps thinner. A study of 2010 interpreted the gap under East Java as a hole in the plate (ledger L34).

6. Sumatra: a section at an angle

Java lies almost exactly from west to east, so latitude was a good x axis. The coast of Sumatra runs from north-west to south-east, and a view along this coast needs a rotated map.

You could calculate the rotation with sines and cosines, but a projection can do it. The oblique Mercator projection, +proj=omerc, uses a line at an angle instead of the equator (ledger L35):

Part Meaning
+lat_0=-0.95 +lonc=100.35 the centre of the map, here Padang
+alpha=-45 the direction of the line through it: 45 degrees to the left of north, roughly along the coast
+gamma=0 rotate the result so that this line is vertical
+units=km kilometres, as for the depth

As in Chapter 3, first a test with a known result. A point one degree east and one degree north of Padang should have a large x, and a y close to 0:

gdaltransform -output_xy -s_srs EPSG:4326 -t_srs "+proj=omerc +lat_0=-0.95 +lonc=100.35 +alpha=-45 +gamma=0 +units=km +ellps=WGS84" -coord 101.35 0.05
156.915134544507 -0.538320850487743

This is the case. So x is now the distance from the coast into the land, and y is the distance along the coast. The next picture is made like the one before, with two changes: the layers are rotated first, and abs(st_y(geom))<300 keeps a strip that reaches 300 km to each side of Padang.

ogr2ogr -update -overwrite quakes.gpkg quakes.gpkg quakes -t_srs "+proj=omerc +lat_0=-0.95 +lonc=100.35 +alpha=-45 +gamma=0 +units=km +ellps=WGS84" -nln turned

ogr2ogr -update -overwrite quakes.gpkg quakes.gpkg land -clipsrc 85 -15 115 15 -t_srs "+proj=omerc +lat_0=-0.95 +lonc=100.35 +alpha=-45 +gamma=0 +units=km +ellps=WGS84" -nln turned_land

gdal pipeline read quakes.gpkg ! sql "with recursive k(d) as (select 0 union all select d+100 from k where d<600), cut as (select st_intersection(st_buffer(geom,0), makeline(makepoint(-400,0),makepoint(600,0))) g from turned_land) select 1 v, st_buffer(makeline(makepoint(-400,-d),makepoint(510,-d)),0.4) geom from k union all select 7, st_buffer(makeline(makepoint(st_minx(g),6),makepoint(st_maxx(g),6)),5) from cut where st_length(g)>10 union all select * from (select case when depth in (10,33,35) then 3 when depth<70 then 4 when depth<300 then 5 else 6 end, st_buffer(makepoint(st_x(geom), -depth), 0.8+1.5*pow(1.6,mag-5)) from turned where abs(st_y(geom))<300 order by depth in (10,33,35) desc, mag)" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,3600" --extent "-400,-690,510,30" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,1200" -r average ! write sumatra.png --overwrite

Side view across Sumatra at the same scale as Java. Yellow dots start at the left, in the ocean, and red dots continue down under the white bar of Sumatra to about 260 km. Below that the picture is empty.

Look before moving on. The scale and the depth range are the same as for Java, so you can compare the two pictures directly. Here the slope ends at about 260 km, and there are no violet dots. The study of 1996 reports the same: no earthquakes deeper than 300 km under Sumatra (ledger L34). Is this also true for the whole island, and until today?

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select utc, mag, depth, place from quakes where depth>300 and st_x(geom)<106 and st_y(geom)>-6"
utc,mag,depth,place
2004-07-25 14:35:19,7.3,582.1,"100 km SSE of Jambi City, Indonesia"

There is one, and it is a large one. It happened eight years after the study, near Jambi, and outside the strip of the picture. One earthquake is not a pattern, but it shows that deep earthquakes are possible there.

7. The whole arc, seen from the south

This picture looks from the south to the north. The x axis is the longitude, with about 110 km for each degree, because the region is close to the equator. The y axis is the depth again. The strip is wide and flat, so the depth is drawn at twice its size:

gdal pipeline read quakes.gpkg ! sql "with recursive k(d) as (select 0 union all select d+100 from k where d<600) select 1 v, st_buffer(makeline(makepoint(100*110,-d*2),makepoint(132*110,-d*2)),1) geom from k union all select * from (select case when depth in (10,33,35) then 3 when depth<70 then 4 when depth<300 then 5 else 6 end, st_buffer(makepoint(st_x(geom)*110, -depth*2), 3+3*pow(1.6,mag-5)) from quakes where st_y(geom)<-4 order by depth in (10,33,35) desc, mag)" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,1980" --extent "11000,-1435,14520,55" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,660" -r average ! write south.png --overwrite

A wide side view from southern Sumatra on the left to the Banda Sea on the right. Yellow and red dots run along the top. Violet dots lie at the bottom from West Java eastwards. At the right end they curve upwards in a smooth arc and join a dense red cluster near the surface.

Look before moving on. On the left, south of Sumatra, there are no deep earthquakes. From West Java to the east, violet dots appear at 500 to 650 km, with the gap of section 5 above them. Towards the middle of the picture, there are more and more earthquakes in the gap. At the right end, under the Banda Sea, the deep dots form a curve that rises to the surface. The same curve is also in the first map, where the red and yellow bands bend around the Banda Sea. The view from the side shows its depth.

8. Time on the x axis

On 26 December 2004 an earthquake of magnitude 9.1 started off the west coast of northern Sumatra. To see the earthquakes that followed, put the time on the x axis, in days, and the latitude on the y axis. Every vertical line is the first day of a month, from July 2004 to December 2005, and the two white dots are the earthquakes of magnitude 8 or more:

gdal pipeline read quakes.gpkg ! sql "with recursive m(d) as (select '2004-07-01' union all select date(d,'+1 month') from m where d<'2005-12-01') select 1 v, st_buffer(makeline(makepoint(julianday(d),-90),makepoint(julianday(d),450)),0.15) geom from m union all select * from (select case when mag>=8 then 7 else 4 end, st_buffer(makepoint(julianday(utc), st_y(geom)*30), 0.4+0.8*pow(1.6,mag-5)) from quakes where st_x(geom)<100 and utc>'2004-06-01' and utc<'2006-01-01' order by mag)" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,4320" --extent "2453157,-90,2453742,450" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,1440" -r average ! write aceh.png --overwrite

Time runs from left to right and latitude from bottom to top. The left third is almost empty. Then a white dot appears with a vertical column of yellow dots above it, and there are fewer dots further to the right. A dense cluster follows a month later, and further right a second white dot with a shorter column.

julianday() gives a date as a number of days, as in Chapter 3, and this number is the x coordinate. st_y(geom)*30 only stretches the latitude so that the picture is not too flat.

Look before moving on. For half a year there are almost no dots. Then, within hours, there are many earthquakes, from the white dot to the north. How far do they reach on the first day?

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select count(*) events_in_24_hours, round(min(st_y(geom)),1) south, round(max(st_y(geom)),1) north, round((max(st_y(geom))-min(st_y(geom)))*111.2) km from quakes where st_x(geom)<100 and st_y(geom)>2 and utc>='2004-12-26 00:58:53' and utc<'2004-12-27 00:58:53'"
events_in_24_hours,south,north,km
142,2.8,13.7,1219

That is only the distance from south to north. The USGS describes a zone of aftershocks more than 1,300 km long, and a rupture that went north from the place where the earthquake started (ledger L36). The white dot is only this starting point. This is a common mistake when people read an earthquake map: the dot of a large earthquake does not show the whole area that broke.

Three months later, the second white dot follows further south, off Nias, with its own aftershocks.

How long does it last? Count in periods that double in length each time: the first day, the second day, days 3 and 4, and so on.

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "with recursive w(a,b) as (select 0,1 union all select b,b*2 from w where b<128) select a after_day, b to_day, count(q.fid) events, round(1.0*count(q.fid)/(b-a),1) per_day, sum(st_y(q.geom) between 7 and 9) between_7_and_9_north from w left join quakes q on st_x(q.geom)<100 and st_y(q.geom)>2 and julianday(q.utc)-julianday('2004-12-26 00:58:53')>a and julianday(q.utc)-julianday('2004-12-26 00:58:53')<=b group by a"
after_day,to_day,events,per_day,between_7_and_9_north
0,1,141,141,38
1,2,45,45,15
2,4,37,18.5,6
4,8,34,8.5,10
8,16,30,3.8,2
16,32,28,1.8,6
32,64,165,5.2,126
64,128,52,0.8,1

Look before moving on. The number per day falls quickly, and then more slowly. One row is an exception: after day 32 there are more again. The last column shows where they come from. Three quarters of them lie between 7 and 9 degrees north, and in the picture they are the dense cluster at the end of January. The table and the picture together explain this row.

9. The number of earthquakes, and their energy

Which place has the most earthquakes? Count them on a grid of half a degree. gdal_rasterize -add adds a number to a cell for every point in it, instead of overwriting the cell:

gdal_rasterize -q -add -burn 1 -init 0 -ot Float32 -te 90 -13 142 15 -tr 0.5 0.5 -l quakes quakes.gpkg count.tif

gdal pipeline read count.tif ! resize --size "1560,840" -r nearest ! color-map --color-map heat.txt ! write count_map.tif --overwrite

gdal_rasterize -q -b 1 -b 2 -b 3 -burn 120 -burn 135 -burn 155 -sql "select st_buffer(st_boundary(geom),0.02) from land" quakes.gpkg count_map.tif

gdal_translate -q -of PNG count_map.tif count.png

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select floor(st_x(geom)*2)/2 west, floor(st_y(geom)*2)/2 south, count(*) events, max(mag) largest from quakes group by 1,2 order by events desc limit 3"
west,south,events,largest
126,1,129,7.5
126.5,3.5,109,6.5
94,7.5,102,6.4

Grid of coloured squares with thin coastlines. The brightest squares lie in the Molucca Sea between Sulawesi and Halmahera, along the east of the Philippines, in the Banda Sea, and at the left edge near the Nicobar Islands.

The third line shows another use of gdal_rasterize. Without -te and -tr, and with an existing file as its target, it draws into that file. Here it draws the coast, in grey, into the three bands of the picture.

Look before moving on. The cell with the most earthquakes lies in the Molucca Sea, between Sulawesi and Halmahera. The north of Sumatra is not at the top of the list.

Now use the same data for another question: where was the most energy released? The USGS gives a formula for the energy of an earthquake with magnitude M: log E = 5.24 + 1.44 M (ledger L37). One whole magnitude more is therefore 10 to the power of 1.44, about 28 times the energy. The shares of the largest events:

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select mag, date(utc) day, place, round(pow(10,1.44*(mag-5))) equal_to_magnitude_5_events, round(100*pow(10,1.44*(mag-5))/(select sum(pow(10,1.44*(mag-5))) from quakes),1) percent_of_all_energy from quakes order by mag desc limit 5"
mag,day,place,equal_to_magnitude_5_events,percent_of_all_energy
9.1,2004-12-26,2004 Great Sumatra-Andaman Islands Earthquake,801678,47.3
8.6,2012-04-11,2012 Wharton Basin Earthquake,152757,9
8.6,2005-03-28,2005 Nias-Simeulue Earthquake,152757,9
8.4,2007-09-12,2007 Bengkulu Earthquake,78705,4.6
8.2,2012-04-11,2012 Wharton Basin Aftershock,40551,2.4

Look before moving on. One earthquake has nearly half of all the energy of 36 years, and the five largest together have more than two thirds. All the others in the table, more than 11,000 earthquakes, have the rest. The formula is for one type of magnitude, and the catalogue contains several types, so the percentages are only approximate.

A grid is not suitable for such numbers, because one cell would be so much larger than the others that their differences would not be visible. Circles can show them: the area of each circle is the energy. The area grows with the square of the radius, so the radius needs half of the exponent, 0.72:

gdal pipeline read quakes.gpkg ! sql "select 1 v, geom from land union all select * from (select case when mag>=9 then 7 when mag>=8 then 4 else 5 end, st_buffer(geom, 4.2*pow(10,0.72*(mag-9.1))) from quakes order by mag desc)" ! rasterize --attribute-name v --init 0 --ot Byte --size "4680,2520" --extent "90,-13,142,15" ! edit --nodata none ! color-map --color-map quake.txt ! materialize ! resize --size "1560,840" -r average ! write energy.png --overwrite

The same region with circles. One huge white circle covers the sea and the land at the north end of Sumatra. Yellow circles lie on it, off Bengkulu and north of Papua. All the other earthquakes are small red circles or barely visible specks.

Look before moving on. The cell with the most earthquakes is hardly visible in this picture. Both maps are correct, and both come from the same 11,000 rows. Before you map a count, decide whether the question is about the number of events or about their size.

The circles do not show the area that shook or broke. They show one number for each earthquake, like the bars of a bar chart.

10. Which town is nearest?

This is a line for everyday work. Natural Earth has a list of populated places. For each of the largest earthquakes, find the nearest one, and measure the distance on the ellipsoid:

ogr2ogr -update -overwrite quakes.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/10m/cultural/ne_10m_populated_places_simple.zip -nln town -sql "select name, adm0name country from ne_10m_populated_places_simple where adm0name in ('Indonesia','East Timor','Malaysia','Philippines')"

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select q.mag, date(q.utc) day, t.name town, round(st_length(makeline(t.geom,q.geom),1)/1000) km, q.place usgs_says from quakes q join town t on t.fid=(select fid from town order by st_distance(town.geom,q.geom) limit 1) where q.mag>=7.8 order by q.mag desc"
mag,day,town,km,usgs_says
9.1,2004-12-26,Lhokseumawe,246,2004 Great Sumatra-Andaman Islands Earthquake
8.6,2012-04-11,Banda Aceh,436,2012 Wharton Basin Earthquake
8.6,2005-03-28,Sibolga,192,2005 Nias-Simeulue Earthquake
8.4,2007-09-12,Bengkulu,123,2007 Bengkulu Earthquake
8.2,2012-04-11,Banda Aceh,614,2012 Wharton Basin Aftershock
8.09,1996-02-17,Biak,105,"1996 Biak, Indonesia Earthquake"
7.9,2007-09-12,Sungaipenuh,88,"87 km SW of Sungai Penuh, Indonesia"
7.9,2000-06-04,Bengkulu,104,"103 km S of Bengkulu, Indonesia"
7.9,1996-06-17,Maumere,169,"169 km NNE of Maumere, Indonesia"
7.9,1996-01-01,Palu,181,"181 km N of Palu, Indonesia"
7.8,2016-03-02,Padang,802,"southwest of Sumatra, Indonesia"
7.8,2010-10-25,Sungaipenuh,215,"215 km SW of Sungai Penuh, Indonesia"
7.8,2010-04-06,Sibolga,207,"75 km E of Sinabang, Indonesia"
7.8,1994-06-02,Jember,272,"249 km SSW of Kencong, Indonesia"
7.8,1992-12-12,Maumere,38,"37 km WNW of Maumere, Indonesia"
7.8,1990-04-18,Gorontalo,74,"75 km NNW of Gorontalo, Indonesia"

The inner query, select fid from town order by st_distance(...) limit 1, runs once for every earthquake and returns the number of the closest town. It compares degrees. Near the equator this is accurate enough to choose a town, but not to give a distance. So the kilometres come from st_length(..., 1), where the 1 means “on the ellipsoid”, for a line between the two points.

Is it right? The last column is the place name from the USGS. Where both give the same town, as with Maumere or Palu, the distances agree to within one kilometre. In the other rows with a distance, the USGS gives a place that is not in our list and is closer. The result depends on the list of places.

The next line answers the opposite question. Which towns had the most shallow earthquakes within 100 km?

ogr2ogr -f CSV /vsistdout/ quakes.gpkg -sql "select t.name town, count(*) shallow_events_within_100_km, max(q.mag) largest from town t join quakes q on q.depth<70 and abs(st_y(q.geom)-st_y(t.geom))<1 and abs(st_x(q.geom)-st_x(t.geom))<1 and st_length(makeline(t.geom,q.geom),1)<100000 where t.country='Indonesia' group by t.name order by 2 desc limit 6"
town,shallow_events_within_100_km,largest
Banda Aceh,118,6.5
Bengkulu,112,6.9
Nabire,104,7.3
Gorontalo,83,7.8
Jayapura,81,6.5
Manokwari,76,7.4

The two tests with abs do not change the result. They quickly remove the pairs that are far apart, so that the exact and slower distance is calculated only for the rest. One degree is a little more than 100 km here, so no pair is lost.

This is a count of past earthquakes of magnitude 5 and more. It is not a measure of danger, which also depends on the ground, the buildings and on earthquakes that have not happened in these 36 years.

Try it yourself

  • This month. Take the first line of section 1 and remove &starttime=1990-01-01&endtime=2026-01-01. Without them, the server returns the last 30 days (ledger L29).
  • Another plate. In section 3, use a box around Tonga, Japan or Chile. In Japan and Chile the coast does not run from west to east, so use the method of section 6 there.
  • Depth over time. Put the time on the x axis and the depth on the y axis, for the layer java. The change of section 4 becomes visible as one row that ends where another begins.
  • Energy on a grid. Section 9 adds 1 for each event. Replace -burn 1 -l quakes with -a e and a query that gives the energy a name: -sql "select pow(10,1.44*(mag-5)) e, geom from quakes".

Checkpoint

The cell below stops with an error if the results are not what this chapter expects. The limits are wide, because the catalogue is corrected from time to time.

import csv
import io

def rows(sql, dataset="quakes.gpkg"):
    """The rows of a query, as dictionaries."""
    return list(csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -sql "{sql}"'))))

n, deep = (int(rows(q)[0]["n"]) for q in ("select count(*) n from quakes", "select count(*) n from java where depth between 300 and 450"))
assert 11_000 < n < 12_500, "section 1 should find about 11,600 earthquakes"
assert deep <= 3, "the space between 300 and 450 km under Java should be (almost) empty"

fixed = float(rows("select 100.0*avg(depth in (10,33,35)) p from java")[0]["p"])
assert 30 < fixed < 50, "about four in ten depths should be 10, 33 or 35 km"

top = float(rows("select 100*max(pow(10,1.44*mag))/sum(pow(10,1.44*mag)) p from quakes")[0]["p"])
assert 40 < top < 55, "the largest earthquake should hold nearly half of the energy"

# The grid of section 9 counts every earthquake exactly once
from osgeo import gdal
gdal.UseExceptions()
total = gdal.Open("count.tif").ReadAsArray().sum()
assert total == n, f"the cells add up to {total:.0f}, and there are {n} earthquakes"

pictures = ("above.png", "first.png", "java.png", "sumatra.png", "south.png", "aceh.png", "count.png", "energy.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: {n:,} earthquakes; {fixed:.0f} percent of the depths under Java are fixed; the largest event holds {top:.0f} percent of the energy")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 11,622 earthquakes; 40 percent of the depths under Java are fixed; the largest event holds 47 percent of the energy
time since the first cell: 59 s

Troubleshooting

Symptom Cause Fix
'minmagnitude' is not recognized as an internal or external command, or the line never ends The address has no quotes, and the shell stopped at the first & Put the whole address in double quotes
HTTP error code : 400 from the USGS The result has more than 20,000 events Use a higher minmagnitude, a smaller box or a shorter time (ledger L29)
No answer from the server It is not available, or your network blocks it Use usgs.gpkg.zip as in section 1
Automatic computation of xscale at high latitudes may lead to incorrect results GDAL treated kilometres as degrees Add edit --crs none after sql
unknown SRID: 4326 many times, and the line takes minutes st_distance(a, b, 1) on the points of a GeoPackage (ledger L38) Use st_length(makeline(a, b), 1)
Dots have edges in a wrong, third colour The class numbers were averaged, not the colours Put materialize between color-map and resize (ledger L28)

What comes next

This is the end of the first part, about places. Until now, every point was used alone: a city, a star, an earthquake. In Chapter 5: Storm tracks from points the points belong together. The positions of tropical cyclones are joined into tracks in the order of time, and the tracks are counted in a map.

Earthquake data: U.S. Geological Survey, ANSS Comprehensive Earthquake Catalog, in the public domain (ledger L32). Land and towns: Natural Earth, in the public domain.