In this series: Part VI, Decisions. The chapters before measured distance, height, rain, change and people. This chapter uses several of them together to support a decision
You will build: A map of Padang, coloured by the walking time to a safe place; the same map for 27 combinations of assumptions, because the assumptions may be wrong; a line that finds the best place for a new shelter, and the next best when you run it again; and one table for the mayor
You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. Chapter 8 explains the SQL queries on a raster
Time to run: The commands took about two minutes when tested, including about 10 MB of downloads, or a little less with the copies in the folder. About 400 MB of free space
Level: Intermediate; two longer queries of sections 5 and 6 are in files, with comments
The chapters before measured distance, height and the number of people. This chapter uses these measurements together, to support a decision: where should a shelter be built, and which villages come first?
The place is Padang, the capital of West Sumatra. Off its coast, the Mentawai megathrust has been collecting strain since the great earthquakes of 1797 and 1833. Both caused a tsunami in Padang (ledger L144). One day, there will be another. The question of this chapter is: who can not walk to a safe place in time?
The answer will be a number, and this number will not be exact. So the second half of the chapter measures how uncertain it is, and shows which decisions are possible all the same.
WarningThis is an exercise, and no evacuation plan
This chapter uses open data, straight lines and assumptions. If you live in Padang, or visit it, use the evacuation map and the signs of the city (BPBD Kota Padang). In its drills, the city tells people in the danger zone to go at once and by themselves, walking fast and not running, to a shelter or to safe ground (ledger L150).
NoteLearning objectives
By the end of this chapter you will be able to:
turn several rasters into one table of cells, and answer many questions with it;
measure how the roofs in a satellite elevation model change a number of people;
make a surface from a few measurements in three ways, and test it with points that were not used;
draw one picture with two messages: colour for the danger, brightness for the people;
calculate a result for 27 combinations of assumptions at once;
find good places for new shelters, one after the other;
write a table for people who do not use maps.
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/ch15. 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("15")print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT /"sample-data/ch15").iterdir()))
How many people of Padang live lower than 5 m? You need a map of people, which is in the folder (people.tif, WorldPop 2025, ledger L79), and the relief that is used since Chapter 0, from its server. Put both into the same cells, 30 m wide:
Without a connection, use the copy: gdal raster convert offline_roofs.tif roofs.tif --overwrite. Now mark the low cells, and add up the people on them:
the map of people has cells of 92 m. Each person in it must be counted in one of the small cells, and not in all of them. sum divides the people among the small cells, and the total stays the same
(H<5) ? 1 : 0
1 where the height is below 5 m
zonal-stats ... --stat sum
adds up the people, once for the cells with 0, and once for those with 1
Look before moving on. The second row says 189,000 people. A report could now begin with “about 190,000 people live lower than 5 m”.
But this number is too small by nearly 90,000 people. The three lines have no error. The reason is in the data: the file is called roofs.tif, and the next section explains why.
1. The height of the ground, or of the roofs?
A radar satellite measures the highest surface that it can reach from above. In a city, this is often a roof. So in this model, the people of Padang are placed at the height of their roofs, and not at the height of the ground.
There are models in which the roofs and the trees are removed. One of them is DeltaDTM, made for low coasts all over the world (ledger L142). Its tiles for Asia are in one zip file of 17 GB. This chapter needs two of them. GDAL can read inside the zip file on the server, and download only the parts that it needs:
band_1 is the number of people, band_2 the ground, and band_3 the roof. (The numbers of people are not whole numbers, because the map is an estimate. It divides the people of a district among its buildings.)
The table has 810,000 rows, which SQLite can process quickly. And one query can answer several questions at the same time:
ogr2ogr-f CSV /vsistdout/ cells.gpkg -dialect SQLite -sql"select value below_m, cast(sum(case when band_3<value then band_1 end) as integer) by_the_roofs, cast(sum(case when band_2<value then band_1 end) as integer) by_the_ground from cell, json_each(json_array(3,5,7,10,15)) where band_2>-9000 group by value"
makes a small table of the list. The comma before it joins each cell with each height
case when ... then band_1 end
the people of this cell, if it is lower. sum leaves out the others
band_2>-9000
only land. A few thousand people are in water cells, because the two maps draw the shore differently
Look before moving on. Below 5 m, the roofs give 185,000 people, and the ground gives 278,000. This is half as many again. And look at the other rows. At 3 m, the number nearly doubles. At 15 m, the two are nearly the same. An error of one or two metres is not important on a hill. It is important on the low coast, which is where the danger is.
Other studies have found the same. In the whole world, 110 million people live below the high tide of today, according to an elevation model that was corrected for such errors. The old model of the Space Shuttle gave 28 million (ledger L151). In Padang itself, a group of researchers calculated the same tsunami on two elevation models. On a good local one, it floods 16 km². On that of the Space Shuttle, 7 km² (ledger L149).
Where are the people that are missing in the model with roofs? Give each cell a class, colour it, and make it brighter where more people live:
Grey: the ground is higher than 5 m. Turquoise: lower than 5 m in both models. Orange: lower than 5 m, but only in the model without roofs.
Part
What it does
C
the colours, with three bands
P/6
people for each cell, so that a cell with 6 of them has the full brightness (here that is 67 people on a hectare)
min(1,...)
no cell gets brighter than its colour
0.2+...*0.9
a cell without people keeps a fifth of its colour
S*0.05
a little shading, so that the mountains are not completely black
(G<-9000) ? C
water gets its colour without a change
This one line makes a map with two messages: the colour shows the class, and the brightness shows the number of people. An orange rice field stays dark. The chapter uses the same line four more times, and only the colours in c.tif change.
2. From a few measurements to a surface
Perhaps there is no DeltaDTM for your place, or you are not sure about its quality. Then you can measure the height yourself. How good is the result with 200 points?
spots.csv has 200 spot heights. They were not measured in the field. For this exercise, 200 cells in which people live were chosen at random, and their heights were read from the ground model of section 1. This is useful for a test, because the correct surface is known, and each result can be compared with it.
Chapter 0 has shown the three methods: the nearest point, a mean of all points, and triangles. There, the smooth one was the worst. First put 50 spots aside, and do not use them for the surfaces. Then make a surface from the other 150:
surface,error_m,leans_by_m
nearest ,1.7,0.4
mean ,4.3,0.3
triangles,1.9,0.2
roofs ,1.4,0.9
error_m is the mean error at the spots that were kept back, in metres. (DeltaDTM ends at 30 m, so 30 means “30 or more”, and min(30,...) gives the others the same limit.) leans_by_m is the mean with the sign: above 0, the surface is too high.
So the satellite model has the smallest error, with 1.4 m, the mean of all spots has clearly the largest, and the other two are between them. Many reports would stop here, and recommend the satellite model.
Chapter 0 asked another question: how does such an error change a decision? Count the people again:
gdal raster stack who.tif near.tif mean.tif plane.tif roofs.tif ground.tif six.tif --overwritegdal raster as-features six.tif six.gpkg --output-layer cell --geometry-type none --overwriteogr2ogr-f CSV /vsistdout/ six.gpkg -dialect SQLite -sql"select substr('nearest mean trianglesroofs ground',1+9*key,9) surface, cast(sum(case when value<5 then band_1 end) as integer) below_5_m, cast(total(case when (value<5)<>(band_6<5) then band_1 end) as integer) on_the_wrong_side from cell, json_each(json_array(band_2,band_3,band_4,band_5,band_6)) where band_6>-9000 group by key"gdal raster calc -i S=five.tif -i G=ground.tif -o land.tif --calc"(G<-9000) ? -9999 : S"--nodata-9999--overwriteogr2ogr-overwrite four.gpkg spots.csv -dialect SQLite -sql"select 'vrt://land.tif?bands='||value||'&projwin=645000,9911000,657000,9891000&a_ullr='||(key*410)||',667,'||(key*410+400)||',0' location, buildmbr(key*410,0,key*410+400,667) geom from json_each(json_array(1,2,3,5))"-nln four -nlt POLYGON -a_srs EPSG:32747gdal raster color-map GTI:four.gpkg four.png --color-map height.txt --overwrite
surface,below_5_m,on_the_wrong_side
nearest ,222962,91011
mean ,25648,253801
triangles,220763,86926
roofs ,184661,122821
ground,277778,0
The last three lines put four windows side by side, as in Chapter 14 (GTI: reads the table as one picture).
Look before moving on. From the left: nearest, mean of all, triangles, and the correct ground. Orange is lower than 5 m. Read the table with the pictures:
Nearest consists of polygons with one height each. It looks simple, but its number is not bad.
The mean of all looks smooth. But it misses nine of ten people. Far from a spot, the result is close to the mean height of all spots, including the hills. Only small areas of low ground remain, around the low spots.
Triangles have flat faces and sharp edges. Where there are few spots, as in the south, they miss low ground.
The roofs had the smallest error. But they put more people on the wrong side of the 5 m than nearest or triangles do.
How can the surface with the smallest error give a worse answer? Look at leans_by_m. The errors of nearest and triangles go up and down. Some people are missing and others are added, and in the sum, many of these errors cancel each other. A roof is always higher than the ground. So the errors of the satellite model are small, but nearly all in the same direction, and in this direction people are missing from the result.
So do not only check how large an error is. Check its direction, too.
The same test with 20 other sets of points gives between 221,000 and 306,000 people with nearest, and between 198,000 and 266,000 with triangles (ledger L153). The correct number of this exercise is 278,000. So one such result is uncertain, but 150 good measurements can be as useful as a satellite model.
(A good measurement means levelling, or a good GNSS receiver. Before you use the height from a phone, test it on a point with a known height.)
3. How long is the walk to a safe place?
Low ground alone does not mean danger. If there is a hill behind the house, people can walk up. So the time to a safe place is needed. And first, what is safe? This chapter uses the height, as the city does, and adds the distance, because a wave loses its power on land:
A place is safe if its ground is at 10 m or higher, or if it is 3 km or more from the open sea.
Both numbers are assumptions. The old zones of the city were: red below 5 m, yellow from 5 to 10 m, and green above 15 m. One study of Padang used everything above 10 m as safe (ledger L147). For the 3 km, no official number was found. In computed tsunamis, the water reaches 1 to 2.5 km into the city, and the larger number is the careful choice. Section 4 tests all of these assumptions.
Where is the open sea?
In the ground model, the sea is water, and so is the river that runs through the city. But only the distance to the open sea is needed. How can a line separate the two? A river is water that is never far from land:
proximity writes for each cell how far away the nearest cell with a 1 is. The first line gives each water cell its distance to land. The second one keeps the water that is more than 300 m from land, which is certainly sea, and measures from there. So sea.tif starts at a line 300 m from the beach, and 3 km from the beach is 3,300 in it.
Chapter 0 used sieve to remove small areas. Here it is important. Without it, there are 47 small areas of safe ground in the low city. One has only the size of three football fields, and 13,700 people live within a 15-minute walk of it. On the map, all of them would be safe, but they do not have enough space there. So only places with 30 cells, which is 2.7 hectares, or more are counted.
way2.tif has the straight line to safe ground, in metres. But people do not walk in a straight line. A comparison with the roads of OpenStreetMap, for all people of the danger zone, shows that the way by road is 1.4 times as long (ledger L152). And how fast do people walk? This chapter uses 1.1 m in a second, a slow walk, because a family walks at the speed of its slowest member (ledger L146). So the minutes are:
Look before moving on. The people in the turquoise areas are in a safe place, or close to one. Yellow is 15 minutes of walking, orange-red is 25, and the violet beach needs 45 and more.
Look at the south, where the red strip ends in yellow at the mouth of the river Arau. Behind the river is a hill, Gunung Padang, and the straight line crosses the water. By road and bridge, the people there need about 15 minutes and not 12. Here, the difference is small. But always check which obstacles your straight lines cross.
These lines also prepare data for the next sections. way1.tif and way3.tif are made with the same line, but with other definitions of “safe”: 5 m or 2 km, and 15 m or 4 km. village.tif has the number of the village (kelurahan) in each cell. All of them go into one table, city.gpkg. In it, band_3, band_4 and band_5 are the three distances.
How much time is there? Published estimates for the first wave at Padang are about 20, 30 and 40 minutes (ledger L144). But people do not start to walk in the first second. First there is the earthquake itself, then the warning, and then the preparation, for example to collect the children. One study counts 15 minutes for this (ledger L146). If the wave needs 30 minutes, 15 minutes of walking are left.
So read the row with 15: about 262,000 people need more time than this. That is more than a quarter of the people of this city.
How certain is this number?
4. What if the assumptions are wrong?
The calculation has three assumptions:
Assumption
Low
Middle
High
What is safe?
5 m, or 2 km
10 m, or 3 km
15 m, or 4 km
How fast do people walk?
0.9 m/s
1.1 m/s
1.5 m/s
How many minutes are left for walking?
5
15
25
(5, 15 and 25 minutes are the 20, 30 and 40 minutes of the wave, less 15 for the start.)
Many reports use only the middle column. But three assumptions with three values each give 27 combinations, and each of them is possible. In the code, a combination is called a world. One query can calculate all 27:
ogr2ogr-overwrite guess.csv city.gpkg -dialect SQLite -sql"with way as (select j.key+1 safe, cast(j.value as integer) m, sum(band_1) n from cell, json_each(json_array(band_3,band_4,band_5)) j where band_1>0 and band_2>-9000 group by 1,2) select safe, s.value speed, t.value minutes, cast(sum(case when m*1.4>s.value*60*t.value then n end) as integer) people from way, json_each(json_array(0.9,1.1,1.5)) s, json_each(json_array(5,15,25)) t group by 1,2,3"ogr2ogr-f CSV /vsistdout/ guess.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql"select *, substr('##################################################',1,people/10000) tens_of_thousands from guess order by people"
first a small table: for each definition of safe, the number of people at each distance in metres
j.key
the position in the list, 0, 1 or 2, so safe is 1, 2 or 3
m*1.4>s.value*60*t.value
the way is longer than the distance that people can walk in this time
group by 1,2,3
one row for each combination
Look before moving on. In the best combination, 13,000 people do not reach a safe place in time. In the worst, 480,000. That is a factor of 37. The middle row says 262,000, and this number alone does not show how uncertain it is.
Which assumption changes the number most? Calculate the mean of the nine combinations that have the same value:
ogr2ogr-f CSV /vsistdout/ guess.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql"select j.key my_guess, cast(j.value as real) value, cast(avg(people) as integer) people from guess, json_each(json_object('safe',safe,'speed',speed,'minutes',minutes)) j group by 1,2 order by 1 desc,2"
The definition of “safe” changes it most, from 82,000 to 377,000. So if the city has money for one study, it should be about how far the water reaches.
The time is second, from 313,000 to 172,000. The 15 minutes before the start are a part of this time. Nobody can change the arrival time of the wave. But people can start earlier. In the middle combination, a start ten minutes earlier brings 69,000 more people to safety. This needs no new building. It only needs that everybody has learned the rule: if the earthquake is strong, leave at once, and do not wait for an order.
The walking speed changes the number least. This is useful, because it is also the most difficult to change.
A map of the certain and the uncertain places
Now count for every cell in how many combinations it is too far from a safe place, from 0 to 27:
gdal raster stack way1.tif way2.tif way3.tif ways.tif --overwritegdal raster calc -i W=ways.tif -o lost.tif --calc"(W>193)+(W>236)+(W>321)+(W>579)+(W>707)+2*(W>964)+(W>1179)+(W>1607)"--ot Byte --nodata none --overwritegdal raster calc -i L=lost.tif -i G=ground.tif -o sum.tif --calc"(G[1]<-9000) ? -1 : sum(L)"--flatten--ot Int16 --nodata none --overwritegdal raster color-map sum.tif c.tif --color-map worlds.txt --overwritegdal raster pipeline calc -i C=c.tif -i P=who.tif -i S=shade.tif -i G=ground.tif --calc"(G<-9000) ? C : min(255,C*(0.2+min(1,P/6)*0.9)+S*0.05)"--ot Byte --nodata none ! resize --size 1350,1350 -r cubic ! write worlds.jpg --overwrite--co QUALITY=90gdal raster zonal-stats who.tif sum.csv --zones sum.tif --stat sum --overwriteogr2ogr-f CSV /vsistdout/ sum.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql"select case value when 0 then 'in no world' when 27 then 'in all 27' else 'it depends' end too_late, cast(sum(sum) as integer) people from sum where value>=0 group by 1 order by min(value)"
too_late,people
in no world,469622
it depends,466794
in all 27,12983
Speed and time together give one number, the distance in metres that people can walk. (0.9 m/s, 5 minutes, and a way of 1.4: 193 m.) The second line has these nine distances, and adds up in how many combinations a cell is too far away. Two of them are equal, with 964 m, so this one counts twice. sum(L) with --flatten adds the three bands, one for each definition of safe. With --flatten, every input is a list of bands, so the ground is now G[1].
Look before moving on. Blue: people reach a safe place in time in all 27 combinations. Pink: they do not reach it in any of them. Cream: the result depends on the assumptions. About half of the people live in the cream areas.
So what is certain without any other study? In the pink strip, there are 13,000 people for whom walking to safe ground is not possible in time. They need a tall building or another high place nearby. And the 470,000 people in the blue areas should stay off the roads, if they can, so that the roads are free for the others. In September 2009, after the last strong earthquake, people left the low zone by car and motorcycle, and the streets were blocked for hours (ledger L148).
5. Where should the next shelter be?
If the way to safe ground is too long, people can go up in a strong building. shelters.csv has 23 buildings of Padang that were planned as evacuation shelters: schools, offices, hotels, mosques. The list is from a study of 2017 (ledger L149).
Put two tables into one file. far has the people who are too far from safe ground in the middle combination (more than 707 m in a straight line), in blocks of 90 m, to keep it small. shelter has the buildings:
ogr2ogr-overwrite plan.gpkg city.gpkg -dialect SQLite -sql"select sum(center_x*band_1)/sum(band_1) x, sum(center_y*band_1)/sum(band_1) y, sum(band_1) people from cell where band_1>0 and band_2>-9000 and band_4>707 group by cast(center_x/90 as integer), cast(center_y/90 as integer)"-nln far -nlt NONEogr2ogr-update-overwrite plan.gpkg shelters.csv -dialect SQLite -oo AUTODETECT_TYPE=YES -sql"select id, name, places, st_x(g) x, st_y(g) y from (select *, st_transform(makepoint(lon,lat,4326),32747) g from shelters)"-nln shelter -nlt NONEogr2ogr-f CSV /vsistdout/ plan.gpkg -sql"select cast(sum(people) as integer) too_far, cast(sum(case when exists(select 1 from shelter s where (s.x-f.x)*(s.x-f.x)+(s.y-f.y)*(s.y-f.y)<707*707) then people end) as integer) near_a_shelter, (select sum(places) from shelter) places from far f"
too_far,near_a_shelter,places
261812,124888,58200
262,000 people are too far from safe ground. 125,000 of them have one of the 23 buildings within 15 minutes. And these buildings have 58,200 places. So even if all of them can be used after the earthquake, there is space for less than half of these people.
Where would a new one help most? Test every block as a place, and count the people who could reach it. This query is longer, so it is in a file:
insertinto shelter (id, name, places, x, y)with-- people who are still too far from every building in the table (707 m = 15 minutes of walking) alone asmaterialized (select*from far f wherenotexists (select1from shelter s where (s.x-f.x)*(s.x-f.x)+(s.y-f.y)*(s.y-f.y) <707*707)),-- for each of their places: how many of them would reach a building that stands here? here as (select a.x, a.y, sum(b.people) peoplefrom alone a join alone b on (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y) <707*707groupby a.fid)select (selectmax(id)+1from shelter), 'new', cast(people asinteger), x, yfrom here orderby people desclimit1
x*x+y*y < 707*707 is the theorem of Pythagoras: closer than 707 m, without a square root. And look at the first line. The query does not only find the best place. It also writes it into the table shelter, so that the next query uses it:
ogrinfo-q plan.gpkg -sql"@next.sql"
Nothing is printed, and one shelter is added. Now press the arrow key ↑ and Enter, and you get the next best place, on the condition that the first one is built. Do this five times:
ogr2ogr-update-overwrite plan.gpkg villages.gpkg villageogr2ogr-f CSV /vsistdout/ plan.gpkg -dialect SQLite -sql"select s.id, v.name village, v.district, s.places people_who_could_reach_it from shelter s join village v on st_contains(v.geom,makepoint(s.x,s.y,32747)) where s.id>23 order by s.id"
The first place is in Bungo Pasang, and the second in Parupuk Tabing. After this calculation, the result was compared with the shelters that the city itself has built since 2017. It has a shelter in Bungo Pasang (Shelter Darussalam), and one in Parupuk Tabing (Shelter Nurul Haq), each for about 5,000 people (ledger L150). They are not in the list of this chapter. So the query has found the same two villages, only from a map of people, a map of heights and distances.
But look at the last column. More than 11,000 people could reach the first place. At 1 m² for each person, which is the usual number (ledger L149), they need 11,000 m² of floor above the water. This is the area of one and a half football fields. The query gives a good place. It does not solve the question of the size.
Draw it. People who can reach a building of the old list get the class 3, and people who can reach one of the six new places the class 4:
ogr2ogr-overwrite near.gpkg plan.gpkg -dialect SQLite -sql"select case when id>23 then 4 else 3 end kind, st_buffer(makepoint(x,y),707) geom from shelter"-nln near -nlt POLYGON -a_srs EPSG:32747gdal vector rasterize near.gpkg kind.tif --sql"select * from near order by kind desc"--attribute-name kind --extent 642000,9885000,669000,9912000 --resolution 30,30 --ot Byte --nodata 0 --overwritegdal raster edit kind.tif --nodata nonegdal raster pipeline calc -i G=ground.tif -i W=way2.tif -i K=kind.tif --calc"(G<-9000) ? 0 : (W<=707) ? 1 : (K>0) ? K : 2"--ot Byte --nodata none ! color-map --color-map shelter.txt ! write c.tif --overwritegdal raster pipeline calc -i C=c.tif -i P=who.tif -i S=shade.tif -i G=ground.tif --calc"(G<-9000) ? C : min(255,C*(0.2+min(1,P/6)*0.9)+S*0.05)"--ot Byte --nodata none ! resize --size 1350,1350 -r cubic ! write shelter.jpg --overwrite--co QUALITY=90
Look before moving on. In the blue-grey areas, people can walk to safe ground. In the yellow ones, they can reach a building of the list, and in the mint green ones, one of the new places. In the red ones, they can reach nothing in time.
The list of 2017 covers the old centre. The six places of the query are all to the north of it, in a row along the coast, where many people live on the same low strip. And the red areas between them show that six are not enough.
6. A table for the mayor
A mayor needs a short table and not a GeoPackage. The question is: which villages first?
In section 4, the total changed by a factor of 37. So is any list reliable? To test this, find in each of the 27 combinations the ten villages with the most people who can not reach a safe place in time. Then count how often each village is on the list. The query is in mayor.sql:
with-- how many people of each village are how far from safety, for my three ideas of "safe" way as (selectcast(band_6 asinteger) village, j.key safe, cast(j.valueasinteger) m, sum(band_1) nfrom cell, json_each(json_array(band_3, band_4, band_5)) jwhere band_1 >0and band_2 >-9000and band_6 >0groupby1, 2, 3),-- the people who do not make it, for each village in each of the 27 worlds world as (select village, 9*safe +3*s.key+ t.key world, sum(casewhen m*1.4> s.value*60*t.valuethen n else0end) nfrom way, json_each(json_array(0.9, 1.1, 1.5)) s, json_each(json_array(5, 15, 25)) t groupby1, 2),-- the place of the village in the list of its worldlistas (select*, rank() over (partitionby world orderby n desc) place from world)select v.name, v.district,cast(min(n) asinteger) lowest,cast(max(casewhen world =13then n end) asinteger) middle,cast(max(n) asinteger) highest,sum(place <=10and n >0) in_top_10, v.geomfromlistjoin village v on v.fid =list.villagegroupby v.fid orderby in_top_10 desc, middle desc
rank() over (partition by world order by n desc) makes a list for each combination, and gives each village its position in it. lowest, middle and highest are the people who can not reach a safe place in time, in the best combination, in the middle one and in the worst.
Look before moving on. The number changes very much: in Lubuk Buaya, from 6 people to more than 21,000. But the top of the list changes very little. Three villages are among the first ten in all 27 combinations, and Batang Kabung and Bungo Pasang in 26 and 25. (Further down, the list does change: 19 villages are among the first ten at least once.) So the number of people is uncertain, but the villages where the work should begin are nearly certain.
This is often the case. Many decisions do not need the exact number. They need the order, and the order can be reliable when the number is not. But this must be tested, with different assumptions.
Pale yellow: on the list in nearly every combination. Orange and red: in some. Grey: in none.
mayor.csv is the file that you send. Write three sentences with it. Where the first six villages are. That the numbers can be wrong by a factor of 37, but the top of the list stays the same. And that a start ten minutes earlier helps many people, and needs no new building.
Try it yourself
All 200 spots. In section 2, leave --sql out. Is the number of people closer to the correct one? And can you still test it?
More weight for near spots.gdal vector grid invdist ... --power 6 gives the near spots much more weight. To which of the other pictures does the result become similar?
No distance. In section 3, use only the height: write --calc "(G>=10) ? 1 : 0". What changes in the south of the city, and what in the north?
An earlier start. In next.sql, write 1179 (25 minutes) in place of 707, make plan.gpkg again with it, and find six places. Are they in other villages?
Your own list. Do you have information about other shelters of Padang? Add them to shelters.csv, with a new id, and run section 5 again.
Your own coast. The same question is important for Bengkulu, Cilacap, Pacitan and Palu. The tiles of DeltaDTM have the names of their south-west corners, such as S04E102. WorldPop has the people.
Checkpoint
The cell below stops with an error if the results are not what this chapter expects.
import csvdef table(name):withopen(name) as f:returnlist(csv.DictReader(f))low =float([x for x in table("low.csv") if x["value"] =="1"][0]["sum"])assert180_000< low <200_000, "the roofs should put about 189,000 people below 5 m"world = {(x["safe"], x["speed"], x["minutes"]): int(x["people"]) for x in table("guess.csv")}middle = world["2", "1.1", "15"]assertlen(world) ==27and250_000< middle <275_000, "the middle world should have about 262,000 people"assertmax(world.values()) >30*min(world.values()), "the worlds should differ strongly"villages = table("mayor.csv")assert villages[0]["name"] =="Parupuk Tabing"and villages[0]["in_top_10"] =="27", "Parupuk Tabing should be first"assertsum(int(v["in_top_10"]) >24for v in villages) ==5new =int(oneline.run('ogr2ogr -f CSV /vsistdout/ plan.gpkg -sql "select count(*) n from shelter where id>23"').split()[-1])assert new ==6, "section 5 should have added six shelters"pictures = ("hidden.jpg", "four.png", "minutes.jpg", "worlds.jpg", "shelter.jpg", "list.jpg")assertall((WORK / f).stat().st_size >10_000for f in pictures)print(f"checkpoint passed: {middle:,} people in the middle world, {min(world.values()):,} to {max(world.values()):,} in all 27; first village: {villages[0]['name']}")print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 261,812 people in the middle world, 12,983 to 479,778 in all 27; first village: Parupuk Tabing
time since the first cell: 129 s
Troubleshooting
Symptom
Cause
Fix
The sea is full of safe or low “land”
calc writes 0 where the input has no data
gdal raster edit ground.tif --nodata none, after each time that you make the file
There are far too many people
The map of people was put into smaller cells with near or bilinear
-r sum. Compare the totals with gdalinfo -stats, or with the warm-up
no such column: band_4
stack got fewer files than the query expects
The bands have the order of the files. Count them
A new shelter lies exactly on the last one
next.sql ran on a table without the column people in far, or with another distance than far
Use the same distance in all places: 707
Cannot open for the long name with /vsizip/
The quotes are missing, so the shell reads the curly brackets
Keep the quotes. Or use offline_ground.tif
Section 5 gives other places when you run it twice
The table still contains the shelters of the first time
Begin again with the two lines that make plan.gpkg
What comes next
A table like this is needed again when there are new data. This chapter has about seventy lines, and it is not practical to type them again each time. Chapter 16: Repeating and sharing the work shows how to save the lines, repeat them automatically, and share them.