Skip to main content

Chapter 13: When the rain peaks

Chapter 13: When the rain peaks

TipAt a glance
  • In this series: Part IV, Surfaces. A surface can change through the year. This chapter uses 36 maps of the same area, one for every ten days of the year
  • You will build: Circular charts of the rain for thirteen cities, a map of the season with a colour circle for the year, the three rain regions of Indonesia, and a map of the beginning of the rainy season, which is later in the east than in the west
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. No download: all data is in the folder of the chapter. About 450 MB of free space
  • Time to run: The commands took less than two minutes when tested
  • Level: Intermediate; some school trigonometry appears and is explained

When is the rainy season? In Jakarta, it is around January. In Ambon, it is around June. Both are in the same country.

The file of this chapter has 36 maps. Each shows the rain of one dekad, a period of about ten days, on average over thirty years (ledger L94, L106). Three dekads make a month, and 36 make a year. It is not possible to compare 36 maps by eye. So this chapter calculates three things for each cell: when its wettest time is, how long it lasts, and when it begins.

A year has a special property. It is a circle. After dekad 36 comes dekad 1, and most of the methods in this chapter are needed because of that.

NoteLearning objectives

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

  • reduce many bands to one answer for each cell;
  • turn bands into rows, with one function of SQL;
  • draw a year as a circular chart;
  • explain why dates must not be averaged like other numbers, and average them correctly;
  • find out whether a place has one rainy season, or two, or none;
  • calculate the beginning of the rainy season with the rule of Indonesia’s weather service;
  • test a result against a published study.

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/ch13. In this notebook, the next cell does that. This chapter needs no internet connection.

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("13")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch13").iterdir()))
working folder: ch13 | files copied there: ['cities.csv', 'dekads.tif', 'letters.gpkg.zip', 'most.txt', 'region.txt', 'wet.txt', 'words.csv', 'year.txt']

Warm-up

A few short commands first, in the form of Chapter 0. Read the file at one place, Jakarta. The result is one number for each band, from the beginning of January to the end of December:

gdallocationinfo -valonly -wgs84 dekads.tif 106.83 -6.17
853
1301
1470
1489
1340
897
765
545
696
531
531
553
505
381
299
361
284
208
189
281
194
207
201
231
164
101
199
300
290
429
407
441
491
581
477
754

The numbers are tenths of a millimetre, so the first one is 85.3 mm. The list shows the year of Jakarta: much rain at the beginning, little in the middle, and more again at the end.

Now find the largest number of every cell, and give it a colour:

gdal raster calc -i A=dekads.tif -o most.tif --flatten --dialect builtin --calc max --overwrite

gdal raster color-map most.tif most_colour.tif --color-map most.txt --overwrite

gdal raster resize most_colour.tif most.png --size 1880,720 -r nearest --overwrite

Indonesia in colours from pale yellow over green to dark blue. Most land is green. The darkest blue lies on Seram, in Papua, on the east coast of Malaysia and at one place on the north coast of Java, and the palest land around Palu and on the islands north of Timor.

Look before moving on. This map shows how much rain falls in the wettest ten days: the palest land has less than 60 mm, and the darkest blue means 450 mm or more. It does not show when they are. For that, one word in the first line must change.

1. Not how much, but when

max gives the largest value. argmax gives the number of the band with this value, which is the dekad. First convert the numbers to millimetres. The file contains the information that they are tenths, and unscale uses it:

gdal raster unscale dekads.tif rain.tif --ot Float32 --overwrite

gdal raster calc -i A=rain.tif -o peak.tif --flatten --dialect builtin --calc argmax --overwrite

gdal raster edit peak.tif --nodata none

gdal raster color-map peak.tif peak_colour.tif --color-map year.txt --color-selection nearest --overwrite

gdal raster resize peak_colour.tif peak.png --size 1880,720 -r nearest --overwrite

Indonesia on black in many colours. Java, Bali and the islands to the east are evenly blue. Sumatra and Borneo have many small areas of blue, green and violet with sharp edges, and Sulawesi, the Moluccas and Papua are mostly orange, pink and violet.

