Nanuq dev log Β· 31 October 2026

The great polar bear census

Watch out where the huskies go, and don't you eat that rusty data.

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

This post was written before the code it shows. We drafted it while Nanuq 0.2 was still being designed, used it to decide the API, and checked every output against the same steps run in Python Polars. Now 0.2 is built and the page runs for real: each output below comes from Nanuq, and the page build compares it with the Python one.

Every spring, the rangers of Svalbard radio in the polar bears they see, and someone at base has to turn their notes into a report. This post follows one season of those notes through everything new in Nanuq 0.2: data types and casts, joins and concatenation, frame verbs, CSV reading options, conditional expressions, window functions and column selectors. A spring's worth of field logs needs every one of them.

Why anyone counts polar bears↑ contents

Svalbard's polar bears are counted for real, and the real numbers are small. An aerial survey in August 2015 estimated about 264 bears on the islands themselves, and about 973 including the pack ice to the north (Aars et al. 2017). Every spring since the 1990s, from March to May, the Norwegian Polar Institute has captured and marked bears, recording sex, weight, length and body condition, and it counts maternity dens on islands such as Hopen and KongsΓΈya (MOSJ).

Our census is invented, but it is shaped like that work: five stations, four weeks of spring, one row per station per week (the week is a plain number: date types come in a later release). Each row has the bears seen, the cubs among them, the weight of one bear weighed that week, whether it wore a collar, and the seals it was seen eating.

The first week↑ contents

Week one came in from four stations. Ingrid saw "lots" of bears and couldn't weigh any of them, so she wrote ?.

let week1 = readCsv("data/logs/week_01.csv")
echo week1
shape: (4, 9)
β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ week ┆ station      ┆ ranger ┆ bears ┆ cubs ┆ weight_kg ┆ collared ┆ ringed ┆ bearded β”‚
β”‚ ---  ┆ ---          ┆ ---    ┆ ---   ┆ ---  ┆ ---       ┆ ---      ┆ ---    ┆ ---     β”‚
β”‚ i64  ┆ str          ┆ str    ┆ str   ┆ i64  ┆ str       ┆ i64      ┆ i64    ┆ i64     β”‚
β•žβ•β•β•β•β•β•β•ͺ══════════════β•ͺ════════β•ͺ═══════β•ͺ══════β•ͺ═══════════β•ͺ══════════β•ͺ════════β•ͺ═════════║
β”‚ 1    ┆ Longyearbyen ┆ Ingrid ┆ lots  ┆ 2    ┆ ?         ┆ 0        ┆ 3      ┆ 0       β”‚
β”‚ 1    ┆ Ny-Alesund   ┆ Ola    ┆ 1     ┆ 0    ┆ 389.0     ┆ 1        ┆ 2      ┆ 0       β”‚
β”‚ 1    ┆ Barentsburg  ┆ Sasha  ┆ 0     ┆ 0    ┆ null      ┆ 0        ┆ 0      ┆ 0       β”‚
β”‚ 1    ┆ Hornsund     ┆ Kari   ┆ 3     ┆ 1    ┆ 515.0     ┆ 1        ┆ 5      ┆ 1       β”‚
β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

bears and weight_kg are strings: Polars doesn't guess that "lots" is a number or that ? means "don't know". Barentsburg left the weight empty, which already reads as null.

Reading the whole season↑ contents

The logs are one file per week. Polars can read all of them lazily with one glob, and 0.2 adds the reading options from Polars' CSV reader: here, ? is a null value, and two columns get their type up front with schemaOverrides, which takes DataType values just like cast. bears stays text for now; we'll come back to "lots".

try:
  discard scanCsv("data/logs/*.csv", nullValues = ["?"],
                  schemaOverrides = {"bears": String, "weight_kg": Float64}).collect
except PolarsError as e:
  echo e.msg.splitLines[0]
schema lengths differ

It fails. In week two a fifth station joined: Hopen, a small island in the southeast where bears den every winter. Its ranger, Magnus, also measures the sea ice, so from week two the logs have an extra ice_cm column, and a glob needs every file to have the same columns.

