Nanuq dev log · 1 November 2026

Above 4000

Eighty-two summits, eight treks, and every mountain range on Earth.

Explainer · Nanuq 0.5 · built with Nanuq 0.6.1, Polars 2.1.0 and Nim 2.2.4 · rendered with nimib

The code this page talks about is folded under Source files, at the end.

Sunset view west from above Craveggia towards Monte Rosa, Dom and Weissmies, with peak labels
Val Vigezzo, about 400 m above Craveggia (46.150°N 8.494°E, 1304 m), looking west in the late afternoon of 1 November 2026, while the author read a draft of this post. Peak names and heights are the labels of a peak-identification app; six of the labelled summits are on the UIAA list of 4000ers: Piramide Vincent, Dufourspitze, Strahlhorn, Dom, Weissmies and Lagginhorn. Dufourspitze is about 54 km away. Photo: Pietro Peterlongo.
setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, fmtStrLengths = 40, floatPrecision = 1)

Every step of this post is shown twice: 👑 in Nim with Nanuq, and 🐍 in Python with py-polars, in tabs (the choice sticks for the whole page). The Python version came first, while Nanuq 0.5 was being built, and its outputs are recorded next to its code; the Nim outputs are the ones this page computed, and the page build checks that they are the same. The charts and maps are Plotly figures, made with nim-plotly in Nim and Plotly in Python, from the same data.

1. Eighty-two summits↑ contents

How many mountains in the Alps are higher than 4000 metres? It depends on what you call a mountain. Mont Blanc has a dozen bumps above 4000 m on its shoulders; is each one a summit? In 1994 the UIAA, the international federation of mountaineering clubs, settled it with an official list of 82 four-thousanders, using a mix of topography (how far a peak rises above the col that joins it to a higher one) and mountaineering judgement.

Wikipedia has the list as a table. We saved it as a CSV exactly as it comes, footnote markers and all.

let raw = readCsv("data/uiaa_4000ers_raw.csv").filter(col("Nr.").isNotNull)
echo raw.glimpse(maxItemsPerColumn = 3)
Rows: 82
Columns: 10
$ Nr.                               1.0, 2.0, 3.0
$ Summit                            'Mont Blanc[Note 2]', 'Mont Blanc de Courmayeur', 'Dufourspitze'
$ Height (m)                        4809.0, 4748.0, 4634.0
$ Range                             'Mont Blanc Group', 'Mont Blanc Group', 'Monte Rosa Massif'
$ Country                           'France/ Italy [9]', 'France[10]/ Italy [11][12][9]', 'Italy/Switzerland'
$ Isolation[6] (km)                 '2,812  Elbrus (RU)', '0.6  Mont Blanc', '78.3  Mont Blanc de Courmayeur'
$ Prominence[6] (m)                 '4,697  near Lake Kubenskoye (RU) [Note 3]', '18  Col Major', '2,165  Grosser Sankt Bernhard'
$ First ascent[7]                   '8 August 1786  Jacques Balmat, Michel-Gabriel Paccard', '18 August 1822  F. Clissold, J. M. Couttet and five guides[13][14]', '1 August 1855  Charles Hudson and 7 companions'
$ Easiest (normal) route to summit  'Goûter Route (PD-/PD+)', 'Goûter Route (PD-/PD+) extension from summit of Mont Blanc', 'From Monte Rosa Hut via Monte Rosa glacier (III, 40°, AD-)'
$ Observations                      'Highest mountain of the Alps, border dispute France/Italy', 'Fore-summit of Mont Blanc, border dispute France/Italy', 'Highest peak of the Monte Rosa Massif, highest peak of the Alps outside of the Mont Blanc Massif'

Every column after the height is a string with more than one thing inside. Country is a list of countries. Isolation (the distance to the nearest higher point) carries the name of that point. Prominence carries the name of the col. First ascent is a date followed by a list of people. Let's take them apart one at a time.

2. Countries: from a string to a list↑ contents

The Country column has slashes, spaces and footnotes: France/ Italy [9], France Italy, Italy/Switzerland. We strip the footnotes, split on slashes and spaces, and drop the empty pieces. What comes back is a column of type list[str].

var peaks = raw.select(
  col("Nr.").cast(Int64).alias("nr"),
  col("Summit").str.replaceAll(r"\[.*?\]", "").alias("summit"),
  col("Height (m)").cast(Int64).alias("height"),
  col("Range").alias("range"),
  col("Country")
    .str.replaceAll(r"\[\d+\]", "")
    .str.replaceAll(r"[/ ]+", "/")
    .str.stripChars("/")
    .str.split("/")
    .alias("countries"),
  col("Isolation[6] (km)").alias("isolation"),
  col("Prominence[6] (m)").alias("prominence"),
  col("First ascent[7]").alias("first_ascent"),
)
echo peaks.select(col.summit, col.height, col.countries).head(8)
shape: (8, 3)
┌──────────────────────────┬────────┬──────────────────────────┐
│ summit                   ┆ height ┆ countries                │
│ ---                      ┆ ---    ┆ ---                      │
│ str                      ┆ i64    ┆ list[str]                │
╞══════════════════════════╪════════╪══════════════════════════╡
│ Mont Blanc               ┆ 4809   ┆ ["France", "Italy"]      │
│ Mont Blanc de Courmayeur ┆ 4748   ┆ ["France", "Italy"]      │
│ Dufourspitze             ┆ 4634   ┆ ["Italy", "Switzerland"] │
│ Nordend                  ┆ 4608   ┆ ["Italy", "Switzerland"] │
│ Zumsteinspitze           ┆ 4563   ┆ ["Italy", "Switzerland"] │
│ Signalkuppe              ┆ 4554   ┆ ["Italy", "Switzerland"] │
│ Dom                      ┆ 4546   ┆ ["Switzerland"]          │
│ Lyskamm (Eastern Summit) ┆ 4532   ┆ ["Italy", "Switzerland"] │
└──────────────────────────┴────────┴──────────────────────────┘

A list column can be measured with list.len, searched with list.contains, and turned back into rows with explode. Here is how many four-thousanders each country can claim, how many sit right on a border, and which countries share them (sorting and joining each list gives one label per combination).

echo peaks.explode("countries")["countries"].valueCounts(sort = true)
echo peaks.select((col.countries.list.len > 1).sum.alias("on_a_border"))
echo peaks.groupBy(col.countries.list.sort.list.join(" + ")).agg(len().alias("len")).sort(
  ["len", "countries"], descending = [true, false]
)
shape: (3, 2)
┌─────────────┬───────┐
│ countries   ┆ count │
│ ---         ┆ ---   │
│ str         ┆ u32   │
╞═════════════╪═══════╡
│ Switzerland ┆ 48    │
│ Italy       ┆ 38    │
│ France      ┆ 26    │
└─────────────┴───────┘
shape: (1, 1)
┌─────────────┐
│ on_a_border │
│ ---         │
│ u32         │
╞═════════════╡
│ 30          │
└─────────────┘
shape: (5, 2)
┌─────────────────────┬─────┐
│ countries           ┆ len │
│ ---                 ┆ --- │
│ str                 ┆ u32 │
╞═════════════════════╪═════╡
│ Switzerland         ┆ 31  │
│ Italy + Switzerland ┆ 17  │
│ France              ┆ 13  │
│ France + Italy      ┆ 13  │
│ Italy               ┆ 8   │
└─────────────────────┴─────┘

Switzerland has 48, Italy 38, France 26, which adds up to more than 82 because 30 summits sit on a border: 17 between Italy and Switzerland, 13 between France and Italy. Only 13 are entirely French and 8 entirely Italian, against 31 entirely Swiss, and not a single one stands on the French-Swiss border. Mont Blanc is on the French-Italian one, and France and Italy have disagreed about exactly where that border runs over the top since the 18th century.

3. Prominence: from a string to a struct↑ contents

Prominence is how far a peak rises above the lowest col you must cross to reach anything higher. It is the number mountaineers use to tell a mountain from a bump on a ridge. The column packs the number and the name of that col into one string, 1,043 Col Durand, and Isolation does the same with a distance and the nearest higher peak.

str.extractGroups pulls both parts out at once into a struct: a single column whose values have named fields, like a small row inside a row. struct.field reads one field back, unnest spreads them all into columns.