The file year.txt has a colour for each dekad. They go around the colour circle and are all equally bright, as in section 2 of Chapter 11. So December and January look alike, as they should. Blue is January, pink is April, orange is July, and green is October.

Look before moving on. Java has one colour, January. But Borneo has many small areas with sharp edges. Is the rain so different from one cell to the next? No. Many places there have two wet times of nearly the same size. A few millimetres decide whether the first or the second one is larger. argmax gives the larger one, and does not show that the difference was small.

A mistake with dates. For the typical peak of east Java, it seems right to take a box and calculate the mean:

ogr2ogr -overwrite box.gpkg cities.csv -dialect SQLite -sql "select buildmbr(110,-8,114,-7,4326) geom from cities limit 1" -nln box -a_srs EPSG:4326

gdal raster edit peak.tif --crs EPSG:4326 --nodata -9999

gdal raster zonal-stats peak.tif /vsistdout/ --zones box.gpkg --stat mean --stat mode --stat min --stat max --output-format CSV
mean,mode,min,max
5.95003376097232,3,3,35

The mode, the value that occurs most often, is 3: the last dekad of January. The mean is nearly 6, which is the last dekad of February. And not one cell in this box has its peak in dekad 6. In nine of ten cells it is dekad 3, and in most of the others it is dekad 35, in the middle of December. The true middle of 35 and 3 is 1, the beginning of January. But the calculation of the mean does not include that 36 is followed by 1, so the result moves in the wrong direction. The mean of 36 and 1 would even be 18.5, at the end of June.

Dates, directions and times of day must not be averaged like other numbers. Section 4 does it correctly.

2. From bands to rows

A raster with 36 bands becomes a table with 36 columns, band_1 to band_36. This form is not suitable for questions about the year, because SQL works on rows. It can add up a million rows with one word, but it needs a list for 36 columns.

So turn the columns into rows. SQLite can write them as a list, with json_array, and read the list as a table, with json_each. Each cell then gives 36 rows, with the position in the list as key (from 0 to 35) and the rain as value:

gdal raster as-features rain.tif year.gpkg --output-layer cell --geometry-type none --include-xy --include-row-col --overwrite
ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select key+1 dekad, round(value,1) mm from cell, json_each(json_array(band_1,band_2,band_3,band_4,band_5,band_6,band_7,band_8,band_9,band_10,band_11,band_12,band_13,band_14,band_15,band_16,band_17,band_18,band_19,band_20,band_21,band_22,band_23,band_24,band_25,band_26,band_27,band_28,band_29,band_30,band_31,band_32,band_33,band_34,band_35,band_36)) where row=253 and col=246 limit 4"
dekad,mm
1,85.3
2,130.1
3,147
4,148.9

This is the cell of Jakarta again, with four of its 36 rows. The list of columns is long, but you only have to copy it.

Next, the cities. cities.csv has their places. A cell of the rain map is 5 km wide, and some ports lie in a cell that counts as sea. So each city takes the nearest cell that has rain:

ogr2ogr -update -overwrite year.gpkg cities.csv -oo AUTODETECT_TYPE=YES -nln city

ogr2ogr -update -overwrite year.gpkg year.gpkg -sql "select name, x, y, lon, lat, min((center_x-lon)*(center_x-lon)+(center_y-lat)*(center_y-lat)) d, row, col from city join cell on abs(center_x-lon)<0.3 and abs(center_y-lat)<0.3 and band_1>=0 group by name" -nln place

