A story · tabelline 0.2

The islands' data, made with nanuq

195 islands from a Wikipedia list, their outlines from OpenStreetMap, and what Wikidata and Wikipedia know about them, joined into a few tidy tables with nanuq, Polars for Nim.

Reading the code

Green cards like this one are about how the page is made. The tables of the islands story are made from CSV files; this page tells how those files were made, and its own tables are tabelline 0.2 too. It does not run nanuq: it reads the files nanuq wrote, and quotes the nanuq code from src/process.nim as it is.

One island, four sources

No single source has everything about an island. Here is Sicily as each of the four sources of this story sees it:

what it says about Sicily
Wikipedia, the listarea 25_834 km², population 5_010_001, main town Palermo
Wikidataitem Q1460, at 37.60 N 14.02 E, up to 3_357 m
OpenStreetMapan outline of 120 points (simplified), 25_349 km², 1348 km of coast
Wikipedia, the restPalermo's weather box, the region's GDP and unemployment
let i = toSeq(0 ..< islands.nrows).filterIt(islands["island", it] == "Sicily")[0]
let m = toSeq(0 ..< main.nrows).filterIt(main["island", it] == "Sicily")[0]
let rows = @[
  (source: "Wikipedia, the list", says: "area " & insertSep($main["km2", m].toFloat.int) & " km², population " & insertSep($islands["population", i].toFloat.int) & ", main town " & $islands["town", i]),
  (source: "Wikidata", says: "item " & $islands["wikidata", i] & ", at " & formatFloat(islands["lat", i].toFloat, ffDecimal, 2) & " N " & formatFloat(islands["lon", i].toFloat, ffDecimal, 2) & " E, up to " & insertSep($islands["elevation", i].toFloat.int) & " m"),
  (source: "OpenStreetMap", says: "an outline of " & $islands["points", i] & " points (simplified), " & insertSep($islands["outline_km2", i].toFloat.int) & " km², " & $islands["coast_km", i].toFloat.int & " km of coast"),
  (source: "Wikipedia, the rest", says: "Palermo's weather box, the region's GDP and unemployment")]
let t = tabella(rows, rownameCol = "source"):
  optCssTheme()
  colsLabel:
    says: "what it says about Sicily"
  tabStyle style.text(size = "13px"), loc.body()
nbTable t

They meet on names. The list names each island by a link to its page; Wikidata knows the page (and not its redirects, so 24 links are followed first to the page they lead to); OpenStreetMap's land polygons have no names, only polygons, and an island gets the polygon that holds its point on Wikidata.

Four steps, one of them nanuq

The data goes from the web to the story's tables in three steps, as the FOSDEM data did, and a fourth draws the maps:

toolwhat it does
1. fetchNim, standard librarydownloads the list and about 70 other Wikipedia pages, 10 Wikidata queries, OpenStreetMap's land polygons, about 900 MB (unzipped to 1.3 GB, not committed), Natural Earth's countries and the IHO's seas
2. extractNim, standard libraryfinds each island's outline and what is on it, every other island and its country and sea, reads the weather boxes and the regions' tables
3. processNim with nanuqjoins, cleans and counts: the eleven tables the story reads
4. mapNim, standard librarydraws the maps of the story, of each sea and of each island in its sea, as SVG
let steps = @[
  (step: "1. fetch", tool: "Nim, standard library", does: "downloads the list and about 70 other Wikipedia pages, 10 Wikidata queries, OpenStreetMap's land polygons, about 900 MB (unzipped to 1.3 GB, not committed), Natural Earth's countries and the IHO's seas"),
  (step: "2. extract", tool: "Nim, standard library", does: "finds each island's outline and what is on it, every other island and its country and sea, reads the weather boxes and the regions' tables"),
  (step: "3. process", tool: "Nim with nanuq", does: "joins, cleans and counts: the eleven tables the story reads"),
  (step: "4. map", tool: "Nim, standard library", does: "draws the maps of the story, of each sea and of each island in its sea, as SVG")]
let t = tabella(steps, rownameCol = "step"):
  optCssTheme()
  colsLabel:
    step: ""
    does: "what it does"
nbTable t

The first two steps only gather and place: what is downloaded is wikitext, CSV from Wikidata and GeoJSON, and what needs geometry, an island's outline and which island a place is on, is plain Nim. Everything that needs a decision (which count of passengers to keep, which airports to add up, which heritage parts make one property) happens in the third step, in nanuq. The downloads are not committed; the tables are. Here are the scripts, whole:

src/fetch.nim 228 lines
## Downloads the raw sources of the islands story into a folder (nothing here is committed):
##
##   nim r -d:ssl fetch.nim <raw dir>
##
## Hosts: en.wikipedia.org (wikitext, `action=raw`), query.wikidata.org (SPARQL, CSV),
## osmdata.openstreetmap.de (OpenStreetMap's land polygons), www.marineregions.org (the IHO's
## seas) and raw.githubusercontent.com (Natural Earth's countries). A file already in the folder is not downloaded
## again, so a run that stops can be started again. Standard library only.
import std/[httpclient, uri, net, sequtils, json]
import common

let raw = if paramCount() >= 1: paramStr(1) else: "raw"
createDir(raw / "wiki")

proc client(): HttpClient =
  ## A client through the proxy in HTTPS_PROXY, when there is one.
  let proxy = getEnv("HTTPS_PROXY")
  newHttpClient(userAgent = "tabelline-docs/0.2 (islands story)", timeout = 120_000,
                proxy = if proxy.len > 0: newProxy(proxy) else: nil)

proc save(path, url: string, body = "", accept = "") =
  ## Writes `url` (POSTed with `body` when there is one) to `path`, unless it is already there.
  if fileExists(path): return
  let c = client()
  defer: c.close()
  if accept.len > 0: c.headers["Accept"] = accept
  var tries = 0
  while true:
    try:
      let r = if body.len > 0:
                c.headers["Content-Type"] = "application/x-www-form-urlencoded"
                c.request(url, HttpPost, body)
              else: c.request(url)
      if r.status.startsWith("404"):   # a red link: no page
        writeFile(path, ""); return
      if not r.status.startsWith("200"): raise newException(IOError, r.status & " " & url)
      writeFile(path, r.body)
      echo "  ", path.extractFilename, " ", r.body.len, " bytes"
      sleep 1500   # Wikipedia limits how fast a client reads
      return
    except IOError, OSError, HttpRequestError, TimeoutError:
      inc tries
      if tries >= 4: raise
      sleep 5000 * tries

proc wiki(title: string): string =
  ## The wikitext of a Wikipedia page, saved as wiki/<title>.wiki.
  let path = raw / "wiki" / title.replace(' ', '_').replace('/', '_') & ".wiki"
  save(path, "https://en.wikipedia.org/w/index.php?title=" & encodeUrl(title.replace(' ', '_')) & "&action=raw")
  readFile(path)

proc redirect(text: string): string =
  ## The page a redirect leads to, or "".
  var target: array[1, string]
  if text.startsWith("#REDIRECT") and text.find(re"\[\[([^\]|#]+)", target) >= 0: target[0].strip else: ""

proc page(title: string): string =
  ## The wikitext of a page, following its redirects.
  result = wiki(title)
  if redirect(result).len > 0: result = page(redirect(result))

proc sparql(name, query: string) =
  ## A Wikidata query, as CSV, saved as <name>.csv; its text is kept beside it, <name>.rq.
  writeFile(raw / name & ".rq", query)
  save(raw / name & ".csv", "https://query.wikidata.org/sparql", "query=" & encodeUrl(query), "text/csv")

# ------------------------------------------------------------------ 1. the list of islands

let rows = listRows(wiki("List of islands in the Mediterranean"))
let titles = rows.mapIt(it.title)
echo titles.len, " islands in the list, ", rows.countIt(it.isMain), " main ones"

# ------------------------------------------------------------------ 2. Wikidata

proc valuesOf(ts: openArray[string]): string =
  for t in ts: result.add "\"" & t.replace("\"", "\\\"") & "\"@en "

# Wikidata knows a page by its title, not by its redirects: first the titles it knows, then the
# others are followed on Wikipedia to the page they redirect to (redirects.csv).
sparql "wd_sitelinks", """
SELECT ?title ?item WHERE {
  VALUES ?title { $1 }
  ?article schema:about ?item; schema:isPartOf <https://en.wikipedia.org/>; schema:name ?title.
}""" % valuesOf(titles)
var known: seq[string]
for line in readFile(raw / "wd_sitelinks.csv").splitLines[1 .. ^1]:
  if line.len > 0: known.add line.rsplit(',', 1)[0].strip(chars = {'"'})
var pages: seq[string]
var redirects = @["title,page"]
for t in titles:
  if t in known: pages.add t; continue
  let to = redirect(wiki(t))
  let p = if to.len > 0: to else: t
  pages.add p
  redirects.add "\"" & t & "\",\"" & p & "\""
writeFile(raw / "redirects.csv", redirects.join("\n") & "\n")
let values = @[valuesOf(pages)]
let island = """
  VALUES ?title { $1 }
  ?article schema:about ?item; schema:isPartOf <https://en.wikipedia.org/>; schema:name ?title.""" % values.join(" ")

# Each island: its coordinates, highest point, archipelago and name in its own language.
sparql "wd_islands", """
SELECT ?title ?item ?coord ?elevation ?archipelagoLabel ?native WHERE {""" & island & """
  OPTIONAL { ?item wdt:P625 ?coord }
  OPTIONAL { ?item wdt:P2044 ?elevation }
  OPTIONAL { ?item wdt:P361 ?archipelago . ?archipelago wdt:P31/wdt:P279* wd:Q33837 }
  OPTIONAL { ?item wdt:P1705 ?native }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}"""

# Each island's highest point (P610) and its elevation: an island's own elevation (P2044) is
# sometimes another height (Sardinia's is 384 m, its highest point 1,834 m).
sparql "wd_peaks", """
SELECT ?title ?peak ?peakLabel ?elevation WHERE {""" & island & """
  ?item wdt:P610 ?peak . ?peak wdt:P2044 ?elevation .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}"""

# The waters each island is in or next to (P206): the Aegean, the Tyrrhenian, a gulf, a strait.
sparql "wd_waters", """
SELECT ?title ?item ?water ?waterLabel ?parent ?parentLabel WHERE {""" & island & """
  ?item wdt:P206 ?water .
  OPTIONAL { ?water wdt:P361 ?parent }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}"""

# Each island's name in Italian, for the Italian page.
sparql "wd_italian", """
SELECT ?title ?item ?italian WHERE {""" & island & """
  OPTIONAL { ?item rdfs:label ?italian . FILTER(LANG(?italian) = "it") }
}"""

# Each island's population, every time it was counted.
sparql "wd_population", """
SELECT ?title ?item ?population ?date ?precision WHERE {""" & island & """
  ?item p:P1082 ?st . ?st ps:P1082 ?population .
  OPTIONAL { ?st pqv:P585 ?t . ?t wikibase:timeValue ?date; wikibase:timePrecision ?precision }
}"""

# The World Heritage Sites around the Mediterranean, with their coordinates and year of listing.
sparql "wd_heritage", """
SELECT ?site ?siteLabel ?whsId ?coord ?listed WHERE {
  ?site wdt:P757 ?whsId; p:P625 ?cst . ?cst ps:P625 ?coord ; psv:P625 [ wikibase:geoLatitude ?lat; wikibase:geoLongitude ?lon ] .
  FILTER(?lat > 30 && ?lat < 46.5 && ?lon > -6 && ?lon < 37)
  OPTIONAL { ?site p:P1435 ?h . ?h ps:P1435 wd:Q9259 . ?h pq:P580 ?listed }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}"""

# The airports around the Mediterranean that have an IATA code.
sparql "wd_airports", """
SELECT ?airport ?airportLabel ?iata ?coord WHERE {
  ?airport wdt:P238 ?iata; p:P625 ?cst . ?cst ps:P625 ?coord ; psv:P625 [ wikibase:geoLatitude ?lat; wikibase:geoLongitude ?lon ] .
  FILTER(?lat > 30 && ?lat < 46.5 && ?lon > -6 && ?lon < 37)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}"""

# Their passengers, every count Wikidata has (by year, by month, from several sources).
sparql "wd_passengers", """
SELECT ?iata ?passengers ?date ?precision WHERE {
  ?airport wdt:P238 ?iata; p:P625 ?cst . ?cst psv:P625 [ wikibase:geoLatitude ?lat; wikibase:geoLongitude ?lon ] .
  FILTER(?lat > 30 && ?lat < 46.5 && ?lon > -6 && ?lon < 37)
  ?airport p:P3872 ?st . ?st ps:P3872 ?passengers ; pqv:P585 ?t . ?t wikibase:timeValue ?date; wikibase:timePrecision ?precision .
}"""

# ------------------------------------------------------------------ 3. Wikipedia

# The regions' unemployment and GDP: Eurostat's figures, as Wikipedia lists them.
discard wiki("List of European regions by unemployment rate")
discard wiki("List of European Union regions by GDP")

# The climate of the main islands: the weather box of the island's main town, of the island, or
# of the closest page that has one (`climateAlso`).
for r in rows:
  if not r.isMain: continue
  discard page(r.title)
  if r.town != r.title: discard page(r.town)
for (isl, other) in climateAlso: discard page(other)

# ------------------------------------------------------------- 4. OpenStreetMap's land

# The land polygons of OpenStreetMap (ODbL), as osmdata.openstreetmap.de builds them every day:
# one shapefile of the world in longitude and latitude, 900 MB zipped, 1.3 GB unzipped. Only the
# .shp and its index .shx are kept; `unzip` is the one tool outside Nim this needs.
const land = "https://osmdata.openstreetmap.de/download/land-polygons-complete-4326.zip"
createDir(raw / "osm")
if not fileExists(raw / "osm" / "land_polygons.shp"):
  let zip = raw / "osm" / "land.zip"
  if not fileExists(zip):
    let c = client()
    c.downloadFile(land, zip)
    c.close()
  if execShellCmd("unzip -o -j -q " & zip.quoteShell & " '*/land_polygons.shp' '*/land_polygons.shx' -d " &
                  (raw / "osm").quoteShell) != 0:
    quit "unzip failed on " & zip
  removeFile(zip)
  echo "  land_polygons.shp ", getFileSize(raw / "osm" / "land_polygons.shp"), " bytes"
# ------------------------------------------------------------- 5. every island, the seas

# Every island around the sea that Wikidata knows (an island or a kind of island, with a place in
# the box of the Mediterranean), with its people, to count every island by country.
sparql "wd_all_islands", """
SELECT ?item ?coord ?population WHERE {
  SERVICE wikibase:box {
    ?item wdt:P625 ?coord.
    bd:serviceParam wikibase:cornerSouthWest "Point(-6 30)"^^geo:wktLiteral.
    bd:serviceParam wikibase:cornerNorthEast "Point(37 46.5)"^^geo:wktLiteral.
  }
  ?item wdt:P31/wdt:P279* wd:Q23442.
  OPTIONAL { ?item wdt:P1082 ?population. }
}"""

# The countries of Natural Earth (public domain), 1:10 million, as GeoJSON from its repository.
createDir(raw / "ne")
save(raw / "ne" / "ne_10m_admin_0_countries.geojson",
     "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_countries.geojson")

