Nanuq dev log · 1 November 2026

Counting El Niños

A warm patch of ocean, and the weather of the whole world.

Explainer · Nanuq 0.4 · 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.

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.4 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.

Every few years a patch of the Pacific Ocean, out in the middle of nowhere, warms up by a degree or two. That sounds like nothing. Yet it floods deserts in Peru, dries out rainforests in Indonesia, shifts storm tracks over North America, and nudges the temperature of the whole planet. The warming is called El Niño, and right now, in the autumn of 2026, one of the strongest on record is under way.

This post counts El Niños the way the scientists do, starting from a single column of monthly sea temperatures, and follows them out into the rest of the world's weather. Nothing is assumed: if you have never heard of El Niño, this is the place to start. Along the way it shows off what is new in Nanuq 0.4: rolling windows and exponential smoothing, cumulative functions, shift and diff, top-k and binning, horizontal functions, pivot and unpivot, dynamic group-by, as-of joins and a real Series.

Data, all public: NOAA's Climate Prediction Center (CPC) for the Niño indices and the Southern Oscillation Index, NASA GISS (GISTEMP v4) for global temperature, NOAA's GHCN-Daily for the rain gauge at Piura airport, Peru, and NOAA's ERSSTv5 for the maps. Downloaded on 1 November 2026.

setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, floatPrecision = 2)

1. A box in the ocean↑ contents

Along the equator, the trade winds blow from east to west across the Pacific. They push the sun-warmed surface water towards Indonesia and Australia, where it piles up, and let cold water well up from the deep along the coast of South America. So the Pacific is normally warm in the west and cool in the east.

Every two to seven years the trade winds weaken, the warm water sloshes back east, and the central and eastern Pacific heat up. Fishermen in Peru noticed this centuries ago, because it came around Christmas and emptied their nets. They called it El Niño de Navidad, the Christmas child.

show plots.walkerSchematic()
plotting code
proc walkerSchematic*(): PlotJson =
  ## Cross-section along the equator, normal conditions vs El Niño, drawn with shapes.
  var p = Plot[float](layout: layout("What changes during El Niño (a slice along the equator)", 360))
  result = p.finish(source = "Schematic, not to scale. After NOAA PMEL's El Niño diagrams.")
  for (sx, title) in [("", "Normal conditions"), ("2", "El Niño")]:
    let nino = sx == "2"
    let (xa, ya) = ("x" & sx, "y" & sx)
    result.layout["xaxis" & sx] = %*{"range": [0, 10], "visible": false,
                                     "domain": (if nino: [0.52, 1.0] else: [0.0, 0.48]), "anchor": ya}
    result.layout["yaxis" & sx] = %*{"range": [-4.8, 4.6], "visible": false, "anchor": xa}
    result.note((if nino: 0.76 else: 0.24), 1.0, title, 14, Ink2, ("paper", "paper"),
                %*{"yanchor": "bottom"})
    let (tw, te) = if nino: (-1.7, -1.4) else: (-2.6, -0.6)  # thermocline depth, west and east
    proc poly(pj: PlotJson, pts: openArray[(float, float)], color: string) =
      pj.shape %*{"type": "path", "xref": xa, "yref": ya, "fillcolor": color, "layer": "below",
                  "line": {"width": 0},
                  "path": "M " & pts.mapIt($it[0] & "," & $it[1]).join(" L ") & " Z"}
    result.poly([(0.6, 0.0), (9.4, 0.0), (9.4, te), (0.6, tw)], "#f2a3a0")    # warm layer
    result.poly([(0.6, tw), (9.4, te), (9.4, -4.0), (0.6, -4.0)], "#9ec5f4")  # cold deep water
    result.poly([(0.0, -4.0), (0.6, -4.0), (0.6, 0.3), (0.0, 0.6)], Land)
    result.poly([(9.4, -4.0), (10.0, -4.0), (10.0, 1.4), (9.4, 0.4)], Land)
    result.shape %*{"type": "line", "xref": xa, "yref": ya, "x0": 0.6, "y0": tw, "x1": 9.4,
                    "y1": te, "line": {"color": Ink2, "dash": "dash", "width": 1}}
    result.note(5, (tw + te) / 2 - 0.5, "thermocline", 10, Ink2, (xa, ya))
    let cx = if nino: 5.8 else: 2.2  # where the air rises and rains
    result.shape %*{"type": "circle", "xref": xa, "yref": ya, "x0": cx - 1.2, "x1": cx + 1.2,
                    "y0": 2.3, "y1": 3.4, "fillcolor": Grey, "line": {"width": 0}}
    for k in 0 .. 4:
      let x = cx - 0.8 + 0.4 * float(k)
      result.shape %*{"type": "line", "xref": xa, "yref": ya, "x0": x, "y0": 2.2,
                      "x1": x - 0.15, "y1": 1.6, "line": {"color": Cool, "width": 1.5}}
    result.note(cx, 3.85, "rain", 11, Ink2, (xa, ya))
    proc arrow(pj: PlotJson, x0, y0, x1, y1: float) =
      pj.note(x1, y1, "", axes = (xa, ya), extra = %*{"ax": x0, "ay": y0, "axref": xa,
              "ayref": ya, "showarrow": true, "arrowhead": 2, "arrowwidth": 1.8, "arrowcolor": Ink})
    if not nino:
      result.arrow(8.6, 0.6, 3.6, 0.6); result.arrow(3.4, 1.0, 3.4, 2.4)
      result.arrow(3.6, 4.2, 8.6, 4.2); result.arrow(8.9, 4.0, 8.9, 1.0)
      result.arrow(8.9, -2.8, 8.9, -0.9)
      result.note(6, 1.0, "strong trade winds", axes = (xa, ya))
      result.note(7.4, 3.0, "dry, sinking air", 10, Ink2, (xa, ya))
      result.note(7.4, -1.9, "cold water wells up", 10, "#0d366b", (xa, ya))
    else:
      result.arrow(3.0, 0.6, 4.4, 0.6); result.arrow(8.6, 0.6, 7.2, 0.6)
      result.note(5.8, -0.6, "warm water spreads east", 10, "#7f1d1d", (xa, ya))
      result.note(1.6, 1.2, "drought", axes = (xa, ya))
      result.note(5.8, 1.0, "weak trade winds", axes = (xa, ya))
    result.note(0.3, -4.5, "Indonesia", 10, Ink2, (xa, ya))
    result.note(9.5, -4.5, "South America", 10, Ink2, (xa, ya))

# ---------------------------------------------------------------- charts

Here is the same ocean seen from above: the mean sea surface temperature of 1991-2020. The warm pool sits in the west, the cold tongue stretches out from South America along the equator.