So read each week separately and stack them with a diagonal concat, which matches columns by name and fills the missing ones with nulls.

var weeks: seq[LazyFrame]
for week in 1..4:
  weeks.add scanCsv("data/logs/week_0" & $week & ".csv", nullValues = ["?"],
                    schemaOverrides = {"bears": String, "weight_kg": Float64})
let season = concat(weeks, how = Diagonal)

for name, t in season.collectSchema:
  echo name.alignLeft(15), t
week           Int64
station        String
ranger         String
bears          String
cubs           Int64
weight_kg      Float64
collared       Int64
ringed         Int64
bearded        Int64
ice_cm         Int64

Nothing has been read yet: collectSchema works out the result's types from the plan alone.

"Lots" is not a number↑ contents

A cast is strict by default, as in Polars: if a single value can't be converted, the query fails, and the error names the culprit. The target can be a plain Nim type.

try:
  discard season.select(col("bears").cast(int)).collect
except PolarsError as e:
  echo e.msg.splitLines[0]
conversion from `str` to `i64` failed in column 'bears' for 1 out of 4 values: ["lots"]

A non-strict cast turns what it can't read into nulls. That's the honest reading of "lots": there were bears, we don't know how many. Cubs fit in a uint8, and the 1/0 collar column becomes a boolean.

let log = season.cast({"bears": Int64, "cubs": UInt8, "collared": Boolean},
                      strict = false).collect
echo log.dtypes
echo "bear counts we couldn't read: ", log.nullCount("bears")
@[Int64, String, String, Int64, UInt8, Float64, Boolean, Int64, Int64, Int64]
bear counts we couldn't read: 2

Two: Ingrid's "lots" and Kari's "many".

Ola radios everything twice↑ contents

Ola, at Ny-Γ…lesund, has a habit of radioing his report twice when the line is bad. Two identical rows are one report, so unique drops the copy. maintainOrder keeps the rows in the order they came in, and a row index gives each report a number.

let tidy = log.unique(maintainOrder = true).withRowIndex("report", offset = 1)
echo "reports: ", log.height, " radioed, ", tidy.height, " after unique"
echo tidy.select(col("report", "week", "station", "ranger", "bears")).tail(3)
reports: 20 radioed, 19 after unique
shape: (3, 5)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”
β”‚ report ┆ week ┆ station     ┆ ranger ┆ bears β”‚
β”‚ ---    ┆ ---  ┆ ---         ┆ ---    ┆ ---   β”‚
β”‚ u32    ┆ i64  ┆ str         ┆ str    ┆ i64   β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ══════β•ͺ═════════════β•ͺ════════β•ͺ═══════║
β”‚ 17     ┆ 4    ┆ Barentsburg ┆ Sasha  ┆ 3     β”‚
β”‚ 18     ┆ 4    ┆ Hornsund    ┆ Kari   ┆ 2     β”‚
β”‚ 19     ┆ 4    ┆ Hopen       ┆ Magnus ┆ 6     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

col with several names selects several columns at once, new in 0.2.

Who was on duty?↑ contents

Twice a ranger forgot to write their name. Each station has one ranger, so the name from the station's previous report is the right one. The obvious fix, a forward fill, takes the name from the row above, and the row above belongs to another station. Adding .over("station") makes the fill run within each station, a window in Polars' terms.

echo tidy
  .select(col("report", "station", "ranger"),
          col("ranger").fillNull(Forward).alias("naive"),
          col("ranger").forwardFill.over("station").alias("per_station"))
  .filter(col("ranger").isNull)
shape: (2, 5)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ report ┆ station     ┆ ranger ┆ naive  ┆ per_station β”‚
β”‚ ---    ┆ ---         ┆ ---    ┆ ---    ┆ ---         β”‚
β”‚ u32    ┆ str         ┆ str    ┆ str    ┆ str         β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ═════════════β•ͺ════════β•ͺ════════β•ͺ═════════════║
β”‚ 12     ┆ Barentsburg ┆ null   ┆ Ola    ┆ Sasha       β”‚
β”‚ 16     ┆ Ny-Alesund  ┆ null   ┆ Ingrid ┆ Ola         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The naive fill would have put Ola in Barentsburg and Ingrid in Ny-Γ…lesund.