# The seas of the Mediterranean as the IHO draws them (Limits of Oceans and Seas, 1953), from
# Marine Regions (CC BY 4.0): each sea's record by its name, then its outline as WKT.
createDir(raw / "iho")
for sea in ihoSeas:
  let rec = raw / "iho" / sea.replace(' ', '_') & ".json"
  save(rec, "https://www.marineregions.org/rest/getGazetteerRecordsByName.json/" & encodeUrl(sea).replace("+", "%20") & "/?like=false")
  for r in parseJson(readFile(rec)):
    if r["placeType"].getStr == "IHO Sea Area":
      save(raw / "iho" / sea.replace(' ', '_') & ".jsonld",
           "https://www.marineregions.org/rest/getGazetteerGeometries.jsonld/" & $r["MRGID"].getInt & "/")
echo "done"
src/extract.nim 643 lines
## Step 1 of the islands' data: flattens the raw downloads of fetch.nim into staging CSVs, which
## process.nim (nanuq) cleans, joins and counts.
##
##   nim r -d:release extract.nim <raw dir> <stage dir>
##
## What needs geometry is done here, with the standard library: each island's outline from
## OpenStreetMap (the land polygon that holds its point on Wikidata), simplified to at most 120
## points, in kilometres; which island each World Heritage Site and each airport is on; and
## what needs reading wikitext: the weather boxes, the regions' unemployment and GDP.
import std/[json, math, algorithm, sequtils, tables, sets, parsecsv, streams, memfiles]
import common

let raw = paramStr(1)
let stage = paramStr(2)
createDir(stage)

proc wikiText(title: string): string =
  ## A page fetch.nim saved, following its redirects ("" when there is none).
  let path = raw / "wiki" / title.replace(' ', '_').replace('/', '_') & ".wiki"
  if not fileExists(path): return ""
  result = readFile(path)
  var target: array[1, string]
  if result.startsWith("#REDIRECT") and result.find(re"\[\[([^\]|#]+)", target) >= 0:
    result = wikiText(target[0].strip)

proc readRows(path: string): seq[Table[string, string]] =
  ## A CSV (Wikidata's) as rows of strings.
  var p: CsvParser
  p.open(newStringStream(readFile(path)), path)
  p.readHeaderRow()
  while p.readRow():
    var r: Table[string, string]
    for c in p.headers: r[c] = p.rowEntry(c)
    result.add r

proc point(wkt: string): (float, float) =
  ## "Point(14.01 37.6)" as (longitude, latitude).
  let xy = wkt.multiReplace(("Point(", ""), (")", "")).splitWhitespace
  (xy[0].parseFloat, xy[1].parseFloat)

func qid(uri: string): string = uri.rsplit('/', 1)[^1]

# ------------------------------------------------------------------------- the islands

let rows = listRows(wikiText("List of islands in the Mediterranean"))
var page: Table[string, string]   # the list's title -> the page Wikidata knows
for r in readRows(raw / "redirects.csv"): page[r["title"]] = r["page"]
for r in rows:
  if r.title notin page: page[r.title] = r.title

type Island = object
  row: ListRow
  item, archipelago, italian: string
  native: seq[string]
  lon, lat, elevation: float
var islands: seq[Island]
var byPage: Table[string, int]
for r in rows:
  byPage[page[r.title]] = islands.len
  islands.add Island(row: r, lon: NaN, lat: NaN, elevation: NaN)
for w in readRows(raw / "wd_islands.csv"):
  if w["title"] notin byPage: continue
  var isl = addr islands[byPage[w["title"]]]
  if isl.item.len == 0:   # the first of several coordinates
    isl.item = w["item"].qid
    (isl.lon, isl.lat) = point(w["coord"])
  if w["elevation"].len > 0 and isl.elevation.isNaN: isl.elevation = w["elevation"].parseFloat
  if w["archipelagoLabel"].len > 0 and isl.archipelago.len == 0: isl.archipelago = w["archipelagoLabel"]
  if w["native"].len > 0 and w["native"] notin isl.native: isl.native.add w["native"]
# The highest point, when Wikidata names one (P610) and it is higher than the island's own
# elevation (P2044), which is sometimes another height: Sardinia's is 384 m, and for many small
# islands it is the elevation of the town (Lipari's 5 m, Pantelleria's 5 m). The islands below are
# by hand, from the infobox or the text of their Wikipedia article (English; Italian, French or
# Greek where it says more), read on 13 Nov 2026: the ones whose Wikidata height was the town's
# or was missing. The rest keep Wikidata's.
const peaksByHand = {
  "Sardinia": 1834.0, "Geography of Cyprus": 1952.0,             # Punta La Marmora, Mount Olympus
  "Pantelleria": 836.0, "Lipari": 602.0, "Favignana": 314.0,     # Montagna Grande, Monte Chirica, Santa Caterina (it)
  "Ustica": 244.0, "Sant'Antioco": 271.0, "Isola del Giglio": 496.0, "Capraia": 466.0, "Caprera": 212.0,
  "Serifos": 585.0, "Gavdos": 345.0, "Kastos": 142.0, "Antikythera": 378.0, "Fourni Korseon": 470.0,
  "Elafonisos": 277.0, "Agathonisi": 209.0, "Salamis Island": 404.0, "Amorgos": 823.0, "Kasos": 550.0,
  "Tilos": 654.0, "Symi": 617.0, "Leros": 320.0, "Halki (Greece)": 601.0, "Kastellorizo": 273.0,
  "Alimia": 274.0, "Dia (island)": 220.0,
  "Cres (island)": 639.0, "Pašman": 272.0, "Premuda": 88.0, "Plavnik": 194.0, "Ilovik": 95.0,
  "Sazan Island": 344.0, "Porquerolles": 142.0, "Port-Cros": 199.0}   # Sazan (en), Porquerolles and Port-Cros (fr)
for w in readRows(raw / "wd_peaks.csv"):
  if w["title"] notin byPage: continue
  var isl = addr islands[byPage[w["title"]]]
  let e = w["elevation"].parseFloat
  if isl.elevation.isNaN or e > isl.elevation: isl.elevation = e
for isl in islands.mitems:
  for (title, e) in peaksByHand:
    if isl.row.title == title or page.getOrDefault(isl.row.title) == title: isl.elevation = e

# The archipelagos of Sicily's islands that Wikidata does not give (P361): Lipari is the largest
# of the Aeolian Islands, Favignana, Marettimo and Levanzo are the Egadi, Lampedusa is the
# largest of the Pelagie (Wikipedia, read on 13 Nov 2026).
const archipelagosByHand = {"Lipari": "Aeolian Islands", "Favignana": "Egadi Islands", "Marettimo": "Egadi Islands",
                            "Levanzo": "Egadi Islands", "Lampedusa": "Pelagie Islands"}
for isl in islands.mitems:
  for (title, a) in archipelagosByHand:
    if isl.row.title == title and isl.archipelago.len == 0: isl.archipelago = a

# Three islands whose page has no Wikidata item (a redirect or a page that does not exist):
# a point from the {{coord}} of the Wikipedia article that stands for them, read by hand on 13
# Nov 2026, so their outline is found like the others'.
const pointsByHand = [
  ("Avsa", 27.4986, 40.5119),                     # Avşa (the page Avsa redirects to): its town
  ("La Maddalena (island)", 9.4069, 41.2153),     # La Maddalena, the town on the island
  ("Megalonisos Petalion", 24.2636, 38.0116)]     # Petalioi, the group it is the largest of
for (title, lon, lat) in pointsByHand:
  if title in byPage and islands[byPage[title]].lon.isNaN:
    (islands[byPage[title]].lon, islands[byPage[title]].lat) = (lon, lat)

# ------------------------------------------------------------------------- the seas

# The sea each island is in. Wikidata says, for most (P206, "located in or next to body of
# water"), often a gulf or a strait: each is taken to the sea it is part of. Islands it puts only
# in "the Mediterranean", or nowhere, take the seas Wikipedia's article on them names, written
# below by Claude (seaOf), or else the sea of the closest island that has one, within 30 km. An
# island on more than one sea lists them all. The Îles d'Hyères and La Galite are left in the
# open Mediterranean, as their articles leave them.
const seas = ["Alboran Sea", "Balearic Sea", "Sea of Sardinia", "Ligurian Sea", "Tyrrhenian Sea",
              "Strait of Sicily", "Ionian Sea", "Adriatic Sea", "Aegean Sea", "Libyan Sea",
              "Levantine Sea", "Sea of Marmara"]
const partOf = {"Sea of Sicily": "Strait of Sicily", "Sea of Crete": "Aegean Sea",
                "Carpathian Sea": "Aegean Sea", "Icarian Sea": "Aegean Sea", "Thracian Sea": "Aegean Sea",
                "Myrtoan Sea": "Aegean Sea", "Lycian Sea": "Levantine Sea"}.toTable
const seaOf = {"Sicily": "Tyrrhenian Sea; Strait of Sicily; Ionian Sea",
               "Sardinia": "Tyrrhenian Sea; Sea of Sardinia", "Corsica": "Ligurian Sea; Tyrrhenian Sea",
               "Geography of Cyprus": "Levantine Sea", "Mallorca": "Balearic Sea", "Menorca": "Balearic Sea",
               "Ibiza": "Balearic Sea", "Formentera": "Balearic Sea", "Cabrera, Balearic Islands": "Balearic Sea",
               "Malta (island)": "Strait of Sicily", "Gozo": "Strait of Sicily", "Pantelleria": "Strait of Sicily",
               "Lampedusa": "Strait of Sicily", "Marettimo": "Strait of Sicily", "Levanzo": "Strait of Sicily",
               "Favignana": "Strait of Sicily", "Gavdos": "Libyan Sea", "Avsa": "Sea of Marmara",
               "La Maddalena (island)": "Tyrrhenian Sea", "Megalonisos Petalion": "Aegean Sea"}.toTable

proc major(name: string): string =
  if name in seas: name elif name in partOf: partOf[name] else: ""

var seaNames = newSeq[seq[string]](islands.len)
var seaHow = newSeq[string](islands.len)
# The Italian name: Wikidata's Italian label, without "isola di" in front (Isola Lunga is a
# name), else the English one. Cyprus's page is its geography's, labelled in Italian by Claude.
for w in readRows(raw / "wd_italian.csv"):
  if w["title"] notin byPage or w["italian"].len == 0: continue
  var name = w["italian"]
  for prefix in ["isola di ", "isola d'", "isola del ", "isola "]:
    if name.toLowerAscii.startsWith(prefix) and name != "Isola Lunga": name = name[prefix.len .. ^1]
  if name[0].isLowerAscii: name[0] = name[0].toUpperAscii
  islands[byPage[w["title"]]].italian = name
for isl in islands.mitems:
  if isl.row.title == "Geography of Cyprus": isl.italian = "Cipro"
  if isl.italian.len == 0: isl.italian = isl.row.label

for w in readRows(raw / "wd_waters.csv"):
  if w["title"] notin byPage: continue
  let i = byPage[w["title"]]
  var s = major(w["waterLabel"])
  if s.len == 0: s = major(w["parentLabel"])
  if s.len > 0 and s notin seaNames[i]:
    seaNames[i].add s
    seaHow[i] = "Wikidata"
for i, isl in islands:
  if seaNames[i].len == 0 and isl.row.title in seaOf:
    seaNames[i] = seaOf[isl.row.title].split("; ")
    seaHow[i] = "Wikipedia's article"
let known = toSeq(0 ..< islands.len).filterIt(seaHow[it] == "Wikidata")
for i, isl in islands:
  if seaNames[i].len > 0 or isl.lon.isNaN: continue
  var (best, d) = (-1, 30.0)
  for k in known:
    let dk = hypot((islands[k].lon - isl.lon) * 111.32 * cos(isl.lat.degToRad), (islands[k].lat - isl.lat) * 110.574)
    if dk < d: (best, d) = (k, dk)
  if best >= 0:
    seaNames[i] = seaNames[best]
    seaHow[i] = "as " & islands[best].row.title & ", " & formatFloat(d, ffDecimal, 0) & " km away"

# ------------------------------------------------------------------------- the outlines

type Ring = object
  pts: seq[(float, float)]        # longitude, latitude
  source: string                  # osm: one of OpenStreetMap's land polygons
  lo, hi: (float, float)          # the bounding box
  km2, coastKm: float
  island: int                     # the island it belongs to, -1 for none

const kmLat = 110.574
proc kmLon(lat: float): float = 111.320 * cos(lat.degToRad)

proc project(r: Ring): seq[(float, float)] =
  ## The ring in kilometres from the middle of its bounding box (x east, y north).
  let lon0 = (r.lo[0] + r.hi[0]) / 2
  let lat0 = (r.lo[1] + r.hi[1]) / 2
  r.pts.mapIt(((it[0] - lon0) * kmLon(lat0), (it[1] - lat0) * kmLat))

proc measure(r: var Ring) =
  r.lo = (r.pts.mapIt(it[0]).min, r.pts.mapIt(it[1]).min)
  r.hi = (r.pts.mapIt(it[0]).max, r.pts.mapIt(it[1]).max)
  let p = r.project
  var a, c = 0.0
  for i in 0 ..< p.len:
    let (x1, y1) = p[i]
    let (x2, y2) = p[(i + 1) mod p.len]
    a += x1 * y2 - x2 * y1
    c += hypot(x2 - x1, y2 - y1)
  r.km2 = abs(a) / 2
  r.coastKm = c

proc contains(r: Ring, lon, lat: float): bool =
  ## Whether the point is inside the ring (ray casting).
  if lon < r.lo[0] or lon > r.hi[0] or lat < r.lo[1] or lat > r.hi[1]: return false
  var j = r.pts.high
  for i in 0 .. r.pts.high:
    let (xi, yi) = r.pts[i]
    let (xj, yj) = r.pts[j]
    if (yi > lat) != (yj > lat) and lon < (xj - xi) * (lat - yi) / (yj - yi) + xi:
      result = not result
    j = i

proc centroid(r: Ring): (float, float) =
  ## The ring's centroid (lon, lat), the middle of its area, in degrees: close enough at this size.
  var (a, cx, cy) = (0.0, 0.0, 0.0)
  for i in 0 .. r.pts.high:
    let (x1, y1) = r.pts[i]
    let (x2, y2) = r.pts[(i + 1) mod r.pts.len]
    let f = x1 * y2 - x2 * y1
    a += f; cx += (x1 + x2) * f; cy += (y1 + y2) * f
  if a == 0: ((r.lo[0] + r.hi[0]) / 2, (r.lo[1] + r.hi[1]) / 2) else: (cx / (3 * a), cy / (3 * a))

proc distanceKm(r: Ring, lon, lat: float): float =
  ## The distance from the point to the closest vertex of the ring.
  result = Inf
  for (x, y) in r.pts:
    result = min(result, hypot((x - lon) * kmLon(lat), (y - lat) * kmLat))

# OpenStreetMap's land polygons are a shapefile: `.shx` holds where each record starts (big
# endian, in 16-bit words), and each record of `.shp` its box, its parts and its points (little
# endian doubles). A polygon is kept when its box is around the Mediterranean and not wider than
# 6 degrees (Sicily is 3.4); its outline is its largest ring (the others are holes).
proc be32(p: pointer): int =
  let b = cast[ptr array[4, uint8]](p)
  int((b[0].uint32 shl 24) or (b[1].uint32 shl 16) or (b[2].uint32 shl 8) or b[3].uint32)
template at(base: pointer, off: int): pointer = cast[pointer](cast[int](base) + off)
template i32(p: pointer): int = cast[ptr int32](p)[].int