show plots.pacificNormal()
plotting code
proc pacificNormal*(): PlotJson =
  ## The Pacific in a normal year: 1991-2020 mean SST, with the Niño 3.4 box.
  let (tr, z) = heatmap(readCsv("data/pacific_normal.csv"), "sst")
  let p = Plot[float](traces: @[tr], layout: layout(
    "The Pacific in a normal year: sea surface temperature, 1991-2020 mean", 420))
  result = p.finish(source = "Data: NOAA ERSSTv5. Land in grey.")
  result.traces[0]["z"] = z
  result.traces[0]["colorscale"] = scale(Sequential)
  result.traces[0]["zmin"] = %14; result.traces[0]["zmax"] = %30
  result.traces[0]["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.8, "outlinewidth": 0}
  result.traces[0]["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:.1f} °C<extra></extra>"
  result.mapAxes
  result.layout["yaxis"]["scaleanchor"] = %"x"
  result.drawBoxes(["Niño 3.4"])
  result.note(145, 4, "<b>warm pool</b>", 13, "white")
  result.note(255, -9, "<b>cold tongue</b>", 13, Ink)
  result.note(205, 11, "", extra = %*{"ax": 258, "ay": 11, "axref": "x", "ayref": "y",
                                      "showarrow": true, "arrowhead": 2, "arrowwidth": 2,
                                      "arrowcolor": Ink})
  result.note(231, 14, "trade winds", color = Ink)

To keep watch, scientists average the sea surface temperature over a box on the equator called Niño 3.4 (5°N to 5°S, 120°W to 170°W): about 1,100 by 5,500 km, six million square kilometres of open ocean with no land in it (the black box on the map). CPC publishes one number per month for that box, back to 1950. Here it is, read into a frame, and its temperature column taken out as a Series, Nanuq 0.4's new one-column type.

var nino = readCsv("data/nino34.csv").select(col.year, col.month, col.sst)
echo nino.tail(4)
let sst = nino["sst"]
echo &"{sst.len} months, from {sst.min.item(float):.2f} to {sst.max.item(float):.2f} °C"
echo nino.slice(sst.argMax.item(int), 1)
shape: (4, 3)
┌──────┬───────┬───────┐
│ year ┆ month ┆ sst   │
│ ---  ┆ ---   ┆ ---   │
│ i64  ┆ i64   ┆ f64   │
╞══════╪═══════╪═══════╡
│ 2026 ┆ 6     ┆ 29.18 │
│ 2026 ┆ 7     ┆ 29.07 │
│ 2026 ┆ 8     ┆ 29.05 │
│ 2026 ┆ 9     ┆ 29.27 │
└──────┴───────┴───────┘
922 months, from 24.32 to 29.27 °C
shape: (1, 3)
┌──────┬───────┬───────┐
│ year ┆ month ┆ sst   │
│ ---  ┆ ---   ┆ ---   │
│ i64  ┆ i64   ┆ f64   │
╞══════╪═══════╪═══════╡
│ 2026 ┆ 9     ┆ 29.27 │
└──────┴───────┴───────┘

The warmest month in 76 years of records was September 2026, the latest month in the file. But a warm month is not yet an El Niño: the ocean has seasons too. The mean for each calendar month, with topK and bottomK, shows the box is warmest in spring and coolest in winter, more than a degree apart.

let climate = nino.groupBy("month").agg(col.sst.mean)
echo concat([climate.topK(2, by = "sst"), climate.bottomK(2, by = "sst")])
shape: (4, 2)
┌───────┬───────┐
│ month ┆ sst   │
│ ---   ┆ ---   │
│ i64   ┆ f64   │
╞═══════╪═══════╡
│ 5     ┆ 27.73 │
│ 4     ┆ 27.66 │
│ 1     ┆ 26.44 │
│ 12    ┆ 26.46 │
└───────┴───────┘

2. What is normal?↑ contents

Climate scientists rarely look at a temperature on its own. They look at the anomaly: how far a month is above or below normal for that time of year. "Normal" is the average of the same calendar month over a 30-year base period, today 1991-2020.

In Nanuq that is one window expression: the mean of sst over the base years, computed separately for each month with over.

let base = col.year.isBetween(1991, 2020)
nino = nino.withColumns(col.sst.filter(base).mean.over("month").alias("normal"))
           .withColumns((col.sst - col.normal).alias("anomaly"))
echo nino.filter(col.month == 9 and col.year.isIn([1982, 1997, 2015, 2023, 2026]))
shape: (5, 5)
┌──────┬───────┬───────┬────────┬─────────┐
│ year ┆ month ┆ sst   ┆ normal ┆ anomaly │
│ ---  ┆ ---   ┆ ---   ┆ ---    ┆ ---     │
│ i64  ┆ i64   ┆ f64   ┆ f64    ┆ f64     │
╞══════╪═══════╪═══════╪════════╪═════════╡
│ 1982 ┆ 9     ┆ 28.15 ┆ 26.74  ┆ 1.41    │
│ 1997 ┆ 9     ┆ 28.79 ┆ 26.74  ┆ 2.05    │
│ 2015 ┆ 9     ┆ 28.77 ┆ 26.74  ┆ 2.03    │
│ 2023 ┆ 9     ┆ 28.26 ┆ 26.74  ┆ 1.52    │
│ 2026 ┆ 9     ┆ 29.27 ┆ 26.74  ┆ 2.53    │
└──────┴───────┴───────┴────────┴─────────┘

September 2026 was 2.5 °C above a normal September: the ocean is running a fever.

The same idea works for every point of the ocean. Here are three Septembers, each compared with a normal September: the two biggest El Niños of the satellite era, and this one.

show plots.anomalyMaps(["1997-09", "2015-09", "2026-09"],
                       ["September 1997", "September 2015", "September 2026"])
plotting code
proc anomalyMaps*(months, titles: openArray[string],
                  boxes: openArray[string] = ["Niño 3.4"], title = ""): PlotJson =
  ## Small multiples of SST anomaly maps on one shared diverging scale (±4 °C), in one row.
  let anomaly = readCsv("data/pacific_anomaly.csv")
  let n = months.len
  var p = Plot[float](layout: layout(
    (if title.len > 0: title else: "Sea temperature compared with normal"), 360))
  var zs: seq[JsonNode]
  for i, mo in months:
    let sx = if i == 0: "" else: $(i + 1)
    let (tr, z) = heatmap(anomaly.filter(col.month == mo), "anomaly", "x" & sx, "y" & sx)
    p.traces.add tr; zs.add z
  result = p.finish(source = "Data: NOAA ERSSTv5. Red: warmer than the 1991-2020 normal " &
                             "for that month; blue: cooler.")
  result.mapAxes(n)
  let gap = 0.05
  let w = (1.0 - gap * float(n - 1)) / float(n)
  for i in 0 ..< n:
    let sx = if i == 0: "" else: $(i + 1)
    let t = result.traces[i]
    t["z"] = zs[i]; t["colorscale"] = scale(Diverging)
    t["zmin"] = %(-4); t["zmax"] = %4; t["zmid"] = %0
    t["showscale"] = %(i == 0)
    if i == 0: t["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.7, "tickvals": [-4, -2, 0, 2, 4], "outlinewidth": 0}
    t["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:+.1f} °C vs normal<extra></extra>"
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & sx]["domain"] = %*[x0, x0 + w]
    result.note(x0 + w / 2, 1.0, titles[i], 12, Ink, ("paper", "paper"),
                %*{"yanchor": "bottom", "xanchor": "center"})
    result.drawBoxes(boxes, ("x" & sx, "y" & sx))

CPC does one thing differently. It does not use a single base period for all 76 years but a sliding one, so that each year is compared with the 30 years around it. The file also carries CPC's own anomaly, and we will see in scene 7 why the difference matters.

3. Three months make a season↑ contents

A single warm month can be a fluke of the weather. So the official Oceanic Niño Index (ONI) is a three-month running mean of the anomaly: the value for "DJF" is the mean of December, January and February, and so on through the twelve overlapping seasons of the year.

CPC publishes the ONI as a wide table, one row per year and one column per season, rounded to one decimal. That shape is good for reading, bad for computing. unpivot turns it into one row per season, and replaceStrict maps each season to its middle month.

const seasons = ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ", "JJA", "JAS", "ASO", "SON", "OND", "NDJ"]
let oniTable = readCsv("data/oni_table.csv")
echo oniTable.tail(3)
var seasonMonth: seq[(string, int)]
for m, s in seasons: seasonMonth.add (s, m + 1)
let oni = oniTable.unpivot(index = "year", variableName = "season", valueName = "oni")
  .dropNulls("oni")
  .withColumns(col.season.replaceStrict(seasonMonth).alias("month"))
  .sort(["year", "month"])
echo oni.tail(3)
shape: (3, 13)
┌──────┬───────┬───────┬───────┬──────┬───┬───────┬───────┬───────┬───────┬───────┐
│ year ┆ DJF   ┆ JFM   ┆ FMA   ┆ MAM  ┆ … ┆ JAS   ┆ ASO   ┆ SON   ┆ OND   ┆ NDJ   │
│ ---  ┆ ---   ┆ ---   ┆ ---   ┆ ---  ┆   ┆ ---   ┆ ---   ┆ ---   ┆ ---   ┆ ---   │
│ i64  ┆ f64   ┆ f64   ┆ f64   ┆ f64  ┆   ┆ f64   ┆ f64   ┆ f64   ┆ f64   ┆ f64   │
╞══════╪═══════╪═══════╪═══════╪══════╪═══╪═══════╪═══════╪═══════╪═══════╪═══════╡
│ 2024 ┆ 1.80  ┆ 1.50  ┆ 1.20  ┆ 0.80 ┆ … ┆ 0.00  ┆ -0.10 ┆ -0.20 ┆ -0.30 ┆ -0.40 │
│ 2025 ┆ -0.50 ┆ -0.20 ┆ -0.10 ┆ 0.00 ┆ … ┆ -0.30 ┆ -0.40 ┆ -0.60 ┆ -0.60 ┆ -0.60 │
│ 2026 ┆ -0.40 ┆ -0.20 ┆ 0.10  ┆ 0.50 ┆ … ┆ 2.20  ┆ null  ┆ null  ┆ null  ┆ null  │
└──────┴───────┴───────┴───────┴──────┴───┴───────┴───────┴───────┴───────┴───────┘
shape: (3, 4)
┌──────┬────────┬──────┬───────┐
│ year ┆ season ┆ oni  ┆ month │
│ ---  ┆ ---    ┆ ---  ┆ ---   │
│ i64  ┆ str    ┆ f64  ┆ i64   │
╞══════╪════════╪══════╪═══════╡
│ 2026 ┆ MJJ    ┆ 1.40 ┆ 6     │
│ 2026 ┆ JJA    ┆ 1.80 ┆ 7     │
│ 2026 ┆ JAS    ┆ 2.20 ┆ 8     │
└──────┴────────┴──────┴───────┘

Now we rebuild the index ourselves from CPC's monthly anomalies, with a centered rollingMean over three rows, and compare.

let cpc = readCsv("data/nino34.csv").select(col.year, col.month,
  col("cpc_anomaly").rollingMean(3, center = true).alias("mine"))
let rebuilt = oni.join(cpc, on = ["year", "month"])
  .withColumns((col.mine - col.oni).abs.alias("diff"))
echo rebuilt.select(col.diff.len.alias("seasons"), col.diff.max.alias("max_diff"),
                    (col.mine.round(1) != col.oni).sum.alias("off_by_rounding"))
shape: (1, 3)
┌─────────┬──────────┬─────────────────┐
│ seasons ┆ max_diff ┆ off_by_rounding │
│ ---     ┆ ---      ┆ ---             │
│ u32     ┆ f64      ┆ u32             │
╞═════════╪══════════╪═════════════════╡
│ 920     ┆ 0.05     ┆ 14              │
└─────────┴──────────┴─────────────────┘

All 920 seasons agree to within 0.05 °C, which is the rounding of the table. Only 14 land on the other side of a rounding tie (CPC averages the unrounded values). We have rebuilt NOAA's El Niño index in one line.

4. Counting El Niños↑ contents

The rule for an El Niño event is simple: the ONI must be at +0.5 °C or more for at least five overlapping seasons in a row. Its cold mirror image, at -0.5 °C or less, is called La Niña (the girl). Anything in between is "neutral". Together they make the El Niño-Southern Oscillation, ENSO for short.

Finding runs is a job for rleId: it gives every run of equal values its own number. Label each season with its phase, number the runs, and keep the runs at least five seasons long.

let phase = choose:
  if col.oni >= 0.5: "El Niño"
  elif col.oni <= -0.5: "La Niña"
  else: "neutral"
let events = oni.withColumns(phase.alias("phase"))
  .withColumns(col.phase.rleId.alias("run"))
  .groupBy("run")
  .agg(col.phase.first,
       format("{} {}", col.season.first, col.year.first).alias("start"),
       format("{} {}", col.season.last, col.year.last).alias("end"),
       col.oni.len.alias("seasons"),
       col.oni.max.alias("peak"), col.oni.min.alias("trough"),
       date(col.year.first, col.month.first, 15).alias("start_date"))
  .filter(col.phase != "neutral" and col.seasons >= 5)
  .drop("run")
echo events["phase"].valueCounts(sort = true)
echo events.tail(5).drop("start_date")
shape: (2, 2)
┌─────────┬───────┐
│ phase   ┆ count │
│ ---     ┆ ---   │
│ str     ┆ u32   │
╞═════════╪═══════╡
│ El Niño ┆ 25    │
│ La Niña ┆ 21    │
└─────────┴───────┘
shape: (5, 6)
┌─────────┬──────────┬──────────┬─────────┬───────┬────────┐
│ phase   ┆ start    ┆ end      ┆ seasons ┆ peak  ┆ trough │
│ ---     ┆ ---      ┆ ---      ┆ ---     ┆ ---   ┆ ---    │
│ str     ┆ str      ┆ str      ┆ u32     ┆ f64   ┆ f64    │
╞═════════╪══════════╪══════════╪═════════╪═══════╪════════╡
│ El Niño ┆ SON 2019 ┆ FMA 2020 ┆ 6       ┆ 0.80  ┆ 0.50   │
│ La Niña ┆ ASO 2020 ┆ MAM 2021 ┆ 8       ┆ -0.60 ┆ -1.10  │
│ La Niña ┆ JAS 2021 ┆ DJF 2023 ┆ 18      ┆ -0.50 ┆ -0.90  │
│ El Niño ┆ AMJ 2023 ┆ MAM 2024 ┆ 12      ┆ 2.00  ┆ 0.50   │
│ El Niño ┆ MAM 2026 ┆ JAS 2026 ┆ 5       ┆ 2.20  ┆ 0.50   │
└─────────┴──────────┴──────────┴─────────┴───────┴────────┘

25 El Niños and 21 La Niñas since 1950. CPC colours its table red and blue with the same rule, and our runs match its colouring season by season, all 920 of them. One detail matters: the rule is applied to the rounded table. On CPC's two-decimal file, where a +0.46 does not reach +0.5, the same code finds only 22 El Niños.

Look at the last row: the current El Niño began in MAM (March to May) 2026 and is still going, so it has no end yet. It already counts as an event: JAS is its fifth season.

The whole record at a glance, red when the index is at +0.5 or more, blue at -0.5 or less.

show plots.oniBars(oni)
plotting code
proc oniBars*(oni: DataFrame): PlotJson =
  ## ONI as bars: red at or above +0.5, blue at or below -0.5, grey in between.
  let v = oni.toList("oni", float)
  let colors = v.mapIt(hex(if it >= 0.5: Warm elif it <= -0.5: Cool else: Grey))
  let tr = Trace[float](`type`: PlotType.Bar, xs: oni.decimalYear, ys: v,
                        marker: Marker[float](color: colors))
  let p = Plot[float](traces: @[tr], layout: layout(
    "Oceanic Niño Index 1950-2026: El Niño in red, La Niña in blue", 380))
  result = p.finish(source = "Data: NOAA CPC. Dotted lines at ±0.5 °C.")
  result.traces[0]["marker"]["line"] = %*{"width": 0}
  result.traces[0]["customdata"] = %zip(oni.toList("season", string), oni.toList("year", int)).mapIt(%*[it[0], it[1]])
  result.traces[0]["hovertemplate"] = %"%{customdata[0]} %{customdata[1]}: %{y:+.1f} °C<extra></extra>"
  result.layout["bargap"] = %0
  for y in [0.5, -0.5]:
    result.shape %*{"type": "line", "xref": "paper", "x0": 0, "x1": 1, "y0": y, "y1": y,
                    "line": {"color": Ink2, "width": 1, "dash": "dot"}}
  for (x, y, t) in [(1983.0, 2.4, "1982-83"), (1998.0, 2.65, "1997-98"),
                    (2016.0, 2.85, "2015-16"), (2026.6, 2.45, "2026")]:
    result.note(x, y, t, 11)
  result.layout["yaxis"]["title"] = %*{"text": "ONI, °C"}
  result.layout["yaxis"]["range"] = %*[-2.3, 3.1]
  result.layout["xaxis"]["range"] = %*[1949.5, 2027.5]

5. How strong?↑ contents

Forecasters grade events by their peak: weak from +0.5, moderate from +1.0, strong from +1.5, very strong from +2.0. cut does the binning; leftClosed makes each band include its lower edge. Then topK picks the five biggest El Niños.

let ninos = events.filter(col.phase == "El Niño").withColumns(
  col.peak.cut([1.0, 1.5, 2.0], labels = ["weak", "moderate", "strong", "very strong"],
               leftClosed = true).alias("strength"))
echo ninos["strength"].valueCounts.sort("strength")
echo ninos.topK(5, by = "peak").select("start", "end", "seasons", "peak", "strength")
shape: (4, 2)
┌─────────────┬───────┐
│ strength    ┆ count │
│ ---         ┆ ---   │
│ enum        ┆ u32   │
╞═════════════╪═══════╡
│ weak        ┆ 8     │
│ moderate    ┆ 6     │
│ strong      ┆ 6     │
│ very strong ┆ 5     │
└─────────────┴───────┘
shape: (5, 5)
┌──────────┬──────────┬─────────┬──────┬─────────────┐
│ start    ┆ end      ┆ seasons ┆ peak ┆ strength    │
│ ---      ┆ ---      ┆ ---     ┆ ---  ┆ ---         │
│ str      ┆ str      ┆ u32     ┆ f64  ┆ enum        │
╞══════════╪══════════╪═════════╪══════╪═════════════╡
│ SON 2014 ┆ AMJ 2016 ┆ 20      ┆ 2.60 ┆ very strong │
│ AMJ 1997 ┆ MAM 1998 ┆ 12      ┆ 2.40 ┆ very strong │
│ MAM 2026 ┆ JAS 2026 ┆ 5       ┆ 2.20 ┆ very strong │
│ AMJ 1982 ┆ MJJ 1983 ┆ 14      ┆ 2.10 ┆ very strong │
│ AMJ 2023 ┆ MAM 2024 ┆ 12      ┆ 2.00 ┆ very strong │
└──────────┴──────────┴─────────┴──────┴─────────────┘

The famous ones are all there: 1982-83, 1997-98 and 2015-16 (which by this index started in late 2014), the three "super El Niños" of the satellite era, and 2023-24, which just makes the very strong band. The current event is already in third place at 2.2 and, according to CPC's October discussion, still strengthening.

And here is what "very strong" looks like next to its opposite: December 1997, at the peak of the 1997-98 El Niño, and December 1988, at the peak of a strong La Niña, when the cold tongue reached far into the central Pacific.

show plots.anomalyMaps(["1997-12", "1988-12"], ["El Niño, December 1997", "La Niña, December 1988"])
plotting code
proc anomalyMaps*(months, titles: openArray[string],
                  boxes: openArray[string] = ["Niño 3.4"], title = ""): PlotJson =
  ## Small multiples of SST anomaly maps on one shared diverging scale (±4 °C), in one row.
  let anomaly = readCsv("data/pacific_anomaly.csv")
  let n = months.len
  var p = Plot[float](layout: layout(
    (if title.len > 0: title else: "Sea temperature compared with normal"), 360))
  var zs: seq[JsonNode]
  for i, mo in months:
    let sx = if i == 0: "" else: $(i + 1)
    let (tr, z) = heatmap(anomaly.filter(col.month == mo), "anomaly", "x" & sx, "y" & sx)
    p.traces.add tr; zs.add z
  result = p.finish(source = "Data: NOAA ERSSTv5. Red: warmer than the 1991-2020 normal " &
                             "for that month; blue: cooler.")
  result.mapAxes(n)
  let gap = 0.05
  let w = (1.0 - gap * float(n - 1)) / float(n)
  for i in 0 ..< n:
    let sx = if i == 0: "" else: $(i + 1)
    let t = result.traces[i]
    t["z"] = zs[i]; t["colorscale"] = scale(Diverging)
    t["zmin"] = %(-4); t["zmax"] = %4; t["zmid"] = %0
    t["showscale"] = %(i == 0)
    if i == 0: t["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.7, "tickvals": [-4, -2, 0, 2, 4], "outlinewidth": 0}
    t["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:+.1f} °C vs normal<extra></extra>"
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & sx]["domain"] = %*[x0, x0 + w]
    result.note(x0 + w / 2, 1.0, titles[i], 12, Ink, ("paper", "paper"),
                %*{"yanchor": "bottom", "xanchor": "center"})
    result.drawBoxes(boxes, ("x" & sx, "y" & sx))

6. 2026, the fast one↑ contents

How quickly did this one arrive? diff gives the change from one season to the next, and shift(4) lets us compare each season with four seasons earlier, about the time it takes an El Niño to grow.

let rise = oni.withColumns(col.oni.diff.alias("step"),
                           (col.oni - col.oni.shift(4)).alias("rise4"))
echo rise.filter(col.year == 2026).select("season", "oni", "step", "rise4")
echo rise.topK(5, by = "rise4").select("year", "season", "oni", "rise4")
shape: (8, 4)
┌────────┬───────┬──────┬───────┐
│ season ┆ oni   ┆ step ┆ rise4 │
│ ---    ┆ ---   ┆ ---  ┆ ---   │
│ str    ┆ f64   ┆ f64  ┆ f64   │
╞════════╪═══════╪══════╪═══════╡
│ DJF    ┆ -0.40 ┆ 0.20 ┆ 0.00  │
│ JFM    ┆ -0.20 ┆ 0.20 ┆ 0.40  │
│ FMA    ┆ 0.10  ┆ 0.30 ┆ 0.70  │
│ MAM    ┆ 0.50  ┆ 0.40 ┆ 1.10  │
│ AMJ    ┆ 0.90  ┆ 0.40 ┆ 1.30  │
│ MJJ    ┆ 1.40  ┆ 0.50 ┆ 1.60  │
│ JJA    ┆ 1.80  ┆ 0.40 ┆ 1.70  │
│ JAS    ┆ 2.20  ┆ 0.40 ┆ 1.70  │
└────────┴───────┴──────┴───────┘
shape: (5, 4)
┌──────┬────────┬──────┬───────┐
│ year ┆ season ┆ oni  ┆ rise4 │
│ ---  ┆ ---    ┆ ---  ┆ ---   │
│ i64  ┆ str    ┆ f64  ┆ f64   │
╞══════╪════════╪══════╪═══════╡
│ 2026 ┆ JAS    ┆ 2.20 ┆ 1.70  │
│ 2026 ┆ JJA    ┆ 1.80 ┆ 1.70  │
│ 2026 ┆ MJJ    ┆ 1.40 ┆ 1.60  │
│ 1997 ┆ JJA    ┆ 1.50 ┆ 1.50  │
│ 1997 ┆ JAS    ┆ 1.80 ┆ 1.50  │
└──────┴────────┴──────┴───────┘

From MAM to JAS 2026 the index climbed 1.7 °C, the fastest four-season rise since 1950, ahead of 1997. To line events up from their first season, cumCount over each run counts the seasons since onset, and pivot puts the big events side by side.

let big = [1982, 1997, 2014, 2023, 2026]
let runs = oni.withColumns(phase.alias("phase"))
  .withColumns(col.phase.rleId.alias("run"))
  .withColumns(col.year.first.over("run").alias("onset"),
               col.oni.cumCount.over("run").alias("season_no"))
  .filter(col.phase == "El Niño" and col.onset.isIn(big) and col("season_no") <= 8)
let side = runs.pivot(on = "onset", index = "season_no", values = "oni")
echo side
shape: (8, 6)
┌───────────┬──────┬──────┬──────┬──────┬──────┐
│ season_no ┆ 1982 ┆ 1997 ┆ 2014 ┆ 2023 ┆ 2026 │
│ ---       ┆ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
│ u32       ┆ f64  ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
╞═══════════╪══════╪══════╪══════╪══════╪══════╡
│ 1         ┆ 0.70 ┆ 0.70 ┆ 0.50 ┆ 0.50 ┆ 0.50 │
│ 2         ┆ 0.70 ┆ 1.10 ┆ 0.70 ┆ 0.70 ┆ 0.90 │
│ 3         ┆ 0.80 ┆ 1.50 ┆ 0.80 ┆ 1.00 ┆ 1.40 │
│ 4         ┆ 1.00 ┆ 1.80 ┆ 0.70 ┆ 1.30 ┆ 1.80 │
│ 5         ┆ 1.50 ┆ 2.00 ┆ 0.70 ┆ 1.50 ┆ 2.20 │
│ 6         ┆ 1.80 ┆ 2.20 ┆ 0.70 ┆ 1.70 ┆ null │
│ 7         ┆ 2.00 ┆ 2.30 ┆ 0.90 ┆ 1.90 ┆ null │
│ 8         ┆ 2.10 ┆ 2.40 ┆ 1.00 ┆ 2.00 ┆ null │
└───────────┴──────┴──────┴──────┴──────┴──────┘

Five seasons in, 2026 is ahead of every other event, 1997 included. (The 2014 column is the 2015-16 event, which began in late 2014 and then idled for months around +0.7 before taking off.)

show plots.growth(side)
plotting code
proc growth*(side: DataFrame): PlotJson =
  ## Each event's ONI by season since onset; the last column drawn on top, thicker.
  let cols = side.columns[1 .. ^1]
  let palette = [Grey, Blue, Aqua, Orange, Warm]
  var p = Plot[float](layout: layout("2026 is growing faster than any El Niño since 1950",
                                     400, legend = true))
  for i, c in cols:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.LinesMarkers,
                              name: (if c == "2014": "2015-16" else: c),
                              xs: side.toList("season_no", float),
                              ys: side.toList(c, Option[float]).mapIt(it.get(NaN)))
  result = p.finish
  for i, c in cols:
    let t = result.traces[i]
    let name = t["name"].getStr
    let ys = side.toList(c, Option[float])
    t["y"] = %ys.mapIt(if it.isSome: %it.get else: newJNull())
    result.line(i, palette[i], if i == cols.high: 3.5 else: 2.0)
    t["marker"] = %*{"size": 7, "color": palette[i]}
    t["mode"] = %"lines+markers+text"
    var text = newSeq[string](ys.len)
    text[ys.filterIt(it.isSome).len - 1] = name
    t["text"] = %text
    t["textposition"] = %"middle right"
    t["hovertemplate"] = %(name & ", season %{x}: %{y:.1f} °C<extra></extra>")
  result.layout["xaxis"]["title"] = %*{"text": "season since the event began"}
  result.layout["xaxis"]["range"] = %*[0.7, 9.0]
  result.layout["xaxis"]["dtick"] = %1
  result.layout["yaxis"]["title"] = %*{"text": "ONI, °C"}

7. A moving ruler↑ contents

Here is a problem. The whole tropical ocean is getting warmer. If "normal" stays fixed, a warming ocean looks more and more like El Niño, even when nothing special is going on. Our fixed 1991-2020 anomaly from scene 2 shows it: groupByDynamic with a ten-year window gives the mean anomaly of each decade.

let monthly = readCsv("data/nino34.csv")
  .withColumns(date(col.year, col.month, 1).alias("date"))
  .join(nino.select("year", "month", "anomaly"), on = ["year", "month"])
echo monthly.filter(col.year >= 1950).groupByDynamic("date", every = "10y").agg(
  col.anomaly.mean.alias("fixed_base"), col("cpc_anomaly").mean.alias("sliding_base"))
shape: (8, 3)
┌────────────┬────────────┬──────────────┐
│ date       ┆ fixed_base ┆ sliding_base │
│ ---        ┆ ---        ┆ ---          │
│ date       ┆ f64        ┆ f64          │
╞════════════╪════════════╪══════════════╡
│ 1950-01-01 ┆ -0.42      ┆ 0.01         │
│ 1960-01-01 ┆ -0.24      ┆ 0.16         │
│ 1970-01-01 ┆ -0.51      ┆ -0.20        │
│ 1980-01-01 ┆ -0.20      ┆ 0.02         │
│ 1990-01-01 ┆ 0.09       ┆ 0.18         │
│ 2000-01-01 ┆ -0.13      ┆ -0.10        │
│ 2010-01-01 ┆ 0.07       ┆ 0.14         │
│ 2020-01-01 ┆ -0.07      ┆ 0.01         │
└────────────┴────────────┴──────────────┘

Against a fixed base, every decade before 1990 averages 0.2 to 0.5 °C below zero: the 1950s to 1980s look like a forty-year La Niña. CPC's sliding base keeps every decade near zero, but it is always computed from past years, so it lags behind a fast warming. So since February 2026 NOAA uses a new official index, the Relative ONI (RONI): the Niño 3.4 anomaly minus the average anomaly of the whole tropics (20°N to 20°S), rescaled to the same spread. El Niño is now measured against the rest of the tropical ocean, not against the past.

Same rules, new ruler: count the events again with RONI and match them to the ONI events with joinAsof, which pairs each ONI event with the RONI event that started nearest in time, if within six months.

let roni = readCsv("data/roni_table.csv")
  .unpivot(index = "year", variableName = "season", valueName = "oni")
  .dropNulls("oni")
  .withColumns(col.season.replaceStrict(seasonMonth).alias("month"))
  .sort(["year", "month"])
let roniEvents = roni.withColumns(phase.alias("phase"))
  .withColumns(col.phase.rleId.alias("run"))
  .groupBy("run")
  .agg(col.phase.first, col.oni.len.alias("seasons"),
       format("{} {}", col.season.first, col.year.first).alias("roni_start"),
       col.oni.max.alias("roni_peak"),
       date(col.year.first, col.month.first, 15).alias("start_date"))
  .filter(col.phase == "El Niño" and col.seasons >= 5)
  .select("start_date", "roni_start", "roni_peak")
echo &"ONI: {ninos.height} El Niños, RONI: {roniEvents.height}"
let paired = ninos.sort("start_date").joinAsof(
  roniEvents.sort("start_date"), on = "start_date", strategy = AsofStrategy.Nearest,
  tolerance = 183.days, coalesce = false)
echo paired.filter(col("start_date").dt.year >= 2000)
  .select("start", "peak", "roni_start", "roni_peak")
echo roniEvents.topK(3, by = "roni_peak")
  .sort(["roni_peak", "start_date"], descending = [true, false])
ONI: 25 El Niños, RONI: 25
shape: (9, 4)
┌──────────┬──────┬────────────┬───────────┐
│ start    ┆ peak ┆ roni_start ┆ roni_peak │
│ ---      ┆ ---  ┆ ---        ┆ ---       │
│ str      ┆ f64  ┆ str        ┆ f64       │
╞══════════╪══════╪════════════╪═══════════╡
│ MJJ 2002 ┆ 1.20 ┆ JJA 2002   ┆ 1.30      │
│ JAS 2004 ┆ 0.70 ┆ JJA 2004   ┆ 0.70      │
│ ASO 2006 ┆ 0.90 ┆ ASO 2006   ┆ 0.90      │
│ JJA 2009 ┆ 1.50 ┆ ASO 2009   ┆ 1.50      │
│ SON 2014 ┆ 2.60 ┆ OND 2014   ┆ 2.30      │
│ ASO 2018 ┆ 1.10 ┆ SON 2018   ┆ 0.80      │
│ SON 2019 ┆ 0.80 ┆ null       ┆ null      │
│ AMJ 2023 ┆ 2.00 ┆ JJA 2023   ┆ 1.40      │
│ MAM 2026 ┆ 2.20 ┆ null       ┆ null      │
└──────────┴──────┴────────────┴───────────┘
shape: (3, 3)
┌────────────┬────────────┬───────────┐
│ start_date ┆ roni_start ┆ roni_peak │
│ ---        ┆ ---        ┆ ---       │
│ date       ┆ str        ┆ f64       │
╞════════════╪════════════╪═══════════╡
│ 1982-04-15 ┆ MAM 1982   ┆ 2.40      │
│ 1997-04-15 ┆ MAM 1997   ┆ 2.30      │
│ 2014-11-15 ┆ OND 2014   ┆ 2.30      │
└────────────┴────────────┴───────────┘

Both rulers count 25 El Niños since 1950, but not quite the same ones, and not equally strong. Since 2000 the two lists mostly agree, with three exceptions:

The RONI record holder is 1982-83 at +2.4. That is why CPC's October discussion speaks of a "historic event" if the 3-month RONI reaches +2.5 or more, which it gives a 54% chance for September-November and 83% for October-December.

Side by side since 1995, the two rulers mostly agree on the ups and downs. They part ways where the whole tropics were warm: 2023 and now.

show plots.twoRulers(oni, roni)
plotting code
proc twoRulers*(oni, roni: DataFrame, since = 1995): PlotJson =
  var p = Plot[float](layout: layout("Two rulers for the same ocean", 360, legend = true))
  let series = [(oni, Grey, "ONI (official until January 2026)"),
                (roni, Warm, "RONI (official since February 2026)")]
  for (df, color, name) in series:
    let d = df.filter(col.year >= since)
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: name,
                              xs: d.decimalYear, ys: d.toList("oni", float))
  result = p.finish(hovermode = "x unified")
  for i, (df, color, name) in series:
    let d = df.filter(col.year >= since)
    result.line(i, color)
    result.traces[i]["customdata"] = %zip(d.toList("season", string), d.toList("year", int)).mapIt(%*[it[0], it[1]])
    result.traces[i]["hovertemplate"] = %(name.split(" ")[0] &
      " %{customdata[0]} %{customdata[1]}: %{y:+.1f}<extra></extra>")
  result.shape %*{"type": "line", "xref": "paper", "x0": 0, "x1": 1, "y0": 0.5, "y1": 0.5,
                  "line": {"color": Ink2, "width": 1, "dash": "dot"}}
  result.layout["yaxis"]["title"] = %*{"text": "°C"}
  result.layout["xaxis"]["range"] = %*[since, 2027]

8. The other half: air pressure↑ contents

El Niño is not only about water. In the 1920s the British scientist Gilbert Walker, looking for a way to forecast India's monsoon, found a seesaw in air pressure across the Pacific: when pressure is high in the east it is low in the west, and vice versa. He called it the Southern Oscillation. Today it is measured as the Southern Oscillation Index (SOI): the pressure at Tahiti minus the pressure at Darwin, Australia, standardized. When the trade winds weaken, the SOI drops.

In 1969 the Norwegian meteorologist Jacob Bjerknes showed that Walker's seesaw and the warm Pacific water were one coupled system: weaker trade winds let the ocean warm, and a warmer east Pacific weakens the trade winds further. corr shows how tightly the two move together, here on three-month means of both.

let soi = readCsv("data/soi.csv").withColumns(col.soi.rollingMean(3, center = true).alias("soi3"))
let both = soi.join(cpc, on = ["year", "month"]).dropNulls
echo both.select(col.soi.len.alias("months"), corr("soi3", "mine").alias("r"))
echo both.filter(col.year == 2026).tail(4)
shape: (1, 2)
┌────────┬───────┐
│ months ┆ r     │
│ ---    ┆ ---   │
│ u32    ┆ f64   │
╞════════╪═══════╡
│ 907    ┆ -0.84 │
└────────┴───────┘
shape: (4, 5)
┌──────┬───────┬───────┬───────┬──────┐
│ year ┆ month ┆ soi   ┆ soi3  ┆ mine │
│ ---  ┆ ---   ┆ ---   ┆ ---   ┆ ---  │
│ i64  ┆ i64   ┆ f64   ┆ f64   ┆ f64  │
╞══════╪═══════╪═══════╪═══════╪══════╡
│ 2026 ┆ 5     ┆ -0.90 ┆ -0.97 ┆ 0.95 │
│ 2026 ┆ 6     ┆ -1.40 ┆ -1.57 ┆ 1.40 │
│ 2026 ┆ 7     ┆ -2.40 ┆ -1.63 ┆ 1.81 │
│ 2026 ┆ 8     ┆ -1.10 ┆ -1.83 ┆ 2.17 │
└──────┴───────┴───────┴───────┴──────┘

A correlation of -0.84 over 75 years: when the sea warms, the pressure seesaw tips. In 2026 the SOI swung from positive (La Niña) in the winter to negative in April, and has stayed there as the ocean warmed.

show plots.soiVsOni(both)
plotting code
proc soiVsOni*(both: DataFrame, since = 1980): PlotJson =
  ## Two stacked panels, one per measure (never a second y-axis).
  let d = both.filter(col.year >= since)
  let t = d.decimalYear
  var p = Plot[float](layout: layout("Ocean and atmosphere move together", 440))
  for (c, warmIfPos, ya) in [("mine", true, "y"), ("soi3", false, "y2")]:
    let v = d.toList(c, float)
    p.traces.add Trace[float](`type`: PlotType.Bar, xs: t, ys: v, yaxis: ya,
      marker: Marker[float](color: v.mapIt(hex(if (it >= 0) == warmIfPos: Warm else: Cool))))
  result = p.finish(source = "Data: NOAA CPC. Red marks the El Niño side of each index.")
  for tr in result.traces:
    tr["marker"]["line"] = %*{"width": 0}
    tr["hovertemplate"] = %"%{x:.1f}: %{y:+.2f}<extra></extra>"
  result.layout["bargap"] = %0
  result.layout["xaxis"]["range"] = %*[since, 2027]
  result.layout["xaxis"]["anchor"] = %"y2"
  result.layout["yaxis"]["domain"] = %*[0.56, 1.0]
  result.layout["yaxis2"] = %*{"domain": [0.0, 0.44], "anchor": "x", "gridcolor": Grid,
                               "zeroline": false}
  result.note(0, 1.0, "Sea: Niño 3.4 anomaly, °C (3-month mean)", 12, Ink, ("paper", "paper"),
              %*{"xanchor": "left", "yanchor": "bottom"})
  result.note(0, 0.44, "Air: Southern Oscillation Index (3-month mean), its mirror image", 12,
              Ink, ("paper", "paper"), %*{"xanchor": "left", "yanchor": "bottom"})

9. Four boxes and a coastal surprise↑ contents

Niño 3.4 is not the only box. CPC also tracks Niño 1+2, right off the coast of Peru and Ecuador, Niño 3 in the east and Niño 4 in the west. The horizontal functions compare columns within each row: maxHorizontal finds the hottest box, meanHorizontal the average of the four.

let anoms = ["nino12_anom", "nino3_anom", "nino34_anom", "nino4_anom"]
let boxes = readCsv("data/nino_boxes.csv").select(@["year", "month"] & @anoms)
  .withColumns(maxHorizontal(anoms).alias("hottest"), meanHorizontal(anoms).alias("mean"))
echo boxes.tail(3)
let coastal = boxes.filter(col("nino12_anom") >= 1.0 and col("nino34_anom").abs < 0.5)
echo coastal.groupBy("year").agg(col.month.len.alias("months"),
                                 col("nino12_anom").max.alias("coast_max")).sort("year")
shape: (3, 8)
┌──────┬───────┬─────────────┬────────────┬─────────────┬────────────┬─────────┬──────┐
│ year ┆ month ┆ nino12_anom ┆ nino3_anom ┆ nino34_anom ┆ nino4_anom ┆ hottest ┆ mean │
│ ---  ┆ ---   ┆ ---         ┆ ---        ┆ ---         ┆ ---        ┆ ---     ┆ ---  │
│ i64  ┆ i64   ┆ f64         ┆ f64        ┆ f64         ┆ f64        ┆ f64     ┆ f64  │
╞══════╪═══════╪═════════════╪════════════╪═════════════╪════════════╪═════════╪══════╡
│ 2026 ┆ 7     ┆ 3.56        ┆ 2.33       ┆ 2.03        ┆ 1.06       ┆ 3.56    ┆ 2.25 │
│ 2026 ┆ 8     ┆ 4.08        ┆ 3.13       ┆ 2.52        ┆ 0.93       ┆ 4.08    ┆ 2.67 │
│ 2026 ┆ 9     ┆ 4.69        ┆ 3.64       ┆ 2.84        ┆ 0.95       ┆ 4.69    ┆ 3.03 │
└──────┴───────┴─────────────┴────────────┴─────────────┴────────────┴─────────┴──────┘
shape: (10, 3)
┌──────┬────────┬───────────┐
│ year ┆ months ┆ coast_max │
│ ---  ┆ ---    ┆ ---       │
│ i64  ┆ u32    ┆ f64       │
╞══════╪════════╪═══════════╡
│ 1983 ┆ 4      ┆ 4.03      │
│ 1997 ┆ 1      ┆ 1.83      │
│ 1998 ┆ 1      ┆ 2.84      │
│ 2008 ┆ 2      ┆ 1.18      │
│ 2012 ┆ 1      ┆ 1.31      │
│ 2014 ┆ 3      ┆ 1.36      │
│ 2017 ┆ 3      ┆ 1.83      │
│ 2023 ┆ 3      ┆ 2.45      │
│ 2025 ┆ 1      ┆ 1.15      │
│ 2026 ┆ 2      ┆ 1.52      │
└──────┴────────┴───────────┘

In September 2026 the coastal box is 4.7 °C above normal, far ahead of the other three. The second table hunts for the opposite: months when the coast was at least a degree too warm while Niño 3.4 stayed neutral. Some are the tail of a big event (the coast stayed hot in mid-1983 after the centre cooled). Others, like early 2017 and early 2023, are "coastal El Niños" (El Niño costero): no event at all by NOAA's index, and floods in Peru all the same.

Three of the boxes since 2014 show both stories: in 2017 only the coast warmed; in 2023 and 2026 the coast warmed first and the centre followed.

show plots.boxLines(boxes)
plotting code
proc boxLines*(boxes: DataFrame, since = 2014): PlotJson =
  let d = boxes.filter(col.year >= since)
  var p = Plot[float](layout: layout("Three of the four boxes, 2014-2026", 380, legend = true))
  let series = [("nino12_anom", Orange, "Niño 1+2 (coast of Peru)"),
                ("nino34_anom", Warm, "Niño 3.4 (central Pacific)"),
                ("nino4_anom", Blue, "Niño 4 (west)")]
  for (c, color, name) in series:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: name,
                              xs: d.decimalYear, ys: d.toList(c, float))
  result = p.finish(source = "Data: NOAA CPC (OISST v2.1).", hovermode = "x unified")
  for i, (c, color, name) in series:
    result.line(i, color)
    result.traces[i]["hovertemplate"] = %(name.split(" (")[0] & ": %{y:+.2f} °C<extra></extra>")
  result.note(2017.2, 2.9, "2017: coast only", 11)
  result.note(2023.2, 2.9, "2023: coast first", 11)
  result.layout["yaxis"]["title"] = %*{"text": "°C vs normal"}
  result.layout["xaxis"]["range"] = %*[since, 2027]

On the map, March 2017 next to September 2026, with all four boxes drawn.

show plots.anomalyMaps(["2017-03", "2026-09"], ["Coastal El Niño, March 2017", "September 2026"],
                       boxes = ["Niño 4", "Niño 3.4", "Niño 3", "Niño 1+2"])
plotting code
proc anomalyMaps*(months, titles: openArray[string],
                  boxes: openArray[string] = ["Niño 3.4"], title = ""): PlotJson =
  ## Small multiples of SST anomaly maps on one shared diverging scale (±4 °C), in one row.
  let anomaly = readCsv("data/pacific_anomaly.csv")
  let n = months.len
  var p = Plot[float](layout: layout(
    (if title.len > 0: title else: "Sea temperature compared with normal"), 360))
  var zs: seq[JsonNode]
  for i, mo in months:
    let sx = if i == 0: "" else: $(i + 1)
    let (tr, z) = heatmap(anomaly.filter(col.month == mo), "anomaly", "x" & sx, "y" & sx)
    p.traces.add tr; zs.add z
  result = p.finish(source = "Data: NOAA ERSSTv5. Red: warmer than the 1991-2020 normal " &
                             "for that month; blue: cooler.")
  result.mapAxes(n)
  let gap = 0.05
  let w = (1.0 - gap * float(n - 1)) / float(n)
  for i in 0 ..< n:
    let sx = if i == 0: "" else: $(i + 1)
    let t = result.traces[i]
    t["z"] = zs[i]; t["colorscale"] = scale(Diverging)
    t["zmin"] = %(-4); t["zmax"] = %4; t["zmid"] = %0
    t["showscale"] = %(i == 0)
    if i == 0: t["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.7, "tickvals": [-4, -2, 0, 2, 4], "outlinewidth": 0}
    t["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:+.1f} °C vs normal<extra></extra>"
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & sx]["domain"] = %*[x0, x0 + w]
    result.note(x0 + w / 2, 1.0, titles[i], 12, Ink, ("paper", "paper"),
                %*{"yanchor": "bottom", "xanchor": "center"})
    result.drawBoxes(boxes, ("x" & sx, "y" & sx))

10. Rain in the desert↑ contents

What does that mean on the ground? Piura, in northern Peru, sits in a coastal desert: a typical year brings a few tens of millimetres of rain. Its airport's rain gauge has daily readings in NOAA's GHCN-Daily archive. groupByDynamic with a one-year window sums them per year, and counts the days that were actually reported, because a gauge that stopped reporting is not a dry year.

let rain = readCsv("data/piura_rain.csv", tryParseDates = true).sort("date")
let years = rain.groupByDynamic("date", every = "1y").agg(
  col("rain_mm").sum.alias("rain_mm"), col("rain_mm").len.alias("days"))
echo years.select(col("rain_mm").filter(col.days >= 300).median.alias("median, complete years"))
echo years.topK(4, by = "rain_mm")
shape: (1, 1)
┌────────────────────────┐
│ median, complete years │
│ ---                    │
│ f64                    │
╞════════════════════════╡
│ 32.00                  │
└────────────────────────┘
shape: (4, 3)
┌────────────┬─────────┬──────┐
│ date       ┆ rain_mm ┆ days │
│ ---        ┆ ---     ┆ ---  │
│ date       ┆ f64     ┆ u32  │
╞════════════╪═════════╪══════╡
│ 1983-01-01 ┆ 2434.60 ┆ 306  │
│ 1998-01-01 ┆ 1693.50 ┆ 275  │
│ 2017-01-01 ┆ 831.00  ┆ 79   │
│ 1997-01-01 ┆ 318.60  ┆ 364  │
└────────────┴─────────┴──────┘
show plots.piura(years)
plotting code
proc piura*(years: DataFrame): PlotJson =
  let d = years.withColumns(col.date.dt.year.alias("y"))
  let full = d.toList("days", int).mapIt(it >= 300)
  let tr = Trace[float](`type`: PlotType.Bar, xs: d.toList("y", float),
                        ys: d.toList("rain_mm", float),
                        marker: Marker[float](color: full.mapIt(hex(if it: Blue else: "#b7d3f6"))))
  let p = Plot[float](traces: @[tr], layout: layout("Piura, Peru: rain in a desert city", 360))
  result = p.finish(source = "Data: NOAA GHCN-Daily, Piura airport. Light bars: fewer than " &
                             "300 days reported that year.")
  result.traces[0]["customdata"] = %d.toList("days", int)
  result.traces[0]["hovertemplate"] = %"%{x}: %{y:,.0f} mm (%{customdata} days reported)<extra></extra>"
  for yr in [1983, 1998, 2017]:
    let v = d.filter(col.y == yr)["rain_mm"].item(float)
    result.note(float(yr), v, $yr, extra = %*{"yshift": 12})
  result.layout["yaxis"]["title"] = %*{"text": "rain per year, mm"}

In 1983 Piura got about 2,400 mm of rain, in 1998 about 1,700 mm, with two months of readings missing: more than fifty times a normal year, in a city that has no rain gutters. (A peer-reviewed tally for the city, Takahashi 2004, gives 2,147 mm for 1982-83 and 1,802 mm for 1997-98: the same picture.) Third is 2017, the coastal El Niño, with only 79 days on record. A 30-day rollingSumBy on the date column finds the wettest month.

echo rain.withColumns(col("rain_mm").rollingSumBy("date", 30.days).alias("mm_30d"))
  .topK(1, by = "mm_30d")
shape: (1, 3)
┌────────────┬─────────┬─────────┐
│ date       ┆ rain_mm ┆ mm_30d  │
│ ---        ┆ ---     ┆ ---     │
│ date       ┆ f64     ┆ f64     │
╞════════════╪═════════╪═════════╡
│ 1983-05-01 ┆ 305.10  ┆ 1042.90 │
└────────────┴─────────┴─────────┘

A thousand millimetres in the thirty days to 1 May 1983, 305 of them on that last day alone, as the station record has it: more than London gets in a whole typical year, in one month, in a desert.

11. The world's temperature↑ contents

El Niño does not only move heat around, it lets the ocean give heat back to the air, and the whole planet warms for a while. To see it we need the global temperature. NASA's GISTEMP gives the global mean surface temperature anomaly for each month since 1880, against a 1951-1980 base (NASA's choice; the base only shifts the numbers, not their differences). The file is another wide table, with one column per month and *** for months not yet measured.

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var monthNo: seq[(string, int)]
for i, m in months: monthNo.add (m, i + 1)
let gistemp = readCsv("data/gistemp.csv", skipRows = 1, nullValues = ["***"])
let world = gistemp.select(@["Year"] & @months)
  .unpivot(index = "Year", variableName = "mon", valueName = "temp")
  .withColumns(date(col("Year"), col.mon.replaceStrict(monthNo), 1).alias("date"))
  .dropNulls("temp").sort("date").select("date", "temp")
let yearly = gistemp.select(col("Year").alias("year"), col("J-D").alias("temp")).dropNulls
echo yearly.topK(5, by = "temp")
shape: (5, 2)
┌──────┬──────┐
│ year ┆ temp │
│ ---  ┆ ---  │
│ i64  ┆ f64  │
╞══════╪══════╡
│ 2024 ┆ 1.28 │
│ 2025 ┆ 1.18 │
│ 2023 ┆ 1.17 │
│ 2016 ┆ 1.01 │
│ 2020 ┆ 1.01 │
└──────┴──────┘

Each new record year breaks the previous best. cumMax keeps the running best, so a record is a year equal to it (and higher than the year before the record).

let records = yearly.filter(col.temp == col.temp.cumMax and
                            col.temp > col.temp.cumMax.shift(1))
echo records.filter(col.year >= 1980)["year"].toList(int)
@[1980, 1981, 1988, 1990, 1997, 1998, 2002, 2005, 2010, 2014, 2015, 2016, 2023, 2024]

Month-to-month the global temperature is noisy. An exponentially weighted mean, ewmMean, smooths it by giving recent months more weight; with span = 12 it acts like a one-year average that reacts faster than a plain 12-month rolling mean.

let smooth = world.withColumns(col.temp.rollingMean(12).alias("rolling12"),
                               col.temp.ewmMean(span = 12).alias("ewm12"))
echo smooth.tail(6)
shape: (6, 4)
┌────────────┬──────┬───────────┬───────┐
│ date       ┆ temp ┆ rolling12 ┆ ewm12 │
│ ---        ┆ ---  ┆ ---       ┆ ---   │
│ date       ┆ f64  ┆ f64       ┆ f64   │
╞════════════╪══════╪═══════════╪═══════╡
│ 2026-04-01 ┆ 1.16 ┆ 1.15      ┆ 1.18  │
│ 2026-05-01 ┆ 1.13 ┆ 1.15      ┆ 1.18  │
│ 2026-06-01 ┆ 1.17 ┆ 1.16      ┆ 1.18  │
│ 2026-07-01 ┆ 1.24 ┆ 1.18      ┆ 1.19  │
│ 2026-08-01 ┆ 1.42 ┆ 1.20      ┆ 1.22  │
│ 2026-09-01 ┆ 1.38 ┆ 1.21      ┆ 1.25  │
└────────────┴──────┴───────────┴───────┘
show plots.world(yearly, smooth, records)
plotting code
proc world*(yearly, smooth, records: DataFrame): PlotJson =
  let s = smooth.withColumns(col.date.dt.year.alias("year"), col.date.dt.month.alias("month"))
  var p = Plot[float](layout: layout("The world's temperature, 1880-2026", 400, legend = true))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines,
                            name: "monthly, smoothed (ewmMean, span 12)",
                            xs: s.decimalYear, ys: s.toList("ewm12", float))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: "yearly mean",
                            xs: yearly.toList("year", float).mapIt(it + 0.5),
                            ys: yearly.toList("temp", float))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "record year",
                            xs: records.toList("year", float).mapIt(it + 0.5),
                            ys: records.toList("temp", float))
  result = p.finish(source = "Data: NASA GISS, GISTEMP v4.")
  result.line(0, "#9ec5f4", 1.2); result.line(1, Blue)
  result.traces[2]["marker"] = %*{"color": Warm, "size": 8, "line": {"color": Surface, "width": 2}}
  result.traces[0]["hovertemplate"] = %"%{y:.2f} °C<extra></extra>"
  result.traces[1]["hovertemplate"] = %"%{x:.0f}: %{y:.2f} °C<extra></extra>"
  result.traces[2]["hovertemplate"] = %"record %{x:.0f}: %{y:.2f} °C<extra></extra>"
  result.layout["yaxis"]["title"] = %*{"text": "°C vs 1951-1980"}
  result.layout["xaxis"]["range"] = %*[1880, 2027]