Sanity checks↑ contents

Adult male polar bears weigh roughly 300 to 600 kg and can reach 800; females are about half that (Norwegian Polar Institute). Anything outside 150 to 800 kg is a typo, so we drop it to null. That's a conditional expression, and in Nanuq you write it with choose and an ordinary Nim if. Without an else, the value is null, as in Polars.

Two stations, Longyearbyen and Barentsburg, are towns, where a bear is a safety matter; isIn flags them.

let filled = tidy.withColumns(col("ranger").forwardFill.over("station"))
let checked = filled.withColumns(
  choose(if col("weight_kg").isBetween(150, 800): col("weight_kg")).alias("weight_kg"),
  col("station").isIn(["Longyearbyen", "Barentsburg"]).alias("near_people"))

echo checked.filter(col("station") == "Ny-Alesund")
  .select(col("report", "station", "weight_kg", "near_people"))
shape: (4, 4)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ report ┆ station    ┆ weight_kg ┆ near_people β”‚
β”‚ ---    ┆ ---        ┆ ---       ┆ ---         β”‚
β”‚ u32    ┆ str        ┆ f64       ┆ bool        β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ════════════β•ͺ═══════════β•ͺ═════════════║
β”‚ 2      ┆ Ny-Alesund ┆ 389.0     ┆ false       β”‚
β”‚ 6      ┆ Ny-Alesund ┆ 451.2     ┆ false       β”‚
β”‚ 11     ┆ Ny-Alesund ┆ null      ┆ false       β”‚
β”‚ 16     ┆ Ny-Alesund ┆ 295.0     ┆ false       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Report 11 said 1420 kg. Ola meant 142.0, but we can't know that, so it's null now.

Where are the stations?↑ contents

Base keeps a small table of station coordinates. Joining it adds latitude and longitude to every report. Each report should match at most one station, and validate checks exactly that:

let stations = readCsv("data/stations.csv")
try:
  discard checked.join(stations, on = ["station"], how = Left, validate = ManyToOne)
except PolarsError as e:
  echo e.msg.splitLines[0]
join keys did not fulfill m:1 validation

Someone typed Hornsund in twice. And is any station missing from the table? An anti join keeps the reports that have no match:

echo checked.join(stations, on = ["station"], how = Anti).select(col("station")).unique
shape: (1, 1)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ station β”‚
β”‚ ---     β”‚
β”‚ str     β”‚
β•žβ•β•β•β•β•β•β•β•β•β•‘
β”‚ Hopen   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Nobody added Hopen. Fine for now: a left join keeps Hopen's reports, with null coordinates.

Slim, solid or chonk↑ contents

Time to name the bears' sizes. choose takes a whole if/elif/else chain, and turns it into Polars' when/then/otherwise, so the order matters: the first true branch wins. The null check comes first, because a comparison with null is null, which isn't true, so without it every unweighed bear would fall through to "chonk".

Polar bears live mostly on seals. Ringed seals are the main prey, and one big bearded seal is worth about ten ringed ones, so the log gets a column of ringed-seal equivalents too.

let located = checked.join(stations.unique(maintainOrder = true), on = ["station"],
                           how = Left, validate = ManyToOne,
                           maintainOrder = MaintainOrderJoin.Left)
let size = choose:
  if col("weight_kg").isNull: "unweighed"
  elif col("weight_kg") < 200: "slim"
  elif col("weight_kg") < 450: "solid"
  else: "chonk"

let sized = located.withColumns(size.alias("size"),
                                (col("ringed") + 10 * col("bearded")).alias("seal_eq"))
