Skip to main content

Chapter 7: Simplifying borders without gaps

Chapter 7: Simplifying borders without gaps

TipAt a glance
  • In this series: Part III, Areas. The bus lines of Chapter 6 cross the borders of districts. This chapter is about these borders, which always belong to two neighbours
  • You will build: Maps of the 522 districts of Indonesia: with gaps and after the repair, with different colours for all neighbours, with every district moved apart, and with lines in the sea as on old charts
  • 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
  • Time to run: The commands took about two minutes when tested
  • Level: Intermediate; one query counts in an unusual way, and is explained step by step

Two districts share a border. On paper, it is one line. In a file of polygons it is two: each district has its own copy, point by point. As long as the copies are identical, they are drawn as one line. If one of them changes, the map has gaps and overlaps.

This chapter makes such a map with gaps, measures the error, and repairs it. Then it makes three pictures that need borders without gaps.

NoteLearning objectives

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

  • check whether the polygons of a layer fit together without gaps and overlaps;
  • simplify a map without making gaps;
  • repair a map with gaps that you got from others;
  • draw each border once, and give coasts, provinces and districts their own lines;
  • draw lines in the sea around the coast, as on old charts;
  • colour a map so that neighbours never have the same colour, with one query;
  • move the pieces of a map apart;
  • join small areas into larger ones that are not in the file yet.

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/ch07. 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("07")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch07").iterdir()))
working folder: ch07 | files copied there: ['chart.txt', 'districts.gpkg.zip', 'map.txt', 'papua.csv']

Warm-up

A few short commands first, in the form of Chapter 0. Take the districts out of the zip, and check whether they fit together:

gdal vector convert /vsizip/districts.gpkg.zip warm.gpkg --overwrite

gdal vector info warm.gpkg --summary

gdal vector check-coverage warm.gpkg faults.gpkg --overwrite
INFO: Open of `warm.gpkg'
      using driver `GPKG' successful.
1: district (Multi Polygon)

check-coverage writes a file with all places where neighbours do not fit. Here it is empty. Now make every district 6 km smaller on all sides. A buffer with a negative distance does that:

gdal vector buffer warm.gpkg apart.shp --distance -6000 --overwrite

gdal vector rasterize apart.shp apart.tif --burn 255 --ot Byte --size 1800,661 --overwrite

gdal raster edit apart.tif --nodata none

gdal raster convert apart.tif apart.png --overwrite

Indonesia in white on black. Dark gaps separate all districts, and many of the small ones on Java are tiny or have disappeared.

(edit --nodata none keeps the sea black. Without it, it would be transparent.)

Look before moving on. Every border has become a gap, and the pattern of the districts is visible without a single line. On Java, where the districts are small, only tiny pieces are left, and some of the districts are gone.

Each district was changed on its own, without its neighbours. Here this was intended. When it happens by accident, the map has gaps where it should have none. Section 3 makes such a map.

One more line for everyday work. It writes a file for each province, all at once:

gdal vector partition warm.gpkg provinces --field prov --scheme flat --output-format GPKG --overwrite

1. The 522 districts

The file districts.gpkg.zip has the districts of Indonesia, kabupaten and kota. They come from BPS, the statistics office of Indonesia, and are published by the United Nations office OCHA under the licence CC BY-IGO (ledger L66). This line unpacks them into the file of this chapter:

ogr2ogr -overwrite map.gpkg districts.gpkg.zip district

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select count(*) pieces, count(distinct prov) provinces, sum(st_numgeometries(geom)) parts, sum(st_npoints(geom)) points, round(sum(st_area(geom))/1e6) km2 from district"

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select name, prov, code, st_numgeometries(geom) parts, round(st_area(geom)/1e6) km2 from district where code between 'ID3301' and 'ID3305' or substr(code,-2)='88' order by code"
pieces,provinces,parts,points,km2
522,34,8580,195772,1890770
name,prov,code,parts,km2
Danau Toba,Sumatera Utara,ID1288,2,1102
Danau,Sumatera Barat,ID1388,1,107
Danau,Sumatera Selatan,ID1688,1,94
Danau,Lampung,ID1888,1,29
Waduk Cirata,Jawa Barat,ID3288,1,56
Cilacap,Jawa Tengah,ID3301,5,2346
Banyumas,Jawa Tengah,ID3302,1,1390
Purbalingga,Jawa Tengah,ID3303,1,808
Banjarnegara,Jawa Tengah,ID3304,1,1150
Kebumen,Jawa Tengah,ID3305,1,1330
Wadung Kedungombo,Jawa Tengah,ID3388,1,29
Danau,Sulawesi Utara,ID7188,2,53

522 pieces: 514 districts, and eight special areas with codes that end in 88 or 99. These are lakes, reservoirs and a forest that belong to no district. The borders are those of April 2020.

substr(code,-2)='88' compares the last two characters. In SQL one often writes like with a percent sign for this. But in cmd a percent sign begins a variable (Chapter 1, section 5), and the line would not work there.

How the small file was made. The original has 3.9 million points and is a download of 219 MB. You do not need it. If you want to make the file yourself, download the geodatabase, and run these two lines:

ogr2ogr -overwrite full.gpkg /vsizip/idn_admin_boundaries.gdb.zip -dialect SQLite -sql "select adm2_name name, adm1_name prov, adm2_pcode code, geometry geom from idn_admin2" -nln district -nlt MULTIPOLYGON -t_srs "+proj=cea +lon_0=118 +datum=WGS84"
gdal vector pipeline read full.gpkg ! make-valid ! set-geom-type --geometry-type MULTIPOLYGON ! simplify-coverage --tolerance 300 ! write districts.gpkg

The projection cea is in metres and keeps areas true, so that a square kilometre is the same size everywhere. make-valid repairs three districts whose outline crosses itself. This matters: without it, small faults appear in section 2 as soon as the map is simplified again. Section 3 explains simplify-coverage.

2. Do the pieces fit?

A layer of polygons that fit together, with no gap and no overlap, is called a coverage. GDAL has a command that checks it. It writes a line wherever two borders ought to be the same and are not:

gdal vector check-coverage map.gpkg faults.gpkg --input-layer district --overwrite

ogr2ogr -f CSV /vsistdout/ faults.gpkg -dialect SQLite -sql "select count(*) districts_with_faults from invalid_edge"
districts_with_faults
0

None, so the borders in this file are identical. Many files are not like this. Run this check before you use a file of areas.

3. Two ways to simplify, and one of them makes gaps

For a small map, 196,000 points are too many. The usual way to reduce them is -simplify, with a distance in metres. The second line does the same job with the command for coverages:

ogr2ogr -overwrite torn.gpkg map.gpkg district -simplify 4000 -nln torn -nlt PROMOTE_TO_MULTI

gdal vector simplify-coverage map.gpkg shut.gpkg --input-layer district --output-layer shut --tolerance 4000 --overwrite

Both maps now have less than a quarter of the points. Draw Central Java and Yogyakarta from each, the version of -simplify on the left and the version of simplify-coverage on the right. Under both lies the true land in red. Where red is visible, the land belongs to no district in the simplified map:

ogr2ogr -update -overwrite map.gpkg torn.gpkg torn

ogr2ogr -update -overwrite map.gpkg shut.gpkg shut

gdal pipeline read map.gpkg ! sql "select 11 v, geom from district where code between 'ID3301' and 'ID3499' union all select 11, st_translate(geom,390000,0,0) from district where code between 'ID3301' and 'ID3499' union all select 2, geom from torn where code between 'ID3301' and 'ID3499' union all select 2, st_translate(geom,390000,0,0) from shut where code between 'ID3301' and 'ID3499'" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "5400,2118" --extent "-1060000,-930000,-281818,-624800" ! edit --nodata none ! color-map --color-map map.txt ! materialize ! resize --size "1800,706" -r average ! write torn.png --overwrite