12. El Niño's echo↑ contents

Does the planet warm after the Pacific does? Take the global temperature minus its own ten-year centered mean (to remove the long warming trend), and correlate it with the Niño 3.4 index shifted by 0 to 6 months.

let wiggles = world
  .withColumns(col.date.dt.year.cast(int).alias("year"), col.date.dt.month.cast(int).alias("month"))
  .join(cpc, on = ["year", "month"])
  .withColumns((col.temp - col.temp.rollingMean(121, center = true, minSamples = 61)).alias("wiggle"))
var lags: seq[Expr]
for k in 0 .. 6: lags.add corr(col.wiggle, col.mine.shift(k)).alias(&"{k} mo")
echo wiggles.select(lags)
shape: (1, 7)
┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐
│ 0 mo ┆ 1 mo ┆ 2 mo ┆ 3 mo ┆ 4 mo ┆ 5 mo ┆ 6 mo │
│ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
│ f64  ┆ f64  ┆ f64  ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
╞══════╪══════╪══════╪══════╪══════╪══════╪══════╡
│ 0.42 ┆ 0.46 ┆ 0.48 ┆ 0.48 ┆ 0.46 ┆ 0.43 ┆ 0.39 │
└──────┴──────┴──────┴──────┴──────┴──────┴──────┘

The match is best when the global temperature lags the Pacific by two to three months. So a record year should follow an El Niño. joinAsof with the default backward strategy pairs every record year since 1980 with the last El Niño that started before its middle (1 July), if one started in the two years before.