let parts = peaks.select(
  col.summit,
  col.height,
  col.prominence.str.extractGroups(r"^(?<metres>[\d,]+)\s+(?<col>.*)$").alias("prom"),
  col.isolation.str.extractGroups(r"^(?<km>[\d.,]+)\s+(?<higher>.*)$").alias("iso"),
)
echo parts.schema["prom"].fields.mapIt(it.name).join(", ")
echo parts.head(5)
metres, col
shape: (5, 4)
┌──────────────────────────┬────────┬───────────────────────────────────────────┬─────────────────────────────────────┐
│ summit                   ┆ height ┆ prom                                      ┆ iso                                 │
│ ---                      ┆ ---    ┆ ---                                       ┆ ---                                 │
│ str                      ┆ i64    ┆ struct[2]                                 ┆ struct[2]                           │
╞══════════════════════════╪════════╪═══════════════════════════════════════════╪═════════════════════════════════════╡
│ Mont Blanc               ┆ 4809   ┆ {"4,697","near Lake Kubenskoye (RU) [Not… ┆ {"2,812","Elbrus (RU)"}             │
│ Mont Blanc de Courmayeur ┆ 4748   ┆ {"18","Col Major"}                        ┆ {"0.6","Mont Blanc"}                │
│ Dufourspitze             ┆ 4634   ┆ {"2,165","Grosser Sankt Bernhard"}        ┆ {"78.3","Mont Blanc de Courmayeur"} │
│ Nordend                  ┆ 4608   ┆ {"89","Silbersattel"}                     ┆ {"0.6","Grenzgipfel"}               │
│ Zumsteinspitze           ┆ 4563   ┆ {"112","Grenzsattel"}                     ┆ {"0.5","Grenzgipfel"}               │
└──────────────────────────┴────────┴───────────────────────────────────────────┴─────────────────────────────────────┘

Careful with the commas. Prominence uses them as thousands separators (2,165), and so does isolation, except that isolation also has decimals (0.6). A naive cast of Mont Blanc's isolation, 2,812, as a decimal comma would put the nearest higher point 2.8 km away; it is Elbrus, in the Caucasus, 2812 km away. We drop the commas before casting.

peaks = peaks.withColumns(
  col.prominence.str.extract(r"^([\d,]+)").str.replaceAll(",", "").cast(Int64).alias("prom_m"),
  col.prominence.str.extract(r"^[\d,]+\s+(.*)$").str.replaceAll(r"\s*\[.*?\]", "").alias("col"),
  col.isolation.str.extract(r"^([\d.,]+)").str.replaceAll(",", "").cast(Float64).alias("iso_km"),
  col.isolation.str.extract(r"^[\d.,]+\s+(.*)$").alias("higher"),
)
echo peaks.select(
  (col.prom_m >= 1000).sum.alias("over_1000"),
  (col.prom_m < 100).sum.alias("under_100"),
  (col.prom_m < 30).sum.alias("under_30"),
)
echo peaks.topK(8, by = "prom_m").select(col.summit, col.height, col.prom_m, col("col"), col.iso_km, col.higher)
shape: (1, 3)
┌───────────┬───────────┬──────────┐
│ over_1000 ┆ under_100 ┆ under_30 │
│ ---       ┆ ---       ┆ ---      │
│ u32       ┆ u32       ┆ u32      │
╞═══════════╪═══════════╪══════════╡
│ 12        ┆ 33        ┆ 6        │
└───────────┴───────────┴──────────┘
shape: (8, 6)
┌──────────────────────┬────────┬────────┬─────────────────────────────┬────────┬──────────────────────────┐
│ summit               ┆ height ┆ prom_m ┆ col                         ┆ iso_km ┆ higher                   │
│ ---                  ┆ ---    ┆ ---    ┆ ---                         ┆ ---    ┆ ---                      │
│ str                  ┆ i64    ┆ i64    ┆ str                         ┆ f64    ┆ str                      │
╞══════════════════════╪════════╪════════╪═════════════════════════════╪════════╪══════════════════════════╡
│ Mont Blanc           ┆ 4809   ┆ 4697   ┆ near Lake Kubenskoye (RU)   ┆ 2812.0 ┆ Elbrus (RU)              │
│ Finsteraarhorn       ┆ 4274   ┆ 2279   ┆ west of the Simplon Pass    ┆ 51.7   ┆ Nadelhorn                │
│ Piz Bernina          ┆ 4048   ┆ 2236   ┆ Maloja Pass                 ┆ 138.0  ┆ Finsteraarhorn           │
│ Dufourspitze         ┆ 4634   ┆ 2165   ┆ Grosser Sankt Bernhard      ┆ 78.3   ┆ Mont Blanc de Courmayeur │
│ Barre des Écrins     ┆ 4102   ┆ 2045   ┆ Col du Lautaret             ┆ 107.3  ┆ Picco Luigi Amedeo       │
│ Gran Paradiso        ┆ 4061   ┆ 1888   ┆ Nahe Kleiner Sankt Bernhard ┆ 45.1   ┆ Grandes Jorasses         │
│ Combin de Grafeneire ┆ 4309   ┆ 1512   ┆ Fenêtre de Durand           ┆ 26.5   ┆ Dent Blanche             │
│ Weisshorn            ┆ 4505   ┆ 1234   ┆ Furggjoch                   ┆ 11.1   ┆ Dom                      │
└──────────────────────┴────────┴────────┴─────────────────────────────┴────────┴──────────────────────────┘

Only 12 of the 82 are mountains in their own right by the 1000-metre rule. Mont Blanc's prominence is its whole height above the lowest col on the way to anything taller, which is somewhere in the flatlands of Russia. Two in five (33) rise less than 100 metres above their col, six of them less than 30: shoulders and towers of bigger mountains, kept because climbers treat them as separate goals.

4. Who climbed them first↑ contents

The First ascent column is the messiest of all: 14 July 1865 Croz, Taugwalder, Whymper, Hudson, Douglas and Hadow. We take the year with a regular expression, and turn the rest into a list of names by treating "and" (and the German "mit", which slipped into the English page) as commas.

let ascents = peaks.select(
  col.summit,
  col.height,
  col.first_ascent.str.extract(r"(\d{4})").cast(Int32).alias("year"),
  col.first_ascent
    .str.replace(r"^.*?\d{4}(\[\d+\])?\s*", "")
    .str.replaceAll(r"\[.*?\]|\(.*?\)|"".*?""", "")
      .str.replaceAll(r" (and|mit) ", ", ")
      .str.split(",")
      .list.eval(element().str.stripChars)
      .alias("party"),
  )
  echo ascents.head(6)
shape: (6, 4)
┌──────────────────────────┬────────┬──────┬───────────────────────────────────────────┐
│ summit                   ┆ height ┆ year ┆ party                                     │
│ ---                      ┆ ---    ┆ ---  ┆ ---                                       │
│ str                      ┆ i64    ┆ i32  ┆ list[str]                                 │
╞══════════════════════════╪════════╪══════╪═══════════════════════════════════════════╡
│ Mont Blanc               ┆ 4809   ┆ 1786 ┆ ["Jacques Balmat", "Michel-Gabriel Pacca… │
│ Mont Blanc de Courmayeur ┆ 4748   ┆ 1822 ┆ ["F. Clissold", "J. M. Couttet", "five g… │
│ Dufourspitze             ┆ 4634   ┆ 1855 ┆ ["Charles Hudson", "7 companions"]        │
│ Nordend                  ┆ 4608   ┆ 1861 ┆ ["Edward N. Buxton", "T.F. Buxton", … "B… │
│ Zumsteinspitze           ┆ 4563   ┆ 1820 ┆ ["Joseph Zumstein", "Joseph Vincent", … … │
│ Signalkuppe              ┆ 4554   ┆ 1842 ┆ ["Giovanni Gnifetti", "7 companions"]     │
└──────────────────────────┴────────┴──────┴───────────────────────────────────────────┘

Explode the lists and count: who stood first on the most four-thousanders?

echo ascents.explode("party").dropNulls("party")["party"].valueCounts(sort = true).head(8)
shape: (8, 2)
┌─────────────────────────┬───────┐
│ party                   ┆ count │
│ ---                     ┆ ---   │
│ str                     ┆ u32   │
╞═════════════════════════╪═══════╡
│ Melchior Anderegg       ┆ 6     │
│ Christian Almer         ┆ 5     │
│ Michel-Clément Payot    ┆ 4     │
│ Leslie Stephen          ┆ 4     │
│ Armand Charlet          ┆ 4     │
│ Johann Zumtaugwald      ┆ 3     │
│ Florence Crauford Grove ┆ 3     │
│ Michel Croz             ┆ 3     │
└─────────────────────────┴───────┘

Melchior Anderegg, a mountain guide from the Bernese Oberland, leads with six, ahead of Christian Almer, another Oberland guide, with five. Most of the famous names of the period show up with three or four: the British climbers Leslie Stephen, Horace Walker and Edward Whymper, the Chamonix guides Michel Croz and Michel-Clément Payot. And the list has its limits: when the page says "Jakob and Melchior Anderegg", our split gives a lone "Jakob". We fix that in section 9 with a Nim callback.

When did all this happen? Group the years by decade.

withConfig(tblRows = 20):
  echo ascents.groupBy((col.year div 10 * 10).alias("decade")).agg(len().alias("len")).sort("decade")
echo ascents.select(
  col.year.isNotNull.sum.alias("dated"),
  col.year.isBetween(1854, 1865).sum.alias("golden_age"),
  col.year.min.alias("first"),
  col.year.max.alias("last"),
)
shape: (14, 2)
┌────────┬─────┐
│ decade ┆ len │
│ ---    ┆ --- │
│ i32    ┆ u32 │
╞════════╪═════╡
│ null   ┆ 8   │
│ 1780   ┆ 2   │
│ 1800   ┆ 1   │
│ 1810   ┆ 5   │
│ 1820   ┆ 3   │
│ 1840   ┆ 1   │
│ 1850   ┆ 13  │
│ 1860   ┆ 26  │
│ 1870   ┆ 6   │
│ 1880   ┆ 7   │
│ 1890   ┆ 1   │
│ 1900   ┆ 3   │
│ 1920   ┆ 5   │
│ 1950   ┆ 1   │
└────────┴─────┘
shape: (1, 4)
┌───────┬────────────┬───────┬──────┐
│ dated ┆ golden_age ┆ first ┆ last │
│ ---   ┆ ---        ┆ ---   ┆ ---  │
│ u32   ┆ u32        ┆ i32   ┆ i32  │
╞═══════╪════════════╪═══════╪══════╡
│ 74    ┆ 36         ┆ 1784  ┆ 1957 │
└───────┴────────────┴───────┴──────┘

Mountaineers call the years from 1854 (the Wetterhorn) to 1865 (the Matterhorn) the golden age of alpinism. Of the 74 summits with a known year, 36 were first climbed in those twelve seasons. The very first was the Dôme du Goûter in 1784, two years before Mont Blanc itself; the last was the Grand Pilier d'Angle, climbed by Walter Bonatti and Toni Gobbi in 1957.

5. On the map↑ contents

The list has no coordinates, so we join them in from a separate file built from Wikidata and Camptocamp (see src/peaks_prep.py), on the list number.

let coords = readCsv("data/uiaa_coords.csv")
peaks = peaks.join(coords, on = ["nr"], how = Left, validate = OneToOne, maintainOrder = MaintainOrderJoin.Left)
withConfig(floatPrecision = 4):
  echo peaks.select(col.summit, col.height, col.lon, col.lat, col.source).head(5)
shape: (5, 5)
┌──────────────────────────┬────────┬────────┬─────────┬────────────────┐
│ summit                   ┆ height ┆ lon    ┆ lat     ┆ source         │
│ ---                      ┆ ---    ┆ ---    ┆ ---     ┆ ---            │
│ str                      ┆ i64    ┆ f64    ┆ f64     ┆ str            │
╞══════════════════════════╪════════╪════════╪═════════╪════════════════╡
│ Mont Blanc               ┆ 4809   ┆ 6.8650 ┆ 45.8328 ┆ wikidata       │
│ Mont Blanc de Courmayeur ┆ 4748   ┆ 6.8697 ┆ 45.8284 ┆ wikidata       │
│ Dufourspitze             ┆ 4634   ┆ 7.8668 ┆ 45.9368 ┆ camptocamp     │
│ Nordend                  ┆ 4608   ┆ 7.8699 ┆ 45.9420 ┆ wikidata-label │
│ Zumsteinspitze           ┆ 4563   ┆ 7.8714 ┆ 45.9322 ┆ camptocamp     │
└──────────────────────────┴────────┴────────┴─────────┴────────────────┘
show plots.alpsMap(peaks)
plotting code
proc alpsMap*(peaks: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_alps.parquet", 4800)
  let label = peaks.select(format("{} {} m", col.summit, col.height).alias("t")).toList("t", string)
  let sizes = peaks.select(((col.height - 3900) / 60 + 5).alias("s")).toList("s", float)
  let dots = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "4000ers",
                          xs: peaks.toList("lon", float), ys: peaks.toList("lat", float), text: label)
  result = finish(@[bg, dots], "The 82 Alpine four-thousanders", 520)
  result.withStyle(0, bgStyle)
  result.withStyle(1, %*{"marker": {"size": sizes, "color": Red, "line": {"width": 1, "color": "white"}},
                         "hoverinfo": "text"})
  for (name, lon, lat) in [("Mont Blanc", 6.865, 45.833), ("Zermatt peaks", 7.75, 46.02),
                           ("Bernese Oberland", 8.0, 46.6), ("Piz Bernina", 9.908, 46.382),
                           ("Barre des Écrins", 6.358, 44.922), ("Gran Paradiso", 7.266, 45.517)]:
    result.note(lon, lat, name)
  result.layout["showlegend"] = %false
  result.geoAxes((5.6, 10.6), (44.6, 47.0))

All 82 fit in a strip about 250 km long, from the Barre des Écrins in the south-west to Piz Bernina in the east, and most crowd around two centres: the Mont Blanc massif and the Valais around Zermatt.

6. Eight treks, as JSON↑ contents

You don't need a rope to see these mountains up close. Several classic multi-day treks go around them, hut to hut: the Tour du Mont Blanc, the Tour du Cervin around the Matterhorn, the Tour Monte Rosa, the Tour des Combins, the Walker's Haute Route from Chamonix to Zermatt, and further south and east the Alta Via 1 of the Aosta Valley and the Alte Vie 1 and 2 of the Dolomites.

OpenStreetMap volunteers have mapped all of them as route relations: a route made of stages, a stage made of ways (stretches of path), a way made of points. We downloaded each one from Waymarked Trails, sampled the terrain height at every point, and saved them as newline-delimited JSON, one trek per line, keeping the nesting (src/treks_prep.py). readNdjson reads it into eight rows.

let treks = readNdjson("data/treks.ndjson", inferSchemaLength = none(int))
echo treks.shape
echo treks.schema["stages"].inner.fields.mapIt(it.name).join(", ")
echo treks.select(col.id, col.name, col.stages.list.len.alias("n_stages"))
(8, 6)
id, name, itinerary, ways
shape: (8, 3)
┌──────────┬───────────────────────────────────────────┬──────────┐
│ id       ┆ name                                      ┆ n_stages │
│ ---      ┆ ---                                       ┆ ---      │
│ i64      ┆ str                                       ┆ u32      │
╞══════════╪═══════════════════════════════════════════╪══════════╡
│ 9678362  ┆ Tour du Mont Blanc - Itinéraire principa… ┆ 1        │
│ 1176308  ┆ Tour du Cervin                            ┆ 1        │
│ 10353523 ┆ Tour Monte Rosa                           ┆ 9        │
│ 49181    ┆ Tour des Combins                          ┆ 9        │
│ 177743   ┆ Alta via n. 1 delle Dolomiti - Dolomiten… ┆ 1        │
│ 404914   ┆ Alta Via n. 2 delle Dolomiti - Dolomiten… ┆ 1        │
│ 1706143  ┆ Alta Via n. 1 della Valle d'Aosta         ┆ 17       │
│ 3020521  ┆ Walker's Haute Route                      ┆ 23       │
└──────────┴───────────────────────────────────────────┴──────────┘

Eight rows, but a lot inside them. The stages column is a list of structs; each stage struct holds a list of way structs; each way holds an OpenStreetMap tags struct and a list of points, each point a list of three numbers. How many tag fields?

let wayType = treks.schema["stages"].inner.fields[3].dtype.inner
let tagFields = wayType.fields[3].dtype.fields.mapIt(it.name)
echo tagFields.len, " ", tagFields.sorted[0 ..< 12].join(", ")
166 4wd_only, FIXME, abandoned:piste:difficulty, abandoned:piste:name, abandoned:piste:ref, abandoned:piste:type, access, access:conditional, alt_name:fr, assisted_trail, bicycle, bridge

166 of them. Every way carries only the few tags someone bothered to map, and the struct holds the union of all of them, with nulls everywhere else.

7. Unnesting, level by level↑ contents

Two explodes and two unnests turn eight treks into one row per way. On the way we give the long official names shorter labels.

let short = {
  "Tour du Mont Blanc - Itinéraire principal": "Tour du Mont Blanc",
  "Alta via n. 1 delle Dolomiti - Dolomiten-Höhenweg Nr. 1": "Alta Via 1 Dolomites",
  "Alta Via n. 2 delle Dolomiti - Dolomiten-Höhenweg Nr. 2": "Alta Via 2 Dolomites",
  "Alta Via n. 1 della Valle d'Aosta": "Alta Via 1 Aosta",
}
let ways = treks.select(col.name.replace(short).alias("trek"), col.stages)
  .explode("stages")
  .unnest("stages")
  .rename({"id": "stage_id", "name": "stage"})
  .explode("ways")
  .unnest("ways")
  .rename({"id": "way_id"})
echo ways.shape
echo ways.select(col.trek, col.stage, col.way_id, col.length, col.points).head(4)
(3904, 9)
shape: (4, 5)
┌────────────────────┬──────────────────────────────────┬───────────┬────────┬─────────────────────────────────┐
│ trek               ┆ stage                            ┆ way_id    ┆ length ┆ points                          │
│ ---                ┆ ---                              ┆ ---       ┆ ---    ┆ ---                             │
│ str                ┆ str                              ┆ i64       ┆ i64    ┆ list[list[f64]]                 │
╞════════════════════╪══════════════════════════════════╪═══════════╪════════╪═════════════════════════════════╡
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 217673748 ┆ 113    ┆ [[766572.8, 5774260.2, 1889.0], │
│                    ┆ principa…                        ┆           ┆        ┆ [766570.…                       │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 943523073 ┆ 10     ┆ [[766644.4, 5774120.2, 1880.3], │
│                    ┆ principa…                        ┆           ┆        ┆ [766656.…                       │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 238362663 ┆ 132    ┆ [[766656.0, 5774109.5, 1882.0], │
│                    ┆ principa…                        ┆           ┆        ┆ [766664.…                       │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 433039971 ┆ 66     ┆ [[766676.8, 5773928.1, 1875.3], │
│                    ┆ principa…                        ┆           ┆        ┆ [766669.…                       │
└────────────────────┴──────────────────────────────────┴───────────┴────────┴─────────────────────────────────┘

Now the tags. OpenStreetMap grades mountain paths on the SAC scale, from Swiss Alpine Club practice: T1 is a walk, T3 a demanding mountain path, T5 and T6 alpine terrain where you may need your hands and a head for heights. struct.field picks it out of the big tags struct, and a group-by sums the lengths per grade.

let grades = {"hiking": "T1", "mountain_hiking": "T2", "demanding_mountain_hiking": "T3",
              "alpine_hiking": "T4", "demanding_alpine_hiking": "T5", "difficult_alpine_hiking": "T6"}
let sac = ways
  .withColumns(col.tags.struct.field("sac_scale").replaceStrict(grades, default = "none").alias("sac"))
  .groupBy("trek", "sac")
  .agg((col.length.sum / 1000).alias("km"))
  .pivot(on = "sac", index = "trek", values = "km", sortColumns = true)
  .fillNull(0)
  .sort("trek")
echo sac
shape: (8, 8)
┌──────────────────────┬──────┬───────┬──────┬─────┬─────┬─────┬──────┐
│ trek                 ┆ T1   ┆ T2    ┆ T3   ┆ T4  ┆ T5  ┆ T6  ┆ none │
│ ---                  ┆ ---  ┆ ---   ┆ ---  ┆ --- ┆ --- ┆ --- ┆ ---  │
│ str                  ┆ f64  ┆ f64   ┆ f64  ┆ f64 ┆ f64 ┆ f64 ┆ f64  │
╞══════════════════════╪══════╪═══════╪══════╪═════╪═════╪═════╪══════╡
│ Alta Via 1 Aosta     ┆ 5.8  ┆ 122.3 ┆ 19.8 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 43.1 │
│ Alta Via 1 Dolomites ┆ 12.3 ┆ 72.7  ┆ 7.6  ┆ 0.1 ┆ 0.0 ┆ 0.0 ┆ 25.2 │
│ Alta Via 2 Dolomites ┆ 11.3 ┆ 79.3  ┆ 20.8 ┆ 6.3 ┆ 4.8 ┆ 0.3 ┆ 35.1 │
│ Tour Monte Rosa      ┆ 15.1 ┆ 79.3  ┆ 21.3 ┆ 0.8 ┆ 2.4 ┆ 0.0 ┆ 45.5 │
│ Tour des Combins     ┆ 8.8  ┆ 68.5  ┆ 0.0  ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 22.8 │
│ Tour du Cervin       ┆ 6.7  ┆ 57.8  ┆ 23.2 ┆ 3.3 ┆ 7.4 ┆ 0.0 ┆ 35.4 │
│ Tour du Mont Blanc   ┆ 8.8  ┆ 96.7  ┆ 1.8  ┆ 0.1 ┆ 0.0 ┆ 0.0 ┆ 58.5 │
│ Walker's Haute Route ┆ 20.3 ┆ 109.7 ┆ 11.3 ┆ 2.5 ┆ 0.0 ┆ 0.0 ┆ 65.5 │
└──────────────────────┴──────┴───────┴──────┴─────┴─────┴─────┴──────┘

OpenStreetMap stores the grades as words (mountain_hiking), which we map back to the T1-T6 the signposts use; none means no grade was mapped (often roads and forest tracks). The SAC grades also tell the treks apart: the Dolomite Alte Vie and the Tour du Cervin have kilometres of T4 and harder, the Tour du Mont Blanc stays mostly on T1-T2 paths.

8. Points: lists, arrays, and a map projection↑ contents

Each point is [x, y, elevation]. The x and y are Web Mercator metres, the projection of every web map. Since every point has exactly three values, we can cast the inner list to a fixed-size array, and read it with the arr namespace.

const R = 6378137.0  # Web Mercator sphere radius, metres
var pts = ways.select(col.trek, col.stage, col.way_id, col.points)
  .withRowIndex("way_seq")
  .explode("points")
  .withColumns(col.points.cast(Array(Float64, 3)))
  .select(
    col.trek, col.stage, col.way_seq,
    col.points.arr.get(0).alias("x"),
    col.points.arr.get(1).alias("y"),
    col.points.arr.get(2).alias("ele"),
  )
  .withColumns(
    (col.x / R * 180 / PI).alias("lon"),
    ((col.y / R).sinh.arctan * 180 / PI).alias("lat"),
  )
echo pts.height
echo pts.head(4)
114756
shape: (4, 8)
┌────────────────────┬──────────────────────────────────┬─────────┬──────────┬───────────┬────────┬─────┬──────┐
│ trek               ┆ stage                            ┆ way_seq ┆ x        ┆ y         ┆ ele    ┆ lon ┆ lat  │
│ ---                ┆ ---                              ┆ ---     ┆ ---      ┆ ---       ┆ ---    ┆ --- ┆ ---  │
│ str                ┆ str                              ┆ u32     ┆ f64      ┆ f64       ┆ f64    ┆ f64 ┆ f64  │
╞════════════════════╪══════════════════════════════════╪═════════╪══════════╪═══════════╪════════╪═════╪══════╡
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 0       ┆ 766572.8 ┆ 5774260.2 ┆ 1889.0 ┆ 6.9 ┆ 46.0 │
│                    ┆ principa…                        ┆         ┆          ┆           ┆        ┆     ┆      │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 0       ┆ 766570.3 ┆ 5774257.0 ┆ 1889.0 ┆ 6.9 ┆ 46.0 │
│                    ┆ principa…                        ┆         ┆          ┆           ┆        ┆     ┆      │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 0       ┆ 766569.6 ┆ 5774253.2 ┆ 1889.0 ┆ 6.9 ┆ 46.0 │
│                    ┆ principa…                        ┆         ┆          ┆           ┆        ┆     ┆      │
│ Tour du Mont Blanc ┆ Tour du Mont Blanc - Itinéraire  ┆ 0       ┆ 766571.0 ┆ 5774249.6 ┆ 1889.0 ┆ 6.9 ┆ 46.0 │
│                    ┆ principa…                        ┆         ┆          ┆           ┆        ┆     ┆      │
└────────────────────┴──────────────────────────────────┴─────────┴──────────┴───────────┴────────┴─────┴──────┘

A distance in Web Mercator metres is stretched by 1/cos(latitude), about 1.43 at 46°N, so we shrink each step back. Steps are measured within a way, so gaps between disconnected ways don't count.

pts = pts.withColumns(
  ((col.x.diff ^ 2 + col.y.diff ^ 2).sqrt * (col.lat * PI / 180).cos)
    .over("way_seq").fillNull(0).alias("step")
).withColumns((col.step.cumSum.over("trek") / 1000).alias("km"))
echo pts.groupBy("trek").agg(
  (col.step.sum / 1000).alias("km"),
  col.ele.max.alias("top"),
  col.ele.min.alias("bottom"),
).sort("km")
shape: (8, 4)
┌──────────────────────┬───────┬────────┬────────┐
│ trek                 ┆ km    ┆ top    ┆ bottom │
│ ---                  ┆ ---   ┆ ---    ┆ ---    │
│ str                  ┆ f64   ┆ f64    ┆ f64    │
╞══════════════════════╪═══════╪════════╪════════╡
│ Tour des Combins     ┆ 100.2 ┆ 2859.5 ┆ 1609.7 │
│ Alta Via 1 Dolomites ┆ 118.1 ┆ 2575.7 ┆ 388.8  │
│ Tour du Cervin       ┆ 134.1 ┆ 3326.0 ┆ 1130.6 │
│ Alta Via 2 Dolomites ┆ 158.0 ┆ 2950.1 ┆ 336.8  │
│ Tour Monte Rosa      ┆ 164.7 ┆ 3326.0 ┆ 1185.3 │
│ Tour du Mont Blanc   ┆ 166.2 ┆ 2522.0 ┆ 977.7  │
│ Alta Via 1 Aosta     ┆ 191.3 ┆ 2891.6 ┆ 319.7  │
│ Walker's Haute Route ┆ 209.7 ┆ 2963.8 ┆ 720.5  │
└──────────────────────┴───────┴────────┴────────┘
show plots.treksMap(pts, peaks)
plotting code
proc treksMap*(pts, peaks: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_west.parquet", 4800)
  result = finish(@[bg], "Six treks around the highest Alps", 560)
  result.withStyle(0, bgStyle)
  result.addTreks(pts, ["Tour du Mont Blanc", "Walker's Haute Route", "Tour des Combins",
                        "Tour du Cervin", "Tour Monte Rosa", "Alta Via 1 Aosta"])
  result.traces.add %*{"type": "scatter", "mode": "markers", "name": "4000ers",
    "x": peaks.toList("lon", float), "y": peaks.toList("lat", float),
    "text": peaks.toList("summit", string), "hoverinfo": "text",
    "marker": {"size": 7, "color": Red, "symbol": "triangle-up", "line": {"width": 0.5, "color": "white"}}}
  result.layout["legend"] = %*{"orientation": "h", "y": -0.12}
  result.geoAxes((6.6, 8.4), (45.55, 46.35))

Two of the eight are far to the east, in the Dolomites, where the limestone towers top out at 3343 m (the Marmolada) and there are no four-thousanders at all.

show plots.dolomitesMap(pts)
plotting code
proc dolomitesMap*(pts: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_dolomites.parquet", 3400)
  result = finish(@[bg], "The Alte Vie 1 and 2 of the Dolomites", 560)
  result.withStyle(0, bgStyle)
  result.addTreks(pts, ["Alta Via 1 Dolomites", "Alta Via 2 Dolomites"])
  result.layout["legend"] = %*{"orientation": "h", "y": -0.12}
  result.geoAxes((11.55, 12.35), (46.1, 46.8))

9. How much climbing? It depends on how closely you look↑ contents

Guidebooks give the Tour du Mont Blanc about 170 km and 10,000 metres of ascent. Our 166 km match the first number. For the second, you add up every rise along the way. But a terrain model has noise, and every little up-and-down gets counted, so the answer depends on how finely you sample. Average the height over bins of increasing length and watch the total ascent shrink.

proc ascent(binKm: float): DataFrame =
  pts.groupBy(col.trek, (col.km / binKm).floor.alias("bin"))
    .agg(col.ele.mean)
    .sort(["trek", "bin"])
    .groupBy("trek")
    .agg(col.ele.diff.clip(lowerBound = 0.0).sum.round.alias($int(binKm * 1000) & " m"))

var table = ascent(0.05)
for b in [0.1, 0.2, 0.5, 1.0]:
  table = table.join(ascent(b), on = ["trek"])
echo table.sort("trek")
shape: (8, 6)
┌──────────────────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ trek                 ┆ 50 m    ┆ 100 m   ┆ 200 m   ┆ 500 m   ┆ 1000 m  │
│ ---                  ┆ ---     ┆ ---     ┆ ---     ┆ ---     ┆ ---     │
│ str                  ┆ f64     ┆ f64     ┆ f64     ┆ f64     ┆ f64     │
╞══════════════════════╪═════════╪═════════╪═════════╪═════════╪═════════╡
│ Alta Via 1 Aosta     ┆ 17016.0 ┆ 15894.0 ┆ 14989.0 ┆ 13663.0 ┆ 12137.0 │
│ Alta Via 1 Dolomites ┆ 8827.0  ┆ 7818.0  ┆ 6945.0  ┆ 6127.0  ┆ 5059.0  │
│ Alta Via 2 Dolomites ┆ 15208.0 ┆ 13818.0 ┆ 12583.0 ┆ 11028.0 ┆ 9538.0  │
│ Tour Monte Rosa      ┆ 12787.0 ┆ 11490.0 ┆ 10451.0 ┆ 9480.0  ┆ 8936.0  │
│ Tour des Combins     ┆ 7191.0  ┆ 6435.0  ┆ 5771.0  ┆ 4956.0  ┆ 4619.0  │
│ Tour du Cervin       ┆ 11439.0 ┆ 10645.0 ┆ 10145.0 ┆ 9519.0  ┆ 8811.0  │
│ Tour du Mont Blanc   ┆ 11146.0 ┆ 10183.0 ┆ 9566.0  ┆ 8882.0  ┆ 8257.0  │
│ Walker's Haute Route ┆ 16265.0 ┆ 14680.0 ┆ 13573.0 ┆ 12549.0 ┆ 11630.0 │
└──────────────────────┴─────────┴─────────┴─────────┴─────────┴─────────┘

Bins of 100 metres give the Tour du Mont Blanc 10,183 metres, right on the guidebook figure; with 1 km bins the passes are smoothed away and only 8,257 m remain. We'll use 100 metres from here on.

let passes = newDataFrame:
  km: [8.0, 23.6, 48.0, 64.1, 73.3, 105.5, 152.3]
  label: ["Brévent", "Col de Voza", "Croix du Bonhomme", "Col de la Seigne",
          "Mont Favre", "Grand Col Ferret", "Col de Balme"]
let tmb = pts.filter(col.trek == "Tour du Mont Blanc").sort("km")
let labels = passes.joinAsof(tmb.select(col.km, col.ele), on = "km", strategy = AsofStrategy.Nearest)
show plots.profile(pts, "Tour du Mont Blanc", labels)
plotting code
proc profile*(pts: DataFrame, trek: string, labels: DataFrame): PlotJson =
  let g = pts.filter(col.trek == trek)
    .groupBy((col.km / 0.1).floor.alias("bin")).agg(col.ele.mean, col.km.mean)
    .sort("bin")
  let line = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: trek,
                          xs: g.toList("km", float), ys: g.toList("ele", float))
  result = finish(@[line], trek & ": elevation profile (100 m bins)", 380)
  result.withStyle(0, %*{"fill": "tozeroy", "line": {"color": "#1f77b4"}})
  for r in labels.rows(tuple[km: float, label: string, ele: float]):
    result.note(r.km, r.ele, r.label, ax = 0, ay = -22, size = 10)
  for a in result.layout["annotations"]: a.delete("bgcolor")
  result.layout["xaxis"] = %*{"title": {"text": "km"}}
  result.layout["yaxis"] = %*{"title": {"text": "m"}, "range": [0, 3000]}

# ---------------------------------------------------------------- the world

10. The guidebook's words, decoded↑ contents

The Aosta Valley's Alta Via 1 is split into 17 official stages, and each stage in OpenStreetMap carries its itinerary as a list of strings with the altitude written in: Sassa (1430 mt.). list.eval runs an expression on every element of a list, so we can pull the numbers out of all of them at once and compare them with what the terrain model says at the start and end of each stage.

let av1 = ways.filter(col.trek == "Alta Via 1 Aosta")
  .groupBy("stage_id", maintainOrder = true)
  .agg(col.stage.first, col.itinerary.first)
  .withColumns(
    col.itinerary.list.eval(
      element().str.extract(r"\((\d[\d.]*)\s*mt?\.?\)").str.replaceAll(r"\.", "").cast(Int64)
    ).alias("stop_m"),
    col.stage.str.extract(r"Tappa (\d+)").cast(Int64).alias("stage_no"),
  )
  .sort("stage_no")
echo av1.select(col.stage_no, col.itinerary, col.stop_m).head(6)
shape: (6, 3)
┌──────────┬───────────────────────────────────────────┬──────────────┐
│ stage_no ┆ itinerary                                 ┆ stop_m       │
│ ---      ┆ ---                                       ┆ ---          │
│ i64      ┆ list[str]                                 ┆ list[i64]    │
╞══════════╪═══════════════════════════════════════════╪══════════════╡
│ 1        ┆ ["Donnas (330 mt.)", "Sassa (1430 mt.)"]  ┆ [330, 1430]  │
│ 2        ┆ ["Sassa (1430 mt.)", "Rifugio Coda (2280… ┆ [1430, 2280] │
│ 3        ┆ ["Rifugio Coda (2280 mt.)", "Rifugio del… ┆ [2280, 2062] │
│ 4        ┆ ["Rifugio della Balma (2062 mt.)", "Niel… ┆ [2062, 550]  │
│ 5        ┆ ["Niel 1(550 mt.)", "Gressoney-Saint-Jea… ┆ [550, 1405]  │
│ 6        ┆ ["Gressoney-Saint-Jean (1405 mt.)", "Rif… ┆ [1405, 1935] │
└──────────┴───────────────────────────────────────────┴──────────────┘

Now the check. For each stage, take the terrain height at its first and last point, put them in a list too, and compare the two lists element by element.

let ends = pts.groupBy("stage", maintainOrder = true).agg(
  concatList(col.ele.first, col.ele.last).first.alias("dem_m")
)
let check = av1.join(ends, on = ["stage"], maintainOrder = MaintainOrderJoin.Left).withColumns(
  maxHorizontal(@[0, 1].mapIt((col.dem_m.list.get(it) - col.stop_m.list.get(it)).abs))
    .round.cast(Int64).alias("diff_m")
)
echo check.filter(col.diff_m > 150).select(col.stage_no, col.itinerary, col.stop_m, col.dem_m, col.diff_m)
shape: (3, 5)
┌──────────┬───────────────────────────────────────────┬──────────────┬──────────────────┬────────┐
│ stage_no ┆ itinerary                                 ┆ stop_m       ┆ dem_m            ┆ diff_m │
│ ---      ┆ ---                                       ┆ ---          ┆ ---              ┆ ---    │
│ i64      ┆ list[str]                                 ┆ list[i64]    ┆ list[f64]        ┆ i64    │
╞══════════╪═══════════════════════════════════════════╪══════════════╪══════════════════╪════════╡
│ 4        ┆ ["Rifugio della Balma (2062 mt.)", "Niel… ┆ [2062, 550]  ┆ [2035.8, 1567.0] ┆ 1017   │
│ 5        ┆ ["Niel 1(550 mt.)", "Gressoney-Saint-Jea… ┆ [550, 1405]  ┆ [1567.0, 1389.9] ┆ 1017   │
│ 15       ┆ ["Saint-Rhémy-en-Bosses (1.600 mt.)", "R… ┆ [1600, 2540] ┆ [1630.5, 2032.8] ┆ 507    │
└──────────┴───────────────────────────────────────────┴──────────────┴──────────────────┴────────┘

Fourteen of the seventeen stages agree with the terrain within 150 metres, about as close as you can expect from a terrain model and a signpost. Two of the misfits share one typo: the village of Niel is written Niel 1(550 mt.), a misplaced bracket that turns 1550 m into a 550-metre valley floor (the terrain says 1567). The third is a hole in the map: stage 15 should climb to the Rifugio Frassati at 2540 m, but its mapped path stops 500 metres lower, and stage 16 picks up from the hut.

11. Walking time, with a Nim callback↑ contents

Swiss and German signposts give walking times, not distances, using a rule of thumb (DIN 33466): 4 km per hour on the flat, 300 metres of ascent per hour, 500 metres of descent per hour; take the larger of the horizontal and vertical times and add half the smaller.

That rule fits in an expression, but it reads better as a plain function, and that is what callbacks are for: mapElements hands each value (here a struct with three fields) to your own function. In Nim, the function is a regular proc on a tuple, and runs at native speed.

proc walkingHours(s: tuple[km, up, down: float]): float =
  let horizontal = s.km / 4
  let vertical = s.up / 300 + s.down / 500
  max(horizontal, vertical) + min(horizontal, vertical) / 2

let legs = pts.groupBy(col.trek, (col.km / 0.1).floor.alias("bin"))
  .agg(col.ele.mean, col.km.max)
  .sort(["trek", "bin"])
  .withColumns(col.ele.diff.over("trek").fillNull(0).alias("d"))
  .groupBy("trek")
  .agg(
    col.km.max.alias("km"),
    col.d.clip(lowerBound = 0.0).sum.alias("up"),
    (-col.d.clip(upperBound = 0.0).sum).alias("down"),
  )
  .withColumns(asStruct("km", "up", "down").mapElements(walkingHours).alias("hours"))
  .withColumns((col.hours / 7).round(1).alias("days_of_7h"))
  .sort("hours")
echo legs
shape: (8, 6)
┌──────────────────────┬───────┬─────────┬─────────┬───────┬────────────┐
│ trek                 ┆ km    ┆ up      ┆ down    ┆ hours ┆ days_of_7h │
│ ---                  ┆ ---   ┆ ---     ┆ ---     ┆ ---   ┆ ---        │
│ str                  ┆ f64   ┆ f64     ┆ f64     ┆ f64   ┆ f64        │
╞══════════════════════╪═══════╪═════════╪═════════╪═══════╪════════════╡
│ Tour des Combins     ┆ 100.2 ┆ 6434.8  ┆ 6430.2  ┆ 46.8  ┆ 6.7        │
│ Alta Via 1 Dolomites ┆ 118.1 ┆ 7817.9  ┆ 8928.9  ┆ 58.7  ┆ 8.4        │
│ Tour du Mont Blanc   ┆ 166.2 ┆ 10183.1 ┆ 10183.1 ┆ 75.1  ┆ 10.7       │
│ Tour du Cervin       ┆ 134.1 ┆ 10644.9 ┆ 11818.0 ┆ 75.9  ┆ 10.8       │
│ Tour Monte Rosa      ┆ 164.7 ┆ 11489.6 ┆ 11490.0 ┆ 81.9  ┆ 11.7       │
│ Alta Via 2 Dolomites ┆ 158.0 ┆ 13818.3 ┆ 13310.4 ┆ 92.4  ┆ 13.2       │
│ Walker's Haute Route ┆ 209.7 ┆ 14680.1 ┆ 14103.6 ┆ 103.4 ┆ 14.8       │
│ Alta Via 1 Aosta     ┆ 191.3 ┆ 15893.9 ┆ 15028.0 ┆ 107.0 ┆ 15.3       │
└──────────────────────┴───────┴─────────┴─────────┴───────┴────────────┘

The rule puts the Tour du Mont Blanc at 75 hours of walking, just under 11 days of seven hours, which is the classic 11-stage itinerary. The Aosta Valley's Alta Via 1 is the longest of the eight, more than two weeks.

The callback also rescues the first ascents from section 4. When a party is written as "Jakob and Melchior Anderegg", the two people share one surname, and no regular expression is going to know which words are first names. A small function can: if an entry is a single word and the next one has a surname, borrow it.

proc lendSurnames(party: seq[string]): seq[string] =
  for i, name in party:
    var name = name
    if ' ' notin name and name.len > 0 and name[0].isUpperAscii and
        i + 1 < party.len and ' ' in party[i + 1]:
      name = name & " " & party[i + 1].split(' ')[^1]
    result.add name

let fixed = ascents.withColumns(col.party.mapElements(lendSurnames).alias("party"))
echo fixed.explode("party").filter(col.party.str.contains("Anderegg"))["party"].valueCounts(sort = true)
shape: (2, 2)
┌───────────────────┬───────┐
│ party             ┆ count │
│ ---               ┆ ---   │
│ str               ┆ u32   │
╞═══════════════════╪═══════╡
│ Melchior Anderegg ┆ 6     │
│ Jakob Anderegg    ┆ 2     │
└───────────────────┴───────┘

The ranking doesn't move, but the Anderegg family is now complete:

12. Asking in SQL↑ contents

Not everyone thinks in method chains. Nanuq 0.5 can register frames in a SQL context and query them by name. Which range has the most four-thousanders, and how high and prominent are they?

let ctx = newSQLContext({"peaks": peaks.drop("countries").lazy, "treks": legs.lazy})
echo ctx.execute("""
      SELECT range, CAST(COUNT(*) AS BIGINT) AS n, MAX(height) AS highest, ROUND(AVG(prom_m)) AS avg_prom
      FROM peaks
      GROUP BY range
      ORDER BY n DESC, highest DESC
  """, eager = true)

Text: """
shape: (9, 4)
┌───────────────────┬─────┬─────────┬──────────┐
│ range             ┆ n   ┆ highest ┆ avg_prom │
│ ---               ┆ --- ┆ ---     ┆ ---      │
│ str               ┆ i64 ┆ i64     ┆ f64      │
╞═══════════════════╪═════╪═════════╪══════════╡
│ Mont Blanc Group  ┆ 28  ┆ 4809    ┆ 295.0    │
│ Wallis Alps       ┆ 18  ┆ 4532    ┆ 458.0    │
│ Mischabel Group   ┆ 11  ┆ 4546    ┆ 314.0    │
│ Monte Rosa Massif ┆ 9   ┆ 4634    ┆ 315.0    │
│ Bernese Alps      ┆ 9   ┆ 4274    ┆ 703.0    │
│ Grand Combin      ┆ 3   ┆ 4309    ┆ 542.0    │
│ Pelvoux           ┆ 2   ┆ 4102    ┆ 1043.0   │
│ Graian Alps       ┆ 1   ┆ 4061    ┆ 1888.0   │
│ Bernina Group     ┆ 1   ┆ 4048    ┆ 2236.0   │
└───────────────────┴─────┴─────────┴──────────┘

Part 2: The world↑ contents

13. Every mountain range on Earth↑ contents

Geographers at the University of Bern (the GMBA, Global Mountain Biodiversity Assessment) have drawn the outline of every named mountain range on Earth, and put them into a hierarchy: Alps, Western Alps, Pennine Alps, and so on. We use their selection of about 300 major ranges, saved as NDJSON with the outlines simplified (src/gmba_prep.py). The Path column is the hierarchy as one string, Europe > Alps, and Countries is another list in disguise.

let ranges = readNdjson("data/gmba_ranges.ndjson").withColumns(
  col.Path.str.split(" > ").alias("path"),
  col.Countries.str.split(", ").alias("countries"),
)
echo ranges.select(col.MapName, col.path, col.Elev_High, col.countries).sort("Elev_High", descending = true).head(6)
shape: (6, 4)
┌──────────────────┬───────────────────────────────────────────┬───────────┬───────────────────────────────────────────┐
│ MapName          ┆ path                                      ┆ Elev_High ┆ countries                                 │
│ ---              ┆ ---                                       ┆ ---       ┆ ---                                       │
│ str              ┆ list[str]                                 ┆ f64       ┆ list[str]                                 │
╞══════════════════╪═══════════════════════════════════════════╪═══════════╪═══════════════════════════════════════════╡
│ Himalaya         ┆ ["Eurasia", "Central Asia", "Himalaya"]   ┆ 8718.0    ┆ ["Afghanistan", "Bhutan", … "Pakistan"]   │
│ Karakoram        ┆ ["Eurasia", "Central Asia", "Karakoram"]  ┆ 8527.0    ┆ ["Afghanistan", "China", … "Pakistan"]    │
│ Hindu Kush       ┆ ["Eurasia", "Central Asia", "Hindu Kush"… ┆ 7645.0    ┆ ["Afghanistan", "Pakistan", … "Turkmenis… │
│ Kunlun Mountains ┆ ["Eurasia", "Central Asia", … "Kunlun Mo… ┆ 7414.0    ┆ ["China", "Pakistan"]                     │
│ Pamir Mountains  ┆ ["Eurasia", "Central Asia", "Pamir Mount… ┆ 7405.0    ┆ ["Afghanistan", "China", … "Tajikistan"]  │
│ Transhimalaya    ┆ ["Eurasia", "Central Asia", … "Transhima… ┆ 7141.0    ┆ ["China", "India", "Myanmar"]             │
└──────────────────┴───────────────────────────────────────────┴───────────┴───────────────────────────────────────────┘

The heights are a fact check of their own. GMBA computes them from a terrain model with cells of a few hundred metres, which shaves off the sharpest tops: the Himalaya reach 8718 m in the inventory, Everest is 8849; the Alps 4713 m, Mont Blanc 4809.

The first element of the path is the continent-sized system the range belongs to. Which ranges cross the most countries? (GMBA's Alps include the foothills, so they reach Hungary and Croatia, ten countries in all.)

echo ranges.filter(col.Feature != "Ocean").select(
  col.MapName, col.countries.list.len.alias("n"), col.Elev_High.alias("top")
).topK(6, by = "n")
echo ranges.groupBy(col.path.list.first.alias("system")).agg(
  len().alias("n"), col.Elev_High.max.alias("highest")
).topK(8, by = "highest")
shape: (6, 3)
┌────────────────────────────┬─────┬────────┐
│ MapName                    ┆ n   ┆ top    │
│ ---                        ┆ --- ┆ ---    │
│ str                        ┆ u32 ┆ f64    │
╞════════════════════════════╪═════╪════════╡
│ Caribbean Islands          ┆ 17  ┆ 3086.0 │
│ European Alps              ┆ 10  ┆ 4713.0 │
│ Cordillera Centroamericana ┆ 9   ┆ 4171.0 │
│ Dinaric Alps               ┆ 8   ┆ 2616.0 │
│ Tian Shan                  ┆ 7   ┆ 7130.0 │
│ Albertine Rift Mountains   ┆ 7   ┆ 4829.0 │
└────────────────────────────┴─────┴────────┘
shape: (8, 3)
┌────────────────┬─────┬─────────┐
│ system         ┆ n   ┆ highest │
│ ---            ┆ --- ┆ ---     │
│ str            ┆ u32 ┆ f64     │
╞════════════════╪═════╪═════════╡
│ Eurasia        ┆ 140 ┆ 8718.0  │
│ South America  ┆ 30  ┆ 6898.0  │
│ North America  ┆ 52  ┆ 6145.0  │
│ Africa         ┆ 36  ┆ 5869.0  │
│ Oceania        ┆ 24  ┆ 4180.0  │
│ Atlantic Ocean ┆ 3   ┆ 3645.0  │
│ Indian Ocean   ┆ 3   ┆ 3033.0  │
│ Pacific Ocean  ┆ 2   ┆ 2273.0  │
└────────────────┴─────┴─────────┘
show plots.worldMap(ranges)
plotting code
proc worldMap*(ranges: DataFrame): PlotJson =
  let r = readParquet("data/relief_world.parquet")
    .select(col.lon, col.lat, (col.ele > 0).cast(Float64).alias("land"))
  let (xs, ys, zs) = grid(r, "land")
  result = finish(@[Trace[float](`type`: PlotType.HeatMap, xs: xs, ys: ys, zs: zs)],
                  "The world's mountain ranges by highest point (GMBA Inventory v2)", 520)
  result.withStyle(0, %*{"colorscale": scale(Land), "showscale": false, "hoverinfo": "skip"})
  let bands = [(0.0, 2000.0, "#f2c48d", "below 2000 m"), (2000.0, 4000.0, "#e08a4c", "2000-4000 m"),
               (4000.0, 6000.0, "#b54b2a", "4000-6000 m"), (6000.0, 9000.0, "#5e1a0e", "above 6000 m")]
  let land = ranges.filter(col.Feature != "Ocean")
  for (lo, hi, color, label) in bands:
    var jx = newJArray()
    var jy = newJArray()
    let band = land.filter(col.Elev_High.isBetween(lo, hi, closed = ClosedInterval.Left))
    for outline in band.toList("outline", seq[seq[seq[float]]]):
      for ring in outline:
        for p in ring:
          jx.add %p[0]; jy.add %p[1]
        jx.add newJNull(); jy.add newJNull()
    result.traces.add %*{"type": "scatter", "mode": "lines", "fill": "toself", "fillcolor": color,
                         "line": {"width": 0.3, "color": color}, "name": label, "x": jx, "y": jy,
                         "hoverinfo": "skip"}
  result.layout["legend"] = %*{"orientation": "h", "y": -0.08}
  result.layout["xaxis"] = %*{"range": [-180, 180], "showgrid": false, "constrain": "domain"}
  result.layout["yaxis"] = %*{"range": [-60, 80], "scaleanchor": "x", "scaleratio": 1,
                              "showgrid": false, "constrain": "domain"}

14. Above 8000, according to Wikidata↑ contents

There are fourteen mountains higher than 8000 metres, all in the Himalaya and the Karakoram. Ask Wikidata, the free knowledge base behind Wikipedia, for every "mountain" with an elevation of at least 8000, and you get rather more.

let wd = readCsv("data/wd_8000.csv").unique("m", keep = First)
echo wd.height
echo wd.sort("elev", descending = true).select(col.mLabel, col.elev, col.coord, col.countries).head(6)
1201
shape: (6, 4)
┌─────────────────┬─────────┬───────────────────────────────────────────┬───────────────┐
│ mLabel          ┆ elev    ┆ coord                                     ┆ countries     │
│ ---             ┆ ---     ┆ ---                                       ┆ ---           │
│ str             ┆ f64     ┆ str                                       ┆ str           │
╞═════════════════╪═════════╪═══════════════════════════════════════════╪═══════════════╡
│ Olympus Mons    ┆ 21229.0 ┆  Po… ┆ null          │
│ Ascraeus Mons   ┆ 18225.0 ┆  Po… ┆ null          │
│ Tharsis Montes  ┆ 18200.0 ┆  Po… ┆ null          │
│ Boösaule Montes ┆ 17850.0 ┆  P… ┆ null          │
│ Arsia Mons      ┆ 17761.0 ┆  Po… ┆ null          │
│ Mount Blackburn ┆ 16390.0 ┆ Point(-143.439297222 61.731908333)        ┆ United States │
└─────────────────┴─────────┴───────────────────────────────────────────┴───────────────┘

Olympus Mons is on Mars (the coordinates start with the Wikidata id of the planet), and the long tail is mostly American summits whose height was entered in feet. Keep the Earth, keep metres (nothing on Earth is higher than Everest's 8849), split the climbers into a list, and look at what is left.

let high = wd.filter(
    not col.coord.str.startsWith("<"),
    col.elev <= 8849,
    col.countries.str.contains("Nepal|China|Pakistan|India"),
  )
  .select(
    col.mLabel.alias("peak"),
    col.elev.alias("height"),
    col.prom.alias("prom_m"),
    col.date.str.slice(0, 4).cast(Int32).alias("year"),
    col.climbers.str.split("|").alias("party"),
    col.countries.str.split("|").alias("countries"),
    col.coord.str.extractGroups(r"Point\((?<lon>[-\d.]+) (?<lat>[-\d.]+)\)").alias("where"),
  )
  .unnest("where")
  .withColumns(col("lon", "lat").cast(Float64))
  .sort("height", descending = true)
echo high.drop(["lon", "lat"])
shape: (15, 6)
┌───────────────┬────────┬────────┬──────┬──────────────────────────────────────┬──────────────────────────────────────┐
│ peak          ┆ height ┆ prom_m ┆ year ┆ party                                ┆ countries                            │
│ ---           ┆ ---    ┆ ---    ┆ ---  ┆ ---                                  ┆ ---                                  │
│ str           ┆ f64    ┆ f64    ┆ i32  ┆ list[str]                            ┆ list[str]                            │
╞═══════════════╪════════╪════════╪══════╪══════════════════════════════════════╪══════════════════════════════════════╡
│ Mount Everest ┆ 8848.9 ┆ 8848.9 ┆ 1953 ┆ ["Edmund Hillary", "Tenzing Norgay"] ┆ ["Nepal", "People's Republic of      │
│               ┆        ┆        ┆      ┆                                      ┆ China"]                              │
│ K2            ┆ 8611.0 ┆ 4020.0 ┆ 1954 ┆ ["Lino Lacedelli", "Achille          ┆ ["Pakistan"]                         │
│               ┆        ┆        ┆      ┆ Compagnoni"]                         ┆                                      │
│ Kanchenjunga  ┆ 8586.0 ┆ 3922.0 ┆ 1955 ┆ ["George Band", "Joe Brown"]         ┆ ["Nepal", "India"]                   │
│ Lhotse        ┆ 8516.0 ┆ 610.0  ┆ 1956 ┆ ["Ernst Reiss", "Fritz Luchsinger"]  ┆ ["Nepal", "People's Republic of      │
│               ┆        ┆        ┆      ┆                                      ┆ China"]                              │
│ Makalu        ┆ 8485.0 ┆ 2378.0 ┆ 1955 ┆ ["Lionel Terray", "Jean Couzy"]      ┆ ["Nepal", "People's Republic of      │
│               ┆        ┆        ┆      ┆                                      ┆ China"]                              │
│ Lhotse Shar   ┆ 8383.0 ┆ 86.0   ┆ 1970 ┆ ["Sepp Mayerl"]                      ┆ ["Nepal", "People's Republic of      │
│               ┆        ┆        ┆      ┆                                      ┆ China"]                              │
│ …             ┆ …      ┆ …      ┆ …    ┆ …                                    ┆ …                                    │
│ Nanga Parbat  ┆ 8126.0 ┆ 4608.0 ┆ 1953 ┆ ["Hermann Buhl"]                     ┆ ["Pakistan"]                         │
│ Annapurna I   ┆ 8091.0 ┆ 2984.0 ┆ 1950 ┆ ["Louis Lachenal", "Maurice Herzog"] ┆ ["Nepal"]                            │
│ Gasherbrum    ┆ 8080.0 ┆ 2155.0 ┆ 1958 ┆ null                                 ┆ ["Pakistan", "People's Republic of   │
│               ┆        ┆        ┆      ┆                                      ┆ China…                               │
│ Broad Peak    ┆ 8051.0 ┆ 1701.0 ┆ 1957 ┆ ["Kurt Diemberger", "Fritz           ┆ ["Pakistan", "People's Republic of   │
│               ┆        ┆        ┆      ┆ Wintersteller…                       ┆ China…                               │
│ Gasherbrum II ┆ 8034.0 ┆ 1524.0 ┆ 1956 ┆ ["Fritz Moravec", "Hans Willenpart", ┆ ["Pakistan", "People's Republic of   │
│               ┆        ┆        ┆      ┆ "Se…                                 ┆ China…                               │
│ Shishapangma  ┆ 8027.0 ┆ 2897.0 ┆ 1964 ┆ ["Wang Fuzhou"]                      ┆ ["People's Republic of China"]       │
└───────────────┴────────┴────────┴──────┴──────────────────────────────────────┴──────────────────────────────────────┘

Fifteen, not fourteen: Lhotse Shar rises only 86 metres above its col with Lhotse, the kind of bump the UIAA had to rule on in the Alps. Keep the peaks with at least 300 m of prominence and the classic fourteen are back. Then explode the parties: does anyone appear twice?

echo high.filter(col.prom_m >= 300).height
echo high.explode("party").dropNulls("party").groupBy("party").agg(
  col.peak, len().alias("n")
).filter(col.n > 1)
14
shape: (1, 3)
┌──────────────┬────────────────────────────────┬─────┐
│ party        ┆ peak                           ┆ n   │
│ ---          ┆ ---                            ┆ --- │
│ str          ┆ list[str]                      ┆ u32 │
╞══════════════╪════════════════════════════════╪═════╡
│ Hermann Buhl ┆ ["Nanga Parbat", "Broad Peak"] ┆ 2   │
└──────────────┴────────────────────────────────┴─────┘

Hermann Buhl, the Austrian who reached the top of Nanga Parbat alone in 1953 and was in the four-man team on Broad Peak in 1957, is the only person with two first ascents of 8000ers in our data. Here are the fifteen, with the coordinates we pulled out of Wikidata's Point(lon lat) strings:

show plots.himalayaMap(high)
plotting code
proc himalayaMap*(high: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_himalaya.parquet", 7000)
  let dots = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "8000ers",
                          xs: high.toList("lon", float), ys: high.toList("lat", float),
                          text: high.toList("peak", string))
  result = finish(@[bg, dots], "The fourteen 8000ers, plus Lhotse Shar", 480)
  result.withStyle(0, bgStyle)
  result.withStyle(1, %*{"marker": {"size": 9, "color": Red, "symbol": "triangle-up",
                                    "line": {"width": 1, "color": "white"}}, "hoverinfo": "text"})
  for r in high.rows(tuple[peak: string, lon, lat: float]):
    var (ax, ay) = (0, -30)
    for (p, x, y) in Offsets:
      if p == r.peak: (ax, ay) = (x, y)
    result.note(r.lon, r.lat, r.peak, ax = ax, ay = ay, size = 10)
  result.layout["showlegend"] = %false
  result.geoAxes((73.0, 89.5), (26.8, 36.6))

15. Two golden ages↑ contents

The fourteen were first climbed between Annapurna in 1950 and Shishapangma in 1964, a golden age of Himalayan climbing that looks a lot like the Alpine one a century earlier. Stack the two tables (vstack needs the same columns) and compare.

let alps = fixed.select(col.year, lit("Alps 4000").alias("region"))
let himalaya = high.filter(col.prom_m >= 300).select(col.year, lit("8000ers").alias("region"))
let both = alps.vstack(himalaya).dropNulls
echo both.groupBy("region").agg(
  len().alias("n"),
  col.year.min.alias("first"),
  col.year.median.alias("median"),
  col.year.max.alias("last"),
  (col.year.quantile(0.75) - col.year.quantile(0.25)).alias("years_for_middle_half"),
).sort("region")
shape: (2, 6)
┌───────────┬─────┬───────┬────────┬──────┬───────────────────────┐
│ region    ┆ n   ┆ first ┆ median ┆ last ┆ years_for_middle_half │
│ ---       ┆ --- ┆ ---   ┆ ---    ┆ ---  ┆ ---                   │
│ str       ┆ u32 ┆ i32   ┆ f64    ┆ i32  ┆ f64                   │
╞═══════════╪═════╪═══════╪════════╪══════╪═══════════════════════╡
│ 8000ers   ┆ 14  ┆ 1950  ┆ 1955.5 ┆ 1964 ┆ 3.0                   │
│ Alps 4000 ┆ 74  ┆ 1784  ┆ 1863.5 ┆ 1957 ┆ 22.0                  │
└───────────┴─────┴───────┴────────┴──────┴───────────────────────┘

The middle half of the Alpine first ascents took 22 years; for the Himalayan giants it took 3.

16. Saving it, as JSON↑ contents

Nested data goes back to JSON as easily as it came in: one line per trek, with the stage list intact.

let summary = legs.withColumns(col("km", "up", "down", "hours").round(1)).join(
  ways.groupBy("trek").agg(col.stage.unique(maintainOrder = true).alias("stages")), on = ["trek"], how = Left, maintainOrder = MaintainOrderJoin.Left
)
let path = getTempDir() / "treks_summary.ndjson"
summary.writeNdjson(path)
let line = readFile(path).splitLines[0]
echo line[0 ..< min(200, line.len)]
{"trek":"Tour des Combins","km":100.2,"up":6434.8,"down":6430.2,"hours":46.8,"days_of_7h":6.7,"stages":["Tour des Combins - stage 1 - BOURG-ST- PIERRE - CABANE COL DE MILLE","Tour des Combins - stage 

What this post used from Nanuq 0.5↑ contents

The Python twin of this post, which recorded the outputs it is checked against, is blog/mountains/mountains.py; the figures are in plots.nim and figs.py; the data preparation scripts are in src/. How these APIs were chosen is in Designing Nanuq 0.5.

Sources: the UIAA list of Alpine four-thousanders as published on English Wikipedia; Wikidata; Camptocamp; OpenStreetMap contributors (ODbL), through Waymarked Trails; the AWS Terrain Tiles (Mapzen/Tilezen terrain); the GMBA Mountain Inventory v2 (Snethlage et al. 2022, earthenv.org). Downloaded on 1 November 2026.

Source files↑ contents

Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.

docs/blog/mountains/mountains.py 705 lines
# %% [markdown]
# # Above 4000
#
# *Nanuq 0.5 explainer, Python draft (py-polars 2.1). Every cell below will become a Nim
# block in the post, written against the 0.5 API. The outputs here are what the Nim
# version must print.*
#
# Mountain data is never flat. A summit has a height, but also a list of countries it
# sits on, a list of people who first stood on top, a parent peak, a col. A trek is a
# list of stages, each a list of paths, each a list of points, each a longitude, a
# latitude and an elevation. Wikipedia tables pack all of this into strings, and
# OpenStreetMap hands it out as JSON nested five levels deep.
#
# That makes mountains the perfect playground for what is new in Nanuq 0.5: **lists,
# arrays and structs**, splitting and decoding strings into them, **JSON** in and out,
# **SQL** queries, and **Nim callbacks** for the bits no built-in expression covers.
#
# The first part stays in the Alps: the 82 official summits above 4000 metres, and eight
# classic multi-day treks around them. The second part zooms out to the mountain ranges
# of the whole world and its fourteen peaks above 8000 metres.
#
# Data, all public, downloaded on 1 November 2026: the UIAA list of Alpine four-thousanders
# as published on English Wikipedia; summit coordinates from Wikidata and Camptocamp; hiking
# routes from OpenStreetMap through Waymarked Trails; elevations from the AWS Terrain Tiles;
# the GMBA Mountain Inventory v2 for the world's ranges; Wikidata for the 8000-metre peaks.

# %%
# id: setup
import math
import os
import tempfile

import polars as pl

import figs  # Plotly charts and maps; the Nim post redoes them with nim-plotly

pl.Config(tbl_rows=12, tbl_cols=10, tbl_width_chars=120, fmt_str_lengths=40, float_precision=1);

# %% [markdown]
# ## Part 1: The Alps
#
# ## 1. Eighty-two summits
#
# How many mountains in the Alps are higher than 4000 metres? It depends on what you call
# a mountain. Mont Blanc has a dozen bumps above 4000 m on its shoulders; is each one a
# summit? In 1994 the UIAA, the international federation of mountaineering clubs, settled
# it with an official list of **82 four-thousanders**, using a mix of topography (how far
# a peak rises above the col that joins it to a higher one) and mountaineering judgement.
#
# Wikipedia has the list as a table. We saved it as a CSV exactly as it comes, footnote
# markers and all.

# %%
# id: s01_raw
raw = pl.read_csv("data/uiaa_4000ers_raw.csv").filter(pl.col("Nr.").is_not_null())
raw.glimpse(max_items_per_column=3)

# %% [markdown]
# Every column after the height is a string with more than one thing inside. Country is
# a list of countries. Isolation (the distance to the nearest higher point) carries the
# name of that point. Prominence carries the name of the col. First ascent is a date
# followed by a list of people. Let's take them apart one at a time.
#
# ## 2. Countries: from a string to a list
#
# The Country column has slashes, spaces and footnotes: `France/ Italy [9]`,
# `France Italy`, `Italy/Switzerland`. We strip the footnotes, split on slashes and
# spaces, and drop the empty pieces. What comes back is a column of type
# `list[str]`.

# %%
# id: s02_countries
peaks = raw.select(
    nr=pl.col("Nr.").cast(pl.Int64),
    summit=pl.col("Summit").str.replace_all(r"\[.*?\]", ""),
    height=pl.col("Height (m)").cast(pl.Int64),
    range=pl.col("Range"),
    countries=pl.col("Country")
    .str.replace_all(r"\[\d+\]", "")
    .str.replace_all(r"[/ ]+", "/")
    .str.strip_chars("/")
    .str.split("/"),
    isolation=pl.col("Isolation[6] (km)"),
    prominence=pl.col("Prominence[6] (m)"),
    first_ascent=pl.col("First ascent[7]"),
)
peaks.select("summit", "height", "countries").head(8)

# %% [markdown]
# A list column can be measured with `list.len`, searched with `list.contains`, and
# turned back into rows with `explode`. Here is how many four-thousanders each country
# can claim, how many sit right on a border, and which countries share them (sorting and
# joining each list gives one label per combination).

# %%
# id: s02_per_country
print(peaks.explode("countries")["countries"].value_counts(sort=True))
print(peaks.select(on_a_border=(pl.col("countries").list.len() > 1).sum()))
print(peaks.group_by(pl.col("countries").list.sort().list.join(" + ")).len().sort(
    "len", "countries", descending=[True, False]
))

# %% [markdown]
# Switzerland has 48, Italy 38, France 26, which adds up to more than 82 because 30
# summits sit on a border: 17 between Italy and Switzerland, 13 between France and Italy.
# Only 13 are entirely French and 8 entirely Italian, against 31 entirely Swiss, and not
# a single one stands on the French-Swiss border. Mont Blanc is on the French-Italian
# one, and France and Italy have disagreed about exactly where that border runs over
# the top since the 18th century.
#
# ## 3. Prominence: from a string to a struct
#
# Prominence is how far a peak rises above the lowest col you must cross to reach
# anything higher. It is the number mountaineers use to tell a mountain from a bump on
# a ridge. The column packs the number and the name of that col into one string,
# `1,043  Col Durand`, and Isolation does the same with a distance and the nearest higher
# peak.
#
# `str.extract_groups` pulls both parts out at once into a **struct**: a single column
# whose values have named fields, like a small row inside a row. `struct.field` reads
# one field back, `unnest` spreads them all into columns.

# %%
# id: s03_structs
parts = peaks.select(
    "summit",
    "height",
    prom=pl.col("prominence").str.extract_groups(r"^(?<metres>[\d,]+)\s+(?<col>.*)$"),
    iso=pl.col("isolation").str.extract_groups(r"^(?<km>[\d.,]+)\s+(?<higher>.*)$"),
)
print(", ".join(f.name for f in parts.schema["prom"].fields))
parts.head(5)

# %% [markdown]
# Careful with the commas. Prominence uses them as thousands separators (`2,165`), and
# so does isolation, except that isolation also has decimals (`0.6`). A naive cast of
# Mont Blanc's isolation, `2,812`, as a decimal comma would put the nearest higher point
# 2.8 km away; it is Elbrus, in the Caucasus, 2812 km away. We drop the commas before
# casting.

# %%
# id: s03_prominence
peaks = peaks.with_columns(
    prom_m=pl.col("prominence").str.extract(r"^([\d,]+)").str.replace_all(",", "").cast(pl.Int64),
    col=pl.col("prominence").str.extract(r"^[\d,]+\s+(.*)$").str.replace_all(r"\s*\[.*?\]", ""),
    iso_km=pl.col("isolation").str.extract(r"^([\d.,]+)").str.replace_all(",", "").cast(pl.Float64),
    higher=pl.col("isolation").str.extract(r"^[\d.,]+\s+(.*)$"),
)
print(peaks.select(
    over_1000=(pl.col("prom_m") >= 1000).sum(),
    under_100=(pl.col("prom_m") < 100).sum(),
    under_30=(pl.col("prom_m") < 30).sum(),
))
peaks.top_k(8, by="prom_m").select("summit", "height", "prom_m", "col", "iso_km", "higher")

# %% [markdown]
# Only 12 of the 82 are mountains in their own right by the 1000-metre rule. Mont
# Blanc's prominence is its whole height above the lowest col on the way to anything
# taller, which is somewhere in the flatlands of Russia. Two in five (33) rise less than
# 100 metres above their col, six of them less than 30: shoulders and towers of bigger mountains,
# kept because climbers treat them as separate goals.
#
# ## 4. Who climbed them first
#
# The First ascent column is the messiest of all:
# `14 July 1865  Croz, Taugwalder, Whymper, Hudson, Douglas and Hadow`. We take the
# year with a regular expression, and turn the rest into a list of names by treating
# "and" (and the German "mit", which slipped into the English page) as commas.

# %%
# id: s04_ascents
ascents = peaks.select(
    "summit",
    "height",
    year=pl.col("first_ascent").str.extract(r"(\d{4})").cast(pl.Int32),
    party=pl.col("first_ascent")
    .str.replace(r"^.*?\d{4}(\[\d+\])?\s*", "")
    .str.replace_all(r"\[.*?\]|\(.*?\)|\".*?\"", "")
    .str.replace_all(r" (and|mit) ", ", ")
    .str.split(",")
    .list.eval(pl.element().str.strip_chars()),
)
ascents.head(6)

# %% [markdown]
# Explode the lists and count: who stood first on the most four-thousanders?

# %%
# id: s04_who
ascents.explode("party").drop_nulls("party")["party"].value_counts(sort=True).head(8)

# %% [markdown]
# Melchior Anderegg, a mountain guide from the Bernese Oberland, leads with six, ahead
# of Christian Almer, another Oberland guide, with five. Most of the famous names of the
# period show up with three or four: the British climbers Leslie Stephen, Horace Walker
# and Edward Whymper, the Chamonix guides Michel Croz and Michel-Clément Payot. And the
# list has its limits: when the page says "Jakob and Melchior Anderegg", our split gives
# a lone "Jakob". We fix that in section 9 with a Nim callback.
#
# When did all this happen? Group the years by decade.

# %%
# id: s04_decades
with pl.Config(tbl_rows=20):
    print(ascents.group_by((pl.col("year") // 10 * 10).alias("decade")).len().sort("decade"))
print(ascents.select(
    dated=pl.col("year").is_not_null().sum(),
    golden_age=pl.col("year").is_between(1854, 1865).sum(),
    first=pl.col("year").min(),
    last=pl.col("year").max(),
))

# %% [markdown]
# Mountaineers call the years from 1854 (the Wetterhorn) to 1865 (the Matterhorn) the
# **golden age of alpinism**. Of the 74 summits with a known year, 36 were first climbed
# in those twelve seasons. The very first was the Dôme du Goûter in 1784, two years before
# Mont Blanc itself; the last was the Grand Pilier d'Angle, climbed by Walter Bonatti and
# Toni Gobbi in 1957.
#
# ## 5. On the map
#
# The list has no coordinates, so we join them in from a separate file built from
# Wikidata and Camptocamp (see `src/peaks_prep.py`), on the list number.

# %%
# id: s05_join
coords = pl.read_csv("data/uiaa_coords.csv")
peaks = peaks.join(coords, on="nr", how="left", validate="1:1")
with pl.Config(float_precision=4):
    print(peaks.select("summit", "height", "lon", "lat", "source").head(5))

# %%
# id: fig_peaks
figs.alps_map(peaks)

# %% [markdown]
# All 82 fit in a strip about 250 km long, from the Barre des Écrins in the south-west to
# Piz Bernina in the east, and most crowd around two centres: the Mont Blanc massif and
# the Valais around Zermatt.
#
# ## 6. Eight treks, as JSON
#
# You don't need a rope to see these mountains up close. Several classic multi-day treks
# go around them, hut to hut: the Tour du Mont Blanc, the Tour du Cervin around the
# Matterhorn, the Tour Monte Rosa, the Tour des Combins, the Walker's Haute Route from
# Chamonix to Zermatt, and further south and east the Alta Via 1 of the Aosta Valley and
# the Alte Vie 1 and 2 of the Dolomites.
#
# OpenStreetMap volunteers have mapped all of them as *route relations*: a route made of
# stages, a stage made of ways (stretches of path), a way made of points. We downloaded
# each one from Waymarked Trails, sampled the terrain height at every point, and saved
# them as newline-delimited JSON, one trek per line, keeping the nesting
# (`src/treks_prep.py`). `read_ndjson` reads it into eight rows.

# %%
# id: s06_read
treks = pl.read_ndjson("data/treks.ndjson", infer_schema_length=None)
print(treks.shape)
print(", ".join(f.name for f in treks.schema["stages"].inner.fields))
treks.select("id", "name", n_stages=pl.col("stages").list.len())

# %% [markdown]
# Eight rows, but a lot inside them. The `stages` column is a list of structs; each
# stage struct holds a list of way structs; each way holds an OpenStreetMap `tags`
# struct and a list of points, each point a list of three numbers. How many tag fields?

# %%
# id: s06_tags
way_type = treks.schema["stages"].inner.fields[3].dtype.inner
tag_fields = [f.name for f in way_type.fields[3].dtype.fields]
print(len(tag_fields), ", ".join(sorted(tag_fields)[:12]))

# %% [markdown]
# 166 of them. Every way carries only the few tags someone bothered to map, and
# the struct holds the union of all of them, with nulls everywhere else.
#
# ## 7. Unnesting, level by level
#
# Two `explode`s and two `unnest`s turn eight treks into one row per way. On the way we
# give the long official names shorter labels.

# %%
# id: s07_ways
short = {
    "Tour du Mont Blanc - Itinéraire principal": "Tour du Mont Blanc",
    "Alta via n. 1 delle Dolomiti - Dolomiten-Höhenweg Nr. 1": "Alta Via 1 Dolomites",
    "Alta Via n. 2 delle Dolomiti - Dolomiten-Höhenweg Nr. 2": "Alta Via 2 Dolomites",
    "Alta Via n. 1 della Valle d'Aosta": "Alta Via 1 Aosta",
}
ways = (
    treks.select(trek=pl.col("name").replace(short), stages="stages")
    .explode("stages")
    .unnest("stages")
    .rename({"id": "stage_id", "name": "stage"})
    .explode("ways")
    .unnest("ways")
    .rename({"id": "way_id"})
)
print(ways.shape)
ways.select("trek", "stage", "way_id", "length", "points").head(4)

# %% [markdown]
# Now the tags. OpenStreetMap grades mountain paths on the SAC scale, from Swiss Alpine
# Club practice: T1 is a walk, T3 a demanding mountain path, T5 and T6 alpine terrain
# where you may need your hands and a head for heights. `struct.field` picks it out of
# the big tags struct, and a group-by sums the lengths per grade.

# %%
# id: s07_sac
grades = {"hiking": "T1", "mountain_hiking": "T2", "demanding_mountain_hiking": "T3",
          "alpine_hiking": "T4", "demanding_alpine_hiking": "T5", "difficult_alpine_hiking": "T6"}
sac = (
    ways.with_columns(sac=pl.col("tags").struct.field("sac_scale").replace_strict(grades, default="none"))
    .group_by("trek", "sac")
    .agg(km=pl.col("length").sum() / 1000)
    .pivot(on="sac", index="trek", values="km", sort_columns=True)
    .fill_null(0)
    .sort("trek")
)
sac

# %% [markdown]
# OpenStreetMap stores the grades as words (`mountain_hiking`), which we map back to
# the T1-T6 the signposts use; `none` means no grade was mapped (often roads and forest
# tracks).
# The SAC grades also tell the treks apart: the Dolomite Alte Vie and the Tour du Cervin
# have kilometres of T4 and harder, the Tour du Mont Blanc stays mostly on
# T1-T2 paths.
#
# ## 8. Points: lists, arrays, and a map projection
#
# Each point is `[x, y, elevation]`. The x and y are Web Mercator metres, the projection
# of every web map. Since every point has exactly three values, we can cast the inner
# list to a fixed-size **array**, and read it with the `arr` namespace.

# %%
# id: s08_points
R = 6378137.0  # Web Mercator sphere radius, metres
pts = (
    ways.select("trek", "stage", "way_id", "points")
    .with_row_index("way_seq")
    .explode("points")
    .with_columns(pl.col("points").cast(pl.Array(pl.Float64, 3)))
    .select(
        "trek", "stage", "way_seq",
        x=pl.col("points").arr.get(0),
        y=pl.col("points").arr.get(1),
        ele=pl.col("points").arr.get(2),
    )
    .with_columns(
        lon=pl.col("x") / R * 180 / math.pi,
        lat=(pl.col("y") / R).sinh().arctan() * 180 / math.pi,
    )
)
print(pts.height)
pts.head(4)

# %% [markdown]
# A distance in Web Mercator metres is stretched by 1/cos(latitude), about 1.43 at 46°N,
# so we shrink each step back. Steps are measured within a way, so gaps between
# disconnected ways don't count.

# %%
# id: s08_distance
pts = pts.with_columns(
    step=((pl.col("x").diff() ** 2 + pl.col("y").diff() ** 2).sqrt()
          * (pl.col("lat") * math.pi / 180).cos()).over("way_seq").fill_null(0)
).with_columns(km=pl.col("step").cum_sum().over("trek") / 1000)
pts.group_by("trek").agg(
    km=pl.col("step").sum() / 1000,
    top=pl.col("ele").max(),
    bottom=pl.col("ele").min(),
).sort("km")

# %%
# id: fig_treks
figs.treks_map(pts, peaks)

# %% [markdown]
# Two of the eight are far to the east, in the Dolomites, where the limestone towers top
# out at 3343 m (the Marmolada) and there are no four-thousanders at all.

# %%
# id: fig_dolomites
figs.dolomites_map(pts)

# %% [markdown]
# ## 9. How much climbing? It depends on how closely you look
#
# Guidebooks give the Tour du Mont Blanc about 170 km and **10,000 metres of ascent**.
# Our 166 km match the first number. For the second, you add up every rise along the
# way. But a terrain model has noise, and every little up-and-down gets counted, so the
# answer depends on how finely you sample. Average the height over bins of increasing
# length and watch the total ascent shrink.

# %%
# id: s09_ascent
def ascent(bin_km):
    return (
        pts.group_by("trek", (pl.col("km") / bin_km).floor().alias("bin"))
        .agg(pl.col("ele").mean())
        .sort("trek", "bin")
        .group_by("trek")
        .agg(pl.col("ele").diff().clip(lower_bound=0).sum().round().alias(f"{int(bin_km * 1000)} m"))
    )

table = ascent(0.05)
for b in [0.1, 0.2, 0.5, 1.0]:
    table = table.join(ascent(b), on="trek")
table.sort("trek")

# %% [markdown]
# Bins of 100 metres give the Tour du Mont Blanc 10,183 metres, right on the guidebook
# figure; with 1 km bins the passes are smoothed away and only 8,257 m remain. We'll use
# 100 metres from here on.

# %%
# id: fig_profile
passes = pl.DataFrame({
    "km": [8.0, 23.6, 48.0, 64.1, 73.3, 105.5, 152.3],
    "label": ["Brévent", "Col de Voza", "Croix du Bonhomme", "Col de la Seigne",
              "Mont Favre", "Grand Col Ferret", "Col de Balme"],
})
tmb = pts.filter(pl.col("trek") == "Tour du Mont Blanc").sort("km")
labels = passes.join_asof(tmb.select("km", "ele"), on="km", strategy="nearest")
figs.profile(pts, "Tour du Mont Blanc", labels)

# %% [markdown]
# ## 10. The guidebook's words, decoded
#
# The Aosta Valley's Alta Via 1 is split into 17 official stages, and each stage in
# OpenStreetMap carries its itinerary as a list of strings with the altitude written in:
# `Sassa (1430 mt.)`. `list.eval` runs an expression on every element of a list, so we
# can pull the numbers out of all of them at once and compare them with what the
# terrain model says at the start and end of each stage.

# %%
# id: s10_stages
av1 = (
    ways.filter(pl.col("trek") == "Alta Via 1 Aosta")
    .group_by("stage_id", maintain_order=True)
    .agg(pl.col("stage").first(), pl.col("itinerary").first())
    .with_columns(
        stop_m=pl.col("itinerary").list.eval(
            pl.element().str.extract(r"\((\d[\d.]*)\s*mt?\.?\)").str.replace_all(r"\.", "").cast(pl.Int64)
        ),
        stage_no=pl.col("stage").str.extract(r"Tappa (\d+)").cast(pl.Int64),
    )
    .sort("stage_no")
)
av1.select("stage_no", "itinerary", "stop_m").head(6)

# %% [markdown]
# Now the check. For each stage, take the terrain height at its first and last point,
# put them in a list too, and compare the two lists element by element.

# %%
# id: s10_check
ends = pts.group_by("stage", maintain_order=True).agg(
    dem_m=pl.concat_list(pl.col("ele").first(), pl.col("ele").last()).first()
)
check = av1.join(ends, on="stage").with_columns(
    diff_m=pl.max_horizontal(
        (pl.col("dem_m").list.get(i) - pl.col("stop_m").list.get(i)).abs() for i in (0, 1)
    ).round().cast(pl.Int64)
)
check.filter(pl.col("diff_m") > 150).select("stage_no", "itinerary", "stop_m", "dem_m", "diff_m")

# %% [markdown]
# Fourteen of the seventeen stages agree with the terrain within 150 metres, about as
# close as you can expect from a terrain model and a signpost. Two of the misfits share
# one typo: the village of Niel is written `Niel 1(550 mt.)`, a misplaced bracket that
# turns 1550 m into a 550-metre valley floor (the terrain says 1567). The third is a hole
# in the map: stage 15 should climb to the Rifugio Frassati at 2540 m, but its mapped path
# stops 500 metres lower, and stage 16 picks up from the hut.

# %% [markdown]
# ## 11. Walking time, with a Nim callback
#
# Swiss and German signposts give walking times, not distances, using a rule of thumb
# (DIN 33466): 4 km per hour on the flat, 300 metres of ascent per hour, 500 metres of
# descent per hour; take the larger of the horizontal and vertical times and add half
# the smaller.
#
# That rule fits in an expression, but it reads better as a plain function, and that is
# what callbacks are for: `map_elements` hands each value (here a struct with three
# fields) to your own function. In Nim, the function is a regular proc on a tuple, and
# runs at native speed.

# %%
# id: s11_time
def walking_hours(s):
    horizontal = s["km"] / 4
    vertical = s["up"] / 300 + s["down"] / 500
    return max(horizontal, vertical) + min(horizontal, vertical) / 2

legs = (
    pts.group_by("trek", (pl.col("km") / 0.1).floor().alias("bin"))
    .agg(pl.col("ele").mean(), pl.col("km").max())
    .sort("trek", "bin")
    .with_columns(d=pl.col("ele").diff().over("trek").fill_null(0))
    .group_by("trek")
    .agg(
        km=pl.col("km").max(),
        up=pl.col("d").clip(lower_bound=0).sum(),
        down=-pl.col("d").clip(upper_bound=0).sum(),
    )
    .with_columns(
        hours=pl.struct("km", "up", "down").map_elements(walking_hours, return_dtype=pl.Float64)
    )
    .with_columns(days_of_7h=(pl.col("hours") / 7).round(1))
    .sort("hours")
)
legs

# %% [markdown]
# The rule puts the Tour du Mont Blanc at 75 hours of walking, just under 11 days of
# seven hours, which is the classic 11-stage itinerary. The Aosta Valley's Alta Via 1
# is the longest of the eight, more than two weeks.
#
# The callback also rescues the first ascents from section 4. When a party is written
# as "Jakob and Melchior Anderegg", the two people share one surname, and no regular
# expression is going to know which words are first names. A small function can: if an
# entry is a single word and the next one has a surname, borrow it.

# %%
# id: s11_names
def lend_surnames(party):
    out = []
    for i, name in enumerate(party):
        if " " not in name and name[:1].isupper() and i + 1 < len(party) and " " in party[i + 1]:
            name = name + " " + party[i + 1].split(" ")[-1]
        out.append(name)
    return out

fixed = ascents.with_columns(
    party=pl.col("party").map_elements(lend_surnames, return_dtype=pl.List(pl.String))
)
fixed.explode("party").filter(pl.col("party").str.contains("Anderegg"))["party"].value_counts(sort=True)

# %% [markdown]
# The ranking doesn't move, but the Anderegg family is now complete:
#
# ## 12. Asking in SQL
#
# Not everyone thinks in method chains. Nanuq 0.5 can register frames in a SQL context
# and query them by name. Which range has the most four-thousanders, and how high and
# prominent are they?

# %%
# id: s12_sql
ctx = pl.SQLContext(peaks=peaks.drop("countries"), treks=legs)
ctx.execute("""
    SELECT range, CAST(COUNT(*) AS BIGINT) AS n, MAX(height) AS highest, ROUND(AVG(prom_m)) AS avg_prom
    FROM peaks
    GROUP BY range
    ORDER BY n DESC, highest DESC
""", eager=True)

# %% [markdown]
# ## Part 2: The world
#
# ## 13. Every mountain range on Earth
#
# Geographers at the University of Bern (the GMBA, Global Mountain Biodiversity
# Assessment) have drawn the outline of every named mountain range on Earth, and put
# them into a hierarchy: Alps, Western Alps, Pennine Alps, and so on. We use their
# selection of about 300 major ranges, saved as NDJSON with the outlines simplified
# (`src/gmba_prep.py`). The `Path` column is the hierarchy as one string,
# `Europe > Alps`, and `Countries` is another list in disguise.

# %%
# id: s13_ranges
ranges = pl.read_ndjson("data/gmba_ranges.ndjson").with_columns(
    path=pl.col("Path").str.split(" > "),
    countries=pl.col("Countries").str.split(", "),
)
ranges.select("MapName", "path", "Elev_High", "countries").sort("Elev_High", descending=True).head(6)

# %% [markdown]
# The heights are a fact check of their own. GMBA computes them from a terrain model
# with cells of a few hundred metres, which shaves off the sharpest tops: the Himalaya
# reach 8718 m in the inventory, Everest is 8849; the Alps 4713 m, Mont Blanc 4809.
#
# The first element of the path is the continent-sized system the range belongs to.
# Which ranges cross the most countries? (GMBA's Alps include the foothills, so they reach
# Hungary and Croatia, ten countries in all.)

# %%
# id: s13_countries
print(ranges.filter(pl.col("Feature") != "Ocean").select(
    "MapName", n=pl.col("countries").list.len(), top=pl.col("Elev_High")
).top_k(6, by="n"))
print(ranges.group_by(system=pl.col("path").list.first()).agg(
    n=pl.len(), highest=pl.col("Elev_High").max()
).top_k(8, by="highest"))

# %%
# id: fig_world
figs.world_map(ranges)

# %% [markdown]
# ## 14. Above 8000, according to Wikidata
#
# There are fourteen mountains higher than 8000 metres, all in the Himalaya and the
# Karakoram. Ask Wikidata, the free knowledge base behind Wikipedia, for every
# "mountain" with an elevation of at least 8000, and you get rather more.

# %%
# id: s14_wikidata
wd = pl.read_csv("data/wd_8000.csv").unique("m", keep="first")
print(wd.height)
wd.sort("elev", descending=True).select("mLabel", "elev", "coord", "countries").head(6)

# %% [markdown]
# Olympus Mons is on Mars (the coordinates start with the Wikidata id of the planet),
# and the long tail is mostly American summits whose height was entered in feet. Keep
# the Earth, keep metres (nothing on Earth is higher than Everest's 8849), split the
# climbers into a list, and look at what is left.

# %%
# id: s14_clean
high = (
    wd.filter(
        ~pl.col("coord").str.starts_with("<"),
        pl.col("elev") <= 8849,
        pl.col("countries").str.contains("Nepal|China|Pakistan|India"),
    )
    .select(
        peak="mLabel",
        height="elev",
        prom_m="prom",
        year=pl.col("date").str.slice(0, 4).cast(pl.Int32),
        party=pl.col("climbers").str.split("|"),
        countries=pl.col("countries").str.split("|"),
        where=pl.col("coord").str.extract_groups(r"Point\((?<lon>[-\d.]+) (?<lat>[-\d.]+)\)"),
    )
    .unnest("where")
    .with_columns(pl.col("lon", "lat").cast(pl.Float64))
    .sort("height", descending=True)
)
high.drop("lon", "lat")

# %% [markdown]
# Fifteen, not fourteen: Lhotse Shar rises only 86 metres above its col with Lhotse, the
# kind of bump the UIAA had to rule on in the Alps. Keep the peaks with at least 300 m of
# prominence and the classic fourteen are back. Then explode the parties: does anyone
# appear twice?

# %%
# id: s14_buhl
print(high.filter(pl.col("prom_m") >= 300).height)
high.explode("party").drop_nulls("party").group_by("party").agg(
    pl.col("peak"), n=pl.len()
).filter(pl.col("n") > 1)

# %% [markdown]
# Hermann Buhl, the Austrian who reached the top of Nanga Parbat alone in 1953 and was
# in the four-man team on Broad Peak in 1957, is the only person with two first ascents
# of 8000ers in our data. Here are the fifteen, with the coordinates we pulled out of
# Wikidata's `Point(lon lat)` strings:

# %%
# id: fig_himalaya
figs.himalaya_map(high)

# %% [markdown]
#
# ## 15. Two golden ages
#
# The fourteen were first climbed between Annapurna in 1950 and Shishapangma in 1964,
# a golden age of Himalayan climbing that looks a lot like the Alpine one a century
# earlier. Stack the two tables (`vstack` needs the same columns) and compare.

# %%
# id: s15_golden
alps = fixed.select("year", region=pl.lit("Alps 4000"))
himalaya = high.filter(pl.col("prom_m") >= 300).select("year", region=pl.lit("8000ers"))
both = alps.vstack(himalaya).drop_nulls()
both.group_by("region").agg(
    n=pl.len(),
    first=pl.col("year").min(),
    median=pl.col("year").median(),
    last=pl.col("year").max(),
    years_for_middle_half=pl.col("year").quantile(0.75) - pl.col("year").quantile(0.25),
).sort("region")

# %% [markdown]
# The middle half of the Alpine first ascents took 22 years; for the Himalayan giants it
# took 3.
#
# ## 16. Saving it, as JSON
#
# Nested data goes back to JSON as easily as it came in: one line per trek, with the
# stage list intact.

# %%
# id: s16_write
summary = legs.with_columns(pl.col("km", "up", "down", "hours").round(1)).join(
    ways.group_by("trek").agg(stages=pl.col("stage").unique(maintain_order=True)),
    on="trek", how="left", maintain_order="left",
)
path = os.path.join(tempfile.gettempdir(), "treks_summary.ndjson")
summary.write_ndjson(path)
print(open(path).readline().rstrip("\n")[:200])

docs/blog/mountains/mountains.py

docs/blog/mountains/figs.py 136 lines
"""Plotly figures for the mountains explainer. Only scatter, heatmap and bar traces plus
layout shapes/annotations, so that nim-plotly can redraw every one of them.
Set SAVE_PATH to write the figure JSON instead of showing it (used by expected.py)."""
import json
import plotly.graph_objects as go
import polars as pl
import plotly.io as pio
pio.renderers.default = "notebook"

SAVE_PATH = None
TERRAIN = [[0.0, "#2b6c8f"], [0.0001, "#e8eedb"], [0.15, "#c9d6a3"], [0.35, "#b9a173"],
           [0.6, "#8c6d4f"], [0.8, "#d8d2cb"], [1.0, "#ffffff"]]

def _out(fig):
    fig.update_layout(template="plotly_white", margin=dict(l=40, r=20, t=50, b=40))
    if SAVE_PATH:
        open(SAVE_PATH, "w").write(fig.to_json())
    else:
        fig.show()

def _relief(path, zmax):
    r = pl.read_parquet(path)
    lons = r["lon"].unique().sort().to_list(); lats = r["lat"].unique().sort().to_list()
    z = r.sort("lat", "lon")["ele"].clip(-1, None).reshape((len(lats), len(lons))).to_list()
    return go.Heatmap(x=lons, y=lats, z=z, colorscale=TERRAIN, zmin=0, zmax=zmax,
                      showscale=False, hoverinfo="skip")

def _geo_axes(fig, lon_range, lat_range):
    import math
    lat0 = sum(lat_range) / 2
    fig.update_xaxes(range=lon_range, showgrid=False, constrain="domain", ticksuffix="°E")
    fig.update_yaxes(range=lat_range, showgrid=False, scaleanchor="x",
                     scaleratio=1 / math.cos(math.radians(lat0)), constrain="domain", ticksuffix="°N")

def alps_map(peaks):
    fig = go.Figure(_relief("data/relief_alps.parquet", 4800))
    fig.add_trace(go.Scatter(x=peaks["lon"], y=peaks["lat"], mode="markers",
        marker=dict(size=(peaks["height"] - 3900) / 60 + 5, color="#c0392b", line=dict(width=1, color="white")),
        text=peaks["summit"] + " " + peaks["height"].cast(pl.String) + " m", hoverinfo="text", name="4000ers"))
    for name, lon, lat in [("Mont Blanc", 6.865, 45.833), ("Zermatt peaks", 7.75, 46.02),
                           ("Bernese Oberland", 8.0, 46.6), ("Piz Bernina", 9.908, 46.382),
                           ("Barre des Écrins", 6.358, 44.922), ("Gran Paradiso", 7.266, 45.517)]:
        fig.add_annotation(x=lon, y=lat, text=name, showarrow=True, arrowhead=0, ax=30, ay=-25,
                           font=dict(size=11), bgcolor="rgba(255,255,255,0.7)")
    fig.update_layout(title="The 82 Alpine four-thousanders", height=520, showlegend=False)
    _geo_axes(fig, [5.6, 10.6], [44.6, 47.0])
    _out(fig)

COLORS = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#17becf"]

def _treks(fig, pts, names):
    for i, trek in enumerate(names):
        g = pts.filter(pl.col("trek") == trek).gather_every(4).with_columns(
            gap=((pl.col("x").diff() ** 2 + pl.col("y").diff() ** 2).sqrt() > 1500).fill_null(False))
        xs, ys = [], []
        for lon, lat, gap in g.select("lon", "lat", "gap").iter_rows():
            if gap: xs.append(None); ys.append(None)
            xs.append(lon); ys.append(lat)
        fig.add_trace(go.Scatter(x=xs, y=ys, mode="lines", name=trek,
                                 line=dict(width=2.5, color=COLORS[i % len(COLORS)])))

def treks_map(pts, peaks):
    west = ["Tour du Mont Blanc", "Walker's Haute Route", "Tour des Combins", "Tour du Cervin",
            "Tour Monte Rosa", "Alta Via 1 Aosta"]
    fig = go.Figure(_relief("data/relief_west.parquet", 4800))
    _treks(fig, pts, west)
    fig.add_trace(go.Scatter(x=peaks["lon"], y=peaks["lat"], mode="markers", name="4000ers",
        marker=dict(size=7, color="#c0392b", symbol="triangle-up", line=dict(width=0.5, color="white")),
        text=peaks["summit"], hoverinfo="text"))
    fig.update_layout(title="Six treks around the highest Alps", height=560,
                      legend=dict(orientation="h", y=-0.12))
    _geo_axes(fig, [6.6, 8.4], [45.55, 46.35])
    _out(fig)

def dolomites_map(pts):
    fig = go.Figure(_relief("data/relief_dolomites.parquet", 3400))
    _treks(fig, pts, ["Alta Via 1 Dolomites", "Alta Via 2 Dolomites"])
    fig.update_layout(title="The Alte Vie 1 and 2 of the Dolomites", height=560,
                      legend=dict(orientation="h", y=-0.12))
    _geo_axes(fig, [11.55, 12.35], [46.1, 46.8])
    _out(fig)

def profile(pts, trek, labels):
    g = (pts.filter(pl.col("trek") == trek)
         .group_by((pl.col("km") / 0.1).floor().alias("bin")).agg(pl.col("ele").mean(), pl.col("km").mean())
         .sort("bin"))
    fig = go.Figure(go.Scatter(x=g["km"], y=g["ele"], mode="lines", fill="tozeroy",
                               line=dict(color="#1f77b4"), name=trek))
    for r in labels.iter_rows(named=True):
        fig.add_annotation(x=r["km"], y=r["ele"], text=r["label"], showarrow=True, arrowhead=0,
                           ax=0, ay=-22, font=dict(size=10))
    fig.update_layout(title=f"{trek}: elevation profile (100 m bins)", xaxis_title="km",
                      yaxis_title="m", yaxis_range=[0, 3000], height=380)
    _out(fig)

LAND = [[0.0, "#cfe3ef"], [0.5, "#cfe3ef"], [0.5, "#ece9e2"], [1.0, "#ece9e2"]]

def world_map(ranges):
    r = pl.read_parquet("data/relief_world.parquet")
    lons = r["lon"].unique().sort().to_list(); lats = r["lat"].unique().sort().to_list()
    land = (r.sort("lat", "lon")["ele"] > 0).cast(pl.Int8).reshape((len(lats), len(lons))).to_list()
    fig = go.Figure(go.Heatmap(x=lons, y=lats, z=land, colorscale=LAND, showscale=False, hoverinfo="skip"))
    bands = [(0, 2000, "#f2c48d", "below 2000 m"), (2000, 4000, "#e08a4c", "2000-4000 m"),
             (4000, 6000, "#b54b2a", "4000-6000 m"), (6000, 9000, "#5e1a0e", "above 6000 m")]
    rows = ranges.filter(pl.col("Feature") != "Ocean")
    for lo, hi, color, label in bands:
        xs, ys = [], []
        for rec in rows.filter(pl.col("Elev_High").is_between(lo, hi, closed="left")).iter_rows(named=True):
            for ring in rec["outline"]:
                xs += [p[0] for p in ring] + [None]; ys += [p[1] for p in ring] + [None]
        fig.add_trace(go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=color,
                                 line=dict(width=0.3, color=color), name=label, hoverinfo="skip"))
    fig.update_layout(title="The world's mountain ranges by highest point (GMBA Inventory v2)",
                      height=520, legend=dict(orientation="h", y=-0.08))
    fig.update_xaxes(range=[-180, 180], showgrid=False, constrain="domain")
    fig.update_yaxes(range=[-60, 80], scaleanchor="x", scaleratio=1, showgrid=False, constrain="domain")
    _out(fig)

OFFSETS = {"Mount Everest": (-40, -30), "Lhotse": (45, -35), "Lhotse Shar": (60, 0), "Makalu": (40, 25),
           "Cho Oyu": (-30, -45), "Kanchenjunga": (30, 30), "Shishapangma": (20, -40),
           "Manaslu": (0, -35), "Annapurna I": (-20, 30), "Dhaulagiri": (-50, -25),
           "K2": (-10, -40), "Broad Peak": (60, -30), "Gasherbrum": (70, 0), "Gasherbrum II": (60, 30),
           "Nanga Parbat": (-40, 30)}

def himalaya_map(high):
    fig = go.Figure(_relief("data/relief_himalaya.parquet", 7000))
    fig.add_trace(go.Scatter(x=high["lon"], y=high["lat"], mode="markers", text=high["peak"],
        marker=dict(size=9, color="#c0392b", symbol="triangle-up", line=dict(width=1, color="white")),
        hoverinfo="text", name="8000ers"))
    for r in high.iter_rows(named=True):
        ax, ay = OFFSETS.get(r["peak"], (0, -30))
        fig.add_annotation(x=r["lon"], y=r["lat"], text=r["peak"], ax=ax, ay=ay, showarrow=True,
                           arrowhead=0, arrowwidth=1, font=dict(size=10), bgcolor="rgba(255,255,255,0.75)")
    fig.update_layout(title="The fourteen 8000ers, plus Lhotse Shar", height=480, showlegend=False)
    _geo_axes(fig, [73, 89.5], [26.8, 36.6])
    _out(fig)

docs/blog/mountains/figs.py

docs/blog/mountains/plots.nim 201 lines
## Plotly figures for "Above 4000", with nim-plotly. The twin of figs.py: same
## traces, colours and layout (without Plotly's "plotly_white" template, which only
## Python ships). nim-plotly builds the traces (type, data, mode, name,
## marker, text) and the basic layout (title, size); what it has no field for (gaps in a
## line, fill colours, colour scales as stops, annotations, axis ranges and aspect ratio)
## is added to the JSON it produces.
import std/[json, math, options, sequtils, strutils]
import plotly except Color
import nanuq

const
  Terrain = [(0.0, "#2b6c8f"), (0.0001, "#e8eedb"), (0.15, "#c9d6a3"), (0.35, "#b9a173"),
             (0.6, "#8c6d4f"), (0.8, "#d8d2cb"), (1.0, "#ffffff")]
  Land = [(0.0, "#cfe3ef"), (0.5, "#cfe3ef"), (0.5, "#ece9e2"), (1.0, "#ece9e2")]
  Colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#17becf"]
  Red = "#c0392b"

proc scale(stops: openArray[(float, string)]): JsonNode =
  result = newJArray()
  for (p, c) in stops: result.add %*[p, c]

proc finish(traces: seq[Trace[float]], title: string, height: int): PlotJson =
  ## The JSON nim-plotly makes, with the white template figs.py uses.
  let p = Plot[float](traces: traces, layout: Layout(title: title, height: height, autosize: true))
  result = p.toPlotJson
  let l = result.layout
  l["title"] = %*{"text": l["title"].getStr, "x": 0.05}
  l["plot_bgcolor"] = %"white"
  l["margin"] = %*{"l": 40, "r": 20, "t": 50, "b": 40}
  for ax in ["xaxis", "yaxis"]:
    if not l.hasKey(ax): l[ax] = newJObject()
    if l[ax].hasKey("autorange"): l[ax].delete("autorange")

proc note(pj: PlotJson, x, y: float, text: string, ax = 30, ay = -25, size = 11) =
  if not pj.layout.hasKey("annotations"): pj.layout["annotations"] = newJArray()
  pj.layout["annotations"].add %*{"x": x, "y": y, "text": text, "showarrow": true,
    "arrowhead": 0, "ax": ax, "ay": ay, "font": {"size": size},
    "bgcolor": "rgba(255,255,255,0.7)"}

proc geoAxes(pj: PlotJson, lon, lat: (float, float)) =
  ## Degrees of longitude shrink by cos(latitude): keep the map's proportions.
  let lat0 = (lat[0] + lat[1]) / 2
  pj.layout["xaxis"] = %*{"range": [lon[0], lon[1]], "showgrid": false, "constrain": "domain",
                          "ticksuffix": "°E"}
  pj.layout["yaxis"] = %*{"range": [lat[0], lat[1]], "showgrid": false, "scaleanchor": "x",
                          "scaleratio": 1 / cos(degToRad(lat0)), "constrain": "domain",
                          "ticksuffix": "°N"}

proc grid(df: DataFrame, value: string): (seq[float], seq[float], seq[seq[float]]) =
  ## A lon/lat grid (one row per point) as heatmap axes and rows of z.
  let wide = df.pivot(on = "lon", index = "lat", values = value).sort("lat")
  let lons = wide.columns[1 .. ^1]
  var z: seq[seq[float]]
  for r in 0 ..< wide.height:
    z.add lons.mapIt(wide[it, r, float])
  (lons.mapIt(parseFloat(it)), wide.toList("lat", float), z)

proc relief(path: string, zmax: float): (Trace[float], JsonNode) =
  ## Terrain heights as a heatmap, sea level and below in blue.
  let r = readParquet(path).select(col.lon, col.lat, col.ele.cast(Float64).clip(lowerBound = -1.0))
  let (xs, ys, zs) = grid(r, "ele")
  (Trace[float](`type`: PlotType.HeatMap, xs: xs, ys: ys, zs: zs),
   %*{"colorscale": scale(Terrain), "zmin": 0, "zmax": zmax, "showscale": false,
      "hoverinfo": "skip"})

proc withStyle(pj: PlotJson, i: int, style: JsonNode) =
  for k, v in style: pj.traces[i][k] = v

proc lineWithGaps(xs, ys: seq[Option[float]]): (JsonNode, JsonNode) =
  ## Plotly breaks a line at null: nim-plotly's float seqs have no null, so the
  ## coordinates go straight into the JSON.
  var jx = newJArray()
  var jy = newJArray()
  for i in 0 ..< xs.len:
    jx.add(if xs[i].isSome: %xs[i].get else: newJNull())
    jy.add(if ys[i].isSome: %ys[i].get else: newJNull())
  (jx, jy)

# ---------------------------------------------------------------- the Alps

proc alpsMap*(peaks: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_alps.parquet", 4800)
  let label = peaks.select(format("{} {} m", col.summit, col.height).alias("t")).toList("t", string)
  let sizes = peaks.select(((col.height - 3900) / 60 + 5).alias("s")).toList("s", float)
  let dots = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "4000ers",
                          xs: peaks.toList("lon", float), ys: peaks.toList("lat", float), text: label)
  result = finish(@[bg, dots], "The 82 Alpine four-thousanders", 520)
  result.withStyle(0, bgStyle)
  result.withStyle(1, %*{"marker": {"size": sizes, "color": Red, "line": {"width": 1, "color": "white"}},
                         "hoverinfo": "text"})
  for (name, lon, lat) in [("Mont Blanc", 6.865, 45.833), ("Zermatt peaks", 7.75, 46.02),
                           ("Bernese Oberland", 8.0, 46.6), ("Piz Bernina", 9.908, 46.382),
                           ("Barre des Écrins", 6.358, 44.922), ("Gran Paradiso", 7.266, 45.517)]:
    result.note(lon, lat, name)
  result.layout["showlegend"] = %false
  result.geoAxes((5.6, 10.6), (44.6, 47.0))

proc trekLines(pts: DataFrame, names: openArray[string]): seq[(string, JsonNode, JsonNode)] =
  ## Every 4th point of each trek; a jump of more than 1.5 km between two of them is a
  ## gap in the mapped route, drawn as a break in the line.
  for name in names:
    let g = pts.filter(col.trek == name).gatherEvery(4)
      .withColumns(((col.x.diff ^ 2 + col.y.diff ^ 2).sqrt > 1500).fillNull(false).alias("gap"))
    var xs, ys: seq[Option[float]]
    for r in g.select(col.lon, col.lat, col.gap).rows(tuple[lon, lat: float, gap: bool]):
      if r.gap:
        xs.add none(float); ys.add none(float)
      xs.add some(r.lon); ys.add some(r.lat)
    let (jx, jy) = lineWithGaps(xs, ys)
    result.add (name, jx, jy)

proc addTreks(pj: PlotJson, pts: DataFrame, names: openArray[string]) =
  for i, (name, jx, jy) in trekLines(pts, names):
    pj.traces.add %*{"type": "scatter", "mode": "lines", "name": name, "x": jx, "y": jy,
                     "line": {"width": 2.5, "color": Colors[i mod Colors.len]}}

proc treksMap*(pts, peaks: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_west.parquet", 4800)
  result = finish(@[bg], "Six treks around the highest Alps", 560)
  result.withStyle(0, bgStyle)
  result.addTreks(pts, ["Tour du Mont Blanc", "Walker's Haute Route", "Tour des Combins",
                        "Tour du Cervin", "Tour Monte Rosa", "Alta Via 1 Aosta"])
  result.traces.add %*{"type": "scatter", "mode": "markers", "name": "4000ers",
    "x": peaks.toList("lon", float), "y": peaks.toList("lat", float),
    "text": peaks.toList("summit", string), "hoverinfo": "text",
    "marker": {"size": 7, "color": Red, "symbol": "triangle-up", "line": {"width": 0.5, "color": "white"}}}
  result.layout["legend"] = %*{"orientation": "h", "y": -0.12}
  result.geoAxes((6.6, 8.4), (45.55, 46.35))

proc dolomitesMap*(pts: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_dolomites.parquet", 3400)
  result = finish(@[bg], "The Alte Vie 1 and 2 of the Dolomites", 560)
  result.withStyle(0, bgStyle)
  result.addTreks(pts, ["Alta Via 1 Dolomites", "Alta Via 2 Dolomites"])
  result.layout["legend"] = %*{"orientation": "h", "y": -0.12}
  result.geoAxes((11.55, 12.35), (46.1, 46.8))

proc profile*(pts: DataFrame, trek: string, labels: DataFrame): PlotJson =
  let g = pts.filter(col.trek == trek)
    .groupBy((col.km / 0.1).floor.alias("bin")).agg(col.ele.mean, col.km.mean)
    .sort("bin")
  let line = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: trek,
                          xs: g.toList("km", float), ys: g.toList("ele", float))
  result = finish(@[line], trek & ": elevation profile (100 m bins)", 380)
  result.withStyle(0, %*{"fill": "tozeroy", "line": {"color": "#1f77b4"}})
  for r in labels.rows(tuple[km: float, label: string, ele: float]):
    result.note(r.km, r.ele, r.label, ax = 0, ay = -22, size = 10)
  for a in result.layout["annotations"]: a.delete("bgcolor")
  result.layout["xaxis"] = %*{"title": {"text": "km"}}
  result.layout["yaxis"] = %*{"title": {"text": "m"}, "range": [0, 3000]}

# ---------------------------------------------------------------- the world

proc worldMap*(ranges: DataFrame): PlotJson =
  let r = readParquet("data/relief_world.parquet")
    .select(col.lon, col.lat, (col.ele > 0).cast(Float64).alias("land"))
  let (xs, ys, zs) = grid(r, "land")
  result = finish(@[Trace[float](`type`: PlotType.HeatMap, xs: xs, ys: ys, zs: zs)],
                  "The world's mountain ranges by highest point (GMBA Inventory v2)", 520)
  result.withStyle(0, %*{"colorscale": scale(Land), "showscale": false, "hoverinfo": "skip"})
  let bands = [(0.0, 2000.0, "#f2c48d", "below 2000 m"), (2000.0, 4000.0, "#e08a4c", "2000-4000 m"),
               (4000.0, 6000.0, "#b54b2a", "4000-6000 m"), (6000.0, 9000.0, "#5e1a0e", "above 6000 m")]
  let land = ranges.filter(col.Feature != "Ocean")
  for (lo, hi, color, label) in bands:
    var jx = newJArray()
    var jy = newJArray()
    let band = land.filter(col.Elev_High.isBetween(lo, hi, closed = ClosedInterval.Left))
    for outline in band.toList("outline", seq[seq[seq[float]]]):
      for ring in outline:
        for p in ring:
          jx.add %p[0]; jy.add %p[1]
        jx.add newJNull(); jy.add newJNull()
    result.traces.add %*{"type": "scatter", "mode": "lines", "fill": "toself", "fillcolor": color,
                         "line": {"width": 0.3, "color": color}, "name": label, "x": jx, "y": jy,
                         "hoverinfo": "skip"}
  result.layout["legend"] = %*{"orientation": "h", "y": -0.08}
  result.layout["xaxis"] = %*{"range": [-180, 180], "showgrid": false, "constrain": "domain"}
  result.layout["yaxis"] = %*{"range": [-60, 80], "scaleanchor": "x", "scaleratio": 1,
                              "showgrid": false, "constrain": "domain"}

const Offsets = [("Mount Everest", -40, -30), ("Lhotse", 45, -35), ("Lhotse Shar", 60, 0),
  ("Makalu", 40, 25), ("Cho Oyu", -30, -45), ("Kanchenjunga", 30, 30), ("Shishapangma", 20, -40),
  ("Manaslu", 0, -35), ("Annapurna I", -20, 30), ("Dhaulagiri", -50, -25), ("K2", -10, -40),
  ("Broad Peak", 60, -30), ("Gasherbrum", 70, 0), ("Gasherbrum II", 60, 30), ("Nanga Parbat", -40, 30)]

proc himalayaMap*(high: DataFrame): PlotJson =
  let (bg, bgStyle) = relief("data/relief_himalaya.parquet", 7000)
  let dots = Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "8000ers",
                          xs: high.toList("lon", float), ys: high.toList("lat", float),
                          text: high.toList("peak", string))
  result = finish(@[bg, dots], "The fourteen 8000ers, plus Lhotse Shar", 480)
  result.withStyle(0, bgStyle)
  result.withStyle(1, %*{"marker": {"size": 9, "color": Red, "symbol": "triangle-up",
                                    "line": {"width": 1, "color": "white"}}, "hoverinfo": "text"})
  for r in high.rows(tuple[peak: string, lon, lat: float]):
    var (ax, ay) = (0, -30)
    for (p, x, y) in Offsets:
      if p == r.peak: (ax, ay) = (x, y)
    result.note(r.lon, r.lat, r.peak, ax = ax, ay = ay, size = 10)
  result.layout["showlegend"] = %false
  result.geoAxes((73.0, 89.5), (26.8, 36.6))

docs/blog/mountains/plots.nim

docs/blog/mountains/expected.py 32 lines
"""Runs mountains.py cell by cell and writes each code cell's output to expected/<id>.txt.

As in a notebook, a cell's last bare expression is printed, unless the cell
ends with a semicolon. Figure cells (fig_*) save the
Plotly JSON instead. These files are what the Nim post must reproduce.
Run from this folder: python3 -I expected.py"""
import ast, contextlib, io, os, re
import sys
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.getcwd())  # -I leaves this folder off the path; the post imports figs from it
os.makedirs("expected", exist_ok=True)
src = open("mountains.py").read()
ns = {}
def run(code, name):
    tree = ast.parse(code)
    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None
    exec(compile(tree, name, "exec"), ns)
    if last is not None:
        v = eval(compile(ast.Expression(last.value), name, "eval"), ns)
        if v is not None and not code.rstrip().endswith(";"): print(v)
for cell in src.split("\n# %%")[1:]:
    if cell.startswith(" [markdown]"): continue
    cid = re.match(r"\n# id: (\S+)", cell).group(1)
    if cid.startswith("fig_"):
        ns["figs"].SAVE_PATH = f"expected/{cid}.json"
        run(cell, cid); ns["figs"].SAVE_PATH = None
        print(cid, "figure"); continue
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        run(cell, cid)
    open(f"expected/{cid}.txt", "w").write(buf.getvalue().rstrip("\n") + "\n")
    print(cid, len(buf.getvalue().splitlines()), "lines")

docs/blog/mountains/expected.py

docs/blog/mountains/src/gmba_prep.py 20 lines
"""GMBA Mountain Inventory v2.0 (standard, 300 selection) -> data/gmba_ranges.ndjson.

Keeps the attribute strings as published (Path "A > B > C", Countries "X, Y") and adds the
outline simplified to ~0.05 degrees as a list of polygons, each a list of [lon, lat] rings
(outer ring only). Source: https://www.earthenv.org/mountains (Snethlage et al. 2022)."""
import json, sys, shapefile
from shapely.geometry import shape
d = sys.argv[1]  # folder with the unzipped shapefile
base = f"{d}/GMBA_Inventory_v2.0_standard_300"
r = shapefile.Reader(shp=open(base + ".shp", "rb"), dbf=open(base + ".dbf", "rb"), shx=open(base + ".shx", "rb"))
keep = ["GMBA_V2_ID", "MapName", "WikiDataUR", "Hier_Lvl", "Feature", "Area", "Elev_Low", "Elev_High", "Path", "Countries", "CountryISO"]
with open("data/gmba_ranges.ndjson", "w") as f:
    for sr in r.iterShapeRecords():
        rec = sr.record.as_dict()
        g = shape(sr.shape.__geo_interface__).simplify(0.05, preserve_topology=True)
        polys = [g] if g.geom_type == "Polygon" else list(g.geoms)
        rings = [[[round(x, 3), round(y, 3)] for x, y in p.exterior.coords] for p in polys if p.area > 0.01]
        out = {k: rec[k] for k in keep}
        out["outline"] = rings
        f.write(json.dumps(out, ensure_ascii=False) + "\n")

docs/blog/mountains/src/gmba_prep.py

docs/blog/mountains/src/peaks_prep.py 32 lines
"""Coordinates for the 82 UIAA 4000ers -> data/uiaa_coords.csv (nr, lon, lat, source).

1. Wikidata P625 of the en.wikipedia article linked from the list (raw/uiaa_coords.csv)
2. else a Camptocamp summit (raw/c2c/alps4000_*.json, Web Mercator) picked by hand below
3. else a Wikidata item in the Alps >= 4000 m with the same label (data/wd_alps4000.csv)
Subsummits that share an article (Breithorn, Lyskamm, Vincent Pyramid) use Camptocamp."""
import csv, glob, json, math, re, sys, unicodedata, urllib.parse
R = 6378137.0
def norm(s):
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()
    return re.sub(r"[^a-z]", "", re.sub(r"\[.*?\]|\(.*?\)", "", s))
C2C = {3: "Pointe Dufour", 5: "Pointe Zumstein", 6: "Pointe Gnifetti", 8: "Lyskamm / Liskamm E",
       11: "Lyskamm / Liskamm W", 15: "Pointe Parrot", 29: "Hobärghorn / Hohberghorn",
       30: "Pyramide Vincent", 39: "Breithorn W", 41: "Breithorn Central", 43: "Breithorn E",
       51: "Breithorn - Pointe 4106", 63: "Grand Paradis", 67: "Pointe Giordani",
       69: "Gross Grünhorn", 72: "Dirruhorn / Dürrenhorn", 79: "Pointe Baretti"}
c2c = {}
for f in glob.glob("raw/c2c/alps4000_*.json"):
    for d in json.load(open(f))["documents"]:
        x, y = json.loads(d["geometry"]["geom"])["coordinates"]
        c2c[d["locales"][0]["title"]] = (x / R * 180 / math.pi, math.degrees(math.atan(math.sinh(y / R))))
pt = lambda s: tuple(float(v) for v in s[6:-1].split())
art = {urllib.parse.unquote(r["article"].split("/wiki/")[1]): pt(r["coord"]) for r in csv.DictReader(open("raw/uiaa_coords.csv")) if r["coord"]}
wd = {}
for r in csv.DictReader(open("data/wd_alps4000.csv")):
    if r["coord"]: wd.setdefault(norm(r["mLabel"]), pt(r["coord"]))
out = csv.writer(open("data/uiaa_coords.csv", "w")); out.writerow(["nr", "lon", "lat", "source"])
for nr, name, link in json.load(open("raw/uiaa_links.json")):
    if nr in C2C: lon, lat = c2c[C2C[nr]]; src = "camptocamp"
    elif link in art: (lon, lat), src = art[link], "wikidata"
    else: (lon, lat), src = wd[norm(name)], "wikidata-label"
    out.writerow([nr, round(lon, 5), round(lat, 5), src])

docs/blog/mountains/src/peaks_prep.py

docs/blog/mountains/src/relief_prep.py 36 lines
"""Elevation grids for the map backgrounds, sampled from AWS terrarium tiles (Mapzen/Tilezen
terrain, https://registry.opendata.aws/terrain-tiles/).
data/relief_alps.parquet : lon 5.5..12.5, lat 44..47.6, step 0.025 deg (zoom 9)
data/relief_world.parquet: lon -180..179, lat -60..80, step 1 deg (zoom 4)
data/relief_west.parquet, relief_dolomites.parquet (zoom 11) and relief_himalaya.parquet (zoom 7): close-ups"""
import math, pathlib, time, urllib.request
from PIL import Image
CACHE = pathlib.Path("tiles"); CACHE.mkdir(exist_ok=True)
_t = {}
def tile(z, x, y):
    if (z, x, y) not in _t:
        p = CACHE / f"{z}_{x}_{y}.png"
        if not p.exists():
            url = f"https://elevation-tiles-prod.s3.amazonaws.com/terrarium/{z}/{x}/{y}.png"
            for i in range(4):
                try: p.write_bytes(urllib.request.urlopen(url, timeout=60).read()); break
                except Exception: time.sleep(2 ** i)
        _t[(z, x, y)] = Image.open(p).convert("RGB").load()
    return _t[(z, x, y)]
def ele(z, lon, lat):
    n = 2 ** z
    fx = (lon + 180) / 360 * n
    fy = (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n
    tx, ty = int(fx) % n, min(int(fy), n - 1)
    r, g, b = tile(z, tx, ty)[min(int((fx - int(fx)) * 256), 255), min(int((fy - int(fy)) * 256), 255)]
    return round(r * 256 + g + b / 256 - 32768)
def grid(path, z, lons, lats):
    import polars as pl
    rows = [(round(lon, 3), round(lat, 3), ele(z, lon, lat)) for lat in lats for lon in lons]
    pl.DataFrame(rows, schema={"lon": pl.Float64, "lat": pl.Float64, "ele": pl.Int16},
                 orient="row").write_parquet(path, compression="zstd", compression_level=19)
grid("data/relief_alps.parquet", 9, [5.5 + i * 0.025 for i in range(281)], [44 + i * 0.025 for i in range(145)])
grid("data/relief_world.parquet", 4, [-180 + i for i in range(360)], [-60 + i for i in range(141)])
grid("data/relief_west.parquet", 11, [6.6 + i * 0.006 for i in range(301)], [45.55 + i * 0.004 for i in range(201)])
grid("data/relief_dolomites.parquet", 11, [11.55 + i * 0.004 for i in range(201)], [46.1 + i * 0.003 for i in range(234)])
grid("data/relief_himalaya.parquet", 7, [70 + i * 0.05 for i in range(501)], [26 + i * 0.05 for i in range(221)])

docs/blog/mountains/src/relief_prep.py

docs/blog/mountains/src/treks_prep.py 71 lines
"""Flatten waymarkedtrails route details into one NDJSON line per trek.

Keeps the nesting the explainer wants to show: trek -> stages -> ways -> points,
with OSM tags kept as raw dicts (heterogeneous keys) and points as [x, y, ele]
in Web Mercator metres (EPSG:3857), elevation sampled from AWS terrarium tiles.
"""
import io, json, math, sys, time, pathlib, urllib.request
from PIL import Image

RAW = pathlib.Path(sys.argv[1])          # raw/wmt
OUT = pathlib.Path(sys.argv[2])          # data/treks.ndjson
TILES = pathlib.Path(sys.argv[3])        # tile cache dir
Z = 13
HALF = 20037508.342789244
_tiles = {}

def tile(x, y):
    key = (x, y)
    if key not in _tiles:
        p = TILES / f"{Z}_{x}_{y}.png"
        if not p.exists():
            url = f"https://elevation-tiles-prod.s3.amazonaws.com/terrarium/{Z}/{x}/{y}.png"
            for i in range(4):
                try:
                    p.write_bytes(urllib.request.urlopen(url, timeout=60).read()); break
                except Exception:
                    time.sleep(2 ** i)
        _tiles[key] = Image.open(p).convert("RGB").load()
    return _tiles[key]

def ele(mx, my):
    n = 2 ** Z
    fx = (mx + HALF) / (2 * HALF) * n
    fy = (HALF - my) / (2 * HALF) * n
    tx, ty = int(fx), int(fy)
    px, py = min(int((fx - tx) * 256), 255), min(int((fy - ty) * 256), 255)
    r, g, b = tile(tx, ty)[px, py]
    return round(r * 256 + g + b / 256 - 32768, 1)

def main_ways(node, stage, out):
    rt = node.get("route_type")
    if rt == "base":
        out.append((stage, node)); return
    if rt == "route" and "id" in node:
        stage = node["id"]
    for c in node.get("main", []):
        main_ways(c, stage, out)
    for c in node.get("ways", []):
        main_ways(c, stage, out)

TREKS = [9678362, 1176308, 10353523, 49181, 177743, 404914, 1706143, 3020521]
with OUT.open("w") as f:
    for tid in TREKS:
        d = json.loads((RAW / f"{tid}.details.json").read_text())
        subs = d.get("subroutes") or {}
        ways = []
        main_ways(d["route"], tid, ways)
        stages, order = {}, []
        for sid, w in ways:
            if sid not in stages:
                s = subs.get(str(sid), {})
                stages[sid] = {"id": sid, "name": s.get("name", d["name"]),
                               "itinerary": s.get("itinerary", d.get("itinerary", [])), "ways": []}
                order.append(sid)
            pts = [[round(x, 1), round(y, 1), ele(x, y)] for x, y in w["geometry"]["coordinates"]]
            stages[sid]["ways"].append({"id": w["id"], "length": w["length"], "direction": w["direction"],
                                        "tags": w.get("tags", {}), "points": pts})
        rec = {"id": tid, "name": d["name"], "ref": d.get("ref"), "tags": d["tags"],
               "official_length": d.get("official_length"), "stages": [stages[s] for s in order]}
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        print(tid, d["name"], len(order), "stages", len(ways), "ways", file=sys.stderr)

docs/blog/mountains/src/treks_prep.py