Two maps of Central Java and Yogyakarta in teal, side by side. In the left one, dozens of narrow red areas run through the land. The right one has no red inside, only thin red spots along the edge.

Look before moving on. -simplify takes one polygon at a time, and removes points that change the outline by less than the given distance. For the neighbour, this calculation can remove other points. The two copies of the border then follow different lines. Between them lies a narrow area that belongs to nobody, or a strip that belongs to both.

simplify-coverage reads the whole layer first. It finds each shared border, simplifies it once, and gives both neighbours the same result. In the right map, red is only left along the outer edge, where the simplified line differs from the true one. It uses the algorithm of Visvalingam and Whyatt, and -simplify another one, so the same number of metres does not give the same number of points (ledger L68).

4. How large is the error?

The overlap is easy to measure. Add up the areas of all pieces, and compare with the area of the whole. The difference is the area that is counted twice:

ogr2ogr -f CSV /vsistdout/ torn.gpkg -sql "select 'torn' map, sum(st_npoints(geom)) points, round((sum(st_area(geom))-st_area(st_union(geom)))/1e6) overlap_km2 from torn"

ogr2ogr -f CSV /vsistdout/ shut.gpkg -sql "select 'shut' map, sum(st_npoints(geom)) points, round((sum(st_area(geom))-st_area(st_union(geom)))/1e6) overlap_km2 from shut"
map,points,overlap_km2
torn,42276,12851
map,points,overlap_km2
shut,45217,0

For the gaps, merge all pieces into one, and count the holes in the result. -explodecollections makes a row for each island first:

ogr2ogr -overwrite whole.gpkg torn.gpkg -sql "select st_union(geom) geom from torn" -nln whole -explodecollections -nlt POLYGON

ogr2ogr -f CSV /vsistdout/ whole.gpkg -sql "select sum(numinteriorrings(geom)) holes, round(sum(st_area(makepolygon(st_exteriorring(geom)))-st_area(geom))/1e6) km2_in_holes from whole"

ogr2ogr -overwrite whole.gpkg shut.gpkg -sql "select st_union(geom) geom from shut" -nln whole -explodecollections -nlt POLYGON

ogr2ogr -f CSV /vsistdout/ whole.gpkg -sql "select sum(numinteriorrings(geom)) holes, round(sum(st_area(makepolygon(st_exteriorring(geom)))-st_area(geom))/1e6) km2_in_holes from whole"
holes,km2_in_holes
816,16100
holes,km2_in_holes
8,24

Look before moving on. In the map torn, an area larger than the province of Banten belongs to two districts, and an even larger one to none. Anyone who counts people, forests or votes by district with this map makes errors at each border.

The map shut has holes as well, eight of them, with 24 km2 together. They are in the original, too.

5. Repair a map with gaps

Often you get such a map from others, and the original is not available. clean-coverage gives overlaps to one of the neighbours. It closes gaps only up to a width that you give:

gdal vector clean-coverage torn.gpkg mended.gpkg --output-layer mended --maximum-gap-width 5000 --overwrite

ogr2ogr -f CSV /vsistdout/ mended.gpkg -sql "select 'mended' map, sum(st_npoints(geom)) points, round((sum(st_area(geom))-st_area(st_union(geom)))/1e6) overlap_km2 from mended"

ogr2ogr -overwrite whole.gpkg mended.gpkg -sql "select st_union(geom) geom from mended" -nln whole -explodecollections -nlt POLYGON

ogr2ogr -f CSV /vsistdout/ whole.gpkg -sql "select sum(numinteriorrings(geom)) holes, round(sum(st_area(makepolygon(st_exteriorring(geom)))-st_area(geom))/1e6) km2_in_holes from whole"
map,points,overlap_km2
mended,44588,0
holes,km2_in_holes
7,697