var rings: seq[Ring]
var shx = memfiles.open(raw / "osm" / "land_polygons.shx")
var shp = memfiles.open(raw / "osm" / "land_polygons.shp")
for k in 0 ..< (shx.size - 100) div 8:
  let rec = at(shp.mem, be32(at(shx.mem, 100 + 8 * k)) * 2 + 8)
  let box = cast[ptr array[4, float64]](at(rec, 4))
  if box[2] < -6 or box[0] > 37 or box[3] < 30 or box[1] > 46.5 or box[2] - box[0] > 6: continue
  let (nParts, nPts) = (i32(at(rec, 36)), i32(at(rec, 40)))
  let pts = at(rec, 44 + 4 * nParts)
  var best = Ring(island: -1)
  for q in 0 ..< nParts:
    let last = if q + 1 < nParts: i32(at(rec, 44 + 4 * (q + 1))) else: nPts
    var r = Ring(source: "osm", island: -1)
    for i in i32(at(rec, 44 + 4 * q)) ..< last:
      let c = cast[ptr array[2, float64]](at(pts, 16 * i))
      r.pts.add (c[0], c[1])
    if r.pts.len > 1 and r.pts[0] == r.pts[^1]: r.pts.setLen(r.pts.len - 1)
    if r.pts.len < 3: continue
    r.measure
    if r.km2 > best.km2: best = r
  if best.pts.len > 0: rings.add best
shx.close; shp.close
echo rings.len, " outlines around the Mediterranean"

# Each island gets the ring that holds its point, if its area is not far from the list's; else
# the closest such ring within 5 km (a point on Wikidata can fall in a bay, the sea, or on an
# islet beside the island, as Ilovik's does).
var how = newSeq[string](islands.len)
for i, isl in islands:
  if isl.lon.isNaN: continue
  var best = -1
  for k, r in rings:
    if r.island < 0 and r.contains(isl.lon, isl.lat) and (best < 0 or r.km2 < rings[best].km2): best = k
  if best >= 0 and isl.row.km2 > 0 and rings[best].km2 / isl.row.km2 notin 0.33 .. 3.0: best = -1
  if best >= 0: how[i] = "inside"
  else:
    var d = 5.0
    for k, r in rings:
      if r.island >= 0: continue
      let ratio = r.km2 / max(isl.row.km2, 0.01)
      if isl.row.km2 > 0 and (ratio < 0.33 or ratio > 3): continue   # the list may have no area
      let dk = r.distanceKm(isl.lon, isl.lat)
      if dk < d: (d, best) = (dk, k)
    if best >= 0: how[i] = "closest, " & formatFloat(d, ffDecimal, 1) & " km"
  if best >= 0: rings[best].island = i

# --------------------------------------------------------------- every island, by country

# All the islands of the Mediterranean, not only the list's: every ring of OpenStreetMap's land
# polygons in the sea (not in the Atlantic, the Black Sea or the Red Sea, and not the
# Peloponnese and Kassandra, cut off only by a canal), its country from Natural Earth's countries
# (the one that holds its middle, or the closest, for an islet Natural Earth does not draw), and
# the largest count of people on Wikidata of an island whose point is on it (process.nim gives the
# list's islands the list's country and people). Lakes are land in OpenStreetMap's polygons, so
# their islands are not here.
proc inSea(lon, lat: float): bool =
  if lon < -5.6: return false                                   # the Atlantic, past Gibraltar
  if lon < 0 and lat > 42.0: return false                       # the Bay of Biscay (the Mediterranean coast west of 0° ends at 40.5° N)
  if (lon > 27.4 and lat > 41.6) or (lon > 28.9 and lat > 41.15): return false   # the Black Sea
  if lon > 32.3 and lat < 31.2: return false                    # the Gulf of Suez and the Red Sea
  true

type Shape = object
  code: string
  rings: seq[Ring]
var countries: seq[Shape]
let neCodes = {"CYN": "CY", "CNM": "CY", "ESB": "CY", "WSB": "CY"}.toTable   # northern Cyprus, the buffer zone, the bases
for f in parseFile(raw / "ne" / "ne_10m_admin_0_countries.geojson")["features"]:
  let a3 = f["properties"]["ADM0_A3"].getStr
  let code = neCodes.getOrDefault(a3, f["properties"]["ISO_A2_EH"].getStr)
  if code == "-99": continue
  var shape = Shape(code: code)
  let g = f["geometry"]
  let polys = if g["type"].getStr == "Polygon": @[g["coordinates"]] else: g["coordinates"].getElems
  for poly in polys:
    var r = Ring(island: -1)
    for c in poly[0]: r.pts.add (c[0].getFloat, c[1].getFloat)
    r.lo = (r.pts.mapIt(it[0]).min, r.pts.mapIt(it[1]).min)
    r.hi = (r.pts.mapIt(it[0]).max, r.pts.mapIt(it[1]).max)
    if r.hi[0] < -7 or r.lo[0] > 38 or r.hi[1] < 29 or r.lo[1] > 47.5: continue
    shape.rings.add r
  if shape.rings.len > 0: countries.add shape

# the countries' coasts in cells of a quarter degree, to find the closest quickly
var coastCells: Table[(int, int), seq[(float, float, int)]]
proc cell(lon, lat: float): (int, int) = (int(floor(lon * 4)), int(floor(lat * 4)))
for k, c in countries:
  for r in c.rings:
    for (x, y) in r.pts: coastCells.mgetOrPut(cell(x, y), @[]).add (x, y, k)

proc countryOf(lon, lat: float): string =
  for c in countries:
    for r in c.rings:
      if r.contains(lon, lat): return c.code
  let (cx, cy) = cell(lon, lat)
  var (best, d) = (-1, Inf)
  for reach in 0 .. 12:   # up to three degrees away
    for i in cx - reach .. cx + reach:
      for j in cy - reach .. cy + reach:
        if max(abs(i - cx), abs(j - cy)) != reach: continue
        for (x, y, k) in coastCells.getOrDefault((i, j)):
          let dk = hypot((x - lon) * kmLon(lat), (y - lat) * kmLat)
          if dk < d: (best, d) = (k, dk)
    if best >= 0 and d < reach.float * 25: break   # a cell is at least 25 km across
  if best >= 0: countries[best].code else: ""

const canals = [(22.0, 37.5), (23.42, 40.05)]   # the Peloponnese and Kassandra, cut off by a canal
var inMed: seq[int]
for k, r in rings:
  let (lon, lat) = ((r.lo[0] + r.hi[0]) / 2, (r.lo[1] + r.hi[1]) / 2)
  if inSea(lon, lat) and not canals.anyIt(r.contains(it[0], it[1])): inMed.add k

# each ring's people
var ringCells: Table[(int, int), seq[int]]
for k in inMed:
  let r = rings[k]
  for i in cell(r.lo[0], r.lo[1])[0] .. cell(r.hi[0], r.hi[1])[0]:
    for j in cell(r.lo[0], r.lo[1])[1] .. cell(r.hi[0], r.hi[1])[1]:
      ringCells.mgetOrPut((i, j), @[]).add k
var people: Table[int, float]
for w in readRows(raw / "wd_all_islands.csv"):
  if w["population"].len == 0 or w["coord"].len == 0: continue
  let (lon, lat) = point(w["coord"])
  for k in ringCells.getOrDefault(cell(lon, lat)):
    if rings[k].island < 0 and rings[k].contains(lon, lat):
      people[k] = max(people.getOrDefault(k), w["population"].parseFloat)
# Each island's sea, as the IHO draws them (Marine Regions): the seas are drawn on a grid of
# 0.02 degrees (about 2 km), and an island takes the sea of most of the cells around its coast.
let seaGrid = ihoGrid(raw)

proc ihoSeaOf(r: Ring): string =
  var votes = newSeq[int](ihoSeas.len)
  let every = max(1, r.pts.len div 60)
  for reach in [1, 3, 8, 20]:
    for i in countup(0, r.pts.high, every):
      let col = int((r.pts[i][0] - ihoX0) / ihoStep)
      let row = int((r.pts[i][1] - ihoY0) / ihoStep)
      for dr in -reach .. reach:
        for dc in -reach .. reach:
          let s = seaGrid.sea(row + dr, col + dc)
          if s >= 0: inc votes[s]
    if votes.max > 0: return ihoSeas[votes.maxIndex]
  ""

# An islet whose closest country in Natural Earth is not its own: Alborán, 7 ha, Spanish, is closer
# to Morocco's coast than to Spain's (Wikipedia, Alborán Island: 35.9394 N, 3.0347 W).
const countriesByHand = [(-3.0347, 35.9394, "ES")]
proc countryOf(r: Ring): string =
  for (lon, lat, code) in countriesByHand:
    if r.contains(lon, lat): return code
  countryOf((r.lo[0] + r.hi[0]) / 2, (r.lo[1] + r.hi[1]) / 2)

var everyRows: seq[seq[string]]
for k in inMed:
  let r = rings[k]
  everyRows.add @[(if r.island >= 0: islands[r.island].row.title else: ""), r.countryOf,
                  formatFloat(r.km2, ffDecimal, 4), (if k in people: $people[k].int else: ""),
                  formatFloat((r.lo[0] + r.hi[0]) / 2, ffDecimal, 4), formatFloat((r.lo[1] + r.hi[1]) / 2, ffDecimal, 4),
                  r.ihoSeaOf, formatFloat(r.centroid[0], ffDecimal, 4), formatFloat(r.centroid[1], ffDecimal, 4)]
echo everyRows.len, " islands in the sea"
writeCsv(stage / "every_island.csv", "Every island of the Mediterranean: each of OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL; not the Peloponnese and Kassandra, cut off by canals; lakes are land there), the list's island it is (title), its country from Natural Earth's countries (public domain; the one that holds its middle, or the closest; Alborán by hand), its km², and the largest count of people on Wikidata (P1082) of an island whose point is on it; the middle of its box (lon, lat); its sea as the IHO draws them (Limits of Oceans and Seas, 1953; Marine Regions, CC BY 4.0), the one around most of its coast; and the centroid of its outline (clon, clat).",
  ["title", "code", "km2", "wd_people", "lon", "lat", "iho_sea", "clon", "clat"], everyRows)

proc perpendicular(p, a, b: (float, float)): float =
  let (dx, dy) = (b[0] - a[0], b[1] - a[1])
  let l = hypot(dx, dy)
  if l == 0: hypot(p[0] - a[0], p[1] - a[1]) else: abs(dy * p[0] - dx * p[1] + b[0] * a[1] - b[1] * a[0]) / l

proc douglasPeucker(p: seq[(float, float)], tol: float): seq[(float, float)] =
  ## The points of an open line that keep its shape within `tol`.
  if p.len < 3: return p
  var keep = newSeq[bool](p.len)
  keep[0] = true; keep[^1] = true
  var stack = @[(0, p.high)]
  while stack.len > 0:
    let (a, b) = stack.pop
    var (far, d) = (-1, tol)
    for i in a + 1 ..< b:
      let di = perpendicular(p[i], p[a], p[b])
      if di > d: (far, d) = (i, di)
    if far >= 0:
      keep[far] = true
      stack.add [(a, far), (far, b)]
  for i, k in keep:
    if k: result.add p[i]

proc simplify(ring: seq[(float, float)], most = 120): seq[(float, float)] =
  ## The closed ring with at most `most` points: split at its two farthest points, each half
  ## simplified with the smallest tolerance that is enough (found by halving).
  if ring.len <= most: return ring
  var far = 0
  for i, q in ring:
    if hypot(q[0] - ring[0][0], q[1] - ring[0][1]) > hypot(ring[far][0] - ring[0][0], ring[far][1] - ring[0][1]): far = i
  let a = ring[0 .. far]
  let b = ring[far .. ^1] & @[ring[0]]
  var (lo, hi) = (0.0, 1000.0)
  for _ in 0 ..< 40:
    let mid = (lo + hi) / 2
    if douglasPeucker(a, mid).len + douglasPeucker(b, mid).len - 2 > most: lo = mid else: hi = mid
  douglasPeucker(a, hi) & douglasPeucker(b, hi)[1 .. ^2]

proc nums(xs: seq[float], decimals: int): string = xs.mapIt(formatFloat(it, ffDecimal, decimals)).join(" ")

var islandRows, shapeRows: seq[seq[string]]
for k, r in rings:
  if r.island < 0: continue
  let s = simplify(r.project)
  let d = if r.km2 < 50: 2 else: 1
  shapeRows.add @[islands[r.island].row.title, r.source, how[r.island], formatFloat(r.km2, ffDecimal, 1),
                  formatFloat(r.coastKm, ffDecimal, 1), $r.pts.len, $s.len,
                  formatFloat(r.hi[0] - r.lo[0], ffDecimal, 3), formatFloat(r.hi[1] - r.lo[1], ffDecimal, 3),
                  s.mapIt(it[0]).nums(d), s.mapIt(it[1]).nums(d)]
shapeRows.sort(proc (a, b: seq[string]): int = cmp(a[0], b[0]))
writeCsv(stage / "shapes.csv", "Island outlines: OpenStreetMap's land polygons (© OpenStreetMap contributors, ODbL), the ring holding each island's point on Wikidata, simplified to at most 120 points, in km from the middle of the ring's box (x east, y north).",
  ["title", "source", "matched", "outline_km2", "coast_km", "points_full", "points", "width_deg", "height_deg", "x", "y"], shapeRows)

for i, isl in islands:
  islandRows.add @[$(i + 1), isl.row.title, isl.row.label, page[isl.row.title], isl.item,
                   (if isl.lon.isNaN: "" else: $isl.lon), (if isl.lat.isNaN: "" else: $isl.lat),
                   (if isl.elevation.isNaN: "" else: $isl.elevation), isl.archipelago,
                   isl.native.join(" / "), isl.italian, $isl.row.km2, isl.row.town, $isl.row.isMain,
                   seaNames[i].join("; "), seaHow[i]]
writeCsv(stage / "islands.csv", "The islands of Wikipedia's List of islands in the Mediterranean (table By area, in its order), with their Wikidata item, coordinates, highest point, archipelago, native name, Italian name and sea (Wikidata P206, or the closest island's, or Wikipedia's article).",
  ["rank", "title", "label", "page", "wikidata", "lon", "lat", "elevation", "archipelago", "native", "italian", "list_km2", "town", "main", "sea", "sea_how"], islandRows)

# ------------------------------------------------------------------------- what is on them

proc islandAt(lon, lat: float, near = 0.0): string =
  ## The island whose outline holds the point; or, within `near` km, the closest island of
  ## 100 km² or more (a coastline can leave a pier or a runway out); or "". (Natural Earth needed
  ## 2 km here; OpenStreetMap's coastline needs much less.)
  for r in rings:
    if r.island >= 0 and r.contains(lon, lat): return islands[r.island].row.title
  var d = near
  for r in rings:
    if r.island >= 0 and r.km2 >= 100 and r.distanceKm(lon, lat) < d:
      d = r.distanceKm(lon, lat)
      result = islands[r.island].row.title

var siteRows, propertyRows: seq[seq[string]]
var seen = initHashSet[string]()
for s in readRows(raw / "wd_heritage.csv"):
  if '-' notin s["whsId"] and s["listed"].len > 0 and s["whsId"] notin seen:
    seen.incl s["whsId"]
    propertyRows.add @[s["whsId"], s["siteLabel"], s["listed"].split('-')[0]]
  let (lon, lat) = point(s["coord"])
  let isl = islandAt(lon, lat, near = 0.5)   # a site on the shore can sit just past the coastline
  let key = s["site"] & isl
  if isl.len == 0 or key in seen: continue
  seen.incl key
  siteRows.add @[isl, s["site"].qid, s["siteLabel"], s["whsId"], s["listed"].split('-')[0]]