let recs = records.filter(col.year >= 1980).withColumns(date(col.year, 7, 1).alias("date"))
withConfig(tblRows = 20):
  echo recs.joinAsof(ninos.select("start_date", "start", "peak", "strength").sort("start_date"),
                     leftOn = "date", rightOn = "start_date", tolerance = 730.days)
    .drop(["date", "start_date"])
shape: (14, 5)
┌──────┬──────┬──────────┬──────┬─────────────┐
│ year ┆ temp ┆ start    ┆ peak ┆ strength    │
│ ---  ┆ ---  ┆ ---      ┆ ---  ┆ ---         │
│ i64  ┆ f64  ┆ str      ┆ f64  ┆ enum        │
╞══════╪══════╪══════════╪══════╪═════════════╡
│ 1980 ┆ 0.26 ┆ SON 1979 ┆ 0.60 ┆ weak        │
│ 1981 ┆ 0.32 ┆ SON 1979 ┆ 0.60 ┆ weak        │
│ 1988 ┆ 0.39 ┆ JAS 1986 ┆ 1.50 ┆ strong      │
│ 1990 ┆ 0.45 ┆ null     ┆ null ┆ null        │
│ 1997 ┆ 0.47 ┆ AMJ 1997 ┆ 2.40 ┆ very strong │
│ 1998 ┆ 0.61 ┆ AMJ 1997 ┆ 2.40 ┆ very strong │
│ 2002 ┆ 0.63 ┆ MJJ 2002 ┆ 1.20 ┆ moderate    │
│ 2005 ┆ 0.68 ┆ JAS 2004 ┆ 0.70 ┆ weak        │
│ 2010 ┆ 0.72 ┆ JJA 2009 ┆ 1.50 ┆ strong      │
│ 2014 ┆ 0.75 ┆ null     ┆ null ┆ null        │
│ 2015 ┆ 0.89 ┆ SON 2014 ┆ 2.60 ┆ very strong │
│ 2016 ┆ 1.01 ┆ SON 2014 ┆ 2.60 ┆ very strong │
│ 2023 ┆ 1.17 ┆ AMJ 2023 ┆ 2.00 ┆ very strong │
│ 2024 ┆ 1.28 ┆ AMJ 2023 ┆ 2.00 ┆ very strong │
└──────┴──────┴──────────┴──────┴─────────────┘

Twelve of the fourteen record years since 1980 came within two years of the start of an El Niño (1981 is a stretch: the weak 1979-80 event was already over). The other two, 1990 and 2014, came just before one began. Each of the last three very strong El Niños gave two record years in a row: 1997-98, 2015-16 and 2023-24. (The very strong 1982-83 event set no record: the eruption of El Chichón in Mexico in 1982 filled the stratosphere with sun-blocking haze and cooled the planet.)

13. Hottest year on record?↑ contents

Which brings us to now. A pivot of the last four years, one column per year, puts each month next to the same month of the years before.

let recent = world.filter(col.date.dt.year >= 2023)
  .withColumns(col.date.dt.year.cast(string).alias("year"), col.date.dt.month.alias("mon"))
  .pivot(on = "year", index = "mon", values = "temp")
echo recent.withColumns(maxHorizontal(all().exclude("mon")).alias("hottest"))
shape: (12, 6)
┌─────┬──────┬──────┬──────┬──────┬─────────┐
│ mon ┆ 2023 ┆ 2024 ┆ 2025 ┆ 2026 ┆ hottest │
│ --- ┆ ---  ┆ ---  ┆ ---  ┆ ---  ┆ ---     │
│ i8  ┆ f64  ┆ f64  ┆ f64  ┆ f64  ┆ f64     │
╞═════╪══════╪══════╪══════╪══════╪═════════╡
│ 1   ┆ 0.87 ┆ 1.25 ┆ 1.37 ┆ 1.08 ┆ 1.37    │
│ 2   ┆ 0.96 ┆ 1.43 ┆ 1.25 ┆ 1.23 ┆ 1.43    │
│ 3   ┆ 1.23 ┆ 1.39 ┆ 1.36 ┆ 1.30 ┆ 1.39    │
│ 4   ┆ 0.98 ┆ 1.32 ┆ 1.24 ┆ 1.16 ┆ 1.32    │
│ 5   ┆ 0.94 ┆ 1.16 ┆ 1.07 ┆ 1.13 ┆ 1.16    │
│ 6   ┆ 1.08 ┆ 1.23 ┆ 1.06 ┆ 1.17 ┆ 1.23    │
│ 7   ┆ 1.19 ┆ 1.20 ┆ 1.02 ┆ 1.24 ┆ 1.24    │
│ 8   ┆ 1.19 ┆ 1.30 ┆ 1.17 ┆ 1.42 ┆ 1.42    │
│ 9   ┆ 1.48 ┆ 1.21 ┆ 1.24 ┆ 1.38 ┆ 1.48    │
│ 10  ┆ 1.34 ┆ 1.34 ┆ 1.18 ┆ null ┆ 1.34    │
│ 11  ┆ 1.40 ┆ 1.29 ┆ 1.21 ┆ null ┆ 1.40    │
│ 12  ┆ 1.35 ┆ 1.26 ┆ 1.05 ┆ null ┆ 1.35    │
└─────┴──────┴──────┴──────┴──────┴─────────┘
show plots.recent(recent)
plotting code
proc recent*(table: DataFrame): PlotJson =
  var p = Plot[float](layout: layout("Month by month, 2023-2026", 380, legend = true))
  let series = [("2023", Aqua), ("2024", Blue), ("2025", Grey), ("2026", Warm)]
  for (c, color) in series:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.LinesMarkers, name: c,
                              xs: table.toList("mon", float),
                              ys: table.toList(c, Option[float]).mapIt(it.get(NaN)))
  result = p.finish(hovermode = "x unified")
  for i, (c, color) in series:
    result.traces[i]["y"] = %table.toList(c, Option[float]).mapIt(
      if it.isSome: %it.get else: newJNull())
    result.line(i, color, if c == "2026": 3.5 else: 2.0)
    result.traces[i]["marker"] = %*{"size": 6, "color": color}
    result.traces[i]["hovertemplate"] = %(c & ": %{y:.2f} °C<extra></extra>")
  result.layout["xaxis"]["tickvals"] = %toSeq(1 .. 12)
  result.layout["xaxis"]["ticktext"] = %"JFMAMJJASOND".mapIt($it)
  result.layout["yaxis"]["title"] = %*{"text": "°C vs 1951-1980"}

August 2026 was the warmest August on record and September the second warmest, just behind 2023, also an El Niño year. Yet January to September 2026 still averages a little below 2024, because the year started in La Niña.

echo world.filter(col.date.dt.month <= 9)
  .groupBy(col.date.dt.year.alias("year")).agg(col.temp.mean, col.temp.len.alias("months"))
  .topK(3, by = "temp")
shape: (3, 3)
┌──────┬──────┬────────┐
│ year ┆ temp ┆ months │
│ ---  ┆ ---  ┆ ---    │
│ i32  ┆ f64  ┆ u32    │
╞══════╪══════╪════════╡
│ 2024 ┆ 1.28 ┆ 9      │
│ 2026 ┆ 1.23 ┆ 9      │
│ 2025 ┆ 1.20 ┆ 9      │
└──────┴──────┴────────┘

If the past is a guide, with a two-to-three-month echo and a peak expected around the turn of the year, the full heat of this El Niño reaches the global average in the first half of 2027. Whether 2026 itself beats 2024 depends on the last three months. We will count again in January.

What this post used from Nanuq 0.4↑ contents

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

Sources: NOAA CPC (ONI, RONI, Niño indices, SOI, ENSO Diagnostic Discussion of 8 October 2026, RONI announcement); NASA GISS, GISTEMP v4; NOAA NCEI, GHCN-Daily station PEM00084401 (Piura) and ERSSTv5; NOAA Ocean Service, "What are El Niño and La Niña?"; K. Takahashi (2004), Annales Geophysicae 22, 3917.

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/el_nino/el_nino.py 599 lines
# %% [markdown]
# # Counting El Niños
#
# *Nanuq 0.4 explainer, Python draft (py-polars 2.1). Every cell below will become a Nim
# block in the dev log post, written against the 0.4 API; the outputs here are what the
# Nim version must print.*
#
# Every few years a patch of the Pacific Ocean, out in the middle of nowhere, warms up by
# a degree or two. That sounds like nothing. Yet it floods deserts in Peru, dries out
# rainforests in Indonesia, shifts storm tracks over North America, and nudges the
# temperature of the whole planet. The warming is called **El Niño**, and right now, in
# the autumn of 2026, one of the strongest on record is under way.
#
# This post counts El Niños the way the scientists do, starting from a single column of
# monthly sea temperatures, and follows them out into the rest of the world's weather.
# Nothing is assumed: if you have never heard of El Niño, this is the place to start.
# Along the way it shows off what is new in Nanuq 0.4: rolling windows and exponential
# smoothing, cumulative functions, shift and diff, top-k and binning, horizontal
# functions, pivot and unpivot, dynamic group-by, as-of joins and a real `Series`.
#
# Data, all public: NOAA's Climate Prediction Center (CPC) for the Niño indices and the
# Southern Oscillation Index, NASA GISS (GISTEMP v4) for global temperature, and NOAA's
# GHCN-Daily for the rain gauge at Piura airport, Peru. Downloaded on 1 November 2026.

# %%
# id: setup
import datetime as dt

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, float_precision=2);

# %% [markdown]
# ## 1. A box in the ocean
#
# Along the equator, the trade winds blow from east to west across the Pacific. They push
# the sun-warmed surface water towards Indonesia and Australia, where it piles up, and let
# cold water well up from the deep along the coast of South America. So the Pacific is
# normally warm in the west and cool in the east.
#
# Every two to seven years the trade winds weaken, the warm water sloshes back east, and
# the central and eastern Pacific heat up. Fishermen in Peru noticed this centuries ago,
# because it came around Christmas and emptied their nets. They called it *El Niño de
# Navidad*, the Christmas child.

# %%
# id: fig_walker
figs.walker_schematic()

# %% [markdown]
# Here is the same ocean seen from above: the mean sea surface temperature of
# 1991-2020. The warm pool sits in the west, the cold tongue stretches out from South
# America along the equator.

# %%
# id: fig_normal
figs.pacific_normal()

# %% [markdown]
# To keep watch, scientists average the sea surface temperature over a box on the equator
# called **Niño 3.4** (5°N to 5°S, 120°W to 170°W): about 1,100 by 5,500 km, six million
# square kilometres of open ocean with no land in it (the black box on the map). CPC
# publishes one number per month for that box, back to 1950. Here it is, read into a frame, and its temperature column taken out as a
# `Series`, Nanuq 0.4's new one-column type.

# %%
# id: s01_box
nino = pl.read_csv("data/nino34.csv").select("year", "month", "sst")
print(nino.tail(4))
sst = nino["sst"]
print(f"{sst.len()} months, from {sst.min():.2f} to {sst.max():.2f} °C")
print(nino[sst.arg_max()])

# %% [markdown]
# The warmest month in 76 years of records was September 2026, the latest month in the
# file. But a warm month is not yet an El Niño: the ocean has seasons too. The mean for
# each calendar month, with `topK` and `bottomK`, shows the box is warmest in spring and
# coolest in winter, more than a degree apart.

# %%
# id: s01_seasons
climate = nino.group_by("month").agg(pl.col("sst").mean())
print(pl.concat([climate.top_k(2, by="sst"), climate.bottom_k(2, by="sst")]))

# %% [markdown]
# ## 2. What is normal?
#
# Climate scientists rarely look at a temperature on its own. They look at the
# **anomaly**: how far a month is above or below normal for that time of year. "Normal"
# is the average of the same calendar month over a 30-year **base period**, today
# 1991-2020.
#
# In Nanuq that is one window expression: the mean of `sst` over the base years,
# computed separately for each month with `over`.

# %%
# id: s02_anomaly
base = pl.col("year").is_between(1991, 2020)
nino = nino.with_columns(
    normal=pl.col("sst").filter(base).mean().over("month"),
).with_columns(anomaly=pl.col("sst") - pl.col("normal"))
print(nino.filter(pl.col("month") == 9, pl.col("year").is_in([1982, 1997, 2015, 2023, 2026])))

# %% [markdown]
# September 2026 was 2.5 °C above a normal September: the ocean is running a fever.
#
# The same idea works for every point of the ocean. Here are three Septembers, each
# compared with a normal September: the two biggest El Niños of the satellite era, and
# this one.

# %%
# id: fig_three_septembers
figs.anomaly_maps(["1997-09", "2015-09", "2026-09"],
                  ["September 1997", "September 2015", "September 2026"])

# %% [markdown]
# CPC does one thing differently. It does not use a single base period for all 76 years
# but a sliding one, so that each year is compared with the 30 years around it. The file
# also carries CPC's own anomaly, and we will see in scene 7 why the difference matters.

# %% [markdown]
# ## 3. Three months make a season
#
# A single warm month can be a fluke of the weather. So the official **Oceanic Niño
# Index (ONI)** is a three-month running mean of the anomaly: the value for "DJF" is the
# mean of December, January and February, and so on through the twelve overlapping
# seasons of the year.
#
# CPC publishes the ONI as a wide table, one row per year and one column per season,
# rounded to one decimal. That shape is good for reading, bad for computing. `unpivot`
# turns it into one row per season, and `replaceStrict` maps each season to its middle
# month.