No overlap is left, and of more than 800 holes only seven. These were wider than the limit. The repair does not bring back the lost detail. The borders fit again, but their shapes are still the ones that -simplify made. If you can get the original, simplify it again with simplify-coverage.

Careful with the gap width. A true lake or an enclave of another country is also a gap. The command closes a narrow one of these, too.

6. Draw each border once

Most maps draw the outline of each polygon. Then every inner border is drawn twice, a dashed line turns into a solid one, and the coast looks like any other border. With borders that fit, there is a better way: calculate the piece that two neighbours have in common.

First, which districts are neighbours?

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "select a.fid a, b.fid b from district a join rtree_district_geom r on r.minx<=st_maxx(a.geom) and r.maxx>=st_minx(a.geom) and r.miny<=st_maxy(a.geom) and r.maxy>=st_miny(a.geom) join district b on b.fid=r.id where a.fid<>b.fid and st_intersects(a.geom,b.geom)" -nln next

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select count(*)/2 pairs, (select max(n) from (select count(*) n from next group by a)) most_neighbours from next"
pairs,most_neighbours
1020,11

rtree_district_geom is the spatial index that every layer in a GeoPackage has. It stores the box around each shape. The query compares only districts whose boxes touch, instead of all 272,000 pairs.

Now cut out the common borders, and merge everything into one land for the coast:

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "select * from (select n.a, n.b, case when a.prov=b.prov then 'district' else 'province' end kind, st_collectionextract(st_intersection(a.geom,b.geom),2) geom from next n join district a on a.fid=n.a join district b on b.fid=n.b where n.a<n.b) where geom is not null" -nln border -nlt PROMOTE_TO_MULTI

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "select st_union(geom) geom from district" -nln land -nlt PROMOTE_TO_MULTI

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select kind, round(sum(st_length(geom))/1000) km from border group by 1 union all select 'coast and outer border', round(st_perimeter(geom)/1000) from land union all select 'all outlines', round(sum(st_perimeter(geom))/1000) from district"
kind,km
district,50474
province,8906
coast and outer border,89009
all outlines,207768

st_collectionextract(...,2) keeps only the lines. Six pairs of districts meet in a single point, as two fields of a chessboard do at a corner, and have no border to draw.

Is it right? Every inner border is part of two outlines, and the coast of one. So two times the first two numbers plus the third must give the last one: 2 × (50,474 + 8,906) + 89,009 = 207,769. The last row has 207,768. The difference is rounding, and the pieces fit.

(The length of a coast depends on the detail of the drawing. With the original points, all these numbers are larger.)

7. Lines in the sea

On many old charts, fine lines follow the coast, close together at first, and then further and further apart. They are called water lines. They make it easy to distinguish land and sea. Engravers were well paid for them, and over the last century they went out of use (ledger L69). In SQL they are a row of buffers, each a little wider than the one before:

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "with recursive k(i) as (select 1 union select i+1 from k where i<9) select i, st_boundary(st_buffer(st_simplify(geom,1500), 2200*i*(1+0.13*i), 8)) geom from land, k" -nln ring -nlt PROMOTE_TO_MULTI

gdal pipeline read map.gpkg ! sql "select * from (select 10+i v, st_buffer(geom,650-30*i) geom from ring order by i desc) union all select 1, geom from land union all select 2, st_buffer(geom,350) from border where kind='district' union all select 3, st_buffer(geom,900) from border where kind='province' union all select 4, st_buffer(st_boundary(geom),700) from land" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "5400,3000" --extent "60000,-660000,1410000,90000" ! edit --nodata none ! color-map --color-map chart.txt ! materialize ! resize --size "1800,1000" -r average ! write chart.png --overwrite

A map of Sulawesi and the Moluccas in the style of an old chart. The land is cream with thin brown borders, and the sea is the colour of old paper. Nine fine blue-green rings follow every coast, close together near the land and wider apart further out. They go around small islands and join between them.