ogr2ogr -update -overwrite year.gpkg year.gpkg -sql "select name, x, y, key+1 dekad, value mm, (key+0.5)*pi()/18 a from place join cell using(row,col), json_each(json_array(band_1,band_2,band_3,band_4,band_5,band_6,band_7,band_8,band_9,band_10,band_11,band_12,band_13,band_14,band_15,band_16,band_17,band_18,band_19,band_20,band_21,band_22,band_23,band_24,band_25,band_26,band_27,band_28,band_29,band_30,band_31,band_32,band_33,band_34,band_35,band_36))" -nln petal

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select name, round(sum(mm)) year_mm, round(max(mm)) wettest, round(min(mm)) driest from petal group by name order by year_mm"
name,year_mm,wettest,driest
KUPANG,1540,154,0
SURABAYA,1723,138,1
JAKARTA,1895,149,10
MERAUKE,1906,135,7
MEDAN,2301,109,22
JAYAPURA,2443,113,36
BALIKPAPAN,2611,99,40
SORONG,2763,122,45
AMBON,2865,181,18
MAKASSAR,2983,273,3
MANADO,3169,152,37
PONTIANAK,3206,128,53
PADANG,4359,205,71

The table petal has 36 rows for each city. The last column, a, is an angle. The year is a circle, so a dekad is a 36th of it: 10 degrees, or pi/18.

3. The year as a circular chart

A clock has twelve hours, and a year has twelve months. So the months can be arranged like the hours of a clock. Put January where one o’clock is, and draw each dekad as a line from the middle outwards. The length of the line is the rain. Its end lies at sin(a) to the right and cos(a) upwards.

First the words. words.csv has every word of the drawings with its place and size, and the letters are the ones of Chapter 17:

ogr2ogr -update -overwrite year.gpkg letters.gpkg.zip letter

ogr2ogr -update -overwrite year.gpkg words.csv -oo AUTODETECT_TYPE=YES -nln word

ogr2ogr -update -overwrite year.gpkg year.gpkg -dialect SQLite -sql "with recursive n(i) as (select 1 union all select i+1 from n where i<10), c as (select sheet, w.x, w.y, size s, geom, sum(advance) over (partition by w.rowid order by i)-advance dx, sum(advance) over (partition by w.rowid) total from word w join n on i<=length(word) join letter on code=unicode(substr(word,i,1))) select sheet, shiftcoords(scalecoords(geom,s,s),x+s*(dx-total/2),y) geom from c" -nln text

Then two cities side by side:

gdal pipeline read year.gpkg ! sql --dialect SQLite "select 44 v, st_buffer(st_boundary(st_buffer(makepoint(cx,0),0.3+50*0.0125,60)),0.012) geom from (select 0 cx union select 6.8) union all select dekad, st_buffer(makeline(makepoint(cx+0.3*sin(a),0.3*cos(a)),makepoint(cx+(0.3+mm*0.0125)*sin(a),(0.3+mm*0.0125)*cos(a))),0.028+0.0003*mm,4) from (select case name when 'AMBON' then 6.8 else 0 end cx, * from petal where name in ('JAKARTA','AMBON')) union all select 43, geom from text where sheet='pair'" ! rasterize --attribute-name v --init 0 --ot Byte --size "5100,2754" --extent "-3.4,-4.1,10.2,3.244" ! edit --nodata none ! color-map --color-map year.txt --color-selection nearest ! materialize ! resize --size "1275,688" -r average ! write pair.png --overwrite

Two circular charts of coloured lines on black, with the first letters of the months around them. The lines of Jakarta are long and blue from January to the middle of February and short from June to September. The lines of Ambon are short in winter, and long and orange from May to the beginning of September.

How to read it. Every line is one dekad. January begins at the top, and the year runs clockwise. The grey circle is 50 mm. Section 6 uses this value.

Look before moving on. The long lines of Jakarta are around January, and those of Ambon around June. The two cities are about 2,400 km apart. In Jakarta, the rain is concentrated in four dekads, from 11 January to 20 February, with more than 130 mm each.

Now all thirteen, on the map. The land is the union of all cells that have rain, and a thin line leads from each chart to its city:

ogr2ogr -update -overwrite year.gpkg year.gpkg -dialect SQLite -sql "select st_union(buildmbr(center_x-0.026,center_y-0.026,center_x+0.026,center_y+0.026)) geom from cell where band_1>=0" -nln land