writeCsv(stage / "heritage.csv", "World Heritage Sites (and their parts) on the islands: Wikidata (P757, coordinates P625, listed P580), placed on an island by its outline.",
  ["title", "wikidata", "site", "whs_id", "listed"], siteRows)
writeCsv(stage / "heritage_properties.csv", "World Heritage properties around the Mediterranean (the Wikidata items whose P757 has no part number), their name and the year they were listed.",
  ["whs_id", "name", "listed"], propertyRows)

var airportRows: seq[seq[string]]
var onIsland = initHashSet[string]()
for a in readRows(raw / "wd_airports.csv"):
  let (lon, lat) = point(a["coord"])
  let isl = islandAt(lon, lat, near = 0.5)   # a runway can run just past the coastline
  if isl.len == 0 or a["iata"] in onIsland: continue
  onIsland.incl a["iata"]
  airportRows.add @[isl, a["iata"], a["airportLabel"], a["airport"].qid]
writeCsv(stage / "airports.csv", "Airports with an IATA code on the islands: Wikidata (P238, P625), placed on an island by its outline.",
  ["title", "iata", "airport", "wikidata"], airportRows)

var paxRows: seq[seq[string]]
for p in readRows(raw / "wd_passengers.csv"):
  if p["iata"] in onIsland:
    paxRows.add @[p["iata"], p["passengers"], p["date"][0 ..< 10], p["precision"]]
writeCsv(stage / "passengers.csv", "Passengers of the islands' airports, every count on Wikidata (P3872 with its date P585 and the date's precision: 9 a year, 10 a month).",
  ["iata", "passengers", "date", "precision"], paxRows)

var popRows: seq[seq[string]]
for p in readRows(raw / "wd_population.csv"):
  for r in rows:
    if page[r.title] == p["title"]:
      popRows.add @[r.title, p["population"], (if p["date"].len >= 10: p["date"][0 ..< 10] else: ""), p["precision"]]
writeCsv(stage / "population.csv", "The islands' population, every count on Wikidata (P1082, with its date P585 and precision).",
  ["title", "population", "date", "precision"], popRows)

# ------------------------------------------------------------------------- the climate

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const measures = [("high C", "high_c"), ("mean C", "mean_c"), ("low C", "low_c"),
                  ("precipitation mm", "rain_mm"), ("rain mm", "rain_mm"), ("sun", "sun_hours"),
                  ("precipitation days", "rain_days"), ("rain days", "rain_days")]

proc weatherBox(text: string): string =
  ## The first weather box of a page ("" when it has none).
  let a = text.toLowerAscii.find("{{weather box")
  if a < 0: return ""
  var depth = 0
  var i = a
  while i < text.len - 1:
    if text[i] == '{' and text[i + 1] == '{': (inc depth; inc i)
    elif text[i] == '}' and text[i + 1] == '}':
      dec depth; inc i
      if depth == 0: return text[a .. i]
    inc i
  text[a .. ^1]

proc seaTemperatures(text: string): seq[string] =
  ## The twelve months of a table row "Average sea temperature", when the page has one.
  let a = text.find(re"(?i)!\s*Average sea temperature")
  if a < 0: return
  for line in text[a .. ^1].splitLines[1 .. ^1]:
    if line.startsWith("|-") or line.startsWith("!") or line.startsWith("|}"): break
    let cell = line.split('|')[^1]
    let n = number(cell)
    if n.len > 0: result.add n
  result = if result.len < 12: @[] else: result[0 ..< 12]   # a 13th cell is the year's

var climateRows, stationRows: seq[seq[string]]
for r in rows:
  if not r.isMain: continue
  var pages = @[r.town, r.title]
  for (isl, other) in climateAlso:
    if page[r.title] == isl: pages.add other
  var found = false
  var sea: seq[string]
  var seaPage = ""
  for p in pages:
    let text = wikiText(p)
    if sea.len == 0:
      sea = seaTemperatures(text)
      if sea.len > 0: seaPage = p
    let box = weatherBox(text)
    if box.len == 0 or found: continue
    found = true
    var fields: Table[string, string]
    for line in box.replace(re"\n[ \t]+\|", "\n|").split("\n|"):   # some boxes indent their fields
      let kv = line.split('=', 1)
      if kv.len == 2: fields[kv[0].strip.toLowerAscii] = kv[1].strip
    stationRows.add @[r.title, p, plain(fields.getOrDefault("location"))]
    for (key, name) in measures:
      for m, mon in months:
        var v = number(fields.getOrDefault((mon & " " & key).toLowerAscii))
        if v.len == 0:   # a box in Fahrenheit and inches (Ermoupoli, Lefkada): to °C and mm
          if key.endsWith(" C"):
            let f = number(fields.getOrDefault((mon & " " & key[0 .. ^2] & "F").toLowerAscii))
            if f.len > 0: v = formatFloat((f.parseFloat - 32) * 5 / 9, ffDecimal, 1)
          elif key.endsWith(" mm"):
            let inch = number(fields.getOrDefault((mon & " " & key[0 .. ^3] & "inch").toLowerAscii))
            if inch.len > 0: v = formatFloat(inch.parseFloat * 25.4, ffDecimal, 0)
        if v.len > 0: climateRows.add @[r.title, name, $(m + 1), v]
  if sea.len > 0:
    for m, v in sea: climateRows.add @[r.title, "sea_c", $(m + 1), v]
    stationRows.add @[r.title, seaPage, "sea temperature"]
writeCsv(stage / "climate.csv", "Monthly normals of the main islands: the first weather box of the island's main town, of the island, or of the closest page with one (Wikipedia), and a row Average sea temperature where a page has one.",
  ["title", "measure", "month", "value"], climateRows)
writeCsv(stage / "stations.csv", "Where each island's climate comes from: the Wikipedia page and the weather box's location.",
  ["title", "page", "location"], stationRows)

# ------------------------------------------------------------------------- the regions

proc cells(line: string): seq[string] = line.split("||").mapIt(it.strip)

proc regionName(cell: string): string =
  ## A region's name in a cell: the label of its link or of its flag.
  var m: array[1, string]
  if cell.find(re"\[\[(?:[^|\]]*\|)?([^\]]*)\]\]", m) >= 0: return m[0].strip
  if cell.find(re"\{\{flag\|([^}|]+)", m) >= 0: return m[0].strip
  plain(cell)

var gdpRows: seq[seq[string]]
let gdp = wikiText("List of European Union regions by GDP")
let gdp2024 = gdp[gdp.find("== 2024 list ==") ..< gdp.find("==See also")]
var country = ""
for line in gdp2024.splitLines:
  if not line.startsWith("|") or line.startsWith("|-") or line.startsWith("|}") or line.startsWith("|+"): continue
  let c = line[1 .. ^1].cells
  if c.len < 6: continue
  if c.len >= 7: country = regionName(c[1].replace(re"rowspan=""?\d+""?\s*\|", ""))
  let n = c[^5 .. ^1].mapIt(number(it))
  let name = regionName(c[0])
  gdpRows.add @[(if name == "Toscana": "Tuscany" else: name), country] & n   # the other list's name
writeCsv(stage / "gdp.csv", "GDP of the EU's NUTS 2 regions in 2024: Wikipedia, List of European Union regions by GDP (Eurostat). Nominal million EUR, PPS million EUR, PPS per person, PPS per person as % of the EU, population in millions (2025).",
  ["region", "country", "gdp_meur", "pps_meur", "pps_per_person", "pps_index", "population_m"], gdpRows)

var jobRows: seq[seq[string]]
let jobs = wikiText("List of European regions by unemployment rate")
for (head, first) in [("== 2016 to 2025 list ==", 2016), ("== 2006 to 2015 list ==", 2006)]:
  let a = jobs.find(head)
  let part = jobs[a ..< jobs.find("|}", a)]
  for chunk in part.split("\n|-")[1 .. ^1]:
    let lines = chunk.splitLines.filterIt(it.startsWith("|"))
    if lines.len < 12: continue
    let region = regionName(lines[0])
    var cc: array[1, string]
    let code = if lines[1].find(re"\{\{([A-Z]{3})\}\}", cc) >= 0: cc[0] else: plain(lines[1][1 .. ^1])
    for k in 0 ..< 10:
      let v = number(lines[2 + k][1 .. ^1])
      if v.len > 0: jobRows.add @[region, code, $(first + k), v]
writeCsv(stage / "unemployment.csv", "Unemployment rate (%) of Europe's NUTS 2 regions, 2006-2025: Wikipedia, List of European regions by unemployment rate (Eurostat).",
  ["region", "country", "year", "rate"], jobRows)
src/process.nim 211 lines
## Step 2 of the islands' data: cleans, joins and counts the staging CSVs of extract.nim with
## nanuq (Polars for Nim), and writes the tables of the story (docs/stories/isole.nim).
##
##   nim r -d:release --path:<nanuq>/src process.nim <stage dir> <out dir>
##
## Every output is a CSV whose first line is a `#` comment naming what it is made from, read by
## the story with `readCsv(path, comment = "#")`. The hand-written tables (regions.csv,
## history.csv, highlights.csv) are read from <out dir>.

import std/os
import nanuq

let stage = paramStr(1)
let outDir = paramStr(2)
let tabelline = currentSourcePath().parentDir.parentDir.parentDir.parentDir.parentDir.parentDir

proc rd(path: string): LazyFrame =
  ## A CSV with its `#` line, every column read as text first: types are chosen here.
  readCsv(path, inferSchemaLength = some(0), commentPrefix = "#").lazy

proc save(df: DataFrame, name, comment: string) =
  ## nanuq's writeCsv has no comment option, so the `#` line is put in front afterwards.
  let path = outDir / name
  df.writeCsv(path)
  writeFile(path, "# " & comment & "\n" & readFile(path))
  echo name, ": ", df.height, " rows x ", df.width, " columns"

proc num(e: Expr): Expr = e.cast(Float64, strict = false)
proc int64(e: Expr): Expr = e.cast(Float64, strict = false).cast(Int64)

# ---------------------------------------------------------------- 1. the islands

# tabelline's own isole dataset has each island's country and population; the staging list has
# its page, Wikidata item, place and main town. They meet on the name the list shows.
let isole = rd(tabelline / "src" / "tabelline" / "data" / "isole.csv")
  .select(col.island.alias("label"), col.country, col.population.int64)
  .unique(["label"], keep = UniqueKeepStrategy.First, maintainOrder = true)

# Each heritage property once: its parts share the number before the dash (1733-001 is Knossos,
# part of 1733, the Minoan Palatial Centres), and a letter after it marks an extension (132ter).
# The name and year are the property's own.
let propertyNames = rd(stage / "heritage_properties.csv")
  .select(col.whs_id.str.replace(r"(bis|ter|rev)$", "").alias("property"), col.name, col.listed)
  .unique(["property"], keep = UniqueKeepStrategy.First, maintainOrder = true)
let properties = rd(stage / "heritage.csv")
  .withColumns(col.whs_id.str.replace(r"-.*", "").str.replace(r"(bis|ter|rev)$", "").alias("property"))
  .groupBy(col.title, col.property, maintainOrder = true)
  .agg(col.site.sort.first.alias("part"), len().alias("parts"))
  .join(propertyNames, on = ["property"], how = JoinType.Left)
  .withColumns(col.name.fillNull(col.part).alias("site"))

let airports = rd(stage / "airports.csv")

# Wikipedia's list gives Cyprus no population: the island has been divided since 1974. Its
# estimate is the sum of the two counts on Wikipedia (read 13 Nov 2026): 918,100 in the areas the
# Republic of Cyprus controls (census 2021, page Cyprus) and 382,836 in the north (estimate 2021,
# page Northern Cyprus).
const cyprusPeople = 918_100 + 382_836

# The ISO code of each of the list's countries, for its flag and to add up every island by country.
const codeOf = [("Italy", "IT"), ("Greece", "GR"), ("Cyprus", "CY"), ("France", "FR"), ("Spain", "ES"),
                ("Croatia", "HR"), ("Tunisia", "TN"), ("Turkey", "TR"), ("Malta", "MT"), ("Albania", "AL")]
var listCode = `when`(col.country == codeOf[0][0]).then(codeOf[0][1])
for (name, code) in codeOf[1 .. ^1]: listCode = listCode.`when`(col.country == name).then(code)
let islands = rd(stage / "islands.csv")
  .join(isole, on = ["label"], how = JoinType.Left)
  .join(rd(stage / "shapes.csv").select(col.title, col.outline_km2.num, col.coast_km.num,
                                        col.points.int64, col.matched, col.x, col.y),
        on = ["title"], how = JoinType.Left)
  .join(properties.groupBy(col.title).agg(len().alias("heritage")), on = ["title"], how = JoinType.Left)
  .join(airports.groupBy(col.title).agg(len().alias("airports")), on = ["title"], how = JoinType.Left)
  .join(rd(stage / "every_island.csv").filter(col.title.isNotNull).select(col.title, col.iho_sea, col.clon.num, col.clat.num),
        on = ["title"], how = JoinType.Left)
  .select(col.rank.int64, col.label.alias("island"), col.title,
          # two islands tabelline's isole has no country for
          `when`(col.label == "La Galite").then("Tunisia").`when`(col.label == "Île du Levant").then("France")
            .otherwise(col.country).alias("country"),
          listCode.`when`(col.label == "La Galite").then("TN").`when`(col.label == "Île du Levant").then("FR")
            .otherwise("").alias("code"),
          col.list_km2.num.alias("km2"),
          `when`(col.title == "Geography of Cyprus").then(cyprusPeople).otherwise(col.population).alias("population"),
          col.town, col.wikidata, col.lat.num, col.lon.num, col.elevation.num,
          col.archipelago, col.native, col.italian, (col.main == "true").alias("main"), col.sea, col.sea_how,
          col.outline_km2, col.coast_km, col.points, col.matched,
          col.heritage.fillNull(0), col.airports.fillNull(0), col.iho_sea, col.clon, col.clat, col.x, col.y)
  .sort("rank").collect
islands.save("islands.csv", "The 195 islands of Wikipedia's List of islands in the Mediterranean (by area, its rank), with tabelline's isole (country, population), Wikidata (item, place, highest point, archipelago, native name, Italian name, sea), the country's ISO code, the sea as the IHO draws them (Marine Regions, CC BY 4.0), the OpenStreetMap outline (© OpenStreetMap contributors, ODbL) that holds each (km², coast km, points, its centroid clon and clat, x and y in km) and the counts of World Heritage properties and airports on it.")

# ---------------------------------------------------------------- 2. what is on them

properties.join(islands.lazy.select(col.title, col.island), on = ["title"])
  .select(col.island, col.title, col.property, col.site, col.listed.int64, col.parts)
  .sort(["title", "listed", "property"]).collect
  .save("heritage.csv", "World Heritage properties on the islands, one row each (parts of a serial property counted in parts): Wikidata, placed by the islands' outlines.")

# Passengers: Wikidata has counts by year and by month, sometimes several for the same year from
# different sources. A year counts once, with its largest yearly count (a smaller one is often
# part of the year). An island's airports then add up: its small airports (never a million
# passengers in a year, when another one has) are left out, as they are often counted for a
# few years only, and a year counts when every one of the others has a count.
let yearly = rd(stage / "passengers.csv")
  .filter(col.precision == "9")
  .withColumns(col.date.str.slice(0, 4).cast(Int64).alias("year"), col.passengers.int64)
  .groupBy(col.iata, col.year).agg(col.passengers.max)
  .join(airports.select(col.iata, col.title, col.airport), on = ["iata"])