echo sized.select(col("station", "weight_kg", "size", "ringed", "bearded", "seal_eq")).head(8)
shape: (8, 6)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ station      ┆ weight_kg ┆ size      ┆ ringed ┆ bearded ┆ seal_eq β”‚
β”‚ ---          ┆ ---       ┆ ---       ┆ ---    ┆ ---     ┆ ---     β”‚
β”‚ str          ┆ f64       ┆ str       ┆ i64    ┆ i64     ┆ i64     β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════════β•ͺ═══════════β•ͺ════════β•ͺ═════════β•ͺ═════════║
β”‚ Longyearbyen ┆ null      ┆ unweighed ┆ 3      ┆ 0       ┆ 3       β”‚
β”‚ Ny-Alesund   ┆ 389.0     ┆ solid     ┆ 2      ┆ 0       ┆ 2       β”‚
β”‚ Barentsburg  ┆ null      ┆ unweighed ┆ 0      ┆ 0       ┆ 0       β”‚
β”‚ Hornsund     ┆ 515.0     ┆ chonk     ┆ 5      ┆ 1       ┆ 15      β”‚
β”‚ Longyearbyen ┆ 412.5     ┆ solid     ┆ 3      ┆ 0       ┆ 3       β”‚
β”‚ Ny-Alesund   ┆ 451.2     ┆ chonk     ┆ 4      ┆ 1       ┆ 14      β”‚
β”‚ Barentsburg  ┆ 402.8     ┆ solid     ┆ 4      ┆ 0       ┆ 4       β”‚
β”‚ Hornsund     ┆ 622.0     ┆ chonk     ┆ 7      ┆ 2       ┆ 27      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

A bare string in choose is a value. (In Python Polars, then("slim") would look for a column named "slim", a classic surprise; Nanuq takes columns only through col.)

Each bear against its station↑ contents

Hornsund keeps weighing heavy bears. How heavy compared with Hornsund's usual? A mean over the station gives every row its station's average, without collapsing the rows the way groupBy would.

echo sized.filter(col("station") == "Hornsund").select(
  col("week"), col("weight_kg"),
  (col("weight_kg") - col("weight_kg").mean.over("station")).round(1).alias("vs_station"))