# %%
# id: s03_table
seasons = ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ", "JJA", "JAS", "ASO", "SON", "OND", "NDJ"]
oni_table = pl.read_csv("data/oni_table.csv")
print(oni_table.tail(3))
oni = (oni_table.unpivot(index="year", variable_name="season", value_name="oni")
       .drop_nulls("oni")
       .with_columns(month=pl.col("season").replace_strict(
           {s: m for m, s in enumerate(seasons, start=1)}, return_dtype=pl.Int64))
       .sort("year", "month"))
print(oni.tail(3))

# %% [markdown]
# Now we rebuild the index ourselves from CPC's monthly anomalies, with a centered
# `rollingMean` over three rows, and compare.

# %%
# id: s03_rebuild
cpc = pl.read_csv("data/nino34.csv").select(
    "year", "month", mine=pl.col("cpc_anomaly").rolling_mean(3, center=True))
check = oni.join(cpc, on=["year", "month"]).with_columns(diff=(pl.col("mine") - pl.col("oni")).abs())
print(check.select(seasons=pl.len(), max_diff=pl.col("diff").max(),
                   off_by_rounding=(pl.col("mine").round(1) != pl.col("oni")).sum()))

# %% [markdown]
# All 920 seasons agree to within 0.05 °C, which is the rounding of the table. Only 14
# land on the other side of a rounding tie (CPC averages the unrounded values). We have
# rebuilt NOAA's El Niño index in one line.

# %% [markdown]
# ## 4. Counting El Niños
#
# The rule for an El Niño **event** is simple: the ONI must be at **+0.5 °C or more for
# at least five overlapping seasons in a row**. Its cold mirror image, at -0.5 °C or less,
# is called **La Niña** (the girl). Anything in between is "neutral". Together they make
# the **El Niño-Southern Oscillation**, ENSO for short.
#
# Finding runs is a job for `rleId`: it gives every run of equal values its own number.
# Label each season with its phase, number the runs, and keep the runs at least five
# seasons long.

# %%
# id: s04_events
phase = (pl.when(pl.col("oni") >= 0.5).then(pl.lit("El Niño"))
         .when(pl.col("oni") <= -0.5).then(pl.lit("La Niña"))
         .otherwise(pl.lit("neutral")))
events = (oni.with_columns(phase=phase)
          .with_columns(run=pl.col("phase").rle_id())
          .group_by("run", maintain_order=True)
          .agg(pl.col("phase").first(),
               start=pl.format("{} {}", pl.col("season").first(), pl.col("year").first()),
               end=pl.format("{} {}", pl.col("season").last(), pl.col("year").last()),
               seasons=pl.len(),
               peak=pl.col("oni").max(), trough=pl.col("oni").min(),
               start_date=pl.date(pl.col("year").first(), pl.col("month").first(), 15))
          .filter(pl.col("phase") != "neutral", pl.col("seasons") >= 5)
          .drop("run"))
print(events["phase"].value_counts(sort=True))
print(events.tail(5).drop("start_date"))

# %% [markdown]
# 25 El Niños and 21 La Niñas since 1950. CPC colours its table red and blue with the
# same rule, and our runs match its colouring season by season, all 920 of them. One
# detail matters: the rule is applied to the rounded table. On CPC's two-decimal file,
# where a +0.46 does not reach +0.5, the same code finds only 22 El Niños.
#
# Look at the last row: the current El Niño began in MAM (March to May) 2026 and is
# still going, so it has no end yet. It already counts as an event: JAS is its fifth
# season.
#
# The whole record at a glance, red when the index is at +0.5 or more, blue at -0.5 or
# less.

# %%
# id: fig_oni_bars
figs.oni_bars(oni)

# %% [markdown]
# ## 5. How strong?
#
# Forecasters grade events by their peak: weak from +0.5, moderate from +1.0, strong
# from +1.5, very strong from +2.0. `cut` does the binning; `leftClosed` makes each band
# include its lower edge. Then `topK` picks the five biggest El Niños.

# %%
# id: s05_strength
ninos = (events.filter(pl.col("phase") == "El Niño")
         .with_columns(strength=pl.col("peak").cut(
             [1.0, 1.5, 2.0], labels=["weak", "moderate", "strong", "very strong"],
             left_closed=True)))
print(ninos["strength"].value_counts().sort("strength"))
print(ninos.top_k(5, by="peak").select("start", "end", "seasons", "peak", "strength"))

# %% [markdown]
# The famous ones are all there: 1982-83, 1997-98 and 2015-16 (which by this index
# started in late 2014), the three "super El Niños" of the satellite era, and 2023-24,
# which just makes the very strong band. The current event is already in third place at
# 2.2 and, according to CPC's October discussion, still strengthening.
#
# And here is what "very strong" looks like next to its opposite: December 1997, at the
# peak of the 1997-98 El Niño, and December 1988, at the peak of a strong La Niña, when
# the cold tongue reached far into the central Pacific.

# %%
# id: fig_nino_nina
figs.anomaly_maps(["1997-12", "1988-12"], ["El Niño, December 1997", "La Niña, December 1988"])

# %% [markdown]
# ## 6. 2026, the fast one
#
# How quickly did this one arrive? `diff` gives the change from one season to the next,
# and `shift(4)` lets us compare each season with four seasons earlier, about the time it
# takes an El Niño to grow.

# %%
# id: s06_rise
rise = oni.with_columns(
    step=pl.col("oni").diff(),
    rise4=pl.col("oni") - pl.col("oni").shift(4),
)
print(rise.filter(pl.col("year") == 2026).select("season", "oni", "step", "rise4"))
print(rise.top_k(5, by="rise4").select("year", "season", "oni", "rise4"))

# %% [markdown]
# From MAM to JAS 2026 the index climbed 1.7 °C, the fastest four-season rise since
# 1950, ahead of 1997. To line events up from their first season, `cumCount` over each
# run counts the seasons since onset, and `pivot` puts the big events side by side.

# %%
# id: s06_side_by_side
big = [1982, 1997, 2014, 2023, 2026]
runs = (oni.with_columns(phase=phase)
        .with_columns(run=pl.col("phase").rle_id())
        .with_columns(onset=pl.col("year").first().over("run"),
                      season_no=pl.col("oni").cum_count().over("run"))
        .filter(pl.col("phase") == "El Niño", pl.col("onset").is_in(big),
                pl.col("season_no") <= 8))
side = runs.pivot(on="onset", index="season_no", values="oni")
print(side)

# %% [markdown]
# Five seasons in, 2026 is ahead of every other event, 1997 included. (The 2014 column
# is the 2015-16 event, which began in late 2014 and then idled for months around +0.7
# before taking off.)

# %%
# id: fig_growth
figs.growth(side)

# %% [markdown]
# ## 7. A moving ruler
#
# Here is a problem. The whole tropical ocean is getting warmer. If "normal" stays fixed,
# a warming ocean looks more and more like El Niño, even when nothing special is going
# on. Our fixed 1991-2020 anomaly from scene 2 shows it: `groupByDynamic` with a
# ten-year window gives the mean anomaly of each decade.

# %%
# id: s07_drift
monthly = (pl.read_csv("data/nino34.csv")
           .with_columns(date=pl.date("year", "month", 1))
           .join(nino.select("year", "month", "anomaly"), on=["year", "month"]))
print(monthly.filter(pl.col("year") >= 1950).group_by_dynamic("date", every="10y").agg(
    fixed_base=pl.col("anomaly").mean(), sliding_base=pl.col("cpc_anomaly").mean()))

# %% [markdown]
# Against a fixed base, every decade before 1990 averages 0.2 to 0.5 °C below zero:
# the 1950s to 1980s look like a forty-year La Niña. CPC's sliding base keeps every decade
# near zero, but it is always computed from past years, so it lags behind a fast
# warming. So since February 2026 NOAA uses a new official index, the **Relative ONI
# (RONI)**: the Niño 3.4 anomaly minus the average anomaly of the whole tropics (20°N to
# 20°S), rescaled to the same spread. El Niño is now measured against the rest of the
# tropical ocean, not against the past.
#
# Same rules, new ruler: count the events again with RONI and match them to the ONI
# events with `joinAsof`, which pairs each ONI event with the RONI event that started
# nearest in time, if within six months.

# %%
# id: s07_roni
roni = (pl.read_csv("data/roni_table.csv")
        .unpivot(index="year", variable_name="season", value_name="oni")
        .drop_nulls("oni")
        .with_columns(month=pl.col("season").replace_strict(
            {s: m for m, s in enumerate(seasons, start=1)}, return_dtype=pl.Int64))
        .sort("year", "month"))
roni_events = (roni.with_columns(phase=phase)
               .with_columns(run=pl.col("phase").rle_id())
               .group_by("run", maintain_order=True)
               .agg(pl.col("phase").first(), seasons=pl.len(),
                    roni_start=pl.format("{} {}", pl.col("season").first(), pl.col("year").first()),
                    roni_peak=pl.col("oni").max(),
                    start_date=pl.date(pl.col("year").first(), pl.col("month").first(), 15))
               .filter(pl.col("phase") == "El Niño", pl.col("seasons") >= 5)
               .select("start_date", "roni_start", "roni_peak"))
print(f"ONI: {ninos.height} El Niños, RONI: {roni_events.height}")
paired = ninos.sort("start_date").join_asof(
    roni_events.sort("start_date"), on="start_date", strategy="nearest",
    tolerance=dt.timedelta(days=183), coalesce=False)
print(paired.filter(pl.col("start_date").dt.year() >= 2000)
      .select("start", "peak", "roni_start", "roni_peak"))
print(roni_events.top_k(3, by="roni_peak")
      .sort("roni_peak", "start_date", descending=[True, False]))

# %% [markdown]
# Both rulers count 25 El Niños since 1950, but not quite the same ones, and not equally
# strong. Since 2000 the two lists mostly agree, with three exceptions:
#
# - 2023-24 shrinks from 2.0 to 1.4. It peaked while the whole tropical ocean was
#   unusually hot, so relative to its surroundings it was a moderate event.
# - The weak 2019-20 warm spell is not an El Niño by RONI.
# - Neither is the current one, yet. By RONI it reached +0.5 only in AMJ, so JAS was its
#   fourth season. NOAA has nevertheless issued an El Niño Advisory: the five-season
#   rule is for the history books, while forecasters declare an event as soon as ocean
#   and atmosphere agree and are expected to stay that way.
#
# The RONI record holder is 1982-83 at +2.4. That is why CPC's October discussion speaks
# of a "historic event" if the 3-month RONI reaches +2.5 or more, which it gives a 54%
# chance for September-November and 83% for October-December.
#
# Side by side since 1995, the two rulers mostly agree on the ups and downs. They part
# ways where the whole tropics were warm: 2023 and now.

# %%
# id: fig_rulers
figs.two_rulers(oni, roni)

# %% [markdown]
# ## 8. The other half: air pressure
#
# El Niño is not only about water. In the 1920s the British scientist Gilbert Walker,
# looking for a way to forecast India's monsoon, found a seesaw in air pressure across
# the Pacific: when pressure is high in the east it is low in the west, and vice versa.
# He called it the **Southern Oscillation**. Today it is measured as the **Southern
# Oscillation Index (SOI)**: the pressure at Tahiti minus the pressure at Darwin,
# Australia, standardized. When the trade winds weaken, the SOI drops.
#
# In 1969 the Norwegian meteorologist Jacob Bjerknes showed that Walker's seesaw and the
# warm Pacific water were one coupled system: weaker trade winds let the ocean warm, and
# a warmer east Pacific weakens the trade winds further. `corr` shows how tightly the
# two move together, here on three-month means of both.

# %%
# id: s08_soi
soi = pl.read_csv("data/soi.csv").with_columns(soi3=pl.col("soi").rolling_mean(3, center=True))
both = soi.join(cpc, on=["year", "month"]).drop_nulls()
print(both.select(months=pl.len(), r=pl.corr("soi3", "mine")))
print(both.filter(pl.col("year") == 2026).tail(4))

# %% [markdown]
# A correlation of -0.84 over 75 years: when the sea warms, the pressure seesaw tips. In
# 2026 the SOI swung from positive (La Niña) in the winter to negative in April, and
# has stayed there as the ocean warmed.

# %%
# id: fig_soi
figs.soi_vs_oni(both)

# %% [markdown]
# ## 9. Four boxes and a coastal surprise
#
# Niño 3.4 is not the only box. CPC also tracks Niño 1+2, right off the coast of Peru and
# Ecuador, Niño 3 in the east and Niño 4 in the west. The horizontal functions compare
# columns within each row: `maxHorizontal` finds the hottest box, `meanHorizontal` the
# average of the four.

# %%
# id: s09_boxes
anoms = ["nino12_anom", "nino3_anom", "nino34_anom", "nino4_anom"]
boxes = pl.read_csv("data/nino_boxes.csv").select("year", "month", *anoms).with_columns(
    hottest=pl.max_horizontal(anoms), mean=pl.mean_horizontal(anoms),
)
print(boxes.tail(3))
coastal = boxes.filter(pl.col("nino12_anom") >= 1.0, pl.col("nino34_anom").abs() < 0.5)
print(coastal.group_by("year").agg(months=pl.len(), coast_max=pl.col("nino12_anom").max()).sort("year"))

# %% [markdown]
# In September 2026 the coastal box is 4.7 °C above normal, far ahead of the other
# three. The second table hunts for the opposite: months when the coast was at least a
# degree too warm while Niño 3.4 stayed neutral. Some are the tail of a big event (the
# coast stayed hot in mid-1983 after the centre cooled). Others, like early 2017 and
# early 2023, are "coastal El Niños" (*El Niño costero*): no event at all by NOAA's
# index, and floods in Peru all the same.
#
# Three of the boxes since 2014 show both stories: in 2017 only the coast warmed; in 2023
# and 2026 the coast warmed first and the centre followed.

# %%
# id: fig_box_lines
figs.box_lines(boxes)

# %% [markdown]
# On the map, March 2017 next to September 2026, with all four boxes drawn.

# %%
# id: fig_coastal_maps
figs.anomaly_maps(["2017-03", "2026-09"], ["Coastal El Niño, March 2017", "September 2026"],
                  boxes=("Niño 4", "Niño 3.4", "Niño 3", "Niño 1+2"))

# %% [markdown]
# ## 10. Rain in the desert
#
# What does that mean on the ground? Piura, in northern Peru, sits in a coastal desert:
# a typical year brings a few tens of millimetres of rain. Its airport's rain gauge has
# daily readings in NOAA's GHCN-Daily archive. `groupByDynamic` with a one-year window
# sums them per year, and counts the days that were actually reported, because a gauge
# that stopped reporting is not a dry year.

# %%
# id: s10_piura
rain = pl.read_csv("data/piura_rain.csv", try_parse_dates=True).sort("date")
years = rain.group_by_dynamic("date", every="1y").agg(
    rain_mm=pl.col("rain_mm").sum(), days=pl.len())
print(years.select(pl.col("rain_mm").filter(pl.col("days") >= 300).median().alias("median, complete years")))
print(years.top_k(4, by="rain_mm"))

# %%
# id: fig_piura
figs.piura(years)

# %% [markdown]
# In 1983 Piura got about 2,400 mm of rain, in 1998 about 1,700 mm, with two months of
# readings missing: more than fifty times a normal year, in a city that has no rain
# gutters. (A peer-reviewed tally for the city, Takahashi 2004, gives 2,147 mm for
# 1982-83 and 1,802 mm for 1997-98: the same picture.) Third is 2017, the coastal El
# Niño, with only 79 days on record. A 30-day `rollingSumBy` on the date column finds
# the wettest month.

# %%
# id: s10_wettest
print(rain.with_columns(mm_30d=pl.col("rain_mm").rolling_sum_by("date", window_size="30d"))
      .top_k(1, by="mm_30d"))

# %% [markdown]
# A thousand millimetres in the thirty days to 1 May 1983, 305 of them on that last day
# alone, as the station record has it: more than London gets in a whole typical year, in
# one month, in a desert.

# %% [markdown]
# ## 11. The world's temperature
#
# El Niño does not only move heat around, it lets the ocean give heat back to the air,
# and the whole planet warms for a while. To see it we need the global temperature.
# NASA's GISTEMP gives the global mean surface temperature anomaly for each month since
# 1880, against a 1951-1980 base (NASA's choice; the base only shifts the numbers, not
# their differences). The file is another wide table, with one column per month and
# `***` for months not yet measured.

# %%
# id: s11_world
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
gistemp = pl.read_csv("data/gistemp.csv", skip_rows=1, null_values="***")
world = (gistemp.select("Year", *months)
         .unpivot(index="Year", variable_name="mon", value_name="temp")
         .with_columns(date=pl.date(pl.col("Year"), pl.col("mon").replace_strict(
             {m: i for i, m in enumerate(months, start=1)}, return_dtype=pl.Int64), 1))
         .drop_nulls("temp").sort("date").select("date", "temp"))
yearly = gistemp.select(year="Year", temp="J-D").drop_nulls()
print(yearly.top_k(5, by="temp"))

# %% [markdown]
# Each new record year breaks the previous best. `cumMax` keeps the running best, so a
# record is a year equal to it (and higher than the year before the record).

# %%
# id: s11_records
records = yearly.filter(
    pl.col("temp") == pl.col("temp").cum_max(),
    pl.col("temp") > pl.col("temp").cum_max().shift(1),
)
print(records.filter(pl.col("year") >= 1980)["year"].to_list())

# %% [markdown]
# Month-to-month the global temperature is noisy. An exponentially weighted mean,
# `ewmMean`, smooths it by giving recent months more weight; with `span = 12` it acts
# like a one-year average that reacts faster than a plain 12-month rolling mean.

# %%
# id: s11_smooth
smooth = world.with_columns(
    rolling12=pl.col("temp").rolling_mean(12),
    ewm12=pl.col("temp").ewm_mean(span=12),
)
print(smooth.tail(6))

# %%
# id: fig_world
figs.world(yearly, smooth, records)

# %% [markdown]
# ## 12. El Niño's echo
#
# Does the planet warm *after* the Pacific does? Take the global temperature minus its
# own ten-year centered mean (to remove the long warming trend), and correlate it with
# the Niño 3.4 index shifted by 0 to 6 months.

# %%
# id: s12_lag
echo = (world.with_columns(year=pl.col("date").dt.year().cast(pl.Int64),
                           month=pl.col("date").dt.month().cast(pl.Int64))
        .join(cpc, on=["year", "month"])
        .with_columns(wiggle=pl.col("temp") - pl.col("temp").rolling_mean(121, center=True, min_samples=61)))
print(echo.select([pl.corr("wiggle", pl.col("mine").shift(k)).alias(f"{k} mo") for k in range(7)]))