yearly.select(col.title, col.iata, col.airport, col.year, col.passengers)
  .sort(["title", "iata", "year"]).collect
  .save("airports.csv", "Passengers of each airport on the islands, by year: Wikidata P3872 (yearly counts; the largest when there are several).")
let active = yearly
  .groupBy(col.title, col.iata).agg(col.passengers.max.alias("most"))
  .filter(col.most >= 1_000_000 or col.most.max.over(col.title) < 1_000_000)
  .select(col.title, col.iata)

let counted = active.groupBy(col.title).agg(len().alias("counted"))
yearly.join(active, on = ["title", "iata"])
  .groupBy(col.title, col.year)
  .agg(col.passengers.sum, len().alias("airports"), col.iata.sort.str.join(" ").alias("iata"))
  .join(counted, on = ["title"])
  .filter(col.airports == col.counted and col.year >= 2000)
  .join(islands.lazy.select(col.title, col.island), on = ["title"])
  .select(col.island, col.title, col.year, col.passengers, col.iata)
  .sort(["title", "year"]).collect
  .save("passengers.csv", "Passengers of the islands' airports by year, 2000 on: the sum of the island's airports (those with a million passengers in some year, or all when none has), in the years every one of them has a count (airports.csv).")

# ---------------------------------------------------------------- 3. the main islands

# Climate: long to wide, a column per month.
rd(stage / "climate.csv")
  .withColumns(col.value.num, format("m{}", col.month.str.zfill(2)).alias("m"))
  .collect
  .pivot(on = "m", index = ["title", "measure"], values = "value", aggregateFunction = PivotAgg.First, sortColumns = true)
  .lazy.join(islands.lazy.select(col.title, col.island), on = ["title"])
  .select(col.island, col.title, col.measure, col("^m\\d\\d$"))
  .sort(["title", "measure"]).collect
  .save("climate.csv", "Monthly normals of the main islands (m01 January ... m12 December): high_c, mean_c and low_c (°C), rain_mm, rain_days, sun_hours, sea_c (sea temperature, where a page has it). From the weather boxes of Wikipedia (stations.csv says which).")

rd(stage / "stations.csv").collect.save("stations.csv", "Where each main island's climate comes from: the Wikipedia page and the weather box's own description of its station.")

# Unemployment: the regions of the main islands, and the median of every region of the list.
let jobs = rd(stage / "unemployment.csv").withColumns(col.year.int64, col.rate.num)
let regions = rd(outDir / "regions.csv")
let islandRegions = regions.select(col.region).filter(col.region.isNotNull).unique(maintainOrder = true)
concat([
    jobs.join(islandRegions, on = ["region"]).select(col.region, col.year, col.rate),
    jobs.groupBy(col.year).agg(col.rate.median).select(lit("All regions (median)").alias("region"), col.year, col.rate)])
  .withColumns(format("y{}", col.year).alias("y"))
  .collect
  .pivot(on = "y", index = "region", values = "rate", aggregateFunction = PivotAgg.First, sortColumns = true)
  .sort("region")
  .save("unemployment.csv", "Unemployment rate (%) of the main islands' regions, 2006-2025 (y2006 ... y2025), and the median of the 300 or so regions listed: Wikipedia, List of European regions by unemployment rate (Eurostat).")

# Every island of the sea, by country: extract.nim's rings of OpenStreetMap, each with its country
# from Natural Earth and its people on Wikidata; the list's islands take the list's country and
# area and people (Natural Earth's closest country for Agathonisi and Kastellorizo is Turkey).
let listed = islands.lazy
  .select(col.title, col.code.alias("list_code"), col.km2.alias("list_km2"), col.population.cast(Float64).alias("list_people"), col.main)
rd(stage / "every_island.csv")
  .select(col.title, col.code, col.km2.num, col.wd_people.num)
  .join(listed, on = ["title"], how = JoinType.Left)
  .withColumns(col.list_code.fillNull(col.code).alias("code"), col.list_km2.fillNull(col.km2).alias("km2"),
               col.list_people.fillNull(col.wd_people).alias("people"))
  .groupBy(col.code)
  .agg(len().alias("islands"), col.km2.filter(col.km2 >= 0.01).len.alias("hectare"),
       col.title.count.alias("listed"), col.main.filter(col.main).len.alias("main"),
       col.km2.sum.round(1).alias("km2"), col.people.sum.cast(Int64).alias("people"),
       col.people.count.alias("peopled"))
  .sort("km2", descending = true).collect
  .save("countries.csv", "Every island of the Mediterranean, by country: OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL; not the Peloponnese and Kassandra, cut off by canals, nor islands in lakes), the country from Natural Earth (public domain), the area and people from Wikipedia's list for its 195 islands, and for the others the polygon's area and the people on Wikidata (P1082). islands: every polygon; hectare: those of 0.01 km² or more; listed and main: of the 195 and the 35; peopled: those with a count.")

# Every island of the sea, by the IHO's sea: the other islands, not the list's, of a hectare or
# more (smaller ones are mostly rocks, and some piers and breakwaters drawn as land).
rd(stage / "every_island.csv")
  .select(col.title, col.km2.num, col.iho_sea)
  .filter(col.title.isNull and col.km2 >= 0.01)
  .groupBy(col.iho_sea)
  .agg(len().alias("others"), col.km2.sum.round(1).alias("others_km2"))
  .sort("iho_sea").collect
  .save("seas.csv", "The other islands of each sea, as the IHO draws them (Marine Regions, CC BY 4.0): OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL) that are not one of the list's 195, of 0.01 km² or more; how many (others) and their km² (others_km2).")

# The other islands themselves, for the map of every island: each with its centroid, country,
# sea and area, of a hectare or more.
rd(stage / "every_island.csv")
  .select(col.title, col.code, col.km2.num, col.iho_sea, col.clon.num, col.clat.num)
  .filter(col.title.isNull and col.km2 >= 0.01)
  .select(col.clon.round(3).alias("lon"), col.clat.round(3).alias("lat"), col.code, col.km2.round(3).alias("km2"), col.iho_sea)
  .sort(["lon", "lat"]).collect
  .save("others.csv", "The islands of the Mediterranean that are not one of the list's 195, of 0.01 km² or more: OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL), each with the centroid of its outline (lon, lat), its country from Natural Earth (public domain), its km² and its sea as the IHO draws them (Marine Regions, CC BY 4.0).")

let gdp = rd(stage / "gdp.csv")
  .select(col.region, col.pps_per_person.num, col.pps_index.num, col.population_m.num)

# One row per main island: its place, size, people, region and what the other tables say.
let lastPax = rd(outDir / "passengers.csv").withColumns(col.year.int64, col.passengers.int64)
  .sort(["title", "year"]).groupBy(col.title).agg(col.year.last.alias("pax_year"), col.passengers.last.alias("pax"))
let climate = rd(outDir / "climate.csv")
let sea = climate.filter(col.measure == "sea_c").select(col.title, col.m08.num.alias("sea_aug"))
let high = climate.filter(col.measure == "high_c").select(col.title, col.m08.num.alias("high_aug"), col.m01.num.alias("high_jan"))
islands.lazy.filter(col.main)
  .join(regions.select(col.title, col.locale, col.region), on = ["title"], how = JoinType.Left)
  .join(gdp, on = ["region"], how = JoinType.Left)
  .join(jobs.filter(col.year == 2025).select(col.region, col.rate.alias("jobless_2025")), on = ["region"], how = JoinType.Left)
  .join(lastPax, on = ["title"], how = JoinType.Left)
  .join(sea, on = ["title"], how = JoinType.Left)
  .join(high, on = ["title"], how = JoinType.Left)
  .select(col.rank, col.island, col.italian, col.title, col.country, col.code, col.locale, col.km2, col.population,
          (col.population / col.km2).round(0).alias("per_km2"), col.coast_km, col.elevation, col.archipelago,
          col.town, col.sea.alias("seas"), col.heritage, col.airports, col.region, col.pps_per_person, col.pps_index,
          col.jobless_2025, col.pax_year, col.pax, col.high_jan, col.high_aug, col.sea_aug)
  .sort("rank").collect
  .save("main.csv", "The 35 main islands (the largest, down to Elba, 224 km²), one row each: islands.csv with their region (regions.csv), its GDP per person in PPS and as % of the EU (2024) and unemployment (2025), the last year of passengers (passengers.csv), and the January and August highs and the August sea (climate.csv).")
src/map.nim 379 lines
## The maps of the story: the Mediterranean, its seas and its islands, as two SVG drawings, the
## west and the east, so the names can be read on a phone.
##
##   nim r -d:release map.nim <raw> <folder>     (writes map-west.svg and map-east.svg, and the
##                                                Italian page's map-west-it.svg and map-east-it.svg,
##                                                a small map of each sea, seas/<sea>.svg, and of
##                                                each island in its sea, locators/<rank>.svg,
##                                                Sicily and its islands, map-sicily(-it).svg, and
##                                                every island as a dot, map-every.svg)
##
## The land is OpenStreetMap's (the land polygons fetch.nim downloads, © OpenStreetMap
## contributors, ODbL), cut to the box of each map and simplified; the islands are islands.csv's
## points, the main ones filled and named, the others a dot. Where each name of a sea or an
## island goes was written by Claude, the AI that wrote the story. The dashed lines are the
## limits of the seas as the IHO draws them (Limits of Oceans and Seas, 1953; Marine Regions,
## CC BY 4.0). The drawing names its parts (sea, land, main, dot, limit, sea-name, name) and the page's theme colours them (`.map` in
## docs/theme.nim), so the maps change with the look.
import std/[math, strutils, strformat, sequtils, parsecsv, memfiles, os, tables, json]
import common
from ../../../../theme import minoanLook   # the colours of the locators, which a picture cannot take from the page

let raw = paramStr(1)
let output = paramStr(2)
let here = currentSourcePath().parentDir.parentDir

# ------------------------------------------------------------------------------ the islands
type Island = object
  rank: int
  name, italian: string
  lon, lat: float
  main: bool
  sea: string   # the IHO's sea it is in
  middle: (float, float)   # the centroid of its outline, or its point
var islands: seq[Island]
var csv: CsvParser
csv.open(here / "islands.csv")
csv.readHeaderRow()   # the first line is the description
csv.readHeaderRow()
while csv.readRow():
  if csv.rowEntry("lat") == "": continue   # three islands have no place on Wikidata
  islands.add Island(rank: csv.rowEntry("rank").parseInt, name: csv.rowEntry("island"), italian: csv.rowEntry("italian"), lon: csv.rowEntry("lon").parseFloat,
                     lat: csv.rowEntry("lat").parseFloat, main: csv.rowEntry("main") == "true",
                     sea: csv.rowEntry("iho_sea"))
  islands[^1].middle = if csv.rowEntry("clon") == "": (islands[^1].lon, islands[^1].lat)
                       else: (csv.rowEntry("clon").parseFloat, csv.rowEntry("clat").parseFloat)
csv.close

# ------------------------------------------------------------------------------ the land
# Every ring of OpenStreetMap's land that has a point around the sea, its points held inside
# that box (outside it they only run along the edge, which is not drawn) and simplified
# (Douglas–Peucker, as in extract.nim) to a hundredth of a degree, about a kilometre.
const (west, east, south, north) = (-6.0, 36.5, 30.0, 46.5)

proc be32(p: pointer): int =
  let b = cast[ptr array[4, uint8]](p)
  int((b[0].uint32 shl 24) or (b[1].uint32 shl 16) or (b[2].uint32 shl 8) or b[3].uint32)
template at(base: pointer, off: int): pointer = cast[pointer](cast[int](base) + off)
template i32(p: pointer): int = cast[ptr int32](p)[].int

proc perpendicular(p, a, b: (float, float)): float =
  let (dx, dy) = (b[0] - a[0], b[1] - a[1])
  let l = hypot(dx, dy)
  if l == 0: hypot(p[0] - a[0], p[1] - a[1]) else: abs(dy * p[0] - dx * p[1] + b[0] * a[1] - b[1] * a[0]) / l

proc douglasPeucker(p: seq[(float, float)], tol: float): seq[(float, float)] =
  if p.len < 3: return p
  var keep = newSeq[bool](p.len)
  keep[0] = true; keep[^1] = true
  var stack = @[(0, p.high)]
  while stack.len > 0:
    let (a, b) = stack.pop
    var (far, d) = (-1, tol)
    for i in a + 1 ..< b:
      let di = perpendicular(p[i], p[a], p[b])
      if di > d: (far, d) = (i, di)
    if far >= 0:
      keep[far] = true
      stack.add [(a, far), (far, b)]
  for i, kept in keep:
    if kept: result.add p[i]

proc contains(p: seq[(float, float)], q: (float, float)): bool =
  var j = p.high
  for i in 0 .. p.high:
    if (p[i][1] > q[1]) != (p[j][1] > q[1]) and
       q[0] < (p[j][0] - p[i][0]) * (q[1] - p[i][1]) / (p[j][1] - p[i][1]) + p[i][0]:
      result = not result
    j = i

type Ring = object
  pts: seq[(float, float)]   # longitude, latitude
  main: bool                 # it holds a main island
var rings: seq[Ring]
var shx = memfiles.open(raw / "osm" / "land_polygons.shx")
var shp = memfiles.open(raw / "osm" / "land_polygons.shp")
for r in 0 ..< (shx.size - 100) div 8:
  let rec = at(shp.mem, be32(at(shx.mem, 100 + 8 * r)) * 2 + 8)
  let box = cast[ptr array[4, float64]](at(rec, 4))
  if box[2] < west or box[0] > east or box[3] < south or box[1] > north: continue
  let (nParts, nPts) = (i32(at(rec, 36)), i32(at(rec, 40)))
  let pts = at(rec, 44 + 4 * nParts)
  for q in 0 ..< nParts:
    let last = if q + 1 < nParts: i32(at(rec, 44 + 4 * (q + 1))) else: nPts
    var ring: seq[(float, float)]
    var inside = false
    for i in i32(at(rec, 44 + 4 * q)) ..< last:
      let c = cast[ptr array[2, float64]](at(pts, 16 * i))
      inside = inside or (c[0] in west .. east and c[1] in south .. north)
      let p = (clamp(c[0], west, east), clamp(c[1], south, north))
      if ring.len == 0 or p != ring[^1]: ring.add p
    if not inside or ring.len < 4: continue
    ring = douglasPeucker(ring, 0.01)
    if ring.len < 4: continue
    rings.add Ring(pts: ring, main: islands.anyIt(it.main and ring.contains((it.lon, it.lat))))
shx.close; shp.close

# ------------------------------------------------------------------------------ the seas' limits
# Where two of the IHO's seas meet (Limits of Oceans and Seas, 1953, from Marine Regions): the
# grid of common.nim, each edge between two cells of different seas, joined into lines from
# corner to corner of the grid and simplified to a twentieth of a degree, so the steps of the
# grid become the straight lines the IHO draws.
type Corner = (int, int)   # a corner of the grid: column, row
var limits: seq[seq[(float, float)]]
block:
  let g = ihoGrid(raw)
  var links: Table[Corner, seq[Corner]]
  proc link(a, b: Corner) =
    links.mgetOrPut(a, @[]).add b
    links.mgetOrPut(b, @[]).add a
  for row in 0 ..< ihoH:
    for col in 0 ..< ihoW:
      let here = g.sea(row, col)
      if here < 0: continue
      let right = g.sea(row, col + 1)
      if right >= 0 and right != here: link((col + 1, row), (col + 1, row + 1))
      let up = g.sea(row + 1, col)
      if up >= 0 and up != here: link((col, row + 1), (col + 1, row + 1))
  var used: Table[(Corner, Corner), bool]
  proc lonLat(c: Corner): (float, float) = (ihoX0 + c[0].float * ihoStep, ihoY0 + c[1].float * ihoStep)
  proc walk(start, next: Corner): seq[(float, float)] =
    var (a, b) = (start, next)
    result.add lonLat(a)
    while true:
      used[(a, b)] = true; used[(b, a)] = true
      result.add lonLat(b)
      if links[b].len != 2: break
      let c = if links[b][0] == a: links[b][1] else: links[b][0]
      if used.hasKey((b, c)): break
      (a, b) = (b, c)
  for start, ends in links:   # lines from their ends (a corner where they meet or stop) first
    if ends.len != 2:
      for e in ends:
        if not used.hasKey((start, e)): limits.add walk(start, e)
  for start, ends in links:   # then the loops
    for e in ends:
      if not used.hasKey((start, e)): limits.add walk(start, e)
  limits = limits.mapIt(douglasPeucker(it, 0.05)).filterIt(it.len >= 2 and
    hypot(it[0][0] - it[^1][0], it[0][1] - it[^1][1]) + it.len.float * 0.01 > 0.15)   # not the crumbs

# ------------------------------------------------------------------------------ the names
# Where the names go, written by Claude: a sea's name by the longitude and latitude of its
# middle, on one or two lines; a main island's from its point, moved by so many points of the
# drawing (1000 wide) and running from there to the right (start), both ways (middle) or to
# the left (end).
# The Italian names of the seas are Claude's too, as in italiano.txt.
const seas = [("Alboran Sea", "Mare di Alborán", -2.8, 36.1), ("Balearic|Sea", "Mare delle|Baleari", 5.2, 41.25),
              ("Sea of|Sardinia", "Mare di|Sardegna", 6.5, 38.6), ("Ligurian Sea", "Mar Ligure", 8.3, 43.65),
              ("Tyrrhenian|Sea", "Mar|Tirreno", 12.4, 39.9), ("Adriatic|Sea", "Mare|Adriatico", 17.3, 41.75),
              ("Strait of|Sicily", "Canale di|Sicilia", 12.2, 36.3), ("Western|Basin", "Bacino|occidentale", 6.0, 37.3),
              ("Eastern|Basin", "Bacino|orientale", 20.6, 34.4), ("Ionian Sea", "Mar Ionio", 19.0, 37.55), ("Aegean Sea", "Mar Egeo", 25.0, 35.95),
              ("Libyan Sea", "Mar Libico", 24.0, 33.9), ("Levantine Sea", "Mar di Levante", 30.6, 33.6),
              ("Sea of Marmara", "Mar di Marmara", 28.4, 40.82)]
const names = [("Sicily", 0.0, 0.0, "middle"), ("Sardinia", 0.0, 0.0, "middle"),
               ("Corsica", 0.0, 0.0, "middle"), ("Cyprus", 0.0, 0.0, "middle"),
               ("Crete", 0.0, 0.0, "middle"), ("Mallorca", 0.0, -30.0, "middle"),
               ("Menorca", 16.0, 0.0, "start"), ("Ibiza", -14.0, 6.0, "end"),
               ("Malta", 0.0, 30.0, "middle"), ("Djerba", -14.0, 4.0, "end"),
               ("Corfu", -14.0, 0.0, "end"), ("Cephalonia", -14.0, 0.0, "end"),
               ("Zakynthos", -14.0, 12.0, "end"), ("Cres", -14.0, 14.0, "end"),
               ("Krk", 14.0, -6.0, "start"), ("Euboea", -14.0, -20.0, "end"),
               ("Lemnos", 0.0, -24.0, "middle"), ("Lesbos", 16.0, 0.0, "start"),
               ("Chios", 16.0, 4.0, "start"), ("Samos", 16.0, 12.0, "start"),
               ("Naxos", 0.0, 32.0, "middle"), ("Rhodes", 16.0, 10.0, "start"),
               ("Brač", -12.0, -16.0, "end"), ("Hvar", -14.0, 10.0, "end"), ("Korčula", -14.0, 36.0, "end"),
               ("Pag", -14.0, 6.0, "end"), ("Elba", -14.0, 0.0, "end"), ("Lefkada", -14.0, 0.0, "end"),
               ("Kythira", -14.0, 10.0, "end"), ("Andros", 14.0, -10.0, "start"), ("Icaria", 0.0, 28.0, "middle"),
               ("Kos", 14.0, 6.0, "start"), ("Karpathos", 14.0, 10.0, "start"), ("Thasos", 0.0, -24.0, "middle"),
               ("Gökçeada", 14.0, 0.0, "start")]

# ------------------------------------------------------------------------------ the drawings
# Equirectangular, east-west shrunk by the cosine of the map's middle latitude, 1000 wide.
proc draw(file: string, w, e, s, n: float, italian = false, seaNames = @seas, islandNames = @names,
          groups: seq[(string, string, float, float)] = @[], highlight: seq[string] = @[], fontSize = 27,
          every = false) =
  ## The land in the box, the main islands filled (or, with `highlight`, the islands named there),
  ## the other islands of the list a dot, the names of the seas and islands given, and `groups`,
  ## the names of groups of islands (English, Italian, longitude, latitude of their middle). With
  ## `every`, no names, no limits and nothing filled: a dot for each island of the list and a
  ## smaller one for each other island of a hectare or more (others.csv).
  let c = cos(((s + n) / 2).degToRad)
  let k = 1000 / ((e - w) * c)
  let height = round((n - s) * k).int
  proc xy(p: (float, float)): (float, float) = ((p[0] - w) * c * k, (n - p[1]) * k)
  proc f(v: float): string = formatFloat(v, ffDecimal, 1)
  proc path(ring: seq[(float, float)]): string =
    var last = (NaN, NaN)
    for p in ring:
      let q = xy(p)
      if abs(q[0] - last[0]) + abs(q[1] - last[1]) < 0.8: continue   # under a point of the drawing
      result.add (if result == "": "M" else: "L") & f(q[0]) & " " & f(q[1])
      last = q
    result.add "Z"
  var land, mainLand: string
  let lit = islands.filterIt(it.name in highlight)
  for r in rings:
    if r.pts.allIt(it[0] < w or it[0] > e or it[1] < s or it[1] > n): continue
    let mine = if every: false elif highlight.len == 0: r.main else: lit.anyIt(r.pts.contains(it.middle) or r.pts.contains((it.lon, it.lat)))
    if mine: mainLand.add r.pts.path else: land.add r.pts.path
  var svg = &"""<svg xmlns="http://www.w3.org/2000/svg" class="map" viewBox="0 0 1000 {height}" width="1000" height="{height}" font-size="{fontSize}">
<rect class="sea" width="100%" height="100%"/>
<path class="land" d="{land}"/>
<path class="main" d="{mainLand}"/>
"""
  if every:
    var csvo: CsvParser
    csvo.open(here / "others.csv")
    csvo.readHeaderRow()   # the description
    csvo.readHeaderRow()
    while csvo.readRow():
      let (x, y) = xy((csvo.rowEntry("lon").parseFloat, csvo.rowEntry("lat").parseFloat))
      svg.add &"""<circle cx="{f x}" cy="{f y}" r="3.5" class="other"/>"""
    csvo.close
    svg.add "\n"
    for i in islands:
      let (x, y) = xy(i.middle)
      svg.add &"""<circle cx="{f x}" cy="{f y}" r="6" class="listed"/>"""
    svg.add "\n</svg>\n"
    writeFile(output / file, svg)
    echo file, ": ", svg.len div 1024, " kB"
    return
  var lines = ""
  for l in limits:
    if l.allIt(it[0] < w or it[0] > e or it[1] < s or it[1] > n): continue
    let p = l.path
    lines.add p[0 ..< ^1]   # an open line, not a ring
  svg.add &"""<path class="limit" d="{lines}"/>""" & "\n"
  let inside = proc (i: Island): bool = i.lon in w .. e and i.lat in s .. n
  for i in islands:
    if (i.main and highlight.len == 0) or i.name in highlight or not inside(i): continue
    let (x, y) = xy((i.lon, i.lat))
    svg.add &"""<circle cx="{f x}" cy="{f y}" r="5" class="dot"/>""" & "\n"
  for (english, italiano, lon, lat) in seaNames:
    if lon notin w .. e or lat notin s .. n: continue
    let (x, y) = xy((lon, lat))
    let lines = (if italian: italiano else: english).split('|')
    let size = if english == "Sea of Marmara": 22 else: fontSize   # a small sea between islands
    for i, line in lines:
      let dy = (i.float - (lines.len - 1) / 2) * (size.float * 1.2) + size / 3
      svg.add &"""<text x="{f x}" y="{f y + dy}" text-anchor="middle" font-size="{size}" class="sea-name">{line}</text>""" & "\n"
  for (english, italiano, lon, lat) in groups:
    let (x, y) = xy((lon, lat))
    svg.add &"""<text x="{f x}" y="{f y + fontSize / 3}" text-anchor="middle" class="name">{(if italian: italiano else: english)}</text>""" & "\n"
  for (name, dx, dy, anchor) in islandNames:
    let i = islands.filterIt(it.name == name)[0]
    if not inside(i): continue
    let (x, y) = xy((i.lon, i.lat))
    svg.add &"""<text x="{f x + dx}" y="{f y + dy + fontSize / 3}" text-anchor="{anchor}" class="name">{(if italian: i.italian else: i.name)}</text>""" & "\n"
  svg.add "</svg>\n"
  writeFile(output / file, svg)
  echo file, ": ", svg.len div 1024, " kB"

# the south edge at 30° N, so the Gulf of Sidra, which reaches 30.2°, is on both
draw("map-west.svg", -6.0, 18.9, 30.0, 46.0)
draw("map-east.svg", 17.2, 36.3, 30.0, 41.5)
draw("map-west-it.svg", -6.0, 18.9, 30.0, 46.0, italian = true)
draw("map-east-it.svg", 17.2, 36.3, 30.0, 41.5, italian = true)
# every island: the 195 and the others of a hectare or more, as dots (map-every.svg)
draw("map-every.svg", -6.0, 36.5, 30.0, 46.5, every = true)

# Sicily and its islands, the ones of the list filled, and Malta nearby (map-sicily.svg).
const sicilyIslands = @["Sicily", "Pantelleria", "Lipari", "Salina", "Vulcano", "Lampedusa", "Favignana", "Stromboli",
                        "Marettimo", "Filicudi", "Ustica", "Levanzo"]
const sicilySeas = @[("Tyrrhenian|Sea", "Mar|Tirreno", 12.45, 38.65), ("Strait of|Sicily", "Canale di|Sicilia", 13.0, 36.5),
                     ("Ionian|Sea", "Mar|Ionio", 15.3, 36.3)]
const sicilyNames = @[("Sicily", 0.0, 0.0, "middle"), ("Ustica", 20.0, 0.0, "start"), ("Pantelleria", 22.0, 0.0, "start"),
                      ("Lampedusa", 22.0, 0.0, "start"), ("Malta", 0.0, 46.0, "middle"), ("Gozo", -20.0, 0.0, "end")]
const sicilyGroups = @[("Aeolian Islands", "Isole Eolie", 14.8, 39.0), ("Egadi Islands", "Isole Egadi", 12.32, 38.36)]
for (file, italian) in [("map-sicily.svg", false), ("map-sicily-it.svg", true)]:
  draw(file, 11.7, 15.8, 35.3, 39.1, italian, sicilySeas, sicilyNames, sicilyGroups, sicilyIslands, fontSize = 40)

# ------------------------------------------------------------------------------ the locators
# For the table of every island, by sea (stories/isole-tutte/): a small map of each of the IHO's
# seas in the whole Mediterranean, the sea filled (seas/<sea>.svg), and for each island a map of
# its sea's box with a dot where the island is (locators/<rank>.svg). The land is simplified to
# a size that suits each drawing, in whole points of it, and the smallest rings are left out, so
# a file is a kilobyte or two. A picture in a table does not take the page's colours, so they are
# the Minoan look's, the first look of these pages: the paper for the sea, the ink mixed into the
# paper for the land (a quarter of it), dolphin blue for the sea of the row, a terracotta dot.
proc mix(a, b: string, share: float): string =
  ## `a` mixed into `b`, `share` of `a` (like CSS `color-mix(in srgb, a share, b)`), as #RRGGBB.
  result = "#"
  for k in 0 .. 2:
    let (x, y) = (parseHexInt(a[1 + 2 * k .. 2 + 2 * k]), parseHexInt(b[1 + 2 * k .. 2 + 2 * k]))
    result.add toHex(int(round(x.float * share + y.float * (1 - share))), 2)