Part Meaning
k(i) the numbers 1 to 9, one for each ring
2200*i*(1+0.13*i) the distance from the coast in metres. The steps grow, so the distance between the rings increases outwards
st_simplify(geom,1500) here the simple function is the right one: there is only one shape left, so it has no neighbours and no gaps can appear
order by i desc the outer, paler rings first
the last three parts thin lines for districts, thicker ones for provinces, and the coast on top. Each border is drawn once

Look before moving on. In a narrow bay the rings meet in the middle, and around a group of islands they join. Nobody has drawn this by hand. It comes from the geometry: each ring is the line of all places with the same distance to the nearest land. Chapter 8 calculates the same distance on the other side of the coast.

8. Neighbours with different colours

In 1852, Francis Guthrie coloured the counties of England, and noticed that four colours were enough, so that neighbours were always different. The proof took the mathematicians more than a century (ledger L70). This section uses seven colours, which is easier. But one single query must assign them, and each colour should be used about as often as the others.

The method is the same as by hand. Go from district to district. For each, look at the neighbours that already have a colour, and take one that none of them uses. The difficulty is that in SQL, a row has no access to the results of the rows before it. The solution is a string that gets longer. It holds one digit for each district so far, and every step reads it and adds a digit:

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "with recursive o as materialized (select fid, row_number() over (order by (select count(*) from next where a=fid) desc, fid) n from district), m as materialized (select x.n a, y.n b from next join o x on x.fid=a join o y on y.fid=b where y.n<x.n), c(c) as (values (1),(2),(3),(4),(5),(6),(7)), k(n,s) as (select 0,'' union all select n+1, s||(select c from c where c not in (select cast(substr(s,b,1) as integer) from m where a=n+1) order by length(replace(s,c,'')) desc, c limit 1) from k where n<(select count(*) from district)), z as (select s from k where n=(select count(*) from district)) select o.fid id, cast(substr(s,o.n,1) as integer) v from o, z" -nln tint

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select v colour, count(*) districts from tint group by 1"
colour,districts
1,76
2,75
3,75
4,75
5,75
6,73
7,73
Part Meaning
o the order: districts with many neighbours first, because for them it is hardest to find a free colour
m for each district, the neighbours that come before it
k(n,s) the string that gets longer. Step n+1 takes the string s and adds one digit
c not in (select ... substr(s,b,1) ...) reads the colours of the earlier neighbours from the string, and excludes them
order by length(replace(s,c,'')) desc of the colours that are left, take the one that was used least. Without it, the first colour covered 40 percent of the districts in our test
z the finished string with 522 digits. The last part cuts it into rows again

Is it right? Count the pairs of neighbours with the same colour, and draw the map:

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select count(*) clashes from next join tint x on x.id=a join tint y on y.id=b where x.v=y.v"

gdal pipeline read map.gpkg ! sql "select case when substr(code,-2)='88' then 9 else v end v, geom from district d join tint on id=d.fid union all select 10, st_buffer(geom,700) from border union all select 10, st_buffer(st_boundary(geom),700) from land" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "5400,2160" --extent "-2650000,-1250000,2650000,870000" ! edit --nodata none ! color-map --color-map map.txt ! materialize ! resize --size "1800,720" -r average ! write glass.png --overwrite
clashes
0

All of Indonesia as a mosaic in seven muted colours, with thin dark borders. The pieces on Java are tiny, and those on Borneo and New Guinea are large. No two neighbours have the same colour.

Look before moving on. Among more than a thousand pairs, none has the same colour twice. Each colour covers 73 to 76 districts. The seven colours are also clearly different for readers with red-green colour blindness (ledger L50).

The string grows to 522 characters, and the query takes less than a second. For the 82,000 villages of Indonesia the string would become very long, and a program with a list would be the better tool.

9. Move the districts apart

Pieces that fit can also be moved apart. Move each district away from a point in the middle of Java, by a distance that grows with its distance from this point. Each piece keeps its shape and its size. A copy in grey, moved a little to the lower right, becomes its shadow:

gdal pipeline read map.gpkg ! sql "with k as (select v, geom, 0.4*(st_x(st_centroid(geom))+900000) dx, 0.4*(st_y(st_centroid(geom))+800000) dy from district d join tint on id=d.fid where code between 'ID3100' and 'ID3699') select 9 v, st_translate(geom,dx+3500,dy-3500,0) geom from k union all select v, st_translate(geom,dx,dy,0) from k" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "5400,2025" --extent "-1720000,-1090000,-160000,-505000" ! edit --nodata none ! color-map --color-map map.txt ! materialize ! resize --size "1800,675" -r average ! write puzzle.png --overwrite

The districts of Java as separate pieces on cream paper, in seven colours, each with a small shadow. The island keeps its form, but there is space between all the pieces. A few small pieces sit inside the holes of larger ones.

The middle lies at about -900,000 and -800,000. 0.4*(...) moves every piece by 40 percent of its own distance from it.

Look before moving on. This picture shows something that is hard to see on a normal map: the pieces inside other pieces. These are cities, kota, that lie completely inside a kabupaten, often one with the same name. A piece lies inside another one if the border between the two is as long as its whole outline:

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select i.name piece, o.name lies_inside, i.prov province, round(st_area(i.geom)/1e6) km2, count(*) over () how_many from border e join district i on i.fid in (e.a,e.b) join district o on o.fid in (e.a,e.b) and o.fid<>i.fid where abs(st_length(e.geom)-st_perimeter(i.geom))<1 order by 4 desc limit 5"
piece,lies_inside,province,km2,how_many
Kota Jambi,Muaro Jambi,Jambi,171,17
Kota Tomohon,Minahasa,Sulawesi Utara,150,17
Kota Padangsidimpuan,Tapanuli Selatan,Sumatera Utara,134,17
Kota Bogor,Bogor,Jawa Barat,112,17
Kota Malang,Malang,Jawa Timur,110,17

10. Provinces that are not in the file

The file has the 34 provinces of 2020. In 2022, four laws made four new ones in the Indonesian part of New Guinea (ledger L67). The borders of the districts did not change. So the new provinces are only another way to put the same pieces together, and a small table is enough. papua.csv has a row for each of the 26 districts that moved, as the laws list them:

ogr2ogr -update -overwrite map.gpkg papua.csv -nln papua

ogr2ogr -update -overwrite map.gpkg map.gpkg -sql "select coalesce(new_province, prov) name, count(*) districts, st_union(geom) geom from district left join papua on papua.district=district.name group by 1" -nln province -nlt PROMOTE_TO_MULTI

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select count(*) provinces, sum(districts) pieces from province"

ogr2ogr -f CSV /vsistdout/ map.gpkg -sql "select name, districts, round(st_area(geom)/1e6) km2 from province where substr(name,1,5)='Papua' order by km2 desc"
provinces,pieces
38,522
name,districts,km2
Papua Selatan,4,118522
Papua,9,83275
Papua Barat,7,61937
Papua Tengah,8,58300
Papua Pegunungan,8,53931
Papua Barat Daya,6,36549

left join keeps every district, also those that are not in the table. For these, new_province is empty, and coalesce takes the old province instead. 34 and 4 make 38, the number of provinces today.

gdal pipeline read map.gpkg ! sql "select case name when 'Papua' then 1 when 'Papua Barat' then 2 when 'Papua Pegunungan' then 3 when 'Papua Tengah' then 4 when 'Papua Selatan' then 5 else 6 end v, geom from province where substr(name,1,5)='Papua' union all select 8, st_buffer(geom,600) from border where kind='district' and a in (select fid from district where substr(prov,1,5)='Papua') union all select 10, st_buffer(st_boundary(st_union(geom)),1800) from district where substr(prov,1,5)='Papua' group by prov" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "5400,4500" --extent "1280000,-1060000,2600000,40000" ! edit --nodata none ! color-map --color-map map.txt ! materialize ! resize --size "1800,1500" -r average ! write papua.png --overwrite

The Indonesian part of New Guinea in six colours, one for each province of today, with thin pale lines between the districts. A thick dark line shows the two provinces of 2020 that they were made from.

Look before moving on. The colours are the provinces of today, and the thick dark line is the border of the two old ones. Not a single point had to be digitised.

This works only because the districts fit. With the map torn of section 3, st_union would leave narrow gaps along every old border.

Try it yourself

  • A very large tolerance. Simplify with 20000 instead of 4000, in both ways. The map of simplify-coverage looks very different from the original, and it still has no gap.
  • Four colours. Take three of the seven values out of the list c(c). The query finds no free colour at some point, and tint has no colours. Our simple method needs more colours than the minimum of the mathematicians.
  • Your own island. Change the codes, the middle and the frame in section 9. Sulawesi has the codes ID7100 to ID7699.
  • More water lines. Make twelve rings in section 7, and let them start closer to the land. chart.txt then needs three more rows.
  • Villages. The original file has 81,912 of them, in the layer idn_admin4. Check whether they fit.

Checkpoint

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

import csv
import io

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

def overlap(name):
    return float(rows(f"select (sum(st_area(geom))-st_area(st_union(geom)))/1e6 a from {name}", f"{name}.gpkg")[0]["a"])

assert overlap("torn") > 10_000, "simplifying one by one should tear the map"
assert abs(overlap("shut")) < 1 and abs(overlap("mended")) < 1, "the other two maps should have no overlap"

# Every inner border belongs to two outlines, and the coast to one
inner = float(rows("select sum(st_length(geom)) a from border")[0]["a"])
coast = float(rows("select st_perimeter(geom) a from land")[0]["a"])
outlines = float(rows("select sum(st_perimeter(geom)) a from district")[0]["a"])
assert abs(2 * inner + coast - outlines) < 1e-4 * outlines, "the borders should add up"

assert rows("select count(*) n from next join tint x on x.id=a join tint y on y.id=b where x.v=y.v")[0]["n"] == "0"
assert rows("select count(*) n from tint where v between 1 and 7")[0]["n"] == "522", "every district should have a colour"
assert rows("select count(*) n from province")[0]["n"] == "38"

pictures = ("torn.png", "chart.png", "glass.png", "puzzle.png", "papua.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: overlap {overlap('torn'):,.0f} km2 when torn, {abs(overlap('shut')):.0f} when shut; borders add up to {abs(2 * inner + coast - outlines) / 1000:.1f} km; 38 provinces")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: overlap 12,851 km2 when torn, 0 when shut; borders add up to 0.0 km; 38 provinces
time since the first cell: 129 s

Troubleshooting

Symptom Cause Fix
check-coverage finds faults after simplify-coverage Some polygons were not valid before make-valid first (section 1)
clean-coverage leaves all the gaps Gaps are only closed up to a width, and the width is 0 if you do not give one (ledger L68) --maximum-gap-width
simplify-coverage or clean-coverage is missing They need GDAL 3.12, and GEOS 3.12 or 3.14 The environment of Chapter 1
Almost nothing is left after simplifying The layer is in degrees, and 4000 degrees are a lot Project it to metres first
The column v in tint is empty The query found no free colour for some district More colours in the list c(c)
In cmd, a line with like 'Papua%' fails % begins a variable there (Chapter 1, section 5) substr(name,1,5)='Papua'
A district is missing after the join Two spellings of the same name Join by code where you can

What comes next

This chapter used the distance to the coast for rings in the sea. Chapter 8: The most inland place uses the same distance on land, and looks for the point of an island that is farthest from the coast.

Districts: Badan Pusat Statistik (BPS), by way of OCHA, Indonesia - Subnational Administrative Boundaries, CC BY-IGO, version of April 2020, read on 3 December 2026. The file of this chapter was changed: projected, repaired, simplified and reduced to three columns. The borders and names in it do not imply any official endorsement by the United Nations, by BPS or by us.