# %% [markdown]
# The match is best when the global temperature lags the Pacific by two to three months.
# So a record year should follow an El Niño. `joinAsof` with the default backward
# strategy pairs every record year since 1980 with the last El Niño that started before
# its middle (1 July), if one started in the two years before.

# %%
# id: s12_records
recs = records.filter(pl.col("year") >= 1980).with_columns(date=pl.date("year", 7, 1))
with pl.Config(tbl_rows=20):
    print(recs.join_asof(ninos.select("start_date", "start", "peak", "strength").sort("start_date"),
                         left_on="date", right_on="start_date",
                         tolerance=dt.timedelta(days=730)).drop("date", "start_date"))

# %% [markdown]
# Twelve of the fourteen record years since 1980 came within two years of the start of
# an El Niño (1981 is a stretch: the weak 1979-80 event was already over). The other
# two, 1990 and 2014, came just before one began. Each of the last three very
# strong El Niños gave two record years in a row: 1997-98, 2015-16 and
# 2023-24. (The very strong 1982-83 event set no record: the eruption of El Chichón in
# Mexico in 1982 filled the stratosphere with sun-blocking haze and cooled the planet.)

# %% [markdown]
# ## 13. Hottest year on record?
#
# Which brings us to now. A pivot of the last four years, one column per year, puts each
# month next to the same month of the years before.

# %%
# id: s13_pivot
recent = (world.filter(pl.col("date").dt.year() >= 2023)
          .with_columns(year=pl.col("date").dt.year().cast(pl.String), mon=pl.col("date").dt.month())
          .pivot(on="year", index="mon", values="temp"))
print(recent.with_columns(hottest=pl.max_horizontal(pl.exclude("mon"))))

# %%
# id: fig_recent
figs.recent(recent)

# %% [markdown]
# August 2026 was the warmest August on record and September the second warmest, just
# behind 2023, also an El Niño year. Yet January to September 2026 still averages a
# little below 2024, because the year started in La Niña.

# %%
# id: s13_ytd
print(world.filter(pl.col("date").dt.month() <= 9)
      .group_by(year=pl.col("date").dt.year()).agg(pl.col("temp").mean(), months=pl.len())
      .top_k(3, by="temp"))

# %% [markdown]
# If the past is a guide, with a two-to-three-month echo and a peak expected around the
# turn of the year, the full heat of this El Niño reaches the global average in the first
# half of 2027. Whether 2026 itself beats 2024 depends on the last three months. We will
# count again in January.
#
# *Sources: NOAA CPC (ONI, RONI, Niño indices, SOI, ENSO Diagnostic Discussion of 8
# October 2026, RONI announcement); NASA GISS, GISTEMP v4; NOAA NCEI, GHCN-Daily station
# PEM00084401 (Piura); NOAA Ocean Service, "What are El Niño and La Niña?"; K. Takahashi
# (2004), Annales Geophysicae 22, 3917.*

docs/blog/el_nino/el_nino.py

docs/blog/el_nino/figs.py 312 lines
"""Plotly figures for the El Niño explainer. The post's cells compute frames with Polars and
pass them here, so the Nanuq code stays in the post. Only scatter, bar and heatmap traces,
shapes and annotations are used, so that the Nim version can redo each one with nim-plotly."""
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
import polars as pl

pio.renderers.default = "notebook"  # plotly.js inlined once: the page works offline

SURFACE = "#fcfcfb"
INK, INK2, MUTED, GRID = "#1f1f1e", "#5c5b57", "#8a8984", "#e6e5e1"
BLUE, ORANGE, AQUA, YELLOW = "#2a78d6", "#eb6834", "#1baf7a", "#eda100"
WARM, COOL, GREY = "#d1453f", "#2a78d6", "#c9c8c3"
LAND = "#d9d7d0"
CONFIG = dict(displaylogo=False, modeBarButtonsToRemove=["toImage"])  # no download button: artifact pages cannot download
DIVERGING = [[0, "#0d366b"], [0.2, "#256abf"], [0.38, "#86b6ef"], [0.5, "#f0efec"],
             [0.62, "#f2a3a0"], [0.8, "#d1453f"], [1, "#7f1d1d"]]
SEQUENTIAL = [[0, "#0d366b"], [0.25, "#3987e5"], [0.45, "#cde2fb"], [0.6, "#fbe3c4"],
              [0.75, "#f0a35e"], [0.9, "#d1453f"], [1, "#7f1d1d"]]
BOXES = {  # name: (lon west, lon east, lat south, lat north), lon in degrees east
    "Niño 4": (160, 210, -5, 5), "Niño 3.4": (190, 240, -5, 5),
    "Niño 3": (210, 270, -5, 5), "Niño 1+2": (270, 280, -10, 0),
}


SAVE_PATH = None  # expected.py sets this to keep each figure as JSON for the Nim post


def _show(fig):
    if SAVE_PATH:
        with open(SAVE_PATH, "w") as f:
            f.write(fig.to_json())
    else:
        fig.show(config=CONFIG)


def _layout(fig, title, height=380, source=None, **kw):
    fig.update_layout(
        title=dict(text=f"<b>{title}</b>", x=0.01, xanchor="left", font=dict(size=15, color=INK)),
        height=height, margin=dict(l=60, r=30, t=50, b=55 if source else 40),
        paper_bgcolor=SURFACE, plot_bgcolor=SURFACE,
        font=dict(family="Inter, system-ui, sans-serif", size=12, color=INK2),
        hoverlabel=dict(bgcolor="white", font_color=INK), **{"showlegend": False, **kw})
    fig.update_xaxes(gridcolor=GRID, zeroline=False, linecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, zeroline=False, linecolor=GRID)
    if source:
        fig.add_annotation(text=source, xref="paper", yref="paper", x=0, y=-0.17,
                           xanchor="left", showarrow=False, font=dict(size=10, color=MUTED))
    return fig


def _months(df):
    """Decimal year at mid-month, for monthly series on a continuous axis."""
    return (df["year"] + (df["month"] - 0.5) / 12).to_list()


# ---------------------------------------------------------------- maps

def _lon_label(t):
    return f"{t}°E" if t < 180 else ("180°" if t == 180 else f"{360 - t}°W")


def _map(fig, field, value, colorscale, zmin, zmax, row=None, col=None, colorbar=None,
         hover="%{z:.1f} °C", boxes=("Niño 3.4",)):
    """A heatmap of `value` on the lat/lon grid of `field` (one row per grid point)."""
    grid = field.pivot(on="lon", index="lat", values=value).sort("lat")
    lons = [float(c) for c in grid.columns[1:]]
    kw = dict(row=row, col=col) if row else {}
    fig.add_trace(go.Heatmap(
        x=lons, y=grid["lat"].to_list(), z=grid.drop("lat").rows(), colorscale=colorscale,
        zmin=zmin, zmax=zmax, zmid=0 if zmin < 0 else None, showscale=colorbar is not None,
        colorbar=colorbar, hovertemplate="%{x}°E, %{y}°<br>" + hover + "<extra></extra>"), **kw)
    ticks = [120, 150, 180, 210, 240, 270]
    fig.update_xaxes(range=[120, 290], tickvals=ticks, ticktext=[_lon_label(t) for t in ticks],
                     showgrid=False, constrain="domain", **kw)
    fig.update_yaxes(range=[-30, 30], tickvals=[-30, -15, 0, 15, 30],
                     ticktext=["30°S", "15°S", "0°", "15°N", "30°N"], showgrid=False, **kw)
    for b in boxes:
        w, e, s, n = BOXES[b]
        fig.add_shape(type="rect", x0=w, x1=e, y0=s, y1=n, line=dict(color=INK, width=1.5), **kw)
        fig.add_annotation(x=(w + e) / 2, y=n + 2.5 if b != "Niño 1+2" else s - 3, text=f"<b>{b}</b>",
                           showarrow=False, font=dict(size=10, color=INK), **kw)


def pacific_normal():
    """The Pacific in a normal year: 1991-2020 mean SST, with the Niño 3.4 box."""
    normal = pl.read_csv("data/pacific_normal.csv")
    fig = go.Figure()
    _map(fig, normal, "sst", SEQUENTIAL, 14, 30, colorbar=dict(title="°C", len=0.8))
    for x, y, t, c in [(145, 4, "warm pool", "white"), (255, -9, "cold tongue", INK)]:
        fig.add_annotation(x=x, y=y, text=f"<b>{t}</b>", showarrow=False, font=dict(color=c, size=13))
    fig.add_annotation(x=205, y=11, ax=258, ay=11, axref="x", ayref="y", text="", showarrow=True,
                       arrowhead=2, arrowwidth=2, arrowcolor=INK)
    fig.add_annotation(x=231, y=14, text="trade winds", showarrow=False, font=dict(color=INK))
    fig.update_yaxes(scaleanchor="x")
    _layout(fig, "The Pacific in a normal year: sea surface temperature, 1991-2020 mean",
            height=420, source="Data: NOAA ERSSTv5. Land in grey.")
    fig.update_layout(plot_bgcolor=LAND)
    _show(fig)


def anomaly_maps(months, titles, ncols=None, boxes=("Niño 3.4",), title=None):
    """Small multiples of SST anomaly maps on one shared diverging scale (±4 °C)."""
    from plotly.subplots import make_subplots
    anomaly = pl.read_csv("data/pacific_anomaly.csv")
    n = len(months); ncols = ncols or n; nrows = int(np.ceil(n / ncols))
    fig = make_subplots(rows=nrows, cols=ncols, subplot_titles=titles,
                        horizontal_spacing=0.05, vertical_spacing=0.14)
    for i, mo in enumerate(months):
        r, c = i // ncols + 1, i % ncols + 1
        _map(fig, anomaly.filter(pl.col("month") == mo), "anomaly", DIVERGING, -4, 4,
             row=r, col=c, boxes=boxes,
             hover="%{z:+.1f} °C vs normal",
             colorbar=dict(title="°C", len=0.7, tickvals=[-4, -2, 0, 2, 4]) if i == 0 else None)
    for a in fig.layout.annotations[:n]:
        a.update(x=a.x, font=dict(size=12, color=INK))
    _layout(fig, title or "Sea temperature compared with normal", height=230 * nrows + 130,
            source="Data: NOAA ERSSTv5. Red: warmer than the 1991-2020 normal for that month; blue: cooler.")
    fig.update_layout(plot_bgcolor=LAND)
    _show(fig)


def walker_schematic():
    """Cross-section along the equator, normal conditions vs El Niño, drawn with shapes."""
    from plotly.subplots import make_subplots
    fig = make_subplots(rows=1, cols=2, subplot_titles=["Normal conditions", "El Niño"],
                        horizontal_spacing=0.04)
    for col, nino in [(1, False), (2, True)]:
        k = dict(row=1, col=col)
        tw, te = (-2.6, -0.6) if not nino else (-1.7, -1.4)  # thermocline depth west, east
        poly = lambda pts, color: fig.add_shape(
            type="path", path="M " + " L ".join(f"{x},{y}" for x, y in pts) + " Z",
            fillcolor=color, line=dict(width=0), layer="below", **k)
        poly([(0.6, 0), (9.4, 0), (9.4, te), (0.6, tw)], "#f2a3a0")   # warm layer
        poly([(0.6, tw), (9.4, te), (9.4, -4), (0.6, -4)], "#9ec5f4")  # cold deep water
        poly([(0, -4), (0.6, -4), (0.6, 0.3), (0, 0.6)], LAND)
        poly([(9.4, -4), (10, -4), (10, 1.4), (9.4, 0.4)], LAND)
        fig.add_shape(type="line", x0=0.6, y0=tw, x1=9.4, y1=te, line=dict(color=INK2, dash="dash", width=1), **k)
        fig.add_annotation(x=5, y=(tw + te) / 2 - 0.5, text="thermocline", showarrow=False,
                           font=dict(size=10, color=INK2), **k)
        cx = 2.2 if not nino else 5.8  # where the air rises and rains
        fig.add_shape(type="circle", x0=cx - 1.2, x1=cx + 1.2, y0=2.3, y1=3.4, fillcolor=GREY,
                      line=dict(width=0), **k)
        for x in np.linspace(cx - 0.8, cx + 0.8, 5):
            fig.add_shape(type="line", x0=x, y0=2.2, x1=x - 0.15, y1=1.6, line=dict(color=COOL, width=1.5), **k)
        fig.add_annotation(x=cx, y=3.85, text="rain", showarrow=False, font=dict(size=11), **k)
        arrow = lambda x0, y0, x1, y1: fig.add_annotation(
            x=x1, y=y1, ax=x0, ay=y0, axref=f"x{col if col > 1 else ''}", ayref=f"y{col if col > 1 else ''}",
            text="", showarrow=True, arrowhead=2, arrowwidth=1.8, arrowcolor=INK, **k)
        if not nino:
            arrow(8.6, 0.6, 3.6, 0.6); arrow(3.4, 1.0, 3.4, 2.4); arrow(3.6, 4.2, 8.6, 4.2)
            arrow(8.9, 4.0, 8.9, 1.0); arrow(8.9, -2.8, 8.9, -0.9)
            fig.add_annotation(x=6, y=1.0, text="strong trade winds", showarrow=False, **k)
            fig.add_annotation(x=7.4, y=3.0, text="dry, sinking air", showarrow=False,
                               font=dict(size=10, color=INK2), **k)
            fig.add_annotation(x=7.4, y=-1.9, text="cold water wells up", showarrow=False,
                               font=dict(size=10, color="#0d366b"), **k)
        else:
            arrow(3.0, 0.6, 4.4, 0.6); arrow(8.6, 0.6, 7.2, 0.6)
            fig.add_annotation(x=5.8, y=-0.6, text="warm water spreads east", showarrow=False,
                               font=dict(size=10, color="#7f1d1d"), **k)
            fig.add_annotation(x=1.6, y=1.2, text="drought", showarrow=False, **k)
            fig.add_annotation(x=5.8, y=1.0, text="weak trade winds", showarrow=False, **k)
        fig.add_annotation(x=0.3, y=-4.5, text="Indonesia", showarrow=False, font=dict(size=10), **k)
        fig.add_annotation(x=9.5, y=-4.5, text="South America", showarrow=False, font=dict(size=10), **k)
    fig.update_xaxes(range=[0, 10], visible=False)
    fig.update_yaxes(range=[-4.8, 4.6], visible=False)
    _layout(fig, "What changes during El Niño (a slice along the equator)", height=360,
            source="Schematic, not to scale. After NOAA PMEL's El Niño diagrams.")
    _show(fig)


# ---------------------------------------------------------------- charts

def oni_bars(oni):
    """ONI as bars: red at or above +0.5, blue at or below -0.5, grey in between."""
    v = oni["oni"].to_list()
    colors = [WARM if x >= 0.5 else COOL if x <= -0.5 else GREY for x in v]
    fig = go.Figure(go.Bar(x=_months(oni), y=v, marker=dict(color=colors, line=dict(width=0)),
                           customdata=list(zip(oni["season"].to_list(), oni["year"].to_list())),
                           hovertemplate="%{customdata[0]} %{customdata[1]}: %{y:+.1f} °C<extra></extra>"))
    fig.update_layout(bargap=0)
    for y in (0.5, -0.5):
        fig.add_hline(y=y, line=dict(color=INK2, width=1, dash="dot"))
    for x, y, t in [(1983, 2.4, "1982-83"), (1998, 2.65, "1997-98"), (2016, 2.85, "2015-16"), (2026.6, 2.45, "2026")]:
        fig.add_annotation(x=x, y=y, text=t, showarrow=False, font=dict(size=11))
    fig.update_yaxes(title="ONI, °C", range=[-2.3, 3.1])
    fig.update_xaxes(range=[1949.5, 2027.5])
    _layout(fig, "Oceanic Niño Index 1950-2026: El Niño in red, La Niña in blue",
            source="Data: NOAA CPC. Dotted lines at ±0.5 °C.")
    _show(fig)


def growth(side):
    """Each event's ONI by season since onset; the last column is drawn on top, thicker."""
    cols = [c for c in side.columns if c != "season_no"]
    palette = [GREY, BLUE, AQUA, ORANGE, WARM]
    fig = go.Figure()
    for c, color in zip(cols, palette):
        name = "2015-16" if c == "2014" else c
        fig.add_trace(go.Scatter(x=side["season_no"].to_list(), y=side[c].to_list(), name=name,
                                 mode="lines+markers+text", line=dict(color=color, width=3.5 if c == cols[-1] else 2),
                                 marker=dict(size=7), text=[""] * 7 + [name] if c != cols[-1] else [""] * 4 + [name],
                                 textposition="middle right",
                                 hovertemplate=name + ", season %{x}: %{y:.1f} °C<extra></extra>"))
    fig.update_xaxes(title="season since the event began", range=[0.7, 9.0], dtick=1)
    fig.update_yaxes(title="ONI, °C")
    _layout(fig, "2026 is growing faster than any El Niño since 1950", height=400, showlegend=True,
            legend=dict(orientation="h", y=1.08, x=0))
    _show(fig)


def two_rulers(oni, roni, since=1995):
    fig = go.Figure()
    for df, color, name in [(oni, GREY, "ONI (official until January 2026)"),
                            (roni, WARM, "RONI (official since February 2026)")]:
        d = df.filter(pl.col("year") >= since)
        fig.add_trace(go.Scatter(x=_months(d), y=d["oni"].to_list(), name=name, mode="lines",
                                 line=dict(color=color, width=2),
                                 customdata=list(zip(d["season"].to_list(), d["year"].to_list())),
                                 hovertemplate=name.split(" ")[0] + " %{customdata[0]} %{customdata[1]}: %{y:+.1f}<extra></extra>"))
    fig.add_hline(y=0.5, line=dict(color=INK2, width=1, dash="dot"))
    fig.update_yaxes(title="°C"); fig.update_xaxes(range=[since, 2027])
    _layout(fig, "Two rulers for the same ocean", height=360, showlegend=True,
            legend=dict(orientation="h", y=1.1, x=0), hovermode="x unified")
    _show(fig)


def soi_vs_oni(both, since=1980):
    """Two stacked panels, one per measure (never a second y-axis)."""
    from plotly.subplots import make_subplots
    d = both.filter(pl.col("year") >= since)
    t = _months(d)
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.12,
                        subplot_titles=["Sea: Niño 3.4 anomaly, °C (3-month mean)",
                                        "Air: Southern Oscillation Index (3-month mean), its mirror image"])
    for r, ycol, warm_if_pos in [(1, "mine", True), (2, "soi3", False)]:
        v = d[ycol].to_list()
        colors = [WARM if (x >= 0) == warm_if_pos else COOL for x in v]
        fig.add_trace(go.Bar(x=t, y=v, marker=dict(color=colors, line=dict(width=0)),
                             hovertemplate="%{x:.1f}: %{y:+.2f}<extra></extra>"), row=r, col=1)
    fig.update_layout(bargap=0)
    for a in fig.layout.annotations:
        a.update(x=0, xanchor="left", font=dict(size=12, color=INK))
    _layout(fig, "Ocean and atmosphere move together", height=440,
            source="Data: NOAA CPC. Red marks the El Niño side of each index.")
    fig.update_xaxes(range=[since, 2027])
    _show(fig)