block:
  let (seaColour, landColour, mineColour, dotColour) = (minoanLook.paper,
    mix(minoanLook.ink, minoanLook.paper, 0.25), mix(minoanLook.secondary, minoanLook.paper, 0.55),
    minoanLook.primary)
  type Frame = object
    w, e, s, n, c, k: float   # the box, and the drawing's scale (equirectangular, as the maps)
    width, height: int
  proc frame(w, e, s, n: float, width: int): Frame =
    result = Frame(w: w, e: e, s: s, n: n, c: cos(((s + n) / 2).degToRad), width: width)
    result.k = width.float / ((e - w) * result.c)
    result.height = round((n - s) * result.k).int
  proc xy(f: Frame, p: (float, float)): (int, int) =
    (round((p[0] - f.w) * f.c * f.k).int, round((f.n - p[1]) * f.k).int)
  proc path(f: Frame, ring: seq[(float, float)]): string =
    ## A ring simplified to about a point of the drawing, or nothing when it is under three.
    let pts = douglasPeucker(ring, 1.5 / f.k)
    var last = (-99999, -99999)
    var n = 0
    var d = ""
    for p in pts:
      let q = f.xy(p)
      if q == last: continue
      d.add (if n == 0: "M" else: "L") & $q[0] & " " & $q[1]
      last = q
      inc n
    if n >= 3: d & "Z" else: ""
  proc landOf(f: Frame): string =
    ## The land in the box: the rings that reach into it and are larger than three points.
    for r in rings:
      let xs = r.pts.mapIt(it[0])
      let ys = r.pts.mapIt(it[1])
      if xs.max < f.w or xs.min > f.e or ys.max < f.s or ys.min > f.n: continue
      if (xs.max - xs.min + ys.max - ys.min) * f.k < 4: continue
      result.add f.path(r.pts)
  proc svg(f: Frame, body: string): string =
    &"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {f.width} {f.height}" width="{f.width}" height="{f.height}">""" &
      &"""<rect width="100%" height="100%" fill="{seaColour}"/>{body}</svg>""" & "\n"

  # each sea, filled, in the whole Mediterranean
  let whole = frame(-6.0, 36.5, 30.0, 46.5, 160)
  let land = whole.landOf
  var boxes: Table[string, Frame]
  createDir(output / "seas")
  for sea in ihoSeas:
    let doc = parseFile(raw / "iho" / sea.replace(' ', '_') & ".jsonld")
    let seaRings = wktRings(doc["mr:hasGeometry"][0]["gsp:asWKT"].getStr)
    var (w, e, s, n) = (180.0, -180.0, 90.0, -90.0)
    var filled = ""
    for ring in seaRings:
      for p in ring: (w = min(w, p[0]); e = max(e, p[0]); s = min(s, p[1]); n = max(n, p[1]))
      filled.add whole.path(ring)
    writeFile(output / "seas" / (sea.replace(' ', '_') & ".svg"), whole.svg(
      &"""<path d="{filled}" fill="{mineColour}" fill-rule="evenodd"/><path d="{land}" fill="{landColour}"/>"""))
    # the sea's box, a little larger, and wider than high, for the islands' maps
    let (mx, my) = (max(0.4, (e - w) * 0.08), max(0.4, (n - s) * 0.08))
    (w, e, s, n) = (w - mx, e + mx, s - my, n + my)
    let c = cos(((s + n) / 2).degToRad)
    if (e - w) * c < (n - s) * 1.6:   # at least 1.6 times as wide as high
      let grow = ((n - s) * 1.6 / c - (e - w)) / 2
      (w, e) = (w - grow, e + grow)
    boxes[sea] = frame(w, e, s, n, 120)
  var seaLand: Table[string, string]
  for sea, f in boxes: seaLand[sea] = f.landOf
  createDir(output / "locators")
  var largest = 0
  for i in islands:
    if i.sea notin boxes: continue
    let f = boxes[i.sea]
    let (x, y) = f.xy((i.lon, i.lat))
    let text = f.svg(&"""<path d="{seaLand[i.sea]}" fill="{landColour}"/>""" &
      &"""<circle cx="{x}" cy="{y}" r="5" fill="{dotColour}" stroke="{seaColour}" stroke-width="1.5"/>""")
    largest = max(largest, text.len)
    writeFile(output / "locators" / ($i.rank & ".svg"), text)
  echo "seas: ", ihoSeas.len, " maps; locators: ", islands.len, ", the largest ", largest div 1024, " kB"
src/common.nim 112 lines
## What fetch.nim and extract.nim share: the list of islands as Wikipedia has it, which of them
## are the story's main islands, wikitext as plain text, and CSV lines. Standard library only.
import std/[re, strutils, os, json, algorithm, math]
export re, strutils, os

type ListRow* = object
  title*, label*, town*: string   ## the island's page, its name in the list, its main town's page
  km2*: float                     ## its area in the list (0 when the list has none)

proc listRows*(list: string): seq[ListRow] =
  ## The rows of the list's table "By area", in its order.
  let byArea = list[list.find("== By area ==") ..< list.find("==By population")]
  for chunk in byArea.split("\n|-")[1 .. ^1]:
    var links, labels: seq[string]
    for m in chunk.findAll(re"\[\[[^\]]+\]\]"):
      let parts = m[2 .. ^3].split('|')
      if parts[0].toLowerAscii.startsWith("file"): continue
      links.add parts[0].strip
      labels.add parts[^1].strip
    if links.len == 0: continue
    var area: array[1, string]
    let km2 = if chunk.find(re"\{\{convert\|([\d,.]+)\|km2", area) >= 0: area[0].replace(",", "").parseFloat
              else: 0.0
    result.add ListRow(title: links[0], label: labels[0], town: links[^1], km2: km2)

proc isMain*(r: ListRow): bool =
  ## The story's main islands: the 35 largest, down to Elba (224 km²), Pietro's pick, so the
  ## story reaches the Tuscan islands. Cyprus has no area in the list.
  r.km2 >= 224 or r.title == "Geography of Cyprus"

const climateAlso* = [("Krk", "Rijeka"), ("Cres", "Mali Lošinj"), ("Brač", "Split, Croatia"), ("Pag (island)", "Zadar"),
                      ("Korčula", "Dubrovnik"), ("Andros, Greece", "Ermoupoli"), ("Ikaria", "Samos")]
  ## Islands whose town and page have no weather box: the closest page with one (by the page
  ## Wikidata knows: Pag (island), Ikaria).

const ihoSeas* = ["Strait of Gibraltar", "Alboran Sea", "Balearic Sea", "Ligurian Sea", "Tyrrhenian Sea",
                  "Mediterranean Sea - Western Basin", "Adriatic Sea", "Ionian Sea", "Aegean Sea",
                  "Mediterranean Sea - Eastern Basin", "Sea of Marmara"]
  ## The seas of the IHO's Limits of Oceans and Seas (1953) in the Mediterranean, west to east.

proc wktRings*(wkt: string): seq[seq[(float, float)]] =
  ## The rings of a WKT polygon or multipolygon (outer rings and holes alike), as (lon, lat).
  for m in wkt.findAll(re"\([^()]+\)"):
    var ring: seq[(float, float)]
    for pair in m[1 .. ^2].split(','):
      let xy = pair.splitWhitespace
      if xy.len >= 2: ring.add (xy[0].parseFloat, xy[1].parseFloat)
    if ring.len >= 3: result.add ring

proc csvLine*(fields: openArray[string]): string =
  ## One CSV line: a field with a comma or a quote goes in quotes.
  var cells: seq[string]
  for x in fields:
    cells.add(if ',' in x or '"' in x or '\n' in x: '"' & x.replace("\"", "\"\"") & '"' else: x)
  cells.join(",")

proc writeCsv*(path, comment: string, header: openArray[string], rows: seq[seq[string]]) =
  ## A CSV whose first line is a `#` comment naming its sources.
  var lines = @["# " & comment, header.csvLine]
  for r in rows: lines.add r.csvLine
  writeFile(path, lines.join("\n") & "\n")
  echo path.extractFilename, ": ", rows.len, " rows"

proc plain*(s: string): string =
  ## The text of some wikitext: links as their label, no templates, tags, refs or bold.
  s.replace(re"<ref[^>]*/>", "").replace(re"(?s)<ref.*?</ref>", "")
   .replacef(re"\[\[(?:[^|\]]*\|)?([^\]]*)\]\]", "$1")
   .replace(re"\{\{[^{}]*\}\}", "").replace(re"\{\{.*", "").replace(re"\[https?://[^\]]*\]", "")
   .replace(re"<[^>]+>", " ").replace(re"\(\s*\)", "").replace(re"'''?", "")
   .replace("&nbsp;", " ").replace(re"\s+", " ").strip

proc number*(s: string): string =
  ## The first number in a piece of wikitext, without thousands commas; "" when there is none.
  var m: array[1, string]
  let t = s.replace(re"<[^>]+>.*", "").replace("−", "-").replace("&minus;", "-")
  if t.find(re"(-?[\d,]*\.?\d+)", m) >= 0: m[0].replace(",", "") else: ""

type IhoGrid* = object
  ## The IHO's seas painted on a grid of 0.02 degrees (about 2 km), from 6° W and 30° N: each
  ## cell holds the index of its sea in `ihoSeas`, or -1 (land, or outside every sea).
  cells*: seq[int8]
const ihoStep* = 0.02
const (ihoX0*, ihoY0*, ihoW*, ihoH*) = (-6.0, 30.0, 2150, 850)

proc ihoGrid*(raw: string): IhoGrid =
  ## The grid, from the seas' polygons fetch.nim downloads from Marine Regions (`raw/iho/`):
  ## each row of cells is filled between the crossings of its middle with the polygons' edges.
  result.cells = newSeq[int8](ihoW * ihoH)
  for c in result.cells.mitems: c = -1
  for s, sea in ihoSeas:
    let doc = parseFile(raw / "iho" / sea.replace(' ', '_') & ".jsonld")
    let seaRings = wktRings(doc["mr:hasGeometry"][0]["gsp:asWKT"].getStr)
    var cross = newSeq[seq[float]](ihoH)
    for ring in seaRings:
      for i in 0 ..< ring.len:
        let (x1, y1) = ring[i]
        let (x2, y2) = ring[(i + 1) mod ring.len]
        let lo = max(0, int(ceil((min(y1, y2) - ihoY0) / ihoStep - 0.5)))
        let hi = min(ihoH - 1, int(floor((max(y1, y2) - ihoY0) / ihoStep - 0.5)))
        for row in lo .. hi:
          let y = ihoY0 + (row.float + 0.5) * ihoStep
          if (y1 > y) != (y2 > y): cross[row].add x1 + (y - y1) * (x2 - x1) / (y2 - y1)
    for row in 0 ..< ihoH:
      cross[row].sort
      for k in countup(0, cross[row].len - 2, 2):
        let a = max(0, int(ceil((cross[row][k] - ihoX0) / ihoStep - 0.5)))
        let b = min(ihoW - 1, int(floor((cross[row][k + 1] - ihoX0) / ihoStep - 0.5)))
        for col in a .. b: result.cells[row * ihoW + col] = s.int8

proc sea*(g: IhoGrid, row, col: int): int =
  ## The sea of a cell (-1 for land, outside every sea, or outside the grid).
  if row in 0 ..< ihoH and col in 0 ..< ihoW: g.cells[row * ihoW + col].int else: -1

Outlines

OpenStreetMap's land polygons (© OpenStreetMap contributors, under the ODbL) follow the coast to a few metres, and are rebuilt every day by osmdata.openstreetmap.de as one shapefile of the world. extract.nim reads it with the standard library (memfiles, the file's boxes first, so only the polygons around the Mediterranean are read) and finds about 25,000 of them. An island takes the one that holds its point on Wikidata, when its area is not far from the list's; else the closest such polygon within 5 km (a point can fall in a bay, just off the coast, or on an islet beside the island, as Ilovik's does). Then each outline is simplified to at most 120 points and written in kilometres from its middle, so a shape keeps its proportions. The outlines first came from Natural Earth at 1:10 million, which draws a small island with a couple of dozen points and left 23 islands without one: compared side by side, OpenStreetMap was much better for every island under about 50 km².

islandsshare
the polygon holds its point18997%189
the closest, within 5 km63%6
all195100%
var counts = initOrderedTable[string, int]()
for i in 0 ..< islands.nrows:
  let how = if islands["matched", i].isNull: "no outline" elif ($islands["matched", i]).startsWith("closest"): "the closest, within 5 km" else: "the polygon holds its point"
  counts.mgetOrPut(how, 0).inc
var rows: seq[tuple[outline: string, islands: int, share: float]]
for k, v in counts: rows.add (k, v, v / islands.nrows)
let t = tabella(rows, rownameCol = "outline"):
  optCssTheme()
  colsAdd "bar", rows.mapIt(toValue(it.islands))
  fmtNanoplot "bar", plotType = "bar", plotHeight = "1.1em",
    options = nanoplotOptions(dataBarFillColor = tint("--secondary"), dataBarStrokeColor = tint("--secondary"))
  fmtPercent "share", decimals = 0
  colsLabel:
    outline: ""
    bar: ""
  grandSummaryRows:
    all: agg.sum
    columns = ["islands", "share"]
    missingText = ""
nbTable t

A check that the right polygon was found: its area against the area in the list. For the 35 main islands they agree within a few percent; the polygon is a drawing at one scale, so it misses bays and rocks, and the list's areas are rounded or come from other surveys.

area, km2difference
listoutline
Djerba523510−2.6%
Korčula276270−2.2%
Ibiza577566−1.9%
Sicily25,83425,350−1.9%
Kos290285−1.6%
Sardinia24,10023,712−1.6%
Hvar300296−1.3%
Lefkada303299−1.3%
Crete8,3128,211−1.2%
Mallorca3,6403,603−1.0%
Elba224222−1.0%
Pag285282−0.9%
Icaria255253−0.8%
Krk406403−0.8%
Kythira278276−0.8%
Corfu592588−0.7%
Andros380377−0.7%
Cephalonia781776−0.7%
Cres406403−0.7%
Karpathos301299−0.7%
Menorca694690−0.6%
Lemnos476473−0.6%
Cyprus9,2519,198−0.6%
Zakynthos406404−0.5%
Samos476474−0.5%
Lesbos1,6301,623−0.4%
Euboea3,6553,640−0.4%
Chios842839−0.4%
Brač395393−0.3%
Rhodes1,3981,393−0.3%
Naxos428427−0.3%
Malta246245−0.2%
Corsica8,6818,662−0.2%
Thasos3793810.5%
Gökçeada2792810.7%
var d = TableData()
d.addColumn("island", toSeq(0 ..< main.nrows).mapIt(main["island", it]))
d.addColumn("list", toSeq(0 ..< main.nrows).mapIt(main["km2", it]))
var outlines, ratio: seq[Value]
for k in 0 ..< main.nrows:
  let i = islandRow(main["title", k])
  outlines.add islands["outline_km2", i]
  ratio.add toValue(islands["outline_km2", i].toFloat / main["km2", k].toFloat - 1)
d.addColumn("outline", outlines)
d.addColumn("difference", ratio)
let t = tabella(d, rownameCol = "island"):
  optCssTheme()
  fmtInteger ["list", "outline"]
  fmtPercent "difference", decimals = 1
  dataColor "difference", palette = palette("rdbu"), domain = (-0.1, 0.1)
  tabSpanner "area, {{km^2}}", ["list", "outline"]
  rowOrder "difference"
nbTable t

dataColor colours the difference on a blue–white–red scale fixed at ±10%, so a pale cell is a good match: blue where the outline is smaller than the list says, red where it is larger. The spanner's label has gt's units syntax, {{km^2}}.

Length

Areas are hard to picture; lengths are not. An island's length here is the longest straight line between two points of its outline: in geometry the diameter of a shape, in the study of particles the maximum Feret diameter, the widest a caliper opens around it as it turns. It is not in the data: the page of all 195 islands computes it from the outline, every pair of its points, at most 120 × 119 / 2 = 7,140 of them for an island:

proc length(xs, ys: seq[float]): float =
  for a in 0 ..< xs.len:
    for b in a + 1 ..< xs.len: result = max(result, hypot(xs[a] - xs[b], ys[a] - ys[b]))

The outline is simplified, so the length can be a little short of the true one: Sicily's is 290 km, Sardinia's 269 km, Crete's 255 km.

Highest points

Wikidata gives an island's elevation (P2044) and, for some, its highest point (P610), a peak with an elevation of its own. The highest of the two is kept, since P2044 is sometimes another height: Sardinia's is 384 m, its highest point Punta La Marmora, 1,834 m. For many small islands P2044 is the height of the town, not of the island: Lipari's and Pantelleria's 5 m, Favignana's 6 m, Ustica's 49 m. Comparing every island without a P610 with its article on Wikipedia found 34 such heights, wrong or missing: they are written by hand in extract.nim, each from the infobox or the text of the article, in English, or in Italian, French or Greek where those say more (Pantelleria 836 m, Lipari 602 m, Favignana 314 m, Ustica 244 m, Porquerolles 142 m). Twenty-one islands still have no height.

Seas

Each island's sea comes from Wikidata, which puts an island in or beside a body of water (property P206): often a gulf or a strait, taken to the sea it is part of (the Saronic Gulf to the Aegean). When Wikidata says only "the Mediterranean", or nothing, extract.nim uses the seas that Wikipedia's article on the island names, written into it by Claude for 20 islands, and else the sea of the closest island that has one, within 30 km. An island on several seas keeps them all: Sicily is on three.

islands
Wikidata166
Wikipedia's article20
the closest island's5
none: the open Mediterranean4
all195
var counts = initOrderedTable[string, int]()
for i in 0 ..< islands.nrows:
  let how = if islands["sea_how", i].isNull: "none: the open Mediterranean"
            elif ($islands["sea_how", i]).startsWith("as "): "the closest island's"
            else: $islands["sea_how", i]
  counts.mgetOrPut(how, 0).inc
var rows: seq[tuple[sea: string, islands: int]]
for k, v in counts: rows.add (k, v)
rows.sort(proc (a, b: auto): int = cmp(b.islands, a.islands))
let t = tabella(rows, rownameCol = "sea"):
  optCssTheme()
  colsLabel:
    sea: "the sea from"
  grandSummaryRows:
    all: agg.sum
    columns = ["islands"]
    missingText = ""
    fmtInteger()
nbTable t

The IHO's seas

Wikidata's seas are many, and overlap: a gulf in a sea in a basin. The page of all 195 islands needs one sea per island, from a map that leaves no water out: the International Hydrographic Organization's Limits of Oceans and Seas (1953), whose outlines Marine Regions publishes (CC BY 4.0). It divides the Mediterranean into eleven: nine seas and straits, and the two basins, western and eastern, for the open water the others leave.

fetch.nim downloads each sea's outline, common.nim draws them on a grid of 0.02° (about 2 km, 2,150 by 850 cells), and an island takes the sea of most of the cells around its coast (sixty of its points, and the cells within one, three, eight or twenty of them, until one is in a sea). The same grid gives the maps their dashed lines: each edge between two cells of different seas, joined into lines and simplified to a twentieth of a degree.

# Every island of the sea, by the IHO's sea: the other islands, not the list's, of a hectare or
# more (smaller ones are mostly rocks, and some piers and breakwaters drawn as land).
rd(stage / "every_island.csv")
  .select(col.title, col.km2.num, col.iho_sea)
  .filter(col.title.isNull and col.km2 >= 0.01)
  .groupBy(col.iho_sea)
  .agg(len().alias("others"), col.km2.sum.round(1).alias("others_km2"))
  .sort("iho_sea").collect
  .save("seas.csv", "The other islands of each sea, as the IHO draws them (Marine Regions, CC BY 4.0): OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL) that are not one of the list's 195, of 0.01 km² or more; how many (others) and their km² (others_km2).")
Islands by the IHO's seas
of a hectare or more
of the listthe other islands
otherstheir km2
Aegean Sea89798272.6
Adriatic Sea43597195.2
Eastern Basin1220997.6
Western Basin815229.2
Tyrrhenian Sea2113654.9
Ionian Sea1313949.8
Balearic Sea56011.3
Sea of Marmara42817.4
Alboran Sea·164.7
Ligurian Sea·70.7
Strait of Gibraltar·10.1
all1952,143734
let others = story("seas.csv")
var listed = initCountTable[string]()
for i in 0 ..< islands.nrows: listed.inc $islands["iho_sea", i]
var rows: seq[tuple[sea: string, listed: int, others: int, km2: float]]
for j in 0 ..< others.nrows:
  if others["iho_sea", j].isNull: continue
  let sea = $others["iho_sea", j]
  rows.add (sea.replace("Mediterranean Sea - ", ""), listed[sea], others["others", j].toFloat.int, others["others_km2", j].toFloat)
rows.sort(proc (a, b: auto): int = cmp(b.listed + b.others, a.listed + a.others))
let t = tabella(rows, rownameCol = "sea"):
  tabHeader "Islands by the IHO's seas", "of a hectare or more"
  optCssTheme()
  fmtNumber ["km2"], decimals = 1
  subZero ["listed"], zeroText = "·"
  colsLabel:
    sea: ""
    listed: "of the list"
    others: "others"
    km2: "their {{km^2}}"
  tabSpanner "the other islands", ["others", "km2"]
  grandSummaryRows:
    all: agg.sum
    columns = ["listed", "others", "km2"]
    missingText = ""
    fmtInteger()
nbTable t

The count of the list's islands is made on the page from islands.csv, with a CountTable; the others are seas.csv. The Aegean has the most islands, and the most land outside the list.

Every island

The list stops at 5.5 km². To say how many islands a country or a sea has, extract.nim keeps every polygon of OpenStreetMap's land in the sea: 24,358, from Sicily to rocks of a few square metres (not the Peloponnese and Kassandra, which only a canal cuts off, and not the islands in lakes, which OpenStreetMap's land polygons fill as land). The sea is the box of the map, from Gibraltar to the Levant, less the Atlantic, the Bay of Biscay, the Black Sea and the Red Sea, which the box reaches too: eight islets on Spain's and France's coast of the Bay of Biscay were counted until a review of the story saw them on the map. Each gets the list's island it is, if any; a country, from Natural Earth's countries at 1:10 million (public domain), the one that holds its middle or else the closest; the people Wikidata counts on it; and its sea. The story counts those of a hectare or more, 0.01 km²: smaller ones are mostly rocks, and some are piers, breakwaters and harbour works drawn as land, as around the port of Genoa. The closest country is not always the right one: Alborán, seven hectares in the middle of its sea, is Spain's, and closer to Morocco; Agathonisi and Kastellorizo are Greece's, and closer to Turkey. The list's islands take the list's country; Alborán is set by hand.

# Every island of the sea, by country: extract.nim's rings of OpenStreetMap, each with its country
# from Natural Earth and its people on Wikidata; the list's islands take the list's country and
# area and people (Natural Earth's closest country for Agathonisi and Kastellorizo is Turkey).
let listed = islands.lazy
  .select(col.title, col.code.alias("list_code"), col.km2.alias("list_km2"), col.population.cast(Float64).alias("list_people"), col.main)
rd(stage / "every_island.csv")
  .select(col.title, col.code, col.km2.num, col.wd_people.num)
  .join(listed, on = ["title"], how = JoinType.Left)
  .withColumns(col.list_code.fillNull(col.code).alias("code"), col.list_km2.fillNull(col.km2).alias("km2"),
               col.list_people.fillNull(col.wd_people).alias("people"))
  .groupBy(col.code)
  .agg(len().alias("islands"), col.km2.filter(col.km2 >= 0.01).len.alias("hectare"),
       col.title.count.alias("listed"), col.main.filter(col.main).len.alias("main"),
       col.km2.sum.round(1).alias("km2"), col.people.sum.cast(Int64).alias("people"),
       col.people.count.alias("peopled"))
  .sort("km2", descending = true).collect
  .save("countries.csv", "Every island of the Mediterranean, by country: OpenStreetMap's land polygons in the sea (© OpenStreetMap contributors, ODbL; not the Peloponnese and Kassandra, cut off by canals, nor islands in lakes), the country from Natural Earth (public domain), the area and people from Wikipedia's list for its 195 islands, and for the others the polygon's area and the people on Wikidata (P1082). islands: every polygon; hectare: those of 0.01 km² or more; listed and main: of the 195 and the 35; peopled: those with a count.")

Maps

map.nim draws the maps from the same land: every polygon in the map's box, simplified with Douglas–Peucker to a hundredth of a degree, about a kilometre; the 35 main islands filled, the others of the list a dot, the names where Claude placed them, and the IHO's limits dashed. The drawing names its parts (sea, land, main, dot, limit) and the page's theme colours them, so the maps change with the look: the west and the east of the sea, in English and in Italian, and Sicily with its islands, where the islands of Sicily are filled instead of the main ones. A last one, of every island, has no names and nothing filled: a blue dot for each of the 195, and a smaller one for each of the 2,142 others of a hectare or more, from others.csv.

For the page of all 195 islands it draws two small maps more: each sea in the whole Mediterranean (160 points wide) and each island in its sea, a dot in the box of its sea (120 wide), simplified to a point and a half of the drawing so each is a few kilobytes. A picture in a table does not take the page's colours, so these use the Minoan look's, from theme.nim.

Counting passengers

Wikidata has 15,637 counts of passengers for the airports around the Mediterranean: by year, by month, and sometimes the same year twice, from different sources. Of the islands' 64 airports, 3,679 counts; 1,409 of them are for a whole year. A year counts once, with its largest count, since a smaller one is usually part of the year:

let yearly = rd(stage / "passengers.csv")
  .filter(col.precision == "9")
  .withColumns(col.date.str.slice(0, 4).cast(Int64).alias("year"), col.passengers.int64)
  .groupBy(col.iata, col.year).agg(col.passengers.max)
  .join(airports.select(col.iata, col.title, col.airport), on = ["iata"])

An island's passengers are the sum of its airports. Airfields and air bases are counted for a few years only, and would leave holes in every line, so an island that has an airport with a million passengers in some year leaves out those that never had one; and a year counts only when every airport left has a count. One expression of nanuq, with a window (over), says which airports stay:

let active = yearly
  .groupBy(col.title, col.iata).agg(col.passengers.max.alias("most"))
  .filter(col.most >= 1_000_000 or col.most.max.over(col.title) < 1_000_000)
  .select(col.title, col.iata)

Long to wide

The weather boxes give one number per island, measure and month: 1,506 rows. The story wants a row per island and measure, and a column per month, for a heat table and a nanoplot. That is a pivot, as in Polars:

rd(stage / "climate.csv")
  .withColumns(col.value.num, format("m{}", col.month.str.zfill(2)).alias("m"))
  .collect
  .pivot(on = "m", index = ["title", "measure"], values = "value", aggregateFunction = PivotAgg.First, sortColumns = true)
  .lazy.join(islands.lazy.select(col.title, col.island), on = ["title"])
  .select(col.island, col.title, col.measure, col("^m\\d\\d$"))
  .sort(["title", "measure"]).collect
  .save("climate.csv", "Monthly normals of the main islands (m01 January ... m12 December): high_c, mean_c and low_c (°C), rain_mm, rain_days, sun_hours, sea_c (sea temperature, where a page has it). From the weather boxes of Wikipedia (stations.csv says which).")

The same turns twenty years of unemployment into twenty columns, with one more row: the median of all the regions of the list, a group by year.

The tables

Eleven files, in docs/stories/data/isole/, each with a first line that says what it is made from; and three written by Claude, the AI that made these pages.

rowscolumns
made by process.nim
islands.csv19529The 195 islands of Wikipedia's List of islands in the Mediterranean
main.csv3526The 35 main islands
countries.csv228Every island of the Mediterranean, by country
seas.csv113The other islands of each sea, as the IHO draws them
others.csv2,1435The islands of the Mediterranean that are not one of the list's 195, of 0.01 km² or more
heritage.csv296World Heritage properties on the islands
airports.csv9875Passengers of each airport on the islands, by year
passengers.csv6155Passengers of the islands' airports by year, 2000 on
climate.csv18615Monthly normals of the main islands
stations.csv433Where each main island's climate comes from
unemployment.csv1721Unemployment rate
written by Claude
regions.csv354The main islands' country and NUTS 2 region
history.csv359The main islands' history in a line
highlights.csv357One thing to see
var files: seq[tuple[file: string, rows: int, columns: int, about: string]]
for f in ["islands.csv", "main.csv", "countries.csv", "seas.csv", "others.csv", "heritage.csv", "airports.csv", "passengers.csv",
          "climate.csv", "stations.csv", "unemployment.csv", "regions.csv", "history.csv", "highlights.csv"]:
  let d = story(f)
  files.add (f, d.nrows, d.ncols, about(f).split(": ")[0].split(". ")[0].split(" (")[0].split(", with")[0].split(", one")[0])
let t = tabella(files, rownameCol = "file"):
  optCssTheme()
  fmtInteger ["rows", "columns"]
  colsLabel:
    file: ""
    about: ""
  tabStyle style.text(size = "12px") & style.css("overflow-wrap: anywhere"), loc.body(cols("about"))
  tabRowGroup "made by process.nim", toSeq(0 .. 10)
  tabRowGroup "written by Claude", [11, 12, 13]
  rowGroupOrder ["made by process.nim", "written by Claude"]
nbTable t

The largest is islands.csv, a row per island of the list, with its outline as two columns of numbers. A preview of its first and last rows, every column formatted by what is in it:

islandcountrykm2populationseaoutline_km2
1SicilyItaly25,8345MTyrrhenian Sea; Strait of Sicily; Ionian Sea25,349.6
2SardiniaItaly24,1001.7MTyrrhenian Sea; Sea of Sardinia23,712
3CyprusCyprus9,2511.3MLevantine Sea9,198.3
4..193
194IlovikCroatia5.585Adriatic Sea5.5
195PetalasGreece5.50Ionian Sea5.3
let t = tabellaPreview(islands, topN = 3, bottomN = 2):
  optCssTheme()
  colsHide ["rank", "title", "x", "y", "wikidata", "native", "matched", "town", "archipelago", "main",
            "lat", "lon", "elevation", "coast_km", "points", "heritage", "airports", "code", "italian",
            "iho_sea", "clon", "clat", "sea_how"]
  fmtAuto(lgNumPref = "suf")
  subMissing everything(), missingText = ""
  tabOptions(tableFontSize = "12px")
nbTable t

fmtAuto picks a format for each column from its values: integers with separators, decimals as many as needed. tabellaPreview shows the first and last rows of a big table, with the place of each and a line for the rest; most of its columns are hidden to fit a phone.

Checked

Every time this page is built, it checks the tables against each other. A check that fails shows a cross:

the list has 195 islands, in order of area
every island of the list has one of the IHO's seas
every main island has an outline
their outlines' areas are within 10% of the list's
every main island has twelve monthly highs
every main island but Djerba has a region
the heritage table and the islands' counts agree
passengers are counted once per island and year
let pax = story("passengers.csv")
let clim = story("climate.csv")
let sites = story("heritage.csv")
proc has(d: TableData, col, v: string): bool = toSeq(0 ..< d.nrows).anyIt($d[col, it] == v)
let mains = toSeq(0 ..< main.nrows).mapIt($main["title", it])
let worst = toSeq(0 ..< main.nrows).mapIt(abs(islands["outline_km2", islandRow(main["title", it])].toFloat / main["km2", it].toFloat - 1)).max
var siteSum = 0
for i in 0 ..< islands.nrows: siteSum += islands["heritage", i].toFloat.int
let checks = @[
  ("the list has 195 islands, in order of area", islands.nrows == 195 and toSeq(1 ..< islands.nrows).allIt(islands["km2", it].toFloat <= islands["km2", it - 1].toFloat)),
  ("every island of the list has one of the IHO's seas", toSeq(0 ..< islands.nrows).allIt(not islands["iho_sea", it].isNull)),
  ("every main island has an outline", toSeq(0 ..< main.nrows).allIt(not islands["x", islandRow(main["title", it])].isNull)),
  ("their outlines' areas are within 10% of the list's", worst < 0.10),
  ("every main island has twelve monthly highs", mains.allIt(clim.has("title", it))),
  ("every main island but Djerba has a region", toSeq(0 ..< main.nrows).allIt(main["region", it].isNull == (main["island", it] == "Djerba"))),
  ("the heritage table and the islands' counts agree", siteSum == sites.nrows),
  ("passengers are counted once per island and year", toSeq(1 ..< pax.nrows).allIt(pax["title", it] != pax["title", it - 1] or pax["year", it].toFloat > pax["year", it - 1].toFloat))]
var d = TableData()
d.addColumn("ok", checks.mapIt(toValue(if it[1]: "circle-check" else: "circle-xmark")))
d.addColumn("check", checks.mapIt(toValue(it[0])))
let t = tabella(d):
  optCssTheme()
  fmtIcon "ok", fillColor = tint("--success")
  tabStyle style.text(color = tint("--primary-text")), loc.body(rows = where(it.ok == "circle-xmark"))
  colsLabel:
    ok: ""
    check: ""
nbTable t

What nanuq did well, and where it pinched

This is nanuq's second dataset made end to end, after FOSDEM's, and a smaller one: about 150 lines of nanuq, which run in under a second.

Well. Joins on names read as in Polars, and a left join keeps every island when a source has nothing for it. A window, col.most.max.over(col.title), says in one line which airports an island keeps. pivot turned the long weather and unemployment tables wide, with PivotAgg.First and sorted columns. Reading every column as text (inferSchemaLength = some(0)) and casting with strict = false gave each column the type decided here, not guessed from its first rows.

Pinched. pivot on a lazy frame needs the new columns listed beforehand, so the climate goes through collect first. sort with several keys takes nullsLast as a list, even when one value is meant for all of them. And writeCsv writes no comment line, so save adds it afterwards, as in FOSDEM's process.nim.