gdal pipeline read year.gpkg ! sql --dialect SQLite "select 42 v, geom from land union all select 44, st_buffer(makeline(makepoint(x,y),makepoint(lon,lat)),0.02) from place union all select 43, st_buffer(makepoint(lon,lat),0.09) from place union all select 0, st_buffer(makepoint(x,y),0.34) from place union all select dekad, st_buffer(makeline(makepoint(x+0.32*sin(a),y+0.32*cos(a)),makepoint(x+(0.32+mm*0.0125)*sin(a),y+(0.32+mm*0.0125)*cos(a))),0.03+0.0003*mm,2) from petal union all select 43, geom from text where sheet='map'" ! rasterize --attribute-name v --init 0 --ot Byte --size "5880,2616" --extent "93.4,-15,142.4,6.8" ! edit --nodata none ! color-map --color-map year.txt --color-selection nearest ! materialize ! resize --size "1960,872" -r average ! write clocks.png --overwrite

A dark map of Indonesia with thirteen circular charts of rain and the names of the cities. Makassar, Kupang, Surabaya, Jakarta and Merauke have their long lines around January. Ambon and Sorong have them at the bottom, around June. Padang, Pontianak, Balikpapan, Manado and Jayapura are nearly round, and Medan has its longest lines in October.

Look before moving on. There are three kinds of charts. In the south, from Jakarta to Merauke, the long lines are on one side, around January, and the eastern ones of this row have no rain at all in August. Ambon and Sorong have their long lines at the bottom, in the middle of the year. And near the equator the charts are nearly round: it rains all year, and there is hardly a rainy season. Section 5 shows these three kinds as a map.

4. The middle of the rain

This section calculates one date for each cell that does not jump like argmax. Think of each line of the chart as an arrow whose length is the rain, and add up all the arrows. The direction of the sum is the middle of the rain. All 36 dekads are part of it, and not only the largest one.

To calculate it, add up the sin and cos parts of all the arrows. atan2 turns the sum into an angle. The length of the sum is useful, too. If the long lines are on one side, the sum is long, because the arrows point in similar directions. If the chart is round, the sum is nearly zero, because the arrows cancel each other.

The same with twice the angle answers a different question: does the rain come twice a year? An arrow in January and one in July then point in the same direction.

ogr2ogr -update -overwrite year.gpkg year.gpkg -dialect SQLite -sql "select row, col, buildmbr(x-0.026,y-0.026,x+0.026,y+0.026) geom, total, 1+mod(cast((case when s1<0 then 2*pi() else 0 end+atan2(s1,c1))*18/pi()+0.5 as integer),36) centre, 200*sqrt(c1*c1+s1*s1)/total season, case when c2*c2+s2*s2>c1*c1+s1*s1 then 2 when c1>0 then 1 else 3 end kind from (select row, col, center_x x, center_y y, sum(value) total, sum(value*cos(key*pi()/18)) c1, sum(value*sin(key*pi()/18)) s1, sum(value*cos(key*pi()/9)) c2, sum(value*sin(key*pi()/9)) s2 from cell, json_each(json_array(band_1,band_2,band_3,band_4,band_5,band_6,band_7,band_8,band_9,band_10,band_11,band_12,band_13,band_14,band_15,band_16,band_17,band_18,band_19,band_20,band_21,band_22,band_23,band_24,band_25,band_26,band_27,band_28,band_29,band_30,band_31,band_32,band_33,band_34,band_35,band_36)) where band_1>=0 group by row, col)" -nln answer

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select count(*) cells, round(min(season)) least_season, round(avg(season)) mean, round(max(season)) most_season from answer"
cells,least_season,mean,most_season
98174,0,42,154
Column Meaning
centre the dekad in the middle of the rain, from 1 to 36
season how strong the season is, in percent of the mean. 0 means the same rain all year. 100 means that the rain changes between nothing and twice the mean
kind 2, if two wet times a year describe the cell better than one. Otherwise 1 for a wet time around January, and 3 for a wet time around July

This one line has processed 3.5 million numbers.

The map shows two things at once: the colour is the date, and the brightness is the strength of the season. Where there is no season, the date has no meaning, and the colour is dark. The key is a ring with the months in the order of a clock:

ogr2ogr -update -overwrite year.gpkg year.gpkg -dialect SQLite -sql "with recursive d(i) as (select 1 union all select i+1 from d where i<36) select i v, st_buffer(makeline(makepoint(98.4+1.95*sin((i-0.5)*pi()/18),-8.3+1.95*cos((i-0.5)*pi()/18)),makepoint(98.4+2.75*sin((i-0.5)*pi()/18),-8.3+2.75*cos((i-0.5)*pi()/18))),0.19,3) geom from d union all select 43, geom from text where sheet='key'" -nln key -nlt PROMOTE_TO_MULTI
gdal pipeline read year.gpkg ! sql --dialect SQLite "select min(255,60+3*season) v, geom from answer union all select 235, geom from key" ! rasterize --attribute-name v --init 0 --ot Byte --size "5640,2160" --extent "94.5,-11.5,141.5,6.5" ! edit --nodata none ! write strong.tif --overwrite

gdal pipeline read year.gpkg ! sql --dialect SQLite "select centre v, geom from answer union all select v, geom from key" ! rasterize --attribute-name v --init 0 --ot Byte --size "5640,2160" --extent "94.5,-11.5,141.5,6.5" ! edit --nodata none ! color-map --color-map year.txt --color-selection nearest ! blend --operator hsv-value --overlay strong.tif ! materialize ! resize --size "1880,720" -r average ! write centre.png --overwrite

Indonesia on black with a ring of colours as the key. Java, Bali and the islands to the east are bright blue for January. Sumatra and Borneo are darker and turn from blue in the south to green in the north. Sulawesi, Seram and the west of Papua are pink and orange for April to July. The middle of Papua and the north of Borneo are nearly black.

Look before moving on. The small areas with sharp edges are gone. The date now changes slowly from place to place, as weather does. The south is bright and blue: a strong season with its middle in January. To the north through Sumatra, the colour changes to green, which is October, and gets darker, because the season gets weaker. Sulawesi is divided by its mountains: one coast is blue, and the other one pink. And Seram, Ambon and the Bird’s Head of Papua are orange, with their middle in June and July.

5. Three kinds of years

The column kind sorts the cells into the three kinds of charts:

gdal pipeline read year.gpkg ! sql --dialect SQLite "select kind v, geom from answer" ! rasterize --attribute-name v --init 0 --ot Byte --size "5640,2160" --extent "94.5,-11.5,141.5,6.5" ! edit --nodata none ! color-map --color-map region.txt --color-selection nearest ! materialize ! resize --size "1880,720" -r average ! write kind.png --overwrite

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select p.name, a.kind, a.centre, round(a.season) season from place p join answer a using(row,col) order by a.kind, p.name"

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select case when c.center_y<-6 and c.center_x>105 then 'Java to Timor' when c.center_x between 127 and 131.5 and c.center_y between -4 and 2.5 then 'Maluku' when c.center_x<100 then 'north-west Sumatra' end area, round(100.0*avg(kind=1)) one_january, round(100.0*avg(kind=2)) two, round(100.0*avg(kind=3)) one_july, round(avg(season)) season from answer join cell c using(row,col) where c.center_y<-6 and c.center_x>105 or c.center_x between 127 and 131.5 and c.center_y between -4 and 2.5 or c.center_x<100 group by 1"
name,kind,centre,season
BALIKPAPAN,1,7,20
JAKARTA,1,4,84
JAYAPURA,1,4,38
KUPANG,1,3,150
MAKASSAR,1,3,135
MANADO,1,3,46
MERAUKE,1,6,114
PADANG,1,32,25
SURABAYA,1,4,112
PONTIANAK,2,35,16
AMBON,3,18,73
MEDAN,3,27,35
SORONG,3,18,30
area,one_january,two,one_july,season
Java to Timor,99,1,0,88
Maluku,27,14,60,34
north-west Sumatra,67,26,7,30

Indonesia in three colours. Blue covers the south of Sumatra, Java, the Lesser Sunda Islands and most of Borneo and Papua. Pale yellow areas lie in the north of Sumatra, the north-east of Borneo and the east coast of Sumatra. Red covers Seram, Halmahera, parts of Sulawesi and the west of Papua.

Is it right? In 2003, Edvin Aldrian and Dwi Susanto divided Indonesia into three rain regions, with another method and other data (ledger L107). Their region A is the south, from south Sumatra to Timor, with one peak between November and March. Region B is the north-west, from north Sumatra to north-west Kalimantan, with two peaks, in October to November and in March to May. Region C is Maluku and the north of Sulawesi, with one peak in June and July.

  • A is clearly there. From Java to Timor, 99 percent of the cells have one wet time, around January.
  • C is there, too. Around Ambon and Halmahera, 60 percent of the cells have their one wet time in the middle of the year.
  • B is harder. In the north-west of Sumatra, only 26 percent of the cells are of the kind with two wet times. But the strength of the season is 30 there, against 88 from Java to Timor. Look at Medan: its chart has a small peak in May and a large one in October. The study counts such a place as two peaks. In the rule of this chapter, the large peak has more weight than the small one, so Medan is in another class.

So the first two regions are so strong that a single line of SQL finds them again, in other data and with another method. The third depends on the definition of a peak. This is important before you draw a border.

6. The beginning of the rainy season

For farmers, another question is important: when does the rain start? BMKG, the weather service of Indonesia, has a rule for this. The rainy season begins with the first dekad that has at least 50 mm, if the two dekads after it have at least 50 mm, too (ledger L108). This is the grey circle of section 3. (There is a second way to meet the rule: the three dekads together have 150 mm. This chapter leaves it out.)

The rule needs neighbours in time: the dekad before, and two dekads after. Chapter 5 did this with lag and lead. But at the end of the year, the neighbour of dekad 36 is dekad 1. The solution is a longer list: put the last band before the first one, and the first two behind the last one. Then every dekad has its neighbours:

ogr2ogr -update -overwrite year.gpkg year.gpkg -sql "select row, col, k from (select row, col, key k, value v, lag(value) over w p, lead(value) over w n1, lead(value,2) over w n2 from cell, json_each(json_array(band_36,band_1,band_2,band_3,band_4,band_5,band_6,band_7,band_8,band_9,band_10,band_11,band_12,band_13,band_14,band_15,band_16,band_17,band_18,band_19,band_20,band_21,band_22,band_23,band_24,band_25,band_26,band_27,band_28,band_29,band_30,band_31,band_32,band_33,band_34,band_35,band_36,band_1,band_2)) where band_1>=0 window w as (partition by row, col order by key)) where k between 1 and 36 and v>=50 and n1>=50 and n2>=50 and p<50" -nln start

ogr2ogr -update -overwrite year.gpkg year.gpkg -sql "select row, col, min(value) low, key+1 kd, sum(value>=50) wet from cell, json_each(json_array(band_1,band_2,band_3,band_4,band_5,band_6,band_7,band_8,band_9,band_10,band_11,band_12,band_13,band_14,band_15,band_16,band_17,band_18,band_19,band_20,band_21,band_22,band_23,band_24,band_25,band_26,band_27,band_28,band_29,band_30,band_31,band_32,band_33,band_34,band_35,band_36)) where band_1>=0 group by row, col" -nln dry

ogr2ogr -update -overwrite year.gpkg year.gpkg -dialect SQLite -sql "select a.geom, max(d.wet,1) wet, case when s.k is null then case when d.wet>18 then 40 else 41 end else s.k end onset, min(case when s.k>d.kd then s.k-d.kd else s.k-d.kd+36 end) wait from answer a join dry d using(row,col) left join start s using(row,col) group by a.row, a.col" -nln season
Line What it does
1 finds every dekad in which a rainy season begins. A place can have more than one
2 finds the driest dekad of each cell, kd, and counts the dekads with 50 mm or more
3 takes the first beginning after the driest dekad. Cells without one get 40 if they are wet all the time, and 41 if they are mostly dry

In line 2, key stands beside min(value) without a function of its own. SQLite then takes it from the row of the minimum. This is a special feature of SQLite.

gdal pipeline read year.gpkg ! sql --dialect SQLite "select onset v, geom from season union all select v, geom from key" ! rasterize --attribute-name v --init 0 --ot Byte --size "5640,2160" --extent "94.5,-11.5,141.5,6.5" ! edit --nodata none ! color-map --color-map year.txt --color-selection nearest ! materialize ! resize --size "1880,720" -r average ! write onset.png --overwrite

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select 2*cast(center_x/2 as integer) from_east, count(*) cells, round(avg(s.k),1) mean_dekad from start s join cell using(row,col) where center_y<-6 and center_x between 104 and 126 and s.k between 24 and 36 group by 1"
from_east,cells,mean_dekad
104,272,28.3
106,1044,28.7
108,969,29.2
110,1396,30.7
112,1278,31.7
114,891,32.7
116,790,32.3
118,834,33.4
120,1037,32.6
122,821,34
124,1000,33.6

Indonesia on black with the same ring as the key. Java turns from green in the west to blue-green in the east, and the islands up to Timor are light blue. Large parts of Borneo, Papua and the west coast of Sumatra are white. The north-east coast of Sumatra is violet and pink.

Look before moving on. The rainy season begins later in the east than in the west. In the west of Java it begins at the beginning of October, dekad 28. In east Java it is November, and on Timor the beginning of December, dekad 34. That is two months for about 2,000 km. The table gives the mean for strips of two degrees. Here an ordinary mean is allowed, because it uses only the dekads from 24 to 36, which do not include the change from 36 to 1.

White is land where the rainy season has no beginning, because it has no end: all 36 dekads have 50 mm or more. That is nearly a quarter of the cells on this map. Grey is the opposite, a few dry places without three wet dekads in a row.

These are averages of thirty years. A single year can begin much earlier or later. For planting, use the forecast of BMKG. Averages are also smoother than any real year, so a rule made for single years gives slightly different dates here.

7. How long does the rainy season last?

The column wet counts the dekads with at least 50 mm:

gdal pipeline read year.gpkg ! sql --dialect SQLite "select wet v, geom from season" ! rasterize --attribute-name v --init 0 --ot Byte --size "5640,2160" --extent "94.5,-11.5,141.5,6.5" ! edit --nodata none ! color-map --color-map wet.txt ! materialize ! resize --size "1880,720" -r average ! write wet.png --overwrite

Indonesia on black, from dark brown for few wet dekads to white for a whole wet year. Borneo, the middle of Papua and the west coast of Sumatra are nearly white. Java becomes browner from west to east, and the darkest land is around Palu in Sulawesi and on the islands north of Timor.

The same without a table, with a warning. calc can count, too. But --calc "sum(A>=50)" looks right and is wrong: the comparison only applies to the last band (ledger L93). Do it in two steps, first a 1 for each wet dekad, and then the sum. Then compare it with the table at one place:

gdal raster calc -i A=rain.tif -o is_wet.tif --calc "A >= 50" --propagate-nodata --overwrite

gdal raster calc -i A=is_wet.tif -o wet.tif --flatten --calc "sum(A)" --propagate-nodata --overwrite

gdallocationinfo -valonly -wgs84 wet.tif 106.83 -6.17

ogr2ogr -f CSV /vsistdout/ year.gpkg -sql "select name, wet from place join dry using(row,col) where name='JAKARTA'"
15
name,wet
JAKARTA,15

Both give 15 dekads for Jakarta, which is five months.

Try it yourself

  • Your city. Add a row to cities.csv, with its place and a free place for its chart, and run sections 2 and 3 again. The name goes into words.csv.
  • Another limit. 50 mm is the rule for Indonesia. Change it to 25 mm in section 6, and check which white areas get a beginning.
  • The end of the season. Use the opposite rule: three dekads below 50 mm, after one above it. This is how BMKG defines the beginning of the dry season (ledger L108).
  • One wet time or two? Draw (c2*c2+s2*s2)/(c1*c1+s1*s1) as a map. Where is it close to 1?
  • Other data for a year. Temperature, NDVI, river levels, ticket sales: anything with 12 or 36 bands works in the same way.

Checkpoint

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

import csv
import io
import math

def rows(sql, dataset="year.gpkg"):
    """The rows of a query, as dictionaries with small letters in the names."""
    table = csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -sql "{sql}"')))
    return [{k.lower(): v for k, v in r.items()} for r in table]

# Calculate one city again without SQL: the 36 numbers of Ambon, their middle and their strength
r = rows("select name, row, col from place where name='AMBON'")[0]
v = [float(t) for t in oneline.run(f"gdallocationinfo -valonly rain.tif {r['col']} {r['row']}").split()]
s, c = (sum(x * f(k * math.pi / 18) for k, x in enumerate(v)) for f in (math.sin, math.cos))
middle = 1 + round(math.atan2(s, c) % (2 * math.pi) * 18 / math.pi) % 36
a = rows(f"select centre, season, kind from answer where row={r['row']} and col={r['col']}")[0]
assert len(v) == 36 and int(a["centre"]) == middle and abs(float(a["season"]) - 200 * math.hypot(s, c) / sum(v)) < 0.1, "Ambon differs from the calculation by hand"

# The three regions of Aldrian and Susanto: A (one peak in the south), B (two peaks), C (one peak in the middle of the year)
kind = {x["name"]: x["kind"] for x in rows("select name, kind from place join answer using(row,col)")}
assert all(kind[n] == "1" for n in ("JAKARTA", "SURABAYA", "MAKASSAR", "KUPANG", "MERAUKE")) and kind["AMBON"] == "3", "the regions should agree with the study"

# The beginning of the rainy season, by hand for Surabaya
r = rows("select row, col from place where name='SURABAYA'")[0]
v = [float(t) for t in oneline.run(f"gdallocationinfo -valonly rain.tif {r['col']} {r['row']}").split()]
hand = [k + 1 for k in range(36) if v[k - 1] < 50 and all(v[(k + j) % 36] >= 50 for j in range(3))]
assert hand == sorted(int(x["k"]) for x in rows(f"select k from start where row={r['row']} and col={r['col']}")), "the beginning differs from the calculation by hand"

pictures = ("most.png", "peak.png", "pair.png", "clocks.png", "centre.png", "kind.png", "onset.png", "wet.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: the middle of the rain of Ambon is dekad {middle}; the rainy season of Surabaya begins in dekad {hand}; the three regions agree with the study")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: the middle of the rain of Ambon is dekad 18; the rainy season of Surabaya begins in dekad [34]; the three regions agree with the study
time since the first cell: 107 s

Troubleshooting

Symptom Cause Fix
The mean date is in the middle of the year, where no peak is Dates were averaged like ordinary numbers sin and cos, as in section 4
A sharp line between December and January The colours do not go around the circle The first and the last colour must be neighbours
no such function: json_each An old SQLite The environment of Chapter 0
The season that begins in December or January is missing Dekad 36 has no neighbour in the list Put band_36 before the list, and band_1, band_2 behind it
sum(A>=50) gives large numbers The comparison applies only to the last band Two steps, as in section 7
Coastal cities have no data Their cell is sea The nearest cell with rain, as in section 2

What comes next

This chapter described the average year. Single events are not part of an average, and some of them change a place permanently. Chapter 14: An old map and satellite images compared gives an old map its position on Earth, and compares it with satellite images of today.

Rain: CHIRPS3, Climate Hazards Center, UC Santa Barbara, CC BY 4.0, averages of 1991 to 2020 made for this chapter. Places: Natural Earth.