def box_lines(boxes, since=2014):
    d = boxes.filter(pl.col("year") >= since)
    fig = go.Figure()
    for c, color, name in [("nino12_anom", ORANGE, "Niño 1+2 (coast of Peru)"),
                           ("nino34_anom", WARM, "Niño 3.4 (central Pacific)"),
                           ("nino4_anom", BLUE, "Niño 4 (west)")]:
        fig.add_trace(go.Scatter(x=_months(d), y=d[c].to_list(), name=name, mode="lines",
                                 line=dict(color=color, width=2),
                                 hovertemplate=name.split(" (")[0] + ": %{y:+.2f} °C<extra></extra>"))
    for x, t in [(2017.2, "2017: coast only"), (2023.2, "2023: coast first")]:
        fig.add_annotation(x=x, y=2.9, text=t, showarrow=False, font=dict(size=11))
    fig.update_yaxes(title="°C vs normal"); fig.update_xaxes(range=[since, 2027])
    _layout(fig, "Three of the four boxes, 2014-2026", height=380, showlegend=True,
            legend=dict(orientation="h", y=1.1, x=0), hovermode="x unified",
            source="Data: NOAA CPC (OISST v2.1).")
    _show(fig)


def piura(years):
    d = years.with_columns(y=pl.col("date").dt.year())
    full = d["days"] >= 300
    fig = go.Figure(go.Bar(x=d["y"].to_list(), y=d["rain_mm"].to_list(),
                           marker=dict(color=[BLUE if f else "#b7d3f6" for f in full.to_list()]),
                           customdata=d["days"].to_list(),
                           hovertemplate="%{x}: %{y:,.0f} mm (%{customdata} days reported)<extra></extra>"))
    for yr in (1983, 1998, 2017):
        v = d.filter(pl.col("y") == yr)["rain_mm"].item()
        fig.add_annotation(x=yr, y=v, text=str(yr), showarrow=False, yshift=12)
    fig.update_yaxes(title="rain per year, mm")
    _layout(fig, "Piura, Peru: rain in a desert city", height=360,
            source="Data: NOAA GHCN-Daily, Piura airport. Light bars: fewer than 300 days reported that year.")
    _show(fig)


def world(yearly, smooth, records):
    s = smooth.with_columns(year=pl.col("date").dt.year(), month=pl.col("date").dt.month())
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=_months(s), y=s["ewm12"].to_list(), name="monthly, smoothed (ewmMean, span 12)",
                             mode="lines", line=dict(color="#9ec5f4", width=1.2), hovertemplate="%{y:.2f} °C<extra></extra>"))
    fig.add_trace(go.Scatter(x=(yearly["year"] + 0.5).to_list(), y=yearly["temp"].to_list(), name="yearly mean",
                             mode="lines", line=dict(color=BLUE, width=2), hovertemplate="%{x:.0f}: %{y:.2f} °C<extra></extra>"))
    fig.add_trace(go.Scatter(x=(records["year"] + 0.5).to_list(), y=records["temp"].to_list(), name="record year",
                             mode="markers", marker=dict(color=WARM, size=8, line=dict(color=SURFACE, width=2)),
                             hovertemplate="record %{x:.0f}: %{y:.2f} °C<extra></extra>"))
    fig.update_yaxes(title="°C vs 1951-1980"); fig.update_xaxes(range=[1880, 2027])
    _layout(fig, "The world's temperature, 1880-2026", height=400, showlegend=True,
            legend=dict(orientation="h", y=1.1, x=0), source="Data: NASA GISS, GISTEMP v4.")
    _show(fig)


def recent(table):
    fig = go.Figure()
    for c, color in zip(["2023", "2024", "2025", "2026"], [AQUA, BLUE, GREY, WARM]):
        fig.add_trace(go.Scatter(x=table["mon"].to_list(), y=table[c].to_list(), name=c,
                                 mode="lines+markers", line=dict(color=color, width=3.5 if c == "2026" else 2),
                                 marker=dict(size=6), hovertemplate=c + ": %{y:.2f} °C<extra></extra>"))
    fig.update_xaxes(tickvals=list(range(1, 13)), ticktext=list("JFMAMJJASOND"))
    fig.update_yaxes(title="°C vs 1951-1980")
    _layout(fig, "Month by month, 2023-2026", height=380, showlegend=True,
            legend=dict(orientation="h", y=1.1, x=0), hovermode="x unified")
    _show(fig)

docs/blog/el_nino/figs.py

docs/blog/el_nino/plots.nim 404 lines
## Plotly figures for "Counting El Niños", with nim-plotly. The twin of figs.py: same
## traces, colours and layout. nim-plotly builds the traces (data, type, mode, name,
## marker) and the basic layout (title, size, axes, colours, legend); what it has no
## field for (hover templates, shapes, styled annotations, colour scales, subplots
## domains, nulls in a heatmap) is added to the JSON it produces.
import std/[json, sequtils, strutils, math, options]
import plotly except Color
import chroma
import nanuq

const
  Surface* = "#fcfcfb"
  Ink = "#1f1f1e"
  Ink2 = "#5c5b57"
  Muted = "#8a8984"
  Grid = "#e6e5e1"
  Blue = "#2a78d6"
  Orange = "#eb6834"
  Aqua = "#1baf7a"
  Warm = "#d1453f"
  Cool = "#2a78d6"
  Grey = "#c9c8c3"
  Land = "#d9d7d0"
  Diverging = [(0.0, "#0d366b"), (0.2, "#256abf"), (0.38, "#86b6ef"), (0.5, "#f0efec"),
               (0.62, "#f2a3a0"), (0.8, "#d1453f"), (1.0, "#7f1d1d")]
  Sequential = [(0.0, "#0d366b"), (0.25, "#3987e5"), (0.45, "#cde2fb"), (0.6, "#fbe3c4"),
                (0.75, "#f0a35e"), (0.9, "#d1453f"), (1.0, "#7f1d1d")]
  Boxes = [("Niño 4", 160.0, 210.0, -5.0, 5.0), ("Niño 3.4", 190.0, 240.0, -5.0, 5.0),
           ("Niño 3", 210.0, 270.0, -5.0, 5.0), ("Niño 1+2", 270.0, 280.0, -10.0, 0.0)]

proc hex(s: string): chroma.Color = parseHex(s[1 .. ^1])

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

proc layout(title: string, height: int, source = "", legend = false): Layout =
  result = Layout(title: "<b>" & title & "</b>", height: height, autosize: true,
                  backgroundColor: hex(Surface), paperColor: hex(Surface),
                  font: Font(family: "Inter, system-ui, sans-serif", size: 12, color: hex(Ink2)),
                  xaxis: Axis(gridColor: hex(Grid)), yaxis: Axis(gridColor: hex(Grid)))
  if legend:
    result.showlegend = true
    result.legend = Legend(orientation: Orientation.Horizontal, x: 0.0, y: 1.1)

proc finish(p: Plot[float], source = "", hovermode = "closest"): PlotJson =
  ## The JSON nim-plotly makes, plus the common style it has no field for.
  result = p.toPlotJson
  let l = result.layout
  l["title"] = %*{"text": l["title"].getStr, "x": 0.01, "xanchor": "left",
                  "font": {"size": 15, "color": Ink}}
  l["margin"] = %*{"l": 60, "r": 30, "t": 50, "b": (if source.len > 0: 55 else: 40)}
  l["hoverlabel"] = %*{"bgcolor": "white", "font": {"color": Ink}}
  l["hovermode"] = %hovermode
  if not l.hasKey("showlegend"): l["showlegend"] = %false
  for ax in ["xaxis", "yaxis"]:
    if not l.hasKey(ax): l[ax] = newJObject()
    l[ax]["zeroline"] = %false
    l[ax]["linecolor"] = %Grid
    # nim-plotly writes autorange: true when no range is given, which would win over a
    # range set later on the JSON; plotly.js autoranges by default anyway
    l[ax].delete("autorange")
  if source.len > 0:
    if not l.hasKey("annotations"): l["annotations"] = newJArray()
    l["annotations"].add %*{"text": source, "xref": "paper", "yref": "paper", "x": 0,
                            "y": -0.17, "xanchor": "left", "showarrow": false,
                            "font": {"size": 10, "color": Muted}}

proc note(pj: PlotJson, x, y: float, text: string, size = 12, color = Ink2,
          axes = ("x", "y"), extra = newJObject()) =
  if not pj.layout.hasKey("annotations"): pj.layout["annotations"] = newJArray()
  var a = %*{"x": x, "y": y, "text": text, "showarrow": false, "xref": axes[0], "yref": axes[1],
             "font": {"size": size, "color": color}}
  for k, v in extra: a[k] = v
  pj.layout["annotations"].add a

proc shape(pj: PlotJson, s: JsonNode) =
  if not pj.layout.hasKey("shapes"): pj.layout["shapes"] = newJArray()
  pj.layout["shapes"].add s

proc decimalYear(df: DataFrame): seq[float] =
  ## Mid-month as a decimal year, for monthly series on a continuous axis.
  df.select((col.year + (col.month - 0.5) / 12).alias("t")).toList("t", float)

proc line(pj: PlotJson, i: int, color: string, width = 2.0) =
  pj.traces[i]["line"] = %*{"color": color, "width": width}

# ---------------------------------------------------------------- maps

proc lonLabel(t: int): string =
  if t < 180: $t & "°E" elif t == 180: "180°" else: $(360 - t) & "°W"

proc heatmap(field: DataFrame, value: string, xaxis = "x", yaxis = "y"): (Trace[float], JsonNode) =
  ## A heatmap trace of `value` on the lat/lon grid of `field` (one row per grid point).
  ## nim-plotly's `zs` holds no nulls (land), so `z` is returned as JSON.
  let grid = field.pivot(on = "lon", index = "lat", values = value).sort("lat")
  let lons = grid.columns[1 .. ^1].mapIt(parseFloat(it))
  var z = newJArray()
  for r in 0 ..< grid.height:
    var row = newJArray()
    for c in grid.columns[1 .. ^1]:
      let v = grid[c, r, Option[float]]
      row.add(if v.isSome: %v.get else: newJNull())
    z.add row
  (Trace[float](`type`: PlotType.HeatMap, xs: lons, ys: grid.toList("lat", float),
                xaxis: xaxis, yaxis: yaxis), z)

proc mapAxes(pj: PlotJson, n = 1) =
  let ticks = [120, 150, 180, 210, 240, 270]
  for i in 1 .. n:
    let sx = if i == 1: "" else: $i
    pj.layout["xaxis" & sx] = %*{"range": [120, 290], "tickvals": ticks,
                                 "ticktext": ticks.mapIt(lonLabel(it)), "showgrid": false,
                                 "constrain": "domain", "anchor": "y" & sx}
    pj.layout["yaxis" & sx] = %*{"range": [-30, 30], "tickvals": [-30, -15, 0, 15, 30],
                                 "ticktext": ["30°S", "15°S", "0°", "15°N", "30°N"],
                                 "showgrid": false, "anchor": "x" & sx,
                                 "showticklabels": i == 1}
    for ax in ["xaxis" & sx, "yaxis" & sx]:
      pj.layout[ax]["zeroline"] = %false
      pj.layout[ax]["linecolor"] = %Grid
  pj.layout["plot_bgcolor"] = %Land

proc drawBoxes(pj: PlotJson, names: openArray[string], axes = ("x", "y")) =
  for (name, w, e, s, n) in Boxes:
    if name notin names: continue
    pj.shape %*{"type": "rect", "x0": w, "x1": e, "y0": s, "y1": n, "xref": axes[0],
                "yref": axes[1], "line": {"color": Ink, "width": 1.5}}
    pj.note((w + e) / 2, (if name == "Niño 1+2": s - 3 else: n + 2.5), "<b>" & name & "</b>",
            size = 10, color = Ink, axes = axes)

proc pacificNormal*(): PlotJson =
  ## The Pacific in a normal year: 1991-2020 mean SST, with the Niño 3.4 box.
  let (tr, z) = heatmap(readCsv("data/pacific_normal.csv"), "sst")
  let p = Plot[float](traces: @[tr], layout: layout(
    "The Pacific in a normal year: sea surface temperature, 1991-2020 mean", 420))
  result = p.finish(source = "Data: NOAA ERSSTv5. Land in grey.")
  result.traces[0]["z"] = z
  result.traces[0]["colorscale"] = scale(Sequential)
  result.traces[0]["zmin"] = %14; result.traces[0]["zmax"] = %30
  result.traces[0]["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.8, "outlinewidth": 0}
  result.traces[0]["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:.1f} °C<extra></extra>"
  result.mapAxes
  result.layout["yaxis"]["scaleanchor"] = %"x"
  result.drawBoxes(["Niño 3.4"])
  result.note(145, 4, "<b>warm pool</b>", 13, "white")
  result.note(255, -9, "<b>cold tongue</b>", 13, Ink)
  result.note(205, 11, "", extra = %*{"ax": 258, "ay": 11, "axref": "x", "ayref": "y",
                                      "showarrow": true, "arrowhead": 2, "arrowwidth": 2,
                                      "arrowcolor": Ink})
  result.note(231, 14, "trade winds", color = Ink)

proc anomalyMaps*(months, titles: openArray[string],
                  boxes: openArray[string] = ["Niño 3.4"], title = ""): PlotJson =
  ## Small multiples of SST anomaly maps on one shared diverging scale (±4 °C), in one row.
  let anomaly = readCsv("data/pacific_anomaly.csv")
  let n = months.len
  var p = Plot[float](layout: layout(
    (if title.len > 0: title else: "Sea temperature compared with normal"), 360))
  var zs: seq[JsonNode]
  for i, mo in months:
    let sx = if i == 0: "" else: $(i + 1)
    let (tr, z) = heatmap(anomaly.filter(col.month == mo), "anomaly", "x" & sx, "y" & sx)
    p.traces.add tr; zs.add z
  result = p.finish(source = "Data: NOAA ERSSTv5. Red: warmer than the 1991-2020 normal " &
                             "for that month; blue: cooler.")
  result.mapAxes(n)
  let gap = 0.05
  let w = (1.0 - gap * float(n - 1)) / float(n)
  for i in 0 ..< n:
    let sx = if i == 0: "" else: $(i + 1)
    let t = result.traces[i]
    t["z"] = zs[i]; t["colorscale"] = scale(Diverging)
    t["zmin"] = %(-4); t["zmax"] = %4; t["zmid"] = %0
    t["showscale"] = %(i == 0)
    if i == 0: t["colorbar"] = %*{"title": {"text": "°C"}, "len": 0.7, "tickvals": [-4, -2, 0, 2, 4], "outlinewidth": 0}
    t["hovertemplate"] = %"%{x}°E, %{y}°<br>%{z:+.1f} °C vs normal<extra></extra>"
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & sx]["domain"] = %*[x0, x0 + w]
    result.note(x0 + w / 2, 1.0, titles[i], 12, Ink, ("paper", "paper"),
                %*{"yanchor": "bottom", "xanchor": "center"})
    result.drawBoxes(boxes, ("x" & sx, "y" & sx))

proc walkerSchematic*(): PlotJson =
  ## Cross-section along the equator, normal conditions vs El Niño, drawn with shapes.
  var p = Plot[float](layout: layout("What changes during El Niño (a slice along the equator)", 360))
  result = p.finish(source = "Schematic, not to scale. After NOAA PMEL's El Niño diagrams.")
  for (sx, title) in [("", "Normal conditions"), ("2", "El Niño")]:
    let nino = sx == "2"
    let (xa, ya) = ("x" & sx, "y" & sx)
    result.layout["xaxis" & sx] = %*{"range": [0, 10], "visible": false,
                                     "domain": (if nino: [0.52, 1.0] else: [0.0, 0.48]), "anchor": ya}
    result.layout["yaxis" & sx] = %*{"range": [-4.8, 4.6], "visible": false, "anchor": xa}
    result.note((if nino: 0.76 else: 0.24), 1.0, title, 14, Ink2, ("paper", "paper"),
                %*{"yanchor": "bottom"})
    let (tw, te) = if nino: (-1.7, -1.4) else: (-2.6, -0.6)  # thermocline depth, west and east
    proc poly(pj: PlotJson, pts: openArray[(float, float)], color: string) =
      pj.shape %*{"type": "path", "xref": xa, "yref": ya, "fillcolor": color, "layer": "below",
                  "line": {"width": 0},
                  "path": "M " & pts.mapIt($it[0] & "," & $it[1]).join(" L ") & " Z"}
    result.poly([(0.6, 0.0), (9.4, 0.0), (9.4, te), (0.6, tw)], "#f2a3a0")    # warm layer
    result.poly([(0.6, tw), (9.4, te), (9.4, -4.0), (0.6, -4.0)], "#9ec5f4")  # cold deep water
    result.poly([(0.0, -4.0), (0.6, -4.0), (0.6, 0.3), (0.0, 0.6)], Land)
    result.poly([(9.4, -4.0), (10.0, -4.0), (10.0, 1.4), (9.4, 0.4)], Land)
    result.shape %*{"type": "line", "xref": xa, "yref": ya, "x0": 0.6, "y0": tw, "x1": 9.4,
                    "y1": te, "line": {"color": Ink2, "dash": "dash", "width": 1}}
    result.note(5, (tw + te) / 2 - 0.5, "thermocline", 10, Ink2, (xa, ya))
    let cx = if nino: 5.8 else: 2.2  # where the air rises and rains
    result.shape %*{"type": "circle", "xref": xa, "yref": ya, "x0": cx - 1.2, "x1": cx + 1.2,
                    "y0": 2.3, "y1": 3.4, "fillcolor": Grey, "line": {"width": 0}}
    for k in 0 .. 4:
      let x = cx - 0.8 + 0.4 * float(k)
      result.shape %*{"type": "line", "xref": xa, "yref": ya, "x0": x, "y0": 2.2,
                      "x1": x - 0.15, "y1": 1.6, "line": {"color": Cool, "width": 1.5}}
    result.note(cx, 3.85, "rain", 11, Ink2, (xa, ya))
    proc arrow(pj: PlotJson, x0, y0, x1, y1: float) =
      pj.note(x1, y1, "", axes = (xa, ya), extra = %*{"ax": x0, "ay": y0, "axref": xa,
              "ayref": ya, "showarrow": true, "arrowhead": 2, "arrowwidth": 1.8, "arrowcolor": Ink})
    if not nino:
      result.arrow(8.6, 0.6, 3.6, 0.6); result.arrow(3.4, 1.0, 3.4, 2.4)
      result.arrow(3.6, 4.2, 8.6, 4.2); result.arrow(8.9, 4.0, 8.9, 1.0)
      result.arrow(8.9, -2.8, 8.9, -0.9)
      result.note(6, 1.0, "strong trade winds", axes = (xa, ya))
      result.note(7.4, 3.0, "dry, sinking air", 10, Ink2, (xa, ya))
      result.note(7.4, -1.9, "cold water wells up", 10, "#0d366b", (xa, ya))
    else:
      result.arrow(3.0, 0.6, 4.4, 0.6); result.arrow(8.6, 0.6, 7.2, 0.6)
      result.note(5.8, -0.6, "warm water spreads east", 10, "#7f1d1d", (xa, ya))
      result.note(1.6, 1.2, "drought", axes = (xa, ya))
      result.note(5.8, 1.0, "weak trade winds", axes = (xa, ya))
    result.note(0.3, -4.5, "Indonesia", 10, Ink2, (xa, ya))
    result.note(9.5, -4.5, "South America", 10, Ink2, (xa, ya))

# ---------------------------------------------------------------- charts

proc oniBars*(oni: DataFrame): PlotJson =
  ## ONI as bars: red at or above +0.5, blue at or below -0.5, grey in between.
  let v = oni.toList("oni", float)
  let colors = v.mapIt(hex(if it >= 0.5: Warm elif it <= -0.5: Cool else: Grey))
  let tr = Trace[float](`type`: PlotType.Bar, xs: oni.decimalYear, ys: v,
                        marker: Marker[float](color: colors))
  let p = Plot[float](traces: @[tr], layout: layout(
    "Oceanic Niño Index 1950-2026: El Niño in red, La Niña in blue", 380))
  result = p.finish(source = "Data: NOAA CPC. Dotted lines at ±0.5 °C.")
  result.traces[0]["marker"]["line"] = %*{"width": 0}
  result.traces[0]["customdata"] = %zip(oni.toList("season", string), oni.toList("year", int)).mapIt(%*[it[0], it[1]])
  result.traces[0]["hovertemplate"] = %"%{customdata[0]} %{customdata[1]}: %{y:+.1f} °C<extra></extra>"
  result.layout["bargap"] = %0
  for y in [0.5, -0.5]:
    result.shape %*{"type": "line", "xref": "paper", "x0": 0, "x1": 1, "y0": y, "y1": y,
                    "line": {"color": Ink2, "width": 1, "dash": "dot"}}
  for (x, y, t) in [(1983.0, 2.4, "1982-83"), (1998.0, 2.65, "1997-98"),
                    (2016.0, 2.85, "2015-16"), (2026.6, 2.45, "2026")]:
    result.note(x, y, t, 11)
  result.layout["yaxis"]["title"] = %*{"text": "ONI, °C"}
  result.layout["yaxis"]["range"] = %*[-2.3, 3.1]
  result.layout["xaxis"]["range"] = %*[1949.5, 2027.5]

proc growth*(side: DataFrame): PlotJson =
  ## Each event's ONI by season since onset; the last column drawn on top, thicker.
  let cols = side.columns[1 .. ^1]
  let palette = [Grey, Blue, Aqua, Orange, Warm]
  var p = Plot[float](layout: layout("2026 is growing faster than any El Niño since 1950",
                                     400, legend = true))
  for i, c in cols:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.LinesMarkers,
                              name: (if c == "2014": "2015-16" else: c),
                              xs: side.toList("season_no", float),
                              ys: side.toList(c, Option[float]).mapIt(it.get(NaN)))
  result = p.finish
  for i, c in cols:
    let t = result.traces[i]
    let name = t["name"].getStr
    let ys = side.toList(c, Option[float])
    t["y"] = %ys.mapIt(if it.isSome: %it.get else: newJNull())
    result.line(i, palette[i], if i == cols.high: 3.5 else: 2.0)
    t["marker"] = %*{"size": 7, "color": palette[i]}
    t["mode"] = %"lines+markers+text"
    var text = newSeq[string](ys.len)
    text[ys.filterIt(it.isSome).len - 1] = name
    t["text"] = %text
    t["textposition"] = %"middle right"
    t["hovertemplate"] = %(name & ", season %{x}: %{y:.1f} °C<extra></extra>")
  result.layout["xaxis"]["title"] = %*{"text": "season since the event began"}
  result.layout["xaxis"]["range"] = %*[0.7, 9.0]
  result.layout["xaxis"]["dtick"] = %1
  result.layout["yaxis"]["title"] = %*{"text": "ONI, °C"}

proc twoRulers*(oni, roni: DataFrame, since = 1995): PlotJson =
  var p = Plot[float](layout: layout("Two rulers for the same ocean", 360, legend = true))
  let series = [(oni, Grey, "ONI (official until January 2026)"),
                (roni, Warm, "RONI (official since February 2026)")]
  for (df, color, name) in series:
    let d = df.filter(col.year >= since)
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: name,
                              xs: d.decimalYear, ys: d.toList("oni", float))
  result = p.finish(hovermode = "x unified")
  for i, (df, color, name) in series:
    let d = df.filter(col.year >= since)
    result.line(i, color)
    result.traces[i]["customdata"] = %zip(d.toList("season", string), d.toList("year", int)).mapIt(%*[it[0], it[1]])
    result.traces[i]["hovertemplate"] = %(name.split(" ")[0] &
      " %{customdata[0]} %{customdata[1]}: %{y:+.1f}<extra></extra>")
  result.shape %*{"type": "line", "xref": "paper", "x0": 0, "x1": 1, "y0": 0.5, "y1": 0.5,
                  "line": {"color": Ink2, "width": 1, "dash": "dot"}}
  result.layout["yaxis"]["title"] = %*{"text": "°C"}
  result.layout["xaxis"]["range"] = %*[since, 2027]

proc soiVsOni*(both: DataFrame, since = 1980): PlotJson =
  ## Two stacked panels, one per measure (never a second y-axis).
  let d = both.filter(col.year >= since)
  let t = d.decimalYear
  var p = Plot[float](layout: layout("Ocean and atmosphere move together", 440))
  for (c, warmIfPos, ya) in [("mine", true, "y"), ("soi3", false, "y2")]:
    let v = d.toList(c, float)
    p.traces.add Trace[float](`type`: PlotType.Bar, xs: t, ys: v, yaxis: ya,
      marker: Marker[float](color: v.mapIt(hex(if (it >= 0) == warmIfPos: Warm else: Cool))))
  result = p.finish(source = "Data: NOAA CPC. Red marks the El Niño side of each index.")
  for tr in result.traces:
    tr["marker"]["line"] = %*{"width": 0}
    tr["hovertemplate"] = %"%{x:.1f}: %{y:+.2f}<extra></extra>"
  result.layout["bargap"] = %0
  result.layout["xaxis"]["range"] = %*[since, 2027]
  result.layout["xaxis"]["anchor"] = %"y2"
  result.layout["yaxis"]["domain"] = %*[0.56, 1.0]
  result.layout["yaxis2"] = %*{"domain": [0.0, 0.44], "anchor": "x", "gridcolor": Grid,
                               "zeroline": false}
  result.note(0, 1.0, "Sea: Niño 3.4 anomaly, °C (3-month mean)", 12, Ink, ("paper", "paper"),
              %*{"xanchor": "left", "yanchor": "bottom"})
  result.note(0, 0.44, "Air: Southern Oscillation Index (3-month mean), its mirror image", 12,
              Ink, ("paper", "paper"), %*{"xanchor": "left", "yanchor": "bottom"})

proc boxLines*(boxes: DataFrame, since = 2014): PlotJson =
  let d = boxes.filter(col.year >= since)
  var p = Plot[float](layout: layout("Three of the four boxes, 2014-2026", 380, legend = true))
  let series = [("nino12_anom", Orange, "Niño 1+2 (coast of Peru)"),
                ("nino34_anom", Warm, "Niño 3.4 (central Pacific)"),
                ("nino4_anom", Blue, "Niño 4 (west)")]
  for (c, color, name) in series:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: name,
                              xs: d.decimalYear, ys: d.toList(c, float))
  result = p.finish(source = "Data: NOAA CPC (OISST v2.1).", hovermode = "x unified")
  for i, (c, color, name) in series:
    result.line(i, color)
    result.traces[i]["hovertemplate"] = %(name.split(" (")[0] & ": %{y:+.2f} °C<extra></extra>")
  result.note(2017.2, 2.9, "2017: coast only", 11)
  result.note(2023.2, 2.9, "2023: coast first", 11)
  result.layout["yaxis"]["title"] = %*{"text": "°C vs normal"}
  result.layout["xaxis"]["range"] = %*[since, 2027]

proc piura*(years: DataFrame): PlotJson =
  let d = years.withColumns(col.date.dt.year.alias("y"))
  let full = d.toList("days", int).mapIt(it >= 300)
  let tr = Trace[float](`type`: PlotType.Bar, xs: d.toList("y", float),
                        ys: d.toList("rain_mm", float),
                        marker: Marker[float](color: full.mapIt(hex(if it: Blue else: "#b7d3f6"))))
  let p = Plot[float](traces: @[tr], layout: layout("Piura, Peru: rain in a desert city", 360))
  result = p.finish(source = "Data: NOAA GHCN-Daily, Piura airport. Light bars: fewer than " &
                             "300 days reported that year.")
  result.traces[0]["customdata"] = %d.toList("days", int)
  result.traces[0]["hovertemplate"] = %"%{x}: %{y:,.0f} mm (%{customdata} days reported)<extra></extra>"
  for yr in [1983, 1998, 2017]:
    let v = d.filter(col.y == yr)["rain_mm"].item(float)
    result.note(float(yr), v, $yr, extra = %*{"yshift": 12})
  result.layout["yaxis"]["title"] = %*{"text": "rain per year, mm"}

proc world*(yearly, smooth, records: DataFrame): PlotJson =
  let s = smooth.withColumns(col.date.dt.year.alias("year"), col.date.dt.month.alias("month"))
  var p = Plot[float](layout: layout("The world's temperature, 1880-2026", 400, legend = true))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines,
                            name: "monthly, smoothed (ewmMean, span 12)",
                            xs: s.decimalYear, ys: s.toList("ewm12", float))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Lines, name: "yearly mean",
                            xs: yearly.toList("year", float).mapIt(it + 0.5),
                            ys: yearly.toList("temp", float))
  p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers, name: "record year",
                            xs: records.toList("year", float).mapIt(it + 0.5),
                            ys: records.toList("temp", float))
  result = p.finish(source = "Data: NASA GISS, GISTEMP v4.")
  result.line(0, "#9ec5f4", 1.2); result.line(1, Blue)
  result.traces[2]["marker"] = %*{"color": Warm, "size": 8, "line": {"color": Surface, "width": 2}}
  result.traces[0]["hovertemplate"] = %"%{y:.2f} °C<extra></extra>"
  result.traces[1]["hovertemplate"] = %"%{x:.0f}: %{y:.2f} °C<extra></extra>"
  result.traces[2]["hovertemplate"] = %"record %{x:.0f}: %{y:.2f} °C<extra></extra>"
  result.layout["yaxis"]["title"] = %*{"text": "°C vs 1951-1980"}
  result.layout["xaxis"]["range"] = %*[1880, 2027]

proc recent*(table: DataFrame): PlotJson =
  var p = Plot[float](layout: layout("Month by month, 2023-2026", 380, legend = true))
  let series = [("2023", Aqua), ("2024", Blue), ("2025", Grey), ("2026", Warm)]
  for (c, color) in series:
    p.traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.LinesMarkers, name: c,
                              xs: table.toList("mon", float),
                              ys: table.toList(c, Option[float]).mapIt(it.get(NaN)))
  result = p.finish(hovermode = "x unified")
  for i, (c, color) in series:
    result.traces[i]["y"] = %table.toList(c, Option[float]).mapIt(
      if it.isSome: %it.get else: newJNull())
    result.line(i, color, if c == "2026": 3.5 else: 2.0)
    result.traces[i]["marker"] = %*{"size": 6, "color": color}
    result.traces[i]["hovertemplate"] = %(c & ": %{y:.2f} °C<extra></extra>")
  result.layout["xaxis"]["tickvals"] = %toSeq(1 .. 12)
  result.layout["xaxis"]["ticktext"] = %"JFMAMJJASOND".mapIt($it)
  result.layout["yaxis"]["title"] = %*{"text": "°C vs 1951-1980"}

docs/blog/el_nino/plots.nim

docs/blog/el_nino/expected.py 24 lines
"""Runs el_nino.py cell by cell and writes each code cell's stdout to expected/<id>.txt.

Those files are the outputs the Nim post shows, and later its acceptance test.
Run from this folder: python3 -I expected.py"""
import 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("el_nino.py").read()
ns = {}
for cell in src.split("\n# %%")[1:]:
    if cell.startswith(" [markdown]"): continue
    m = re.match(r"\n# id: (\S+)", cell)
    if m.group(1).startswith("fig_"):  # figures: keep the Plotly JSON, no text output
        ns["figs"].SAVE_PATH = f"expected/{m.group(1)}.json"
        exec(compile(cell, m.group(1), "exec"), ns)
        ns["figs"].SAVE_PATH = None
        continue
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        exec(compile(cell, m.group(1), "exec"), ns)
    open(f"expected/{m.group(1)}.txt", "w").write(buf.getvalue().rstrip("\n") + "\n")
    print(m.group(1), len(buf.getvalue().splitlines()), "lines")

docs/blog/el_nino/expected.py

docs/blog/el_nino/src/maps_prep.py 23 lines
"""Cut the Pacific out of NOAA ERSSTv5 (raw/grid/ersst5.nc) for the post's maps.
Writes data/pacific_sst.nc: the 1991-2020 monthly normals and the months the post maps.
Run from the draft folder: python3 -I src/maps_prep.py raw/grid/ersst5.nc data/pacific_sst.nc"""
import sys, xarray as xr
src, out = sys.argv[1:3]
sst = xr.open_dataset(src)["sst"].sel(lat=slice(40, -40), lon=slice(100, 300))
normal = sst.sel(time=slice("1991-01-01", "2020-12-01")).groupby("time.month").mean("time")
months = ["1988-12-01", "1997-09-01", "1997-12-01", "2015-09-01", "2015-12-01",
          "2017-03-01", "2023-12-01", "2026-07-01", "2026-08-01", "2026-09-01"]
picked = sst.sel(time=months)
anom = picked.groupby("time.month") - normal
xr.Dataset({"normal": normal, "sst": picked, "anomaly": anom.drop_vars("month")}).to_netcdf(out)
print(xr.open_dataset(out))

# The same fields as long CSV tables (one row per grid point), which both posts read
# with their DataFrame library: data/pacific_normal.csv and data/pacific_anomaly.csv.
ds = xr.open_dataset(out).sel(lat=slice(30, -30), lon=slice(120, 290))
normal_df = ds.normal.mean("month").to_dataframe(name="sst").reset_index()
normal_df.round(2).to_csv("data/pacific_normal.csv", index=False)
anom_df = ds.anomaly.to_dataframe(name="anomaly").reset_index()
anom_df["month"] = anom_df["time"].dt.strftime("%Y-%m")
anom_df[["month", "lat", "lon", "anomaly"]].round(2).to_csv("data/pacific_anomaly.csv", index=False)
print(len(normal_df), len(anom_df))

docs/blog/el_nino/src/maps_prep.py

docs/blog/el_nino/src/parse_table.py 17 lines
"""Parse CPC's ONI or RONI HTML table into a wide CSV (year x 12 seasons) and a colour CSV."""
import re, sys, csv
src, out, colours = sys.argv[1:4]
t = open(src, errors="replace").read()
seas = "DJF JFM FMA MAM AMJ MJJ JJA JAS ASO SON OND NDJ".split()
vals, cols = [], []
for r in re.findall(r"<tr[^>]*>(.*?)</tr>", t, flags=re.S):
    cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", r, flags=re.S)
    txt = [re.sub(r"<[^>]+>|&nbsp;", "", c).strip() for c in cells]
    if not txt or not re.fullmatch(r"\d{4}", txt[0]) or len(cells) > 13: continue
    col = ["warm" if re.search(r"color:red|roni-warm", c) else "cold" if re.search(r"color:blue|roni-cold", c) else "" for c in cells[1:]]
    pad = 13 - len(cells)
    vals.append([txt[0]] + txt[1:] + [""] * pad); cols.append([txt[0]] + col + [""] * pad)
for path, data in [(out, vals), (colours, cols)]:
    with open(path, "w", newline="") as f:
        w = csv.writer(f); w.writerow(["year"] + seas); w.writerows(data)
print(len(vals), vals[0], vals[-1], cols[-1])

docs/blog/el_nino/src/parse_table.py

docs/blog/el_nino/src/prep.py 36 lines
"""Turn the raw NOAA/NASA downloads (raw/) into the small CSVs the post reads (data/).
Run from the draft folder: python3 -I src/prep.py raw data"""
import csv, gzip, sys, os
raw, out = sys.argv[1:3]
def write(name, header, rows):
    with open(os.path.join(out, name), "w", newline="") as f:
        w = csv.writer(f); w.writerow(header); w.writerows(rows)
    print(name, len(rows))

# Niño 3.4 monthly SST (ERSSTv6) with CPC's sliding 30-year climatology
rows = [l.split() for l in open(f"{raw}/detrend.nino34.ascii.txt") if l.strip()][1:]
write("nino34.csv", ["year", "month", "sst", "cpc_normal", "cpc_anomaly"], rows)

# the four Niño boxes, monthly OISST v2.1 since 1982
rows = [l.split() for l in open(f"{raw}/sstoi.indices") if l.strip()][1:]
write("nino_boxes.csv", ["year", "month", "nino12", "nino12_anom", "nino3", "nino3_anom",
                         "nino4", "nino4_anom", "nino34", "nino34_anom"], rows)

# Southern Oscillation Index, standardized section, fixed width: year(4) + 12 x 6 chars
lines = open(f"{raw}/soi").read().split("\n")
start = [i for i, l in enumerate(lines) if "STANDARDIZED" in l][0] + 3
rows = []
for l in lines[start:]:
    if not l[:4].isdigit(): break
    for m in range(12):
        v = l[4 + 6 * m: 10 + 6 * m].strip()
        rows.append([l[:4], m + 1, "" if v == "-999.9" else v])
while rows and rows[-1][2] == "": rows.pop()
write("soi.csv", ["year", "month", "soi"], rows)

# Piura (Peru) daily rain from GHCN-Daily, tenths of mm -> mm, drop values with a quality flag
rows = []
for r in csv.reader(gzip.open(f"{raw}/PEM00084401.csv.gz", "rt")):
    if r[2] == "PRCP" and r[5] == "":
        d = r[1]; rows.append([f"{d[:4]}-{d[4:6]}-{d[6:]}", int(r[3]) / 10])
write("piura_rain.csv", ["date", "rain_mm"], rows)

docs/blog/el_nino/src/prep.py