shape: (4, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ week ┆ weight_kg ┆ vs_station β”‚
β”‚ ---  ┆ ---       ┆ ---        β”‚
β”‚ i64  ┆ f64       ┆ f64        β”‚
β•žβ•β•β•β•β•β•β•ͺ═══════════β•ͺ════════════║
β”‚ 1    ┆ 515.0     ┆ -76.8      β”‚
β”‚ 2    ┆ 622.0     ┆ 30.2       β”‚
β”‚ 3    ┆ 588.3     ┆ -3.5       β”‚
β”‚ 4    ┆ 641.9     ┆ 50.1       β”‚
β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Every number, per station↑ contents

For the station summary we want the mean of every numeric column, apart from a few that make no sense to average. Column selectors pick columns by type, and Nanuq uses Nim's own type classes for it: col(SomeNumber) is every numeric column, col(SomeFloat) every float column, col(int, float) exactly those types. Averaging many columns at once would give them all the same name, so name.suffix renames each one.

echo sized.groupBy(col("station"))
  .agg(col(SomeNumber).exclude("report", "week", "cubs", "ringed", "bearded", "lat", "lon")
         .mean.round(1).name.suffix("_mean"))
  .sort("station")
shape: (5, 5)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ station      ┆ bears_mean ┆ weight_kg_mean ┆ ice_cm_mean ┆ seal_eq_mean β”‚
β”‚ ---          ┆ ---        ┆ ---            ┆ ---         ┆ ---          β”‚
β”‚ str          ┆ f64        ┆ f64            ┆ f64         ┆ f64          β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ════════════β•ͺ════════════════β•ͺ═════════════β•ͺ══════════════║
β”‚ Barentsburg  ┆ 1.5        ┆ 258.9          ┆ null        ┆ 4.8          β”‚
β”‚ Hopen        ┆ 5.0        ┆ 233.7          ┆ 92.7        ┆ 15.0         β”‚
β”‚ Hornsund     ┆ 2.3        ┆ 591.8          ┆ null        ┆ 19.0         β”‚
β”‚ Longyearbyen ┆ 1.0        ┆ 390.0          ┆ null        ┆ 1.8          β”‚
β”‚ Ny-Alesund   ┆ 1.8        ┆ 378.4          ┆ null        ┆ 5.2          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Hopen sees the most bears but weighs the lightest. That fits: Hopen is a denning island, and the bears Magnus weighs are mostly mothers with cubs, who are about half a male's size. A mother usually has two cubs, and four or five in a week is a busy spring. Hornsund, meanwhile, is where the big males are.

The season's weights in three numbers:

echo sized.select(col("weight_kg").median.alias("median"),
                  col("weight_kg").quantile(0.9).alias("p90"),
                  col("weight_kg").std.round(1).alias("std"))
shape: (1, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”
β”‚ median ┆ p90   ┆ std   β”‚
β”‚ ---    ┆ ---   ┆ ---   β”‚
β”‚ f64    ┆ f64   ┆ f64   β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ═══════β•ͺ═══════║
β”‚ 389.0  ┆ 622.0 ┆ 156.3 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

The report for the Governor↑ contents

Polar bears have been protected since the 1973 international agreement on their conservation, signed in Oslo, and Svalbard's bear reports go to the Governor's office. The Governor likes the heaviest bears first and the unknowns at the end: a sort by two keys, with nullsLast.

let report = sized
  .sort(["weight_kg", "week"], descending = [true, false], nullsLast = [true])
  .select(col("week", "station", "ranger", "bears", "weight_kg", "size", "seal_eq"))
echo report
shape: (19, 7)
β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ week ┆ station      ┆ ranger ┆ bears ┆ weight_kg ┆ size      ┆ seal_eq β”‚
β”‚ ---  ┆ ---          ┆ ---    ┆ ---   ┆ ---       ┆ ---       ┆ ---     β”‚
β”‚ i64  ┆ str          ┆ str    ┆ i64   ┆ f64       ┆ str       ┆ i64     β”‚
β•žβ•β•β•β•β•β•β•ͺ══════════════β•ͺ════════β•ͺ═══════β•ͺ═══════════β•ͺ═══════════β•ͺ═════════║
β”‚ 4    ┆ Hornsund     ┆ Kari   ┆ 2     ┆ 641.9     ┆ chonk     ┆ 18      β”‚
β”‚ 2    ┆ Hornsund     ┆ Kari   ┆ null  ┆ 622.0     ┆ chonk     ┆ 27      β”‚
β”‚ 3    ┆ Hornsund     ┆ Kari   ┆ 2     ┆ 588.3     ┆ chonk     ┆ 16      β”‚
β”‚ 1    ┆ Hornsund     ┆ Kari   ┆ 3     ┆ 515.0     ┆ chonk     ┆ 15      β”‚
β”‚ 2    ┆ Ny-Alesund   ┆ Ola    ┆ 3     ┆ 451.2     ┆ chonk     ┆ 14      β”‚
β”‚ 2    ┆ Longyearbyen ┆ Ingrid ┆ 2     ┆ 412.5     ┆ solid     ┆ 3       β”‚
β”‚ 2    ┆ Barentsburg  ┆ Sasha  ┆ 2     ┆ 402.8     ┆ solid     ┆ 4       β”‚
β”‚ 1    ┆ Ny-Alesund   ┆ Ola    ┆ 1     ┆ 389.0     ┆ solid     ┆ 2       β”‚
β”‚ 3    ┆ Longyearbyen ┆ Ingrid ┆ 1     ┆ 367.4     ┆ solid     ┆ 1       β”‚
β”‚ 4    ┆ Ny-Alesund   ┆ Ola    ┆ 1     ┆ 295.0     ┆ solid     ┆ 2       β”‚
β”‚ 3    ┆ Hopen        ┆ Magnus ┆ 5     ┆ 241.7     ┆ solid     ┆ 15      β”‚
β”‚ 2    ┆ Hopen        ┆ Magnus ┆ 4     ┆ 233.0     ┆ solid     ┆ 6       β”‚
β”‚ 4    ┆ Hopen        ┆ Magnus ┆ 6     ┆ 226.3     ┆ solid     ┆ 24      β”‚
β”‚ 3    ┆ Barentsburg  ┆ Sasha  ┆ 1     ┆ 198.6     ┆ slim      ┆ 2       β”‚
β”‚ 4    ┆ Barentsburg  ┆ Sasha  ┆ 3     ┆ 175.2     ┆ slim      ┆ 13      β”‚
β”‚ 1    ┆ Longyearbyen ┆ Ingrid ┆ null  ┆ null      ┆ unweighed ┆ 3       β”‚
β”‚ 1    ┆ Barentsburg  ┆ Sasha  ┆ 0     ┆ null      ┆ unweighed ┆ 0       β”‚
β”‚ 3    ┆ Ny-Alesund   ┆ Ola    ┆ 2     ┆ null      ┆ unweighed ┆ 3       β”‚
β”‚ 4    ┆ Longyearbyen ┆ Ingrid ┆ 0     ┆ null      ┆ unweighed ┆ 0       β”‚
β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The Governor's auditor checks three reports at random by radio. A seed makes the pick repeatable, which matters on a page that is rebuilt on every change:

echo report.sample(3, seed = 42)
shape: (3, 7)
β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ week ┆ station      ┆ ranger ┆ bears ┆ weight_kg ┆ size      ┆ seal_eq β”‚
β”‚ ---  ┆ ---          ┆ ---    ┆ ---   ┆ ---       ┆ ---       ┆ ---     β”‚
β”‚ i64  ┆ str          ┆ str    ┆ i64   ┆ f64       ┆ str       ┆ i64     β”‚
β•žβ•β•β•β•β•β•β•ͺ══════════════β•ͺ════════β•ͺ═══════β•ͺ═══════════β•ͺ═══════════β•ͺ═════════║
β”‚ 3    ┆ Barentsburg  ┆ Sasha  ┆ 1     ┆ 198.6     ┆ slim      ┆ 2       β”‚
β”‚ 2    ┆ Longyearbyen ┆ Ingrid ┆ 2     ┆ 412.5     ┆ solid     ┆ 3       β”‚
β”‚ 4    ┆ Longyearbyen ┆ Ingrid ┆ 0     ┆ null      ┆ unweighed ┆ 0       β”‚
β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

(Python Polars, with the same seed, picks the same three reports in another order: a seed makes a sample repeatable within one version of Polars, not across versions.)

The office's spreadsheet is Norwegian, so the headers go Norwegian, the separator is a semicolon, and decimals use a comma: all options of writeCsv in 0.2.

let norsk = report.rename({"week": "uke", "station": "stasjon", "bears": "isbjorner",
                           "weight_kg": "vekt_kg", "size": "storrelse",
                           "seal_eq": "sel_ekv"})
norsk.writeCsv("governor.csv", separator = ';', decimalComma = true)
echo readFile("governor.csv").splitLines[0..3].join("\n")
uke;stasjon;ranger;isbjorner;vekt_kg;storrelse;sel_ekv
4;Hornsund;Kari;2;641,9;chonk;18
2;Hornsund;Kari;;622,0;chonk;27
3;Hornsund;Kari;2;588,3;chonk;16

Late ice, light cubs↑ contents

One last table. Hopen's station has also logged its maternity dens for the past eleven years: how many dens were found, the mean weight of the cubs when they first came out in spring, and the day of the year the sea ice reached the island the autumn before. Pregnant females need that ice to reach the island and den there.

let dens = readCsv("data/dens.csv")
let iceArrived = choose:
  if col("ice_day") < 335: "before December"
  else: "December or later"

echo dens.withColumns(iceArrived.alias("ice_arrived"))
  .groupBy(col("ice_arrived"))
  .agg(col("year").len.alias("years"),
       col("dens").mean.round(1).alias("dens"),
       col("cub_kg").mean.round(2).alias("cub_kg"))
  .sort("ice_arrived", descending = true)
shape: (2, 4)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ ice_arrived       ┆ years ┆ dens ┆ cub_kg β”‚
β”‚ ---               ┆ ---   ┆ ---  ┆ ---    β”‚
β”‚ str               ┆ u32   ┆ f64  ┆ f64    β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════β•ͺ══════β•ͺ════════║
β”‚ before December   ┆ 5     ┆ 26.6 ┆ 11.34  β”‚
β”‚ December or later ┆ 6     ┆ 14.2 ┆ 9.75   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

In years when the ice came late, there were fewer dens and the cubs were lighter.

These numbers are made up, but the pattern is real: on Hopen, later autumn sea ice has gone with lighter mothers and cubs at den emergence (Derocher et al. 2011). The full picture is less simple: Svalbard's bears have so far kept, and even improved, their body condition while the ice declined, which researchers expect to change as the ice keeps retreating.

What this post used from Nanuq 0.2↑ contents

Everything on this page, in the order it appeared:

The Python twin of this post, which recorded the outputs it is checked against, is blog/census/expected.py. How these APIs were chosen is in Designing Nanuq 0.2.

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/census/expected.py 185 lines
"""Expected outputs for docs/blog/bear_census.nim, computed with py-polars.

Each function here repeats one Nim code block of the post with py-polars and
writes what that block prints to expected/<scene>.txt. The post was drafted
against these outputs before Nanuq 0.2 existed; now that it runs, rendering it
fails when a Nanuq output differs. Run from this folder: python3 -I expected.py
"""
import os, io, contextlib
import polars as pl
import polars.selectors as cs

pl.Config(tbl_rows=25, tbl_cols=12, tbl_width_chars=120, tbl_hide_dataframe_shape=False)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.makedirs("expected", exist_ok=True)

def short(t):  # Nanuq's `$` on a DataType prints Nanuq code: Int64, String, ...
    simple = str(t)
    if "(" in simple:
        raise ValueError(f"no Nanuq name for {simple} in this scene")
    return simple

def first_line(e):
    return str(e).splitlines()[0]

def scene(name):
    def deco(f):
        buf = io.StringIO()
        with contextlib.redirect_stdout(buf):
            f()
        with open(f"expected/{name}.txt", "w") as fh:
            fh.write(buf.getvalue().rstrip("\n") + "\n")
        return f
    return deco

WEEKS = [f"data/logs/{w}" for w in sorted(os.listdir("data/logs"))]
NULLS = ["?"]
OVERRIDES = {"bears": pl.String, "weight_kg": pl.Float64}

@scene("s01_first_week")
def _():
    week1 = pl.read_csv(WEEKS[0])
    print(week1)

@scene("s02_scan_glob")
def _():
    try:
        pl.scan_csv("data/logs/*.csv", null_values=NULLS, schema_overrides=OVERRIDES).collect()
    except Exception as e:
        print(first_line(e))

season = pl.concat([pl.scan_csv(w, null_values=NULLS, schema_overrides=OVERRIDES) for w in WEEKS],
                   how="diagonal")

@scene("s03_scan_concat")
def _():
    for name, t in season.collect_schema().items():
        print(f"{name:<15}{short(t)}")

@scene("s04_strict")
def _():
    try:
        season.select(pl.col("bears").cast(pl.Int64)).collect()
    except Exception as e:
        print(first_line(e))

log = season.cast({"bears": pl.Int64, "cubs": pl.UInt8, "collared": pl.Boolean},
                  strict=False).collect()

@scene("s05_cast")
def _():
    print("@[" + ", ".join(short(t) for t in log.dtypes) + "]")
    print("bear counts we couldn't read:", log["bears"].null_count())

tidy = log.unique(maintain_order=True).with_row_index("report", offset=1)

@scene("s06_tidy")
def _():
    print(f"reports: {log.height} radioed, {tidy.height} after unique")
    print(tidy.select("report", "week", "station", "ranger", "bears").tail(3))

@scene("s07_fill")
def _():
    print(tidy.select("report", "station", "ranger",
                      pl.col("ranger").fill_null(strategy="forward").alias("naive"),
                      pl.col("ranger").forward_fill().over("station").alias("per_station"))
              .filter(pl.col("ranger").is_null()))

filled = tidy.with_columns(pl.col("ranger").forward_fill().over("station"))

checked = filled.with_columns(
    pl.when(pl.col("weight_kg").is_between(150, 800)).then(pl.col("weight_kg")).alias("weight_kg"),
    pl.col("station").is_in(["Longyearbyen", "Barentsburg"]).alias("near_people"),
)

@scene("s08_sanity")
def _():
    print(checked.filter(pl.col("station") == "Ny-Alesund")
                 .select("report", "station", "weight_kg", "near_people"))

stations = pl.read_csv("data/stations.csv")

@scene("s09_join_validate")
def _():
    try:
        checked.join(stations, on="station", how="left", validate="m:1")
    except Exception as e:
        print(first_line(e))

@scene("s10_join_anti")
def _():
    print(checked.join(stations, on="station", how="anti").select("station").unique())

located = checked.join(stations.unique(maintain_order=True), on="station", how="left",
                       validate="m:1", maintain_order="left")

sized = located.with_columns(
    pl.when(pl.col("weight_kg").is_null()).then(pl.lit("unweighed"))
      .when(pl.col("weight_kg") < 200).then(pl.lit("slim"))
      .when(pl.col("weight_kg") < 450).then(pl.lit("solid"))
      .otherwise(pl.lit("chonk")).alias("size"),
    (pl.col("ringed") + 10 * pl.col("bearded")).alias("seal_eq"),
)

@scene("s11_size")
def _():
    print(sized.select("station", "weight_kg", "size", "ringed", "bearded", "seal_eq")
               .head(8))

@scene("s12_over")
def _():
    print(sized.filter(pl.col("station") == "Hornsund").select(
        "week", "weight_kg",
        (pl.col("weight_kg") - pl.col("weight_kg").mean().over("station")).round(1)
            .alias("vs_station")))

@scene("s13_selectors")
def _():
    print(sized.group_by("station").agg(
            cs.numeric().exclude("report", "week", "cubs", "ringed", "bearded", "lat", "lon")
              .mean().round(1).name.suffix("_mean"))
          .sort("station"))

@scene("s14_quantile")
def _():
    print(sized.select(
        pl.col("weight_kg").median().alias("median"),
        pl.col("weight_kg").quantile(0.9).alias("p90"),
        pl.col("weight_kg").std().round(1).alias("std")))

report = (sized.sort(["weight_kg", "week"], descending=[True, False], nulls_last=True)
               .select("week", "station", "ranger", "bears", "weight_kg", "size", "seal_eq"))

@scene("s15_report")
def _():
    print(report)

@scene("s16_spot")
def _():
    print(report.sample(3, seed=42))

@scene("s17_norsk")
def _():
    norsk = report.rename({"week": "uke", "station": "stasjon", "bears": "isbjorner",
                           "weight_kg": "vekt_kg", "size": "storrelse", "seal_eq": "sel_ekv"})
    norsk.write_csv("governor.csv", separator=";", decimal_comma=True)
    with open("governor.csv") as fh:
        print("".join(fh.readlines()[:4]).rstrip())
    os.remove("governor.csv")

dens = pl.read_csv("data/dens.csv")

@scene("s18_dens")
def _():
    print(dens.with_columns(
            pl.when(pl.col("ice_day") < 335).then(pl.lit("before December"))
              .otherwise(pl.lit("December or later")).alias("ice_arrived"))
          .group_by("ice_arrived").agg(
            pl.col("year").len().alias("years"),
            pl.col("dens").mean().round(1).alias("dens"),
            pl.col("cub_kg").mean().round(2).alias("cub_kg"))
          .sort("ice_arrived", descending=True))

for f in sorted(os.listdir("expected")):
    print("===", f)
    print(open(f"expected/{f}").read())

docs/blog/census/expected.py