Nanuq dev log · 2 November 2026

Move 37

Four hundred years of go games, and the move that changed them.

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

setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, fmtStrLengths = 40, floatPrecision = 3)

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.6 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 boards and charts are Plotly figures, made with nim-plotly in Nim and Plotly in Python, from the same data.

Part 1: Ninety-eight thousand professional games↑ contents

1. The board, the stones, the rules↑ contents

Go is played on a grid of 19 by 19 lines. Black and White take turns placing one stone on an empty intersection; stones never move after that. Stones of the same colour that touch along the lines form a group, and a group whose last empty neighbouring point (its last liberty) is filled by the opponent is captured and taken off the board. At the end, each player counts the area they surround. Black moves first, which is an advantage, so White gets a few points of compensation, called komi.

Games are written down in SGF, a plain-text format where a move is two letters, the column and the row, from a (left, top) to s (right, bottom). pd is the fourth point from the right and the fourth from the top. Our database packs the moves of each game into one Binary value, two bytes per move. Binary columns are new in 0.6.

What is in it: the SGF letters themselves, one byte each, so pd is the two bytes 112 and 100. A String column would have worked just as well; we use Binary to try out the new type. It does fit the job: move n always sits at bytes 2n and 2n+1, bin.get hands back a byte as a number (a is 97, so a column is the byte minus 97), and looking for an opening is a prefix match on bytes.

let pro = readParquet("data/pro_games.parquet")
echo pro.select("file", "DT", "PB", "PW", "KM", "RE", "moves").glimpse(maxItemsPerColumn = 2)
Rows: 98199
Columns: 7
$ file      'AJ1st/01/1.sgf', 'AJ1st/01/10.sgf'
$ DT        '1968-11-28', '1969-08-14'
$ PB        'Sakata Eio', 'Fujisawa Shuko'
$ PW        'Kubouchi Shuchi', 'Hashimoto Shoji'
$ KM        '4.5', '4.5'
$ RE        'B+R', 'B+3.5'
$ moves  qdqpcdedeqodmccqdpcodnqcpcpdocncndnbqbrcobqembnemdcededdcfbeccbfdfdcbdbgbbebdbdacbfdffciadbncnbocldoeoenfoegfeemdleifkgmcjdjelflejbjcrblbmfjglfmekamfihlehdhdick, cpcdpqpoqoqnqppmnppcpfqhedecfcdcqjqfpgqgpeqepdqdocphoknmmklmqlrmmnnlminhoiohkollkjeqgpfodncqgodpfncncmdoemiljmkkjjimjnnknjhkjljklkklijikgifkbncodkgnhngmfrfmfdfi

To draw a game we turn the bytes into points. bin.size tells how many bytes there are; the bytes come out one by one with bin.get. Here are the first 37 moves of the second game between AlphaGo (Black) and Lee Sedol (White).

let game2 = pro.filter(col("file") == "AlphaGo/LeeSedol/2.sgf")
let first37 = game2
  .select(intRange(0, 37).alias("move"), col.moves.first)
  .select(
    (col.move + 1).alias("move"),
    `when`(col.move mod 2 == 0).then("B").otherwise("W").alias("color"),
    (col.moves.bin.get(col.move * 2).cast(Int64) - 97).alias("x"),
    (col.moves.bin.get(col.move * 2 + 1).cast(Int64) - 97).alias("y"),
  )
echo first37.tail(4)
shape: (4, 4)
┌──────┬───────┬─────┬─────┐
│ move ┆ color ┆ x   ┆ y   │
│ ---  ┆ ---   ┆ --- ┆ --- │
│ i64  ┆ str   ┆ i64 ┆ i64 │
╞══════╪═══════╪═════╪═════╡
│ 34   ┆ W     ┆ 15  ┆ 5   │
│ 35   ┆ B     ┆ 13  ┆ 3   │
│ 36   ┆ W     ┆ 15  ┆ 8   │
│ 37   ┆ B     ┆ 14  ┆ 9   │
└──────┴───────┴─────┴─────┘
show plots.board(first37, "AlphaGo vs Lee Sedol, game 2, moves 1 to 37", labels = first37.select(
  col.x, col.y, col.move.cast(String).alias("text"),
  `when`(col.color == "B").then("white").otherwise("black").alias("fg")))
plotting code
proc board*(stones: DataFrame, title: string, labels = DataFrame(), size = 19, height = 560): PlotJson =
  ## stones: x, y, color ("B"/"W"); labels: optional x, y, text, fg.
  var stars: seq[(float, float)]
  for x in Stars:
    for y in Stars: stars.add (x.float, y.float)
  var traces = @[Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                              xs: stars.mapIt(it[0]), ys: stars.mapIt(it[1]))]
  for c in ["B", "W"]:
    let s = stones.filter(col.color == c)
    traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                            name: (if c == "B": "black" else: "white"),
                            xs: s.floats("x"), ys: s.floats("y"))
  result = finish(traces, title, height)
  result.withStyle(0, %*{"marker": {"size": 6, "color": Ink}, "hoverinfo": "skip", "showlegend": false})
  let stoneSize = height.float / (size + 2).float * 0.9
  result.withStyle(1, %*{"marker": {"size": stoneSize, "color": "#111111", "line": {"width": 1, "color": "#000000"}},
                         "hoverinfo": "skip", "showlegend": false})
  result.withStyle(2, %*{"marker": {"size": stoneSize, "color": "#f8f8f4", "line": {"width": 1, "color": "#555555"}},
                         "hoverinfo": "skip", "showlegend": false})
  if labels.width > 0:
    result.traces.add %*{"type": "scatter", "mode": "text", "x": labels.floats("x"), "y": labels.floats("y"),
                         "text": labels.toList("text", string),
                         "textfont": {"color": labels.toList("fg", string), "size": 11},
                         "hoverinfo": "skip", "showlegend": false}
  result.layout["width"] = %(height - 20)
  result.layout["shapes"] = %gridShapes(size)
  result.layout["xaxis"] = %*{"range": [-1, size], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(Cols[0 ..< size]).mapIt($it), "side": "top",
    "constrain": "domain"}
  result.layout["yaxis"] = %*{"range": [size, -1], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(0 ..< size).mapIt($(size - it)),
    "scaleanchor": "x", "constrain": "domain"}

Move 37 is the black stone at P10, alone in the middle of the right side. Moves near the edge, on the third line, take territory; moves on the fourth line build influence towards the centre. A stone on the fifth line, this early, gives White an easy third line underneath. Michael Redmond, commentating in English, called it "a very surprising move". Fan Hui, who had lost to AlphaGo five months earlier: "It's not a human move. I've never seen a human play this move."

2. Komi, exactly↑ contents

How many points should White get for moving second? Go has argued about it for a century. Old Japanese games have no komi at all; komi appeared in the 1930s, and professionals went from 4.5 to 5.5, 6.5 and in China 7.5 points. The half point is there so that a game cannot end in a tie.

Half points are exactly the kind of number that floating point gets almost right. Decimal columns, new in 0.6, store them exactly: str.to_decimal(scale=1) reads the KM property as a number with one digit after the point.

let games = pro
  .filter(col("SZ").isNull or col("SZ") == "19", col("HA").isNull)
  .withColumns(
    col("DT").str.extract(r"^(\d{4})").cast(Int64).alias("year"),
    col("KM").str.stripChars.str.toDecimal(scale = 1).alias("komi"),
    col("RE").str.extract(r"^([BW])\+").alias("winner"),
    col("RE").str.extract(r"^[BW]\+(\d+(?:\.\d)?)$").str.toDecimal(scale = 1).alias("margin"),
  )
echo games.groupBy((col.year div 10 * 10).alias("decade")).agg(
  len().alias("games"), col.komi.mode.first.alias("usual_komi")
).filter(col.decade >= 1920).sort("decade")
shape: (11, 3)
┌────────┬───────┬───────────────┐
│ decade ┆ games ┆ usual_komi    │
│ ---    ┆ ---   ┆ ---           │
│ i64    ┆ u32   ┆ decimal[38,1] │
╞════════╪═══════╪═══════════════╡
│ 1920   ┆ 298   ┆ null          │
│ 1930   ┆ 1355  ┆ 0.0           │
│ 1940   ┆ 631   ┆ 0.0           │
│ 1950   ┆ 1872  ┆ 4.5           │
│ 1960   ┆ 10795 ┆ 0.0           │
│ 1970   ┆ 12173 ┆ 5.5           │
│ 1980   ┆ 9704  ┆ 5.5           │
│ 1990   ┆ 9811  ┆ 5.5           │
│ 2000   ┆ 11500 ┆ 6.5           │
│ 2010   ┆ 18916 ┆ 6.5           │
│ 2020   ┆ 15489 ┆ 6.5           │
└────────┴───────┴───────────────┘

Did it work? With komi 0, Black won 58% of the decisive games. Each extra point of komi took away about two and a half points of percentage, and at 6.5 the game is a coin toss: 50.2%.

let fair = games
  .filter(col.winner.isNotNull)
  .groupBy("komi")
  .agg(len().alias("games"), (col.winner == "B").mean.alias("black_wins"))
  .filter(col.games >= 300, col.komi.isNotNull)
  .sort("komi")
echo fair
shape: (7, 3)
┌───────────────┬───────┬────────────┐
│ komi          ┆ games ┆ black_wins │
│ ---           ┆ ---   ┆ ---        │
│ decimal[38,1] ┆ u32   ┆ f64        │
╞═══════════════╪═══════╪════════════╡
│ 0.0           ┆ 11160 ┆ 0.583      │
│ 4.5           ┆ 6290  ┆ 0.555      │
│ 5.0           ┆ 2893  ┆ 0.537      │
│ 5.5           ┆ 28709 ┆ 0.533      │
│ 6.5           ┆ 38469 ┆ 0.502      │
│ 7.5           ┆ 3066  ┆ 0.486      │
│ 8.0           ┆ 321   ┆ 0.489      │
└───────────────┴───────┴────────────┘
show plots.bars(fair.withColumns(col.komi.cast(String).alias("label")), "label", "black_wins",
                "How often Black wins, by komi (professional games, no handicap)", "Black wins",
                yformat = ".0%")
plotting code
proc bars*(df: DataFrame, x, y: string, title, ytitle: string, color = "#8c5a2b",
           height = 400, yformat = ""): PlotJson =
  result = finish(@[Trace[float](`type`: PlotType.Bar, xs: @[], ys: df.floats(y))], title, height)
  result.traces[0]["x"] = %df.toList(x, string)
  result.withStyle(0, %*{"marker": {"color": color}})
  result.layout["yaxis"] = %*{"title": {"text": ytitle}, "automargin": true}
  if yformat.len > 0: result.layout["yaxis"]["tickformat"] = %yformat

A whole-number komi such as 5 can end in a draw, called jigo. Decimals make the test exact: a komi is whole when komi == komi.floor(), and the margins of half-point komi games always end in .5.

echo games.filter(col.komi.isNotNull).groupBy((col.komi == col.komi.floor).alias("whole_komi")).agg(
  len().alias("games"),
  (col("RE") == "Jigo").sum.alias("draws"),
  (col.margin == lit("0.5").str.toDecimal(scale = 1)).sum.alias("half_point_wins"),
).sort("whole_komi")
shape: (2, 4)
┌────────────┬───────┬───────┬─────────────────┐
│ whole_komi ┆ games ┆ draws ┆ half_point_wins │
│ ---        ┆ ---   ┆ ---   ┆ ---             │
│ bool       ┆ u32   ┆ u32   ┆ u32             │
╞════════════╪═══════╪═══════╪═════════════════╡
│ false      ┆ 76797 ┆ 1     ┆ 4442            │
│ true       ┆ 15061 ┆ 413   ┆ 0               │
└────────────┴───────┴───────┴─────────────────┘

3. Where the first stone goes↑ contents

The board has eight symmetries (four rotations, each with a mirror image), so the opening move at pd and the one at dp are the same move. We fold every first move into one corner by counting lines from the nearest edge: a stone on the third line from one edge and the fourth from the other is a 3-4 point, the classic komoku; the 4-4 point is hoshi, a star point.

proc lineFromEdge(byte: int): Expr =
  let v = col.moves.bin.get(byte).cast(Int64) - 97 + 1
  minHorizontal(v, 20 - v)

let first = games
  .filter(col.moves.bin.size >= 2, col.year.isNotNull)
  .withColumns(lineFromEdge(0).alias("a"), lineFromEdge(1).alias("b"))
  .withColumns(
    format("{}-{}", minHorizontal(col.a, col.b), maxHorizontal(col.a, col.b)).alias("point"),
    `when`(col.year <= 1867).then("1: Edo, to 1867")
      .`when`(col.year <= 1945).then("2: 1868-1945")
      .`when`(col.year <= 1990).then("3: 1946-1990")
      .`when`(col.year <= 2016).then("4: 1991-2016")
      .otherwise("5: AI era, 2017-").alias("era"),
  )
echo first.groupBy("era", "point").agg(len().alias("len")).withColumns(
  (col.len / col.len.sum.over("era")).alias("share")
).filter(col.share > 0.02).sort(["era", "share"], descending = [false, true])
shape: (13, 4)
┌──────────────────┬───────┬───────┬───────┐
│ era              ┆ point ┆ len   ┆ share │
│ ---              ┆ ---   ┆ ---   ┆ ---   │
│ str              ┆ str   ┆ u32   ┆ f64   │
╞══════════════════╪═══════╪═══════╪═══════╡
│ 1: Edo, to 1867  ┆ 3-4   ┆ 1561  ┆ 0.862 │
│ 1: Edo, to 1867  ┆ 3-5   ┆ 182   ┆ 0.100 │
│ 1: Edo, to 1867  ┆ 4-5   ┆ 47    ┆ 0.026 │
│ 2: 1868-1945     ┆ 3-4   ┆ 2220  ┆ 0.759 │
│ 2: 1868-1945     ┆ 4-4   ┆ 516   ┆ 0.176 │
│ 2: 1868-1945     ┆ 4-5   ┆ 66    ┆ 0.023 │
│ …                ┆ …     ┆ …     ┆ …     │
│ 3: 1946-1990     ┆ 4-4   ┆ 15436 ┆ 0.433 │
│ 3: 1946-1990     ┆ 3-3   ┆ 1251  ┆ 0.035 │
│ 4: 1991-2016     ┆ 4-4   ┆ 18543 ┆ 0.577 │
│ 4: 1991-2016     ┆ 3-4   ┆ 12803 ┆ 0.398 │
│ 5: AI era, 2017- ┆ 4-4   ┆ 12937 ┆ 0.587 │
│ 5: AI era, 2017- ┆ 3-4   ┆ 8504  ┆ 0.386 │
└──────────────────┴───────┴───────┴───────┘

In the Edo period nearly nine games in ten opened on a 3-4 point. The 4-4 point took over in the twentieth century, with the "New Opening" of Go Seigen and Kitani Minoru in the 1930s and, later, with komi: a fast, open style pays when Black has points to give back.

let freq = first
  .withColumns(
    (col.moves.bin.get(0).cast(Int64) - 97).alias("x"),
    (col.moves.bin.get(1).cast(Int64) - 97).alias("y"),
    col.era.str.slice(3).alias("panel"),
  )
  .groupBy("panel", "x", "y").agg(len().alias("len"))
  .withColumns((col.len / col.len.sum.over("panel")).alias("share"))
show plots.heatBoards(freq, ["Edo, to 1867", "1868-1945", "1946-1990", "1991-2016", "AI era, 2017-"],
                      "Where Black puts the first stone")
plotting code
proc heatBoards*(freq: DataFrame, panels: openArray[string], title: string, height = 330): PlotJson =
  ## freq: panel, x, y, share; one 19x19 heatmap per panel, side by side.
  let zmax = freq.select(col.share.max).toList("share", float)[0]
  var traces: seq[Trace[float]]
  for p in panels:
    let f = freq.filter(col.panel == p)
    var z = newSeqWith(19, newSeq[float](19))
    for r in f.select(col.x, col.y, col.share).rows(tuple[x, y: int, share: float]):
      z[r.y][r.x] = r.share
    traces.add Trace[float](`type`: PlotType.HeatMap, xs: toSeq(0 .. 18).mapIt(it.float),
                            ys: toSeq(0 .. 18).mapIt(it.float), zs: z)
  result = finish(traces, title, height)
  let n = panels.len
  let gap = 0.03
  let w = (1.0 - gap * float(n - 1)) / float(n)
  var notes = newJArray()
  for i, p in panels:
    let suffix = if i == 0: "" else: $(i + 1)
    result.withStyle(i, %*{"zmin": 0, "zmax": zmax,
      "colorscale": [[0, "#f3e3bd"], [0.25, "#e0a84f"], [0.6, "#b4462b"], [1, "#3a0f12"]],
      "showscale": i == n - 1, "hovertemplate": "%{z:.1%}<extra></extra>",
      "colorbar": {"tickformat": ".0%", "len": 0.8}, "xaxis": "x" & suffix, "yaxis": "y" & suffix})
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & suffix] = %*{"domain": [x0, x0 + w], "anchor": "y" & suffix,
      "range": [-0.5, 18.5], "showticklabels": false, "showgrid": false, "zeroline": false, "constrain": "domain"}
    result.layout["yaxis" & suffix] = %*{"domain": [0, 1], "anchor": "x" & suffix,
      "range": [18.5, -0.5], "showticklabels": false, "showgrid": false, "zeroline": false,
      "constrain": "domain", "scaleanchor": "x" & suffix}
    notes.add %*{"text": p, "x": x0 + w / 2, "y": 1.0, "xref": "paper", "yref": "paper",
                 "xanchor": "center", "yanchor": "bottom", "showarrow": false, "font": {"size": 16}}
  result.layout["annotations"] = notes
  result.layout["plot_bgcolor"] = %"#f3e3bd"

The heatmaps also show a habit: Black's first stone goes in the top-right corner, from Black's point of view. It is a courtesy, leaving the corner nearest to the opponent's right hand free.

4. Searching the moves↑ contents

A Binary column can be searched without decoding it. bin.starts_with finds games by their first moves, bin.slice cuts out a few bytes, and bin.encode shows bytes as hexadecimal text (70 64 is p d). Before AlphaGo, the most common start was Black at pd and White at dd, the two top corners; since 2017 it is pd and dp.

echo games.filter(col.moves.bin.size >= 4, col.year.isNotNull).groupBy(
  (col.year >= 2017).alias("after_alphago")
).agg(
  len().alias("games"),
  col.moves.bin.startsWith("pd").mean.alias("start_pd"),
  col.moves.bin.startsWith("pddp").mean.alias("start_pddp"),
  col.moves.bin.slice(0, 4).mode.first.alias("common_start"),
  col.moves.bin.slice(0, 4).bin.encode(Hex).mode.first.alias("as_hex"),
).sort("after_alphago")
shape: (2, 6)
┌───────────────┬───────┬──────────┬────────────┬──────────────┬──────────┐
│ after_alphago ┆ games ┆ start_pd ┆ start_pddp ┆ common_start ┆ as_hex   │
│ ---           ┆ ---   ┆ ---      ┆ ---        ┆ ---          ┆ ---      │
│ bool          ┆ u32   ┆ f64      ┆ f64        ┆ binary       ┆ str      │
╞═══════════════╪═══════╪══════════╪════════════╪══════════════╪══════════╡
│ false         ┆ 72582 ┆ 0.445    ┆ 0.125      ┆ b"pddd"      ┆ 70646464 │
│ true          ┆ 22031 ┆ 0.580    ┆ 0.299      ┆ b"pddp"      ┆ 70646470 │
└───────────────┴───────┴──────────┴────────────┴──────────────┴──────────┘

5. The 3-3 invasion↑ contents

The clearest trace AlphaGo left on human play is in the corners. When one side holds a 4-4 point, the other can slide in underneath at the 3-3 point and live in the corner. Textbooks said this was fine late in the game, but giving the opponent a wall this early was bad style. AlphaGo did it at once, and won. Within a year everybody did.

We write the test as one expression: a game has an early 3-3 invasion if, in its first twelve moves, some corner has both its 4-4 point and the 3-3 point beneath it. Moves come out of the Binary column as a list of two-letter strings.

let moves12 = col.moves.bin.slice(0, 24).cast(String).str.extractAll("..")
let early33 = anyHorizontal(
  [("dd", "cc"), ("pd", "qc"), ("dp", "cq"), ("pp", "qq")].mapIt(
    moves12.list.contains(it[0]) and moves12.list.contains(it[1]))
).alias("early_33")
let invasions = games
  .filter(col.year >= 1990)
  .groupBy("year")
  .agg(len().alias("games"), early33.mean)
  .sort("year")
echo invasions.tail(13)
shape: (13, 3)
┌──────┬───────┬──────────┐
│ year ┆ games ┆ early_33 │
│ ---  ┆ ---   ┆ ---      │
│ i64  ┆ u32   ┆ f64      │
╞══════╪═══════╪══════════╡
│ 2014 ┆ 1898  ┆ 0.250    │
│ 2015 ┆ 1940  ┆ 0.240    │
│ 2016 ┆ 2328  ┆ 0.210    │
│ 2017 ┆ 2496  ┆ 0.243    │
│ 2018 ┆ 2057  ┆ 0.432    │
│ 2019 ┆ 2188  ┆ 0.452    │
│ …    ┆ …     ┆ …        │
│ 2021 ┆ 2215  ┆ 0.446    │
│ 2022 ┆ 2183  ┆ 0.450    │
│ 2023 ┆ 2395  ┆ 0.459    │
│ 2024 ┆ 2471  ┆ 0.465    │
│ 2025 ┆ 2337  ┆ 0.431    │
│ 2026 ┆ 1394  ┆ 0.419    │
└──────┴───────┴──────────┘

Between 1990 and 2017, a bit more than a game in five had an early 3-3 point next to a star point (some were the old, slow kind of invasion, or a 3-3 point played first). In 2018, a year after AlphaGo's 60 online wins against top professionals, it jumped to almost a game in two, and it stayed there.

show plots.lines(invasions, "year", [("early_33", "early 3-3 invasions", "#b4462b")],
                 "Professional games with a 3-3 invasion in the first 12 moves", "share of games",
                 events = [(2016.2, "AlphaGo-Lee Sedol"), (2017.0, "AlphaGo Master online")], yformat = ".0%")
plotting code
proc lines*(df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
            yformat = "", height = 420, mode = "lines+markers"): PlotJson =
  ## Lines without event markers.
  linesAt(df, x, ys, title, ytitle, newSeq[(int, string)](), yformat, height, mode)

We will want the same yardstick for amateurs in Part 2. Expressions can now be serialized: meta.serialize turns one into JSON (or a compact binary form), and pl.Expr.deserialize brings it back, in another script or another language. We save early_33 to a file.

writeFile("early_33.json", early33.meta.serialize(Json))
echo Expr.deserialize(readFile("early_33.json"), Json).meta.outputName
early_33

6. Same position, different order↑ contents

Players reach the same opening position along different move orders. To find them, go programs give every position a Zobrist hash: draw one random 64-bit number for each point and colour, and XOR together the numbers of the stones on the board. XOR is commutative, so the order of moves doesn't matter, and two different positions almost never get the same hash. (A capture would XOR a stone away again; there are none this early.)

Bitwise operations are new in 0.6. bitwise_xor is an aggregation, so the hash of each game's first ten moves is a group_by.

let keys = readCsv("data/zobrist.csv", schemaOverrides = {"point": Int64, "key": UInt64})
let openings = games
  .filter(col.moves.bin.size >= 20, col.year >= 1990)
  .select(col.file, col.year, col.moves.bin.slice(0, 20).cast(String).str.extractAll("..").alias("mv"))
  .withColumns(lit(@["B", "W", "B", "W", "B", "W", "B", "W", "B", "W"]).alias("color"))
  .explode("mv", "color")
  .withColumns(((col.mv.str.slice(1, 1).str.toInteger(base = 36) - 10) * 19 +
                col.mv.str.slice(0, 1).str.toInteger(base = 36) - 10).alias("point"))
  .join(keys, on = ["point", "color"], maintainOrder = MaintainOrderJoin.Left)
  .groupBy("file", "year")
  .agg(col.key.bitwiseXor.alias("zobrist"), col.mv.str.join("").alias("order"))
echo openings.sort("file").head(3)
shape: (3, 4)
┌────────────────┬──────┬─────────────────────┬──────────────────────┐
│ file           ┆ year ┆ zobrist             ┆ order                │
│ ---            ┆ ---  ┆ ---                 ┆ ---                  │
│ str            ┆ i64  ┆ u64                 ┆ str                  │
╞════════════════╪══════╪═════════════════════╪══════════════════════╡
│ Agon/01/1.sgf  ┆ 1994 ┆ 7591513221675378493 ┆ pddpfqipddfpppeqcjcl │
│ Agon/01/10.sgf ┆ 1994 ┆ 7274345532105593782 ┆ pdddppdppjncjpqfndmd │
│ Agon/01/11.sgf ┆ 1994 ┆ 5897872481684456237 ┆ pddcdpppceckgdedccdf │
└────────────────┴──────┴─────────────────────┴──────────────────────┘

Grouping by the hash shows the most played positions after ten moves since 1990, and how many different move orders led to each.

let top = openings
  .groupBy("zobrist")
  .agg(len().alias("games"), col.order.nUnique.alias("orders"), col.order.mode.first.alias("example"),
       col.year.min.alias("first_year"), col.year.max.alias("last_year"))
  .sort("games", descending = true)
  .head(5)
echo top.withColumns(col.zobrist.cast(String).alias("hash")).drop("zobrist")
shape: (5, 6)
┌───────┬────────┬──────────────────────┬────────────┬───────────┬──────────────────────┐
│ games ┆ orders ┆ example              ┆ first_year ┆ last_year ┆ hash                 │
│ ---   ┆ ---    ┆ ---                  ┆ ---        ┆ ---       ┆ ---                  │
│ u32   ┆ u32    ┆ str                  ┆ i64        ┆ i64       ┆ str                  │
╞═══════╪════════╪══════════════════════╪════════════╪═══════════╪══════════════════════╡
│ 165   ┆ 2      ┆ qdddpqdpocpoqoqnqppn ┆ 1990       ┆ 2026      ┆ 17761928217287973003 │
│ 138   ┆ 2      ┆ pddpppdcdececfcddffc ┆ 1990       ┆ 2026      ┆ 18086621764959758795 │
│ 130   ┆ 2      ┆ pdddpqdpqkncpfqcpcpb ┆ 2005       ┆ 2023      ┆ 1625178054545094845  │
│ 117   ┆ 1      ┆ pdddqpdqdocodpcpeqcn ┆ 1990       ┆ 2025      ┆ 9820471106566910854  │
│ 111   ┆ 2      ┆ qdddpqdpndpoqoqnqppn ┆ 2018       ┆ 2026      ┆ 286001257002867988   │
└───────┴────────┴──────────────────────┴────────────┴───────────┴──────────────────────┘

Good keys are random bits. bitwise_count_ones counts the bits set to 1 (we expect about half of 64), bitwise_leading_zeros counts the zero bits at the front, and the aggregations bitwise_and and bitwise_or keep the bits that are set in all keys, or in any key.

echo keys.select(
  col.key.bitwiseCountOnes.mean.alias("mean_ones"),
  col.key.bitwiseCountOnes.min.alias("min_ones"),
  col.key.bitwiseCountOnes.max.alias("max_ones"),
  col.key.bitwiseLeadingZeros.max.alias("leading_zeros_max"),
  col.key.bitwiseAnd.alias("all_and"),
  col.key.bitwiseOr.bitwiseCountOnes.alias("all_or_ones"),
)
shape: (1, 6)
┌───────────┬──────────┬──────────┬───────────────────┬─────────┬─────────────┐
│ mean_ones ┆ min_ones ┆ max_ones ┆ leading_zeros_max ┆ all_and ┆ all_or_ones │
│ ---       ┆ ---      ┆ ---      ┆ ---               ┆ ---     ┆ ---         │
│ f64       ┆ u32      ┆ u32      ┆ u32               ┆ u64     ┆ u32         │
╞═══════════╪══════════╪══════════╪═══════════════════╪═════════╪═════════════╡
│ 32.130    ┆ 21       ┆ 43       ┆ 11                ┆ 0       ┆ 64          │
└───────────┴──────────┴──────────┴───────────────────┴─────────┴─────────────┘

Part 2: Two point eight million amateur games↑ contents

7. A file too big to read↑ contents

The Online Go Server (OGS) has been running since 2005. Its complete public record, 56 million games up to May 2025, comes as a single 46 GB gzipped file with one JSON object per line: 200 GB once unpacked, far more than the memory of a laptop. We streamed it once over the network and kept every twentieth line: 2,820,649 games in a 10.3 GB NDJSON file. That is still too big to read comfortably, which is the point.

The post ships the first 2,000 lines of that file, so every cell below runs. Each line is the raw API record of one game: players with their ranks, board size, komi, rules, clock settings, the outcome and the moves.

Let Polars guess the types, and it gives up: the same field holds a boolean on one line and a number on another.

try:
  discard readNdjson("data/ogs_slice.ndjson")
except PolarsError as e:
  echo "read failed: ", e.msg.split("'")[0].strip, " ..."
read failed: cannot parse ...

So we say what we want, as a schema, and leave the rest out. The other fields, more than a hundred, are never even parsed. ignore_errors turns the few values that don't fit into nulls.

let player = Struct({"username": String, "rank": Float64, "professional": Boolean})
let schema = {
  "game_id": Int64, "start_time": Int64, "width": Int64, "height": Int64,
  "handicap": Int64, "komi": Float64, "rules": String, "outcome": String,
  "winner": Int64, "black_player_id": Int64,
  "players": Struct({"black": player, "white": player}),
  "time_control": Struct({"speed": String}),
  "moves": List(List(Int64)),
}
let raw = scanNdjson("data/ogs_slice.ndjson", schema = schema, ignoreErrors = true)
echo raw.head(3).collect
shape: (3, 13)
┌─────────┬────────────┬───────┬────────┬──────────┬───┬────────┬─────────────┬─────────────┬─────────────┬────────────┐
│ game_id ┆ start_time ┆ width ┆ height ┆ handicap ┆ … ┆ winner ┆ black_playe ┆ players     ┆ time_contro ┆ moves      │
│ ---     ┆ ---        ┆ ---   ┆ ---    ┆ ---      ┆   ┆ ---    ┆ r_id        ┆ ---         ┆ l           ┆ ---        │
│ i64     ┆ i64        ┆ i64   ┆ i64    ┆ i64      ┆   ┆ i64    ┆ ---         ┆ struct[2]   ┆ ---         ┆ list[list[ │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆ i64         ┆             ┆ struct[1]   ┆ i64]]      │
╞═════════╪════════════╪═══════╪════════╪══════════╪═══╪════════╪═════════════╪═════════════╪═════════════╪════════════╡
│ 1060    ┆ 1366300598 ┆ 19    ┆ 19     ┆ 0        ┆ … ┆ 25     ┆ 411         ┆ {{"rohde101 ┆ {"correspon ┆ [[15, 3,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ 7",0.000,nu ┆ dence"}     ┆ -1], [3,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ ll},{"saya" ┆             ┆ 15, -1], … │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ ,0.000,…    ┆             ┆ [3, 10,    │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆             ┆             ┆ -1]…       │
│ 1317    ┆ 1368717338 ┆ 19    ┆ 19     ┆ 0        ┆ … ┆ 767    ┆ 758         ┆ {{"w121060" ┆ {"correspon ┆ [[3, 16,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ ,0.000,null ┆ dence"}     ┆ -1], [3,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ },{"Arkad", ┆             ┆ 15, -1], … │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ 0.000,n…    ┆             ┆ [16, 2,    │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆             ┆             ┆ -1]…       │
│ 1463    ┆ 1369514049 ┆ 19    ┆ 19     ┆ 0        ┆ … ┆ 782    ┆ 782         ┆ {{"cohet",1 ┆ {"correspon ┆ [[3, 15,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ .000,null}, ┆ dence"}     ┆ -1], [15,  │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ {"matburt", ┆             ┆ 15, -1], … │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆ 3.000,n…    ┆             ┆ [12, 11,   │
│         ┆            ┆       ┆        ┆          ┆   ┆        ┆             ┆             ┆             ┆ -…         │
└─────────┴────────────┴───────┴────────┴──────────┴───┴────────┴─────────────┴─────────────┴─────────────┴────────────┘

8. Streaming into Parquet↑ contents

Now the query: one row per game, with the start as a datetime, the board size, komi as a Decimal, the two ranks, the result, the number of moves, and the first twelve moves turned into the same two-letter Binary form as the professional games. OGS gives a move as [x, y, milliseconds], and [-1, -1, ...] for a pass.

OGS ranks are numbers: 30 is 1 dan, 29 is 1 kyu, 20 is 10 kyu. Kyu grades go down as players get stronger, from 30 kyu (a beginner) to 1 kyu; then dan grades go up, from 1 to about 9 dan for amateurs.

const letters = "abcdefghijklmnopqrstuvwxyz"
proc sgfLetter(i: Expr): Expr =
  `when`(i >= 0).then(lit(letters).str.slice(i, 1)).otherwise("t")

let ogs = raw.filter(col.width == col.height).select(
  col.game_id,
  fromEpoch("start_time", EpochUnit.Seconds).alias("started"),
  col.width.alias("size"),
  col.handicap,
  col.komi.cast(Decimal(10, 1)),
  col.rules.str.toLowercase,
  col.time_control.struct.field("speed").alias("speed"),
  col.players.struct.field("black").struct.field("rank").alias("black_rank"),
  col.players.struct.field("white").struct.field("rank").alias("white_rank"),
  col.outcome,
  `when`(col.winner == col.black_player_id).then("B")
    .`when`(col.winner.isNotNull).then("W").alias("winner"),
  col.moves.list.len.alias("n_moves"),
  col.moves.list.head(12).list.eval(
    sgfLetter(element().list.get(0)) + sgfLetter(element().list.get(1))
  ).list.join("").cast(Binary).alias("moves"),
)
echo ogs.head(0).collect
shape: (0, 13)
┌─────────┬──────────────┬──────┬──────────┬───────────────┬───┬────────────┬─────────┬────────┬─────────┬────────┐
│ game_id ┆ started      ┆ size ┆ handicap ┆ komi          ┆ … ┆ white_rank ┆ outcome ┆ winner ┆ n_moves ┆ moves  │
│ ---     ┆ ---          ┆ ---  ┆ ---      ┆ ---           ┆   ┆ ---        ┆ ---     ┆ ---    ┆ ---     ┆ ---    │
│ i64     ┆ datetime[μs] ┆ i64  ┆ i64      ┆ decimal[10,1] ┆   ┆ f64        ┆ str     ┆ str    ┆ u32     ┆ binary │
╞═════════╪══════════════╪══════╪══════════╪═══════════════╪═══╪════════════╪═════════╪════════╪═════════╪════════╡
└─────────┴──────────────┴──────┴──────────┴───────────────┴───┴────────────┴─────────┴────────┴─────────┴────────┘

Nothing has run yet: ogs is a lazy query, and collecting zero rows of it only shows its columns. The new streaming engine runs it in batches, so memory stays flat however big the file is, and sink_parquet writes the result straight to disk without ever building the whole table. On the 10.3 GB file (on a 4-core machine with 15 GB of memory) the streaming run took 75 seconds and 0.13 GB of working memory. The same query collected in memory took 89 seconds and 11.8 GB. Here it is on the slice.

ogs.sinkParquet("ogs_slice.parquet")
echo scanParquet("ogs_slice.parquet").select(
  len().alias("games"), col.started.min.alias("first"), col.started.max.alias("last")
).collect
shape: (1, 3)
┌───────┬─────────────────────┬─────────────────────┐
│ games ┆ first               ┆ last                │
│ ---   ┆ ---                 ┆ ---                 │
│ u32   ┆ datetime[μs]        ┆ datetime[μs]        │
╞═══════╪═════════════════════╪═════════════════════╡
│ 2000  ┆ 2005-11-05 09:19:00 ┆ 2013-10-30 22:11:52 │
└───────┴─────────────────────┴─────────────────────┘

Is the streamed result the same as an ordinary in-memory run? The new testing helpers answer with one line: assert_frame_equal raises an error that points at the first difference, and returns quietly when there is none.

assertFrameEqual(readParquet("ogs_slice.parquet"), ogs.collect(Engine.InMemory))
echo "streaming and in-memory results agree"
streaming and in-memory results agree

9. Growth, AlphaGo and the lockdowns↑ contents

The streamed table of all 2.8 million games is 80 MB of Parquet. To keep the post small we ship every fifth game of it: 563,622 games, a 1% sample of everything played on OGS. Two moments stand out in the number of games started each month: March 2016, the week AlphaGo beat Lee Sedol, and spring 2020, when half the world was told to stay home.

let gamesOgs = readParquet("data/ogs_games.parquet")
let monthly = gamesOgs.groupBy(col.started.dt.truncate("1mo").dt.date.alias("month")).agg(len().alias("len")).sort("month")
echo monthly.filter(col.month.isBetween(date(2016, 1, 1), date(2016, 6, 1)) or
                    col.month.isBetween(date(2020, 1, 1), date(2020, 6, 1)))
shape: (12, 2)
┌────────────┬──────┐
│ month      ┆ len  │
│ ---        ┆ ---  │
│ date       ┆ u32  │
╞════════════╪══════╡
│ 2016-01-01 ┆ 2094 │
│ 2016-02-01 ┆ 2190 │
│ 2016-03-01 ┆ 4604 │
│ 2016-04-01 ┆ 3365 │
│ 2016-05-01 ┆ 2707 │
│ 2016-06-01 ┆ 2310 │
│ 2020-01-01 ┆ 3535 │
│ 2020-02-01 ┆ 3369 │
│ 2020-03-01 ┆ 4497 │
│ 2020-04-01 ┆ 5420 │
│ 2020-05-01 ┆ 5442 │
│ 2020-06-01 ┆ 5094 │
└────────────┴──────┘

March 2016 had twice the games of February. The lockdowns of 2020 did more, and for longer: from March the number of games grew by half and stayed high all year.

show plots.lines(monthly.withColumns((col.len * 100).alias("games")), "month",
                 [("games", "games per month (estimated: 1% sample × 100)", "#8c5a2b")],
                 "Games started on OGS each month", "games",
                 events = [("2016-03-09", "AlphaGo-Lee Sedol"), ("2020-03-15", "lockdowns")], mode = "lines")
plotting code
proc lines*(df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
            yformat = "", height = 420, mode = "lines+markers"): PlotJson =
  ## Lines without event markers.
  linesAt(df, x, ys, title, ytitle, newSeq[(int, string)](), yformat, height, mode)

10. Small boards, fast games↑ contents

Online, half the games are on smaller boards: 9×9 games last ten minutes and teach the tactics, 13×13 is a step towards the full board. Most games are played live, the rest by correspondence, a move a day.

echo gamesOgs.filter(col.size.isIn([9, 13, 19])).groupBy("size").agg(
  len().alias("games"),
  (len() / gamesOgs.height).alias("share"),
  col.n_moves.median.alias("median_moves"),
  col.speed.isIn(["blitz", "live"]).mean.alias("blitz_or_live"),
).sort("size")
shape: (3, 5)
┌──────┬────────┬───────┬──────────────┬───────────────┐
│ size ┆ games  ┆ share ┆ median_moves ┆ blitz_or_live │
│ ---  ┆ ---    ┆ ---   ┆ ---          ┆ ---           │
│ i64  ┆ u32    ┆ f64   ┆ f64          ┆ f64           │
╞══════╪════════╪═══════╪══════════════╪═══════════════╡
│ 9    ┆ 216463 ┆ 0.384 ┆ 50.000       ┆ 0.864         │
│ 13   ┆ 70942  ┆ 0.126 ┆ 101.000      ┆ 0.853         │
│ 19   ┆ 274730 ┆ 0.487 ┆ 175.000      ┆ 0.847         │
└──────┴────────┴───────┴──────────────┴───────────────┘

11. Does the stronger player win?↑ contents

Ranks are supposed to predict results. We take even games (no handicap) on the full board that ended with a winner, and group them by the rank difference between the two players, rounded to whole grades.

let even = gamesOgs.filter(
  col.size == 19, col.handicap == 0, col.winner.isNotNull, col.n_moves >= 20
).withColumns((col.black_rank - col.white_rank).round.cast(Int64).alias("gap"))
let stronger = even
  .filter(col.gap != 0)
  .groupBy(col.gap.abs.alias("grades"))
  .agg(len().alias("games"),
       ((col.gap > 0) == (col.winner == "B")).mean.alias("stronger_wins"))
  .filter(col.grades <= 9)
  .sort("grades")
echo stronger
shape: (9, 3)
┌────────┬───────┬───────────────┐
│ grades ┆ games ┆ stronger_wins │
│ ---    ┆ ---   ┆ ---           │
│ i64    ┆ u32   ┆ f64           │
╞════════╪═══════╪═══════════════╡
│ 1      ┆ 50074 ┆ 0.581         │
│ 2      ┆ 33810 ┆ 0.658         │
│ 3      ┆ 17809 ┆ 0.703         │
│ 4      ┆ 12754 ┆ 0.754         │
│ 5      ┆ 8176  ┆ 0.775         │
│ 6      ┆ 7064  ┆ 0.790         │
│ 7      ┆ 4868  ┆ 0.793         │
│ 8      ┆ 4182  ┆ 0.802         │
│ 9      ┆ 2681  ┆ 0.801         │
└────────┴───────┴───────────────┘

One grade of difference gives the stronger player 58% of the games, four grades three games in four, and it levels off around 80%. Ranks on a server drift, players have off days, and the handicap system exists for a reason: in a handicap game, the weaker player starts with extra stones, one for each grade of difference.

show plots.lines(stronger, "grades", [("stronger_wins", "stronger player wins", "#2b6c8f")],
                 "Even games on 19×19: how often the higher-ranked player wins", "share of games",
                 yformat = ".0%")
plotting code
proc lines*(df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
            yformat = "", height = 420, mode = "lines+markers"): PlotJson =
  ## Lines without event markers.
  linesAt(df, x, ys, title, ytitle, newSeq[(int, string)](), yformat, height, mode)

12. Do amateurs play like AlphaGo?↑ contents

Back to the saved expression from section 5. We load early_33 from its JSON file and run it on the amateur games: the same yardstick, not a copy of the code. Strong amateurs (dan grades, rank 30 and up) and weaker ones (kyu grades), year by year, for years with at least 50 such games.

let early33Saved = Expr.deserialize(readFile("early_33.json"), Json)
let amateurs = gamesOgs
  .filter(col.size == 19, col.handicap == 0, col.n_moves >= 30)
  .withColumns(col.started.dt.year.alias("year"),
               `when`(minHorizontal(col.black_rank, col.white_rank) >= 30)
                 .then("dan").otherwise("kyu").alias("level"))
  .groupBy("year", "level")
  .agg(len().alias("games"), early33Saved.mean)
  .filter(col.games >= 50)
  .sort(["year", "level"])
let sideBySide = amateurs.pivot(on = "level", index = "year", values = "early_33").join(
  invasions.select(col.year, col.early_33.alias("pro")), on = ["year"], how = Left, maintainOrder = MaintainOrderJoin.Left).filter(col.year >= 2014)
echo sideBySide
shape: (12, 4)
┌──────┬───────┬───────┬───────┐
│ year ┆ kyu   ┆ dan   ┆ pro   │
│ ---  ┆ ---   ┆ ---   ┆ ---   │
│ i32  ┆ f64   ┆ f64   ┆ f64   │
╞══════╪═══════╪═══════╪═══════╡
│ 2014 ┆ 0.287 ┆ null  ┆ 0.250 │
│ 2015 ┆ 0.300 ┆ 0.273 ┆ 0.240 │
│ 2016 ┆ 0.325 ┆ 0.326 ┆ 0.210 │
│ 2017 ┆ 0.352 ┆ 0.285 ┆ 0.243 │
│ 2018 ┆ 0.377 ┆ null  ┆ 0.432 │
│ 2019 ┆ 0.404 ┆ 0.490 ┆ 0.452 │
│ 2020 ┆ 0.429 ┆ 0.547 ┆ 0.482 │
│ 2021 ┆ 0.422 ┆ 0.505 ┆ 0.446 │
│ 2022 ┆ 0.416 ┆ 0.501 ┆ 0.450 │
│ 2023 ┆ 0.444 ┆ 0.500 ┆ 0.459 │
│ 2024 ┆ 0.451 ┆ 0.500 ┆ 0.465 │
│ 2025 ┆ 0.461 ┆ 0.455 ┆ 0.431 │
└──────┴───────┴───────┴───────┘

Strong amateurs followed the professionals: under a third of their games before 2018, one in two from 2019. (2018 is missing because the sample has too few games between two dan players that year.) Kyu players had been playing early 3-3 points more than the professionals all along (it is the simple, safe way to take a corner) and drifted up slowly.

show plots.lines(sideBySide.filter(col.year <= 2024), "year",
                 [("pro", "professionals", "#b4462b"), ("dan", "OGS, dan players", "#2b6c8f"),
                  ("kyu", "OGS, kyu players", "#8fb3c9")],
                 "Early 3-3 invasions: professionals and amateurs", "share of games",
                 events = [(2016.2, "AlphaGo")], yformat = ".0%")
plotting code
proc lines*(df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
            yformat = "", height = 420, mode = "lines+markers"): PlotJson =
  ## Lines without event markers.
  linesAt(df, x, ys, title, ytitle, newSeq[(int, string)](), yformat, height, mode)

Part 3: A go engine in a callback↑ contents

13. Replaying the games↑ contents

The moves alone don't say what the board looks like at the end: stones get captured. To know, you have to play the game through, checking after every move whether a group has lost its last liberty. That is a loop with a flood fill inside, the kind of code no built-in expression covers, so it goes in a callback: a function called on each value.

In Python this is map_elements with a function written in Python (it is in goboard.py, about forty lines), and it is slow, because Python runs the loop. In the Nim tab the same forty lines are Nim, compiled, and Nanuq 0.6 hands the bytes over through the Arrow C Data Interface without copying them.

We replay the 3,997 complete games we kept (AlphaGo's, and all professional games since 2025) and count the stones left and the stones captured.

type FinalCounts = object
  black_stones, white_stones, captured: int

proc finalCounts(moves: string): FinalCounts =
  let (board, capturedByBlack, capturedByWhite) = goboard.replay(moves)
  FinalCounts(black_stones: board.count('\1'), white_stones: board.count('\2'),
              captured: capturedByBlack + capturedByWhite)

let full = readParquet("data/pro_full_moves.parquet")
let replayed = full.withColumns(col.moves.mapElements(finalCounts).alias("final")).unnest("final")
echo replayed.select(col.file, col.PB, col.PW, col.RE, (col.moves.bin.size div 2).alias("n_moves"),
                     col.black_stones, col.white_stones, col.captured).sort(
  "captured", descending = true).head(5)
shape: (5, 8)
┌───────────────────────────┬──────────────┬────────────────┬───────┬─────────┬──────────────┬──────────────┬──────────┐
│ file                      ┆ PB           ┆ PW             ┆ RE    ┆ n_moves ┆ black_stones ┆ white_stones ┆ captured │
│ ---                       ┆ ---          ┆ ---            ┆ ---   ┆ ---     ┆ ---          ┆ ---          ┆ ---      │
│ str                       ┆ str          ┆ str            ┆ str   ┆ u32     ┆ i64          ┆ i64          ┆ i64      │
╞═══════════════════════════╪══════════════╪════════════════╪═══════╪═════════╪══════════════╪══════════════╪══════════╡
│ AlphaGo/Nature2017/AlphaG ┆ AlphaGo Zero ┆ AlphaGo Zero   ┆ B+R   ┆ 535     ┆ 156          ┆ 120          ┆ 114      │
│ o_Zero_40_block…          ┆              ┆                ┆       ┆         ┆              ┆              ┆          │
│ AlphaGo/Nature2017/AlphaG ┆ AlphaGo Zero ┆ AlphaGo Master ┆ W+R   ┆ 364     ┆ 136          ┆ 136          ┆ 92       │
│ o_Zero_40_block…          ┆              ┆                ┆       ┆         ┆              ┆              ┆          │
│ FMeijin/37/P03.sgf        ┆ Nyu Eiko     ┆ Iwata Saeka    ┆ W+2.5 ┆ 328     ┆ 121          ┆ 115          ┆ 92       │
│ AlphaGo/Nature2017/AlphaG ┆ AlphaGo Zero ┆ AlphaGo Zero   ┆ B+R   ┆ 467     ┆ 198          ┆ 121          ┆ 86       │
│ o_Zero_20_block…          ┆              ┆                ┆       ┆         ┆              ┆              ┆          │
│ Samsung/30/P48.sgf        ┆ 辛炫錫       ┆ Ngau Shihte    ┆ W+R   ┆ 358     ┆ 135          ┆ 138          ┆ 85       │
└───────────────────────────┴──────────────┴────────────────┴───────┴─────────┴──────────────┴──────────────┴──────────┘

AlphaGo Zero playing itself leads the table: programs don't resign early, so their games go on until every last group is settled. On a laptop the Python callback takes about 3 seconds for these games, and the Nim one a few hundredths of a second. Here is the bloodiest game between humans, at the end.

let bloodiest = replayed.filter(not col.file.str.startsWith("AlphaGo/")).sort("captured", descending = true).head(1)
let boardBytes = goboard.replay(bloodiest["moves", 0, string])[0]
let finalStones = newDataFrame(series("cell", boardBytes.mapIt(it.int))).withRowIndex("p").filter(col.cell > 0).select(
  (col.p.cast(Int64) mod 19).alias("x"), (col.p.cast(Int64) div 19).alias("y"),
  `when`(col.cell == 1).then("B").otherwise("W").alias("color"))
show plots.board(finalStones, bloodiest["PB", 0, string] & " (B) vs " & bloodiest["PW", 0, string] &
                 " (W), " & bloodiest["DT", 0, string] & ": final position")
plotting code
proc board*(stones: DataFrame, title: string, labels = DataFrame(), size = 19, height = 560): PlotJson =
  ## stones: x, y, color ("B"/"W"); labels: optional x, y, text, fg.
  var stars: seq[(float, float)]
  for x in Stars:
    for y in Stars: stars.add (x.float, y.float)
  var traces = @[Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                              xs: stars.mapIt(it[0]), ys: stars.mapIt(it[1]))]
  for c in ["B", "W"]:
    let s = stones.filter(col.color == c)
    traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                            name: (if c == "B": "black" else: "white"),
                            xs: s.floats("x"), ys: s.floats("y"))
  result = finish(traces, title, height)
  result.withStyle(0, %*{"marker": {"size": 6, "color": Ink}, "hoverinfo": "skip", "showlegend": false})
  let stoneSize = height.float / (size + 2).float * 0.9
  result.withStyle(1, %*{"marker": {"size": stoneSize, "color": "#111111", "line": {"width": 1, "color": "#000000"}},
                         "hoverinfo": "skip", "showlegend": false})
  result.withStyle(2, %*{"marker": {"size": stoneSize, "color": "#f8f8f4", "line": {"width": 1, "color": "#555555"}},
                         "hoverinfo": "skip", "showlegend": false})
  if labels.width > 0:
    result.traces.add %*{"type": "scatter", "mode": "text", "x": labels.floats("x"), "y": labels.floats("y"),
                         "text": labels.toList("text", string),
                         "textfont": {"color": labels.toList("fg", string), "size": 11},
                         "hoverinfo": "skip", "showlegend": false}
  result.layout["width"] = %(height - 20)
  result.layout["shapes"] = %gridShapes(size)
  result.layout["xaxis"] = %*{"range": [-1, size], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(Cols[0 ..< size]).mapIt($it), "side": "top",
    "constrain": "domain"}
  result.layout["yaxis"] = %*{"range": [size, -1], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(0 ..< size).mapIt($(size - it)),
    "scaleanchor": "x", "constrain": "domain"}

And a sanity check across all games: the more moves a game has, the more stones get captured, but the board never holds more than 361.

echo replayed.select(
  len().alias("games"),
  (col.moves.bin.size div 2).mean.alias("mean_moves"),
  col.captured.mean.alias("mean_captured"),
  (col.black_stones + col.white_stones).max.alias("max_on_board"),
  corr(col.moves.bin.size, col.captured).alias("corr_moves_captured"),
)
shape: (1, 5)
┌───────┬────────────┬───────────────┬──────────────┬─────────────────────┐
│ games ┆ mean_moves ┆ mean_captured ┆ max_on_board ┆ corr_moves_captured │
│ ---   ┆ ---        ┆ ---           ┆ ---          ┆ ---                 │
│ u32   ┆ f64        ┆ f64           ┆ i64          ┆ f64                 │
╞═══════╪════════════╪═══════════════╪══════════════╪═════════════════════╡
│ 3997  ┆ 212.202    ┆ 15.075        ┆ 319          ┆ 0.737               │
└───────┴────────────┴───────────────┴──────────────┴─────────────────────┘

Part 4: Italian go↑ contents

14. Champions, in a database↑ contents

Italy has played go seriously since the 1970s. The Italian Go Federation (FIGG) has held a national championship every year since 1980; since 1992 the two best Italian players of the championship tournament meet in a final. The federation's roll of honour lists every winner, the score of the final and the runner-up. (2024 is missing from it; the 2025 result comes from the federation's news.)

New in 0.6, frames go to and from databases: write_database creates a table, read_database runs a SQL query and returns a frame. Here we use SQLite, a database in a single file.

let champions = readCsv("data/champions.csv")
let db = open("italian_go.db", "", "", "")
discard champions.writeDatabase("champions", db, ifTableExists = IfTableExists.Replace)
db.close()
let titles = readDatabaseUri("""
    SELECT winner AS player, COUNT(*) AS titles, MIN(year) AS first, MAX(year) AS last
    FROM champions GROUP BY winner ORDER BY titles DESC, first
    """, "sqlite://italian_go.db")
withConfig(tblRows = -1):  # all fourteen
  echo titles
shape: (14, 4)
┌────────────────────┬────────┬───────┬──────┐
│ player             ┆ titles ┆ first ┆ last │
│ ---                ┆ ---    ┆ ---   ┆ ---  │
│ str                ┆ i64    ┆ i64   ┆ i64  │
╞════════════════════╪════════╪═══════╪══════╡
│ Francesco Marigo   ┆ 10     ┆ 2001  ┆ 2012 │
│ Ramon Soletti      ┆ 6      ┆ 1991  ┆ 1999 │
│ Alessandro Pace    ┆ 6      ┆ 2013  ┆ 2020 │
│ Enzo Burlini       ┆ 5      ┆ 1981  ┆ 2000 │
│ Davide Bernardis   ┆ 4      ┆ 2021  ┆ 2025 │
│ Sergio Parimbelli  ┆ 3      ┆ 1982  ┆ 1988 │
│ Primo Garofalo     ┆ 2      ┆ 1986  ┆ 1990 │
│ Enzo Pedrini       ┆ 2      ┆ 1995  ┆ 1996 │
│ Davide Minieri     ┆ 2      ┆ 2007  ┆ 2008 │
│ Roberto Mercadante ┆ 1      ┆ 1980  ┆ 1980 │
│ Fulvio Savagnone   ┆ 1      ┆ 1985  ┆ 1985 │
│ Marco Vajani       ┆ 1      ┆ 1989  ┆ 1989 │
│ Matias Pankoke     ┆ 1      ┆ 2015  ┆ 2015 │
│ Kim Shakhov        ┆ 1      ┆ 2017  ┆ 2017 │
└────────────────────┴────────┴───────┴──────┘

Fourteen champions in 45 championships, and the first six hold 34 titles between them. The finals are long-running rivalries: some pairs met again and again.

echo readDatabaseUri("""
    SELECT winner, runner_up, COUNT(*) AS finals, GROUP_CONCAT(year, ' ') AS years
    FROM champions WHERE runner_up IS NOT NULL AND runner_up <> ''
    GROUP BY winner, runner_up HAVING COUNT(*) >= 2 ORDER BY finals DESC
    """, "sqlite://italian_go.db")

Text: """
shape: (7, 4)
┌──────────────────┬─────────────────┬────────┬──────────────────────────┐
│ winner           ┆ runner_up       ┆ finals ┆ years                    │
│ ---              ┆ ---             ┆ ---    ┆ ---                      │
│ str              ┆ str             ┆ i64    ┆ str                      │
╞══════════════════╪═════════════════╪════════╪══════════════════════════╡
│ Francesco Marigo ┆ Ramon Soletti   ┆ 5      ┆ 2001 2002 2003 2005 2006 │
│ Francesco Marigo ┆ Carlo Metta     ┆ 4      ┆ 2009 2010 2011 2012      │
│ Ramon Soletti    ┆ Enzo Pedrini    ┆ 4      ┆ 1993 1994 1997 1999      │
│ Alessandro Pace  ┆ Carlo Metta     ┆ 2      ┆ 2019 2020                │
│ Alessandro Pace  ┆ Matias Pankoke  ┆ 2      ┆ 2014 2016                │
│ Davide Bernardis ┆ Alessandro Pace ┆ 2      ┆ 2021 2025                │
│ Enzo Pedrini     ┆ Ramon Soletti   ┆ 2      ┆ 1995 1996                │
└──────────────────┴─────────────────┴────────┴──────────────────────────┘

15. Fifty-six thousand players in a text file↑ contents

The European Go Database records every rated tournament game in Europe. Its player list is a plain text table with fixed-width columns: the PIN, the name (last name first), country, club, grade, a suggested promotion, the rating (GoR), the number of tournaments and the code of the last one (a letter, then the date as YYMMDD). We read each line as one string, keep the lines that start with a PIN, and cut them at fixed positions.

let lines = readCsv("data/egd_players.txt", hasHeader = false, newColumns = ["line"], separator = '\x01').filter(
  col.line.str.contains(r"^ \d{8} "))
proc cut(start, length: int): Expr =
  col.line.str.slice(start, length).str.stripChars

let egd = lines.select(
  cut(0, 10).cast(Int64).alias("pin"),
  cut(11, 38).str.replaceAll("_", " ").alias("name"),
  cut(49, 2).alias("country"),
  cut(53, 4).alias("club"),
  cut(57, 6).alias("grade"),
  cut(68, 7).cast(Int64).alias("gor"),
  cut(75, 6).cast(Int64).alias("tournaments"),
  cut(83, 8).alias("last"),
).withColumns(col.last.str.slice(1, 2).str.toInteger(strict = false).alias("yy")).withColumns(
  `when`(col.yy > 50).then(1900 + col.yy).otherwise(2000 + col.yy).alias("last_year")
).drop("yy")
echo egd.filter(col.country == "IT").sort("gor", descending = true).head(5)
shape: (5, 9)
┌──────────┬──────────────────┬─────────┬──────┬───────┬──────┬─────────────┬──────────┬───────────┐
│ pin      ┆ name             ┆ country ┆ club ┆ grade ┆ gor  ┆ tournaments ┆ last     ┆ last_year │
│ ---      ┆ ---              ┆ ---     ┆ ---  ┆ ---   ┆ ---  ┆ ---         ┆ ---      ┆ ---       │
│ i64      ┆ str              ┆ str     ┆ str  ┆ str   ┆ i64  ┆ i64         ┆ str      ┆ i64       │
╞══════════╪══════════════════╪═════════╪══════╪═══════╪══════╪═════════════╪══════════╪═══════════╡
│ 10725682 ┆ Shigeno Yuki     ┆ IT      ┆ Mila ┆ 2p    ┆ 2717 ┆ 5           ┆ T050719A ┆ 2005      │
│ 17886946 ┆ Bernardis Davide ┆ IT      ┆ Faen ┆ 6d    ┆ 2561 ┆ 110         ┆ T261024B ┆ 2026      │
│ 16762284 ┆ Shakhov Kim      ┆ IT      ┆ Mila ┆ 5d    ┆ 2542 ┆ 125         ┆ T261024B ┆ 2026      │
│ 10950643 ┆ Marigo Francesco ┆ IT      ┆ Mila ┆ 5d    ┆ 2497 ┆ 181         ┆ T260926E ┆ 2026      │
│ 15049650 ┆ Pace Alessandro  ┆ IT      ┆ Roma ┆ 5d    ┆ 2495 ┆ 194         ┆ T261024B ┆ 2026      │
└──────────┴──────────────────┴─────────┴──────┴───────┴──────┴─────────────┴──────────┴───────────┘

How does Italy compare? Ratings work like chess Elo: 2100 is about 1 dan, and every 100 points is one grade. Among players active in the last five years:

echo egd.filter(col.last_year >= 2021).groupBy("country").agg(
  len().alias("players"), (col.gor >= 2050).sum.alias("dan"), col.gor.median.alias("median_gor"),
).filter(col.players >= 300).sort("players", descending = true).head(10)
shape: (10, 4)
┌─────────┬─────────┬─────┬────────────┐
│ country ┆ players ┆ dan ┆ median_gor │
│ ---     ┆ ---     ┆ --- ┆ ---        │
│ str     ┆ u32     ┆ u32 ┆ f64        │
╞═════════╪═════════╪═════╪════════════╡
│ FR      ┆ 2137    ┆ 202 ┆ 1213.000   │
│ DE      ┆ 1960    ┆ 283 ┆ 1353.500   │
│ RU      ┆ 1776    ┆ 139 ┆ 392.000    │
│ TR      ┆ 1106    ┆ 45  ┆ 359.500    │
│ UK      ┆ 980     ┆ 204 ┆ 1410.500   │
│ RO      ┆ 591     ┆ 62  ┆ 317.000    │
│ PL      ┆ 501     ┆ 43  ┆ 1027.000   │
│ KG      ┆ 440     ┆ 1   ┆ -84.000    │
│ IT      ┆ 426     ┆ 28  ┆ 1023.000   │
│ NL      ┆ 417     ┆ 100 ┆ 1661.000   │
└─────────┴─────────┴─────┴────────────┘

16. The champions today, in a spreadsheet↑ contents

Joining the roll of honour with the database gives each champion's current rating and the number of tournaments they have played: some won the title and then stopped, others are still playing forty years later. EGD writes names last name first, so we flip ours.

let championCards = titles
  .withColumns(col.player.str.replace(r"^(\S+) (.+)$", "$2 $1").alias("name"))
  .join(egd.filter(col.country.isIn(["IT", "DE"])), on = ["name"], how = Left, maintainOrder = MaintainOrderJoin.Left)
  .select("player", "titles", "first", "last", "grade", "gor", "tournaments", "last_year")
echo championCards
shape: (14, 8)
┌────────────────────┬────────┬───────┬──────┬───────┬──────┬─────────────┬───────────┐
│ player             ┆ titles ┆ first ┆ last ┆ grade ┆ gor  ┆ tournaments ┆ last_year │
│ ---                ┆ ---    ┆ ---   ┆ ---  ┆ ---   ┆ ---  ┆ ---         ┆ ---       │
│ str                ┆ i64    ┆ i64   ┆ i64  ┆ str   ┆ i64  ┆ i64         ┆ i64       │
╞════════════════════╪════════╪═══════╪══════╪═══════╪══════╪═════════════╪═══════════╡
│ Francesco Marigo   ┆ 10     ┆ 2001  ┆ 2012 ┆ 5d    ┆ 2497 ┆ 181         ┆ 2026      │
│ Ramon Soletti      ┆ 6      ┆ 1991  ┆ 1999 ┆ 2d    ┆ 2145 ┆ 122         ┆ 2026      │
│ Alessandro Pace    ┆ 6      ┆ 2013  ┆ 2020 ┆ 5d    ┆ 2495 ┆ 194         ┆ 2026      │
│ Enzo Burlini       ┆ 5      ┆ 1981  ┆ 2000 ┆ 2d    ┆ 2171 ┆ 9           ┆ 2001      │
│ Davide Bernardis   ┆ 4      ┆ 2021  ┆ 2025 ┆ 6d    ┆ 2561 ┆ 110         ┆ 2026      │
│ Sergio Parimbelli  ┆ 3      ┆ 1982  ┆ 1988 ┆ 2k    ┆ 1926 ┆ 13          ┆ 2018      │
│ …                  ┆ …      ┆ …     ┆ …    ┆ …     ┆ …    ┆ …           ┆ …         │
│ Davide Minieri     ┆ 2      ┆ 2007  ┆ 2008 ┆ 3d    ┆ 2320 ┆ 137         ┆ 2025      │
│ Roberto Mercadante ┆ 1      ┆ 1980  ┆ 1980 ┆ 1d    ┆ 2057 ┆ 1           ┆ 2001      │
│ Fulvio Savagnone   ┆ 1      ┆ 1985  ┆ 1985 ┆ 2k    ┆ 1920 ┆ 28          ┆ 2017      │
│ Marco Vajani       ┆ 1      ┆ 1989  ┆ 1989 ┆ 3d    ┆ 2155 ┆ 19          ┆ 2004      │
│ Matias Pankoke     ┆ 1      ┆ 2015  ┆ 2015 ┆ 6d    ┆ 2573 ┆ 141         ┆ 2026      │
│ Kim Shakhov        ┆ 1      ┆ 2017  ┆ 2017 ┆ 5d    ┆ 2542 ┆ 125         ┆ 2026      │
└────────────────────┴────────┴───────┴──────┴───────┴──────┴─────────────┴───────────┘

Spreadsheets are where results like this end up, so 0.6 also writes and reads Excel files. write_excel makes a real .xlsx with a header row and autofit columns, and read_excel reads a sheet back.

championCards.writeExcel("italian_champions.xlsx", worksheet = "champions", autofit = true)
let back = readExcel("italian_champions.xlsx", sheetName = "champions")
assertFrameEqual(back, championCards, checkDtypes = false)
echo back.shape
(14, 8)

Afterword↑ contents

Go players say that the board holds more positions than there are atoms in the universe; a laptop with Polars can still hold every game humans have played on it. In this post Nanuq streamed an 8 GB file it could not read at once, saved a query and used it again on other data, counted komi in exact half points, searched moves stored as bytes, hashed positions with XOR, replayed four thousand games in a Nim callback, and moved tables in and out of SQLite and Excel.

AlphaGo retired in 2017. Its move 37 is still being played.

What this post used from Nanuq 0.6↑ contents

The Python twin of this post, which recorded the outputs it is checked against, is blog/go/go.py; the figures are in plots.nim and figs.py, the go engine in goboard.nim and goboard.py; the data preparation scripts are in src/.

Sources: Andries Brouwer's database of professional go games (homepages.cwi.nl/~aeb/go/games); all public games on online-go.com, collected by Zachary Vance with the permission of OGS (za3k.com/ogs); the roll of honour and news of the Federazione Italiana Giuoco Go (figg.org); the player list of the European Go Database (europeangodatabase.eu). Downloaded on 1 November 2026.

Source files↑ contents

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

docs/blog/go/go.py 769 lines
# %% [markdown]
# # Move 37
#
# *Nanuq 0.6 explainer, Python draft (py-polars 2.1). Every cell below will become a Nim
# block in the post, written against the 0.6 API. The outputs here are what the Nim
# version must print.*
#
# On 10 March 2016, in the second game of a five-game match in Seoul, the program AlphaGo
# played its 37th move on the fifth line from the right edge of the board, a shoulder hit
# that no strong human player would have chosen. Commentators thought it was a mistake.
# Lee Sedol, one of the best players of his generation, left the room for fifteen minutes.
# AlphaGo won that game, and the match 4 to 1, and the way people play go has not been the
# same since.
#
# Go is a board game for two players, older than chess, simple to state and very hard to
# master. Its games are also very good data: every game is a list of moves, every move a
# point on a grid, and players have been writing games down for four hundred years.
# Online servers record millions more every year.
#
# That makes go a nice playground for what is new in Nanuq 0.6, which is about how
# queries run and how data gets in and out: **streaming** a file too big for memory and
# **sinking** the result to Parquet, **saving queries** to reuse them, exact **Decimal**
# numbers, **Binary** columns and **bitwise** operations, fast **Nim callbacks** on Arrow
# data, **databases** and **Excel** files, and **testing helpers** to check that two
# frames agree.
#
# The story has four parts. First, 98,000 games played by Japanese professionals from
# the seventeenth century to last month. Then 2.8 million games played by amateurs on
# the Online Go Server. Then a tiny go engine, written as a callback. And last, a look at
# the champions of Italian go.
#
# Data, all public, downloaded on 1 November 2026: Andries Brouwer's database of
# professional games (homepages.cwi.nl/~aeb/go/games); the dump of all public games on
# online-go.com put together by Zachary Vance with OGS's permission (za3k.com/ogs); the
# roll of honour of the Italian Go Federation (figg.org); the player list of the European
# Go Database (europeangodatabase.eu).

# %%
# id: setup
import polars as pl

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

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

# %% [markdown]
# ## Part 1: Ninety-eight thousand professional games
#
# ## 1. The board, the stones, the rules
#
# Go is played on a grid of 19 by 19 lines. Black and White take turns placing one stone
# on an empty intersection; stones never move after that. Stones of the same colour that
# touch along the lines form a group, and a group whose last empty neighbouring point
# (its last *liberty*) is filled by the opponent is captured and taken off the board. At
# the end, each player counts the area they surround. Black moves first, which is an
# advantage, so White gets a few points of compensation, called *komi*.
#
# Games are written down in SGF, a plain-text format where a move is two letters, the
# column and the row, from `a` (left, top) to `s` (right, bottom). `pd` is the fourth
# point from the right and the fourth from the top. Our database packs the moves of each
# game into one **Binary** value, two bytes per move. Binary columns are new in 0.6.
#
# What is in it: the SGF letters themselves, one byte each, so `pd` is the two bytes 112
# and 100. A String column would have worked just as well; we use Binary to try out the
# new type. It does fit the job: move *n* always sits at bytes 2*n* and 2*n*+1, `bin.get`
# hands back a byte as a number (`a` is 97, so a column is the byte minus 97), and
# looking for an opening is a prefix match on bytes.

# %%
# id: s01_read
pro = pl.read_parquet("data/pro_games.parquet")
pro.select("file", "DT", "PB", "PW", "KM", "RE", "moves").glimpse(max_items_per_column=2)

# %% [markdown]
# To draw a game we turn the bytes into points. `bin.size` tells how many bytes there
# are; the bytes come out one by one with `bin.get`. Here are the first 37 moves of the
# second game between AlphaGo (Black) and Lee Sedol (White).

# %%
# id: s01_points
game2 = pro.filter(pl.col("file") == "AlphaGo/LeeSedol/2.sgf")
first37 = (
    game2.select(pl.int_range(0, 37).alias("move"), pl.col("moves").first())
    .select(
        move=pl.col("move") + 1,
        color=pl.when(pl.col("move") % 2 == 0).then(pl.lit("B")).otherwise(pl.lit("W")),
        x=pl.col("moves").bin.get(pl.col("move") * 2).cast(pl.Int64) - 97,
        y=pl.col("moves").bin.get(pl.col("move") * 2 + 1).cast(pl.Int64) - 97,
    )
)
first37.tail(4)

# %%
# id: fig_move37
figs.board(first37, "AlphaGo vs Lee Sedol, game 2, moves 1 to 37",
           labels=first37.select("x", "y", text=pl.col("move").cast(pl.String),
                                 fg=pl.when(pl.col("color") == "B").then(pl.lit("white")).otherwise(pl.lit("black"))))

# %% [markdown]
# Move 37 is the black stone at P10, alone in the middle of the right side. Moves near the
# edge, on the third line, take territory; moves on the fourth line build influence
# towards the centre. A stone on the fifth line, this early, gives White an easy third
# line underneath. Michael Redmond, commentating in English, called it "a very surprising
# move". Fan Hui, who had lost to AlphaGo five months earlier: "It's not a human move.
# I've never seen a human play this move."
#
# ## 2. Komi, exactly
#
# How many points should White get for moving second? Go has argued about it for a
# century. Old Japanese games have no komi at all; komi appeared in the 1930s, and
# professionals went from 4.5 to 5.5, 6.5 and in China 7.5 points. The half point is there
# so that a game cannot end in a tie.
#
# Half points are exactly the kind of number that floating point gets almost right.
# **Decimal** columns, new in 0.6, store them exactly: `str.to_decimal(scale=1)` reads
# the `KM` property as a number with one digit after the point.

# %%
# id: s02_komi
games = (
    pro.filter(pl.col("SZ").is_null() | (pl.col("SZ") == "19"), pl.col("HA").is_null())
    .with_columns(
        year=pl.col("DT").str.extract(r"^(\d{4})").cast(pl.Int64),
        komi=pl.col("KM").str.strip_chars().str.to_decimal(scale=1),
        winner=pl.col("RE").str.extract(r"^([BW])\+"),
        margin=pl.col("RE").str.extract(r"^[BW]\+(\d+(?:\.\d)?)$").str.to_decimal(scale=1),
    )
)
games.group_by(decade=pl.col("year") // 10 * 10).agg(
    games=pl.len(), usual_komi=pl.col("komi").mode().first()
).filter(pl.col("decade") >= 1920).sort("decade")

# %% [markdown]
# Did it work? With komi 0, Black won 58% of the decisive games. Each extra point of
# komi took away about two and a half points of percentage, and at 6.5 the game is a
# coin toss: 50.2%.

# %%
# id: s02_fair
fair = (
    games.filter(pl.col("winner").is_not_null())
    .group_by("komi")
    .agg(games=pl.len(), black_wins=(pl.col("winner") == "B").mean())
    .filter(pl.col("games") >= 300, pl.col("komi").is_not_null())
    .sort("komi")
)
fair

# %%
# id: fig_komi
figs.bars(fair.with_columns(label=pl.col("komi").cast(pl.String)), "label", "black_wins",
          "How often Black wins, by komi (professional games, no handicap)", "Black wins",
          text=None, yformat=".0%")

# %% [markdown]
# A whole-number komi such as 5 can end in a draw, called *jigo*. Decimals make the
# test exact: a komi is whole when `komi == komi.floor()`, and the margins of half-point komi
# games always end in `.5`.

# %%
# id: s02_jigo
games.filter(pl.col("komi").is_not_null()).group_by(
    whole_komi=pl.col("komi") == pl.col("komi").floor()
).agg(
    games=pl.len(),
    draws=(pl.col("RE") == "Jigo").sum(),
    half_point_wins=(pl.col("margin") == pl.lit("0.5").str.to_decimal(scale=1)).sum(),
).sort("whole_komi")

# %% [markdown]
# ## 3. Where the first stone goes
#
# The board has eight symmetries (four rotations, each with a mirror image), so the
# opening move at `pd` and the one at `dp` are the same move. We fold every first move
# into one corner by counting lines from the nearest edge: a stone on the third line from
# one edge and the fourth from the other is a *3-4 point*, the classic *komoku*; the
# *4-4 point* is *hoshi*, a star point.

# %%
# id: s03_first
def line_from_edge(byte):
    v = pl.col("moves").bin.get(byte).cast(pl.Int64) - 97 + 1
    return pl.min_horizontal(v, 20 - v)

first = (
    games.filter(pl.col("moves").bin.size() >= 2, pl.col("year").is_not_null())
    .with_columns(a=line_from_edge(0), b=line_from_edge(1))
    .with_columns(
        point=pl.format("{}-{}", pl.min_horizontal("a", "b"), pl.max_horizontal("a", "b")),
        era=pl.when(pl.col("year") <= 1867).then(pl.lit("1: Edo, to 1867"))
        .when(pl.col("year") <= 1945).then(pl.lit("2: 1868-1945"))
        .when(pl.col("year") <= 1990).then(pl.lit("3: 1946-1990"))
        .when(pl.col("year") <= 2016).then(pl.lit("4: 1991-2016"))
        .otherwise(pl.lit("5: AI era, 2017-")),
    )
)
first.group_by("era", "point").len().with_columns(
    share=pl.col("len") / pl.col("len").sum().over("era")
).filter(pl.col("share") > 0.02).sort("era", "share", descending=[False, True])

# %% [markdown]
# In the Edo period nearly nine games in ten opened on a 3-4 point. The 4-4 point took
# over in the twentieth century, with the "New Opening" of Go Seigen and Kitani Minoru in
# the 1930s and, later, with komi: a fast, open style pays when Black has points to give
# back.

# %%
# id: fig_first
freq = (
    first.with_columns(
        x=pl.col("moves").bin.get(0).cast(pl.Int64) - 97,
        y=pl.col("moves").bin.get(1).cast(pl.Int64) - 97,
        panel=pl.col("era").str.slice(3),
    )
    .group_by("panel", "x", "y").len()
    .with_columns(share=pl.col("len") / pl.col("len").sum().over("panel"))
)
figs.heat_boards(freq, ["Edo, to 1867", "1868-1945", "1946-1990", "1991-2016", "AI era, 2017-"],
                 "Where Black puts the first stone")

# %% [markdown]
# The heatmaps also show a habit: Black's first stone goes in the top-right corner, from
# Black's point of view. It is a courtesy, leaving the corner nearest to the opponent's
# right hand free.
#
# ## 4. Searching the moves
#
# A Binary column can be searched without decoding it. `bin.starts_with` finds games by
# their first moves, `bin.slice` cuts out a few bytes, and `bin.encode` shows bytes as
# hexadecimal text (`70 64` is `p d`). Before AlphaGo, the most common start was Black
# at `pd` and White at `dd`, the two top corners; since 2017 it is `pd` and `dp`.

# %%
# id: s04_search
games.filter(pl.col("moves").bin.size() >= 4, pl.col("year").is_not_null()).group_by(
    after_alphago=pl.col("year") >= 2017
).agg(
    games=pl.len(),
    start_pd=pl.col("moves").bin.starts_with(b"pd").mean(),
    start_pddp=pl.col("moves").bin.starts_with(b"pddp").mean(),
    common_start=pl.col("moves").bin.slice(0, 4).mode().first(),
    as_hex=pl.col("moves").bin.slice(0, 4).bin.encode("hex").mode().first(),
).sort("after_alphago")

# %% [markdown]
# ## 5. The 3-3 invasion
#
# The clearest trace AlphaGo left on human play is in the corners. When one side holds a
# 4-4 point, the other can slide in underneath at the 3-3 point and live in the corner.
# Textbooks said this was fine *late* in the game, but giving the opponent a wall this
# early was bad style. AlphaGo did it at once, and won. Within a year everybody did.
#
# We write the test as one expression: a game has an early 3-3 invasion if, in its first
# twelve moves, some corner has both its 4-4 point and the 3-3 point beneath it. Moves come
# out of the Binary column as a list of two-letter strings.

# %%
# id: s05_invasion
moves12 = pl.col("moves").bin.slice(0, 24).cast(pl.String).str.extract_all("..")
early_33 = pl.any_horizontal(
    moves12.list.contains(hoshi) & moves12.list.contains(san_san)
    for hoshi, san_san in [("dd", "cc"), ("pd", "qc"), ("dp", "cq"), ("pp", "qq")]
).alias("early_33")
invasions = (
    games.filter(pl.col("year") >= 1990)
    .group_by("year")
    .agg(games=pl.len(), early_33=early_33.mean())
    .sort("year")
)
invasions.tail(13)

# %% [markdown]
# Between 1990 and 2017, a bit more than a game in five had an early 3-3 point next to a
# star point (some were the old, slow kind of invasion, or a 3-3 point played first). In
# 2018, a year after AlphaGo's 60 online wins against top professionals, it jumped to
# almost a game in two, and it stayed there.

# %%
# id: fig_invasion
figs.lines(invasions, "year", [("early_33", "early 3-3 invasions", "#b4462b")],
           "Professional games with a 3-3 invasion in the first 12 moves", "share of games",
           events=[(2016.2, "AlphaGo-Lee Sedol"), (2017.0, "AlphaGo Master online")], yformat=".0%")

# %% [markdown]
# We will want the same yardstick for amateurs in Part 2. Expressions can now be
# **serialized**: `meta.serialize` turns one into JSON (or a compact binary form), and
# `pl.Expr.deserialize` brings it back, in another script or another language. We save
# `early_33` to a file.

# %%
# id: s05_save
open("early_33.json", "w").write(early_33.meta.serialize(format="json"))
pl.Expr.deserialize("early_33.json", format="json").meta.output_name()

# %% [markdown]
# ## 6. Same position, different order
#
# Players reach the same opening position along different move orders. To find them,
# go programs give every position a *Zobrist hash*: draw one random 64-bit number for each
# point and colour, and XOR together the numbers of the stones on the board. XOR is
# commutative, so the order of moves doesn't matter, and two different positions almost
# never get the same hash. (A capture would XOR a stone away again; there are none this
# early.)
#
# **Bitwise** operations are new in 0.6. `bitwise_xor` is an aggregation, so the hash of
# each game's first ten moves is a `group_by`.

# %%
# id: s06_zobrist
keys = pl.read_csv("data/zobrist.csv", schema_overrides={"point": pl.Int64, "key": pl.UInt64})
openings = (
    games.filter(pl.col("moves").bin.size() >= 20, pl.col("year") >= 1990)
    .select("file", "year", mv=pl.col("moves").bin.slice(0, 20).cast(pl.String).str.extract_all(".."))
    .with_columns(color=pl.lit(["B", "W"] * 5))
    .explode("mv", "color")
    .with_columns(point=(pl.col("mv").str.slice(1, 1).str.to_integer(base=36) - 10) * 19
                  + pl.col("mv").str.slice(0, 1).str.to_integer(base=36) - 10)
    .join(keys, on=["point", "color"], maintain_order="left")
    .group_by("file", "year")
    .agg(zobrist=pl.col("key").bitwise_xor(), order=pl.col("mv").str.join(""))
)
openings.sort("file").head(3)

# %% [markdown]
# Grouping by the hash shows the most played positions after ten moves since 1990, and
# how many different move orders led to each.

# %%
# id: s06_top
top = (
    openings.group_by("zobrist")
    .agg(games=pl.len(), orders=pl.col("order").n_unique(), example=pl.col("order").mode().first(),
         first_year=pl.col("year").min(), last_year=pl.col("year").max())
    .sort("games", descending=True)
    .head(5)
)
top.with_columns(hash=pl.col("zobrist").cast(pl.String)).drop("zobrist")

# %% [markdown]
# Good keys are random bits. `bitwise_count_ones` counts the bits set to 1 (we expect
# about half of 64), `bitwise_leading_zeros` counts the zero bits at the front, and the
# aggregations `bitwise_and` and `bitwise_or` keep the bits that are set in all keys, or in
# any key.

# %%
# id: s06_bits
keys.select(
    mean_ones=pl.col("key").bitwise_count_ones().mean(),
    min_ones=pl.col("key").bitwise_count_ones().min(),
    max_ones=pl.col("key").bitwise_count_ones().max(),
    leading_zeros_max=pl.col("key").bitwise_leading_zeros().max(),
    all_and=pl.col("key").bitwise_and(),
    all_or_ones=pl.col("key").bitwise_or().bitwise_count_ones(),
)

# %% [markdown]
# ## Part 2: Two point eight million amateur games
#
# ## 7. A file too big to read
#
# The Online Go Server (OGS) has been running since 2005. Its complete public record, 56
# million games up to May 2025, comes as a single 46 GB gzipped file with one JSON object
# per line: 200 GB once unpacked, far more than the memory of a laptop. We streamed it
# once over the network and kept every twentieth line: **2,820,649 games** in a 10.3 GB
# NDJSON file. That is still too big to read comfortably, which is the point.
#
# The post ships the first 2,000 lines of that file, so every cell below runs. Each line
# is the raw API record of one game: players with their ranks, board size, komi, rules,
# clock settings, the outcome and the moves.
#
# Let Polars guess the types, and it gives up: the same field holds a boolean on one line
# and a number on another.

# %%
# id: s07_guess
try:
    pl.read_ndjson("data/ogs_slice.ndjson")
except pl.exceptions.ComputeError as e:
    print("read failed:", str(e).split("'")[0].strip(), "...")

# %% [markdown]
# So we say what we want, as a schema, and leave the rest out. The other fields, more
# than a hundred, are never even parsed. `ignore_errors` turns the few values that don't
# fit into nulls.

# %%
# id: s07_schema
player = pl.Struct({"username": pl.String, "rank": pl.Float64, "professional": pl.Boolean})
schema = {
    "game_id": pl.Int64, "start_time": pl.Int64, "width": pl.Int64, "height": pl.Int64,
    "handicap": pl.Int64, "komi": pl.Float64, "rules": pl.String, "outcome": pl.String,
    "winner": pl.Int64, "black_player_id": pl.Int64,
    "players": pl.Struct({"black": player, "white": player}),
    "time_control": pl.Struct({"speed": pl.String}),
    "moves": pl.List(pl.List(pl.Int64)),
}
raw = pl.scan_ndjson("data/ogs_slice.ndjson", schema=schema, ignore_errors=True)
raw.head(3).collect()

# %% [markdown]
# ## 8. Streaming into Parquet
#
# Now the query: one row per game, with the start as a datetime, the board size, komi as
# a Decimal, the two ranks, the result, the number of moves, and the first twelve moves
# turned into the same two-letter Binary form as the professional games. OGS gives a
# move as `[x, y, milliseconds]`, and `[-1, -1, ...]` for a pass.
#
# OGS ranks are numbers: 30 is 1 dan, 29 is 1 kyu, 20 is 10 kyu. Kyu grades go down as
# players get stronger, from 30 kyu (a beginner) to 1 kyu; then dan grades go up, from 1
# to about 9 dan for amateurs.

# %%
# id: s08_query
letters = "abcdefghijklmnopqrstuvwxyz"
def sgf_letter(i):
    return pl.when(i >= 0).then(pl.lit(letters).str.slice(i, 1)).otherwise(pl.lit("t"))

ogs = raw.filter(pl.col("width") == pl.col("height")).select(
    "game_id",
    started=pl.from_epoch("start_time", time_unit="s"),
    size="width",
    handicap="handicap",
    komi=pl.col("komi").cast(pl.Decimal(10, 1)),
    rules=pl.col("rules").str.to_lowercase(),
    speed=pl.col("time_control").struct.field("speed"),
    black_rank=pl.col("players").struct.field("black").struct.field("rank"),
    white_rank=pl.col("players").struct.field("white").struct.field("rank"),
    outcome="outcome",
    winner=pl.when(pl.col("winner") == pl.col("black_player_id")).then(pl.lit("B"))
    .when(pl.col("winner").is_not_null()).then(pl.lit("W")),
    n_moves=pl.col("moves").list.len(),
    moves=pl.col("moves").list.head(12).list.eval(
        sgf_letter(pl.element().list.get(0)) + sgf_letter(pl.element().list.get(1))
    ).list.join("").cast(pl.Binary),
)
ogs.head(0).collect()

# %% [markdown]
# Nothing has run yet: `ogs` is a lazy query, and collecting zero rows of it only shows
# its columns. The new **streaming engine** runs it in
# batches, so memory stays flat however big the file is, and `sink_parquet` writes the
# result straight to disk without ever building the whole table. On the 10.3 GB file
# (on a 4-core machine with 15 GB of memory) the streaming run took 75 seconds and 0.13 GB
# of working memory. The same query collected in memory took 89 seconds and 11.8 GB.
# Here it is on the slice.

# %%
# id: s08_sink
ogs.sink_parquet("ogs_slice.parquet", engine="streaming")
pl.scan_parquet("ogs_slice.parquet").select(
    games=pl.len(), first=pl.col("started").min(), last=pl.col("started").max()
).collect()

# %% [markdown]
# Is the streamed result the same as an ordinary in-memory run? The new **testing
# helpers** answer with one line: `assert_frame_equal` raises an error that points at the
# first difference, and returns quietly when there is none.

# %%
# id: s08_check
from polars.testing import assert_frame_equal
assert_frame_equal(pl.read_parquet("ogs_slice.parquet"), ogs.collect(engine="in-memory"))
print("streaming and in-memory results agree")

# %% [markdown]
# ## 9. Growth, AlphaGo and the lockdowns
#
# The streamed table of all 2.8 million games is 80 MB of Parquet. To keep the post
# small we ship every fifth game of it: 563,622 games, a 1% sample of everything played on
# OGS. Two moments stand out in the number of games started each month: March 2016, the week AlphaGo beat
# Lee Sedol, and spring 2020, when half the world was told to stay home.

# %%
# id: s09_months
games_ogs = pl.read_parquet("data/ogs_games.parquet")
monthly = games_ogs.group_by(month=pl.col("started").dt.truncate("1mo").dt.date()).len().sort("month")
monthly.filter(pl.col("month").is_between(pl.date(2016, 1, 1), pl.date(2016, 6, 1))
               | pl.col("month").is_between(pl.date(2020, 1, 1), pl.date(2020, 6, 1)))

# %% [markdown]
# March 2016 had twice the games of February. The lockdowns of 2020 did more, and for
# longer: from March the number of games grew by half and stayed high all year.

# %%
# id: fig_months
figs.lines(monthly.with_columns(games=pl.col("len") * 100), "month",
           [("games", "games per month (estimated: 1% sample × 100)", "#8c5a2b")],
           "Games started on OGS each month", "games",
           events=[("2016-03-09", "AlphaGo-Lee Sedol"), ("2020-03-15", "lockdowns")], mode="lines")

# %% [markdown]
# ## 10. Small boards, fast games
#
# Online, half the games are on smaller boards: 9×9 games last ten minutes and teach the
# tactics, 13×13 is a step towards the full board. Most games are played live, the rest by
# correspondence, a move a day.

# %%
# id: s10_sizes
games_ogs.filter(pl.col("size").is_in([9, 13, 19])).group_by("size").agg(
    games=pl.len(),
    share=pl.len() / games_ogs.height,
    median_moves=pl.col("n_moves").median(),
    blitz_or_live=pl.col("speed").is_in(["blitz", "live"]).mean(),
).sort("size")

# %% [markdown]
# ## 11. Does the stronger player win?
#
# Ranks are supposed to predict results. We take even games (no handicap) on the full
# board that ended with a winner, and group them by the rank difference between the two
# players, rounded to whole grades.

# %%
# id: s11_gap
even = games_ogs.filter(
    pl.col("size") == 19, pl.col("handicap") == 0, pl.col("winner").is_not_null(),
    pl.col("n_moves") >= 20,
).with_columns(gap=(pl.col("black_rank") - pl.col("white_rank")).round().cast(pl.Int64))
stronger = (
    even.filter(pl.col("gap") != 0)
    .group_by(grades=pl.col("gap").abs())
    .agg(games=pl.len(),
         stronger_wins=((pl.col("gap") > 0) == (pl.col("winner") == "B")).mean())
    .filter(pl.col("grades") <= 9)
    .sort("grades")
)
stronger

# %% [markdown]
# One grade of difference gives the stronger player 58% of the games, four grades three
# games in four, and it levels off around 80%. Ranks on a server drift, players have off
# days, and the handicap system exists for a reason: in a handicap game, the weaker
# player starts with extra stones, one for each grade of difference.

# %%
# id: fig_gap
figs.lines(stronger, "grades", [("stronger_wins", "stronger player wins", "#2b6c8f")],
           "Even games on 19×19: how often the higher-ranked player wins", "share of games",
           yformat=".0%")

# %% [markdown]
# ## 12. Do amateurs play like AlphaGo?
#
# Back to the saved expression from section 5. We load `early_33` from its JSON file and
# run it on the amateur games: the same yardstick, not a copy of the code. Strong
# amateurs (dan grades, rank 30 and up) and weaker ones (kyu grades), year by year, for
# years with at least 50 such games.

# %%
# id: s12_amateurs
early_33_saved = pl.Expr.deserialize("early_33.json", format="json")
amateurs = (
    games_ogs.filter(pl.col("size") == 19, pl.col("handicap") == 0, pl.col("n_moves") >= 30)
    .with_columns(year=pl.col("started").dt.year(),
                  level=pl.when(pl.min_horizontal("black_rank", "white_rank") >= 30)
                  .then(pl.lit("dan")).otherwise(pl.lit("kyu")))
    .group_by("year", "level")
    .agg(games=pl.len(), early_33=early_33_saved.mean())
    .filter(pl.col("games") >= 50)
    .sort("year", "level")
)
side_by_side = amateurs.pivot("level", index="year", values="early_33").join(
    invasions.select("year", pro="early_33"), on="year", how="left", maintain_order="left").filter(pl.col("year") >= 2014)
side_by_side

# %% [markdown]
# Strong amateurs followed the professionals: under a third of their games before 2018,
# one in two from 2019. (2018 is missing because the sample has too few games between two
# dan players that year.) Kyu players had been playing early 3-3 points more than the
# professionals all along (it is the simple, safe way to take a corner) and drifted up
# slowly.

# %%
# id: fig_amateurs
figs.lines(side_by_side.filter(pl.col("year") <= 2024), "year",
           [("pro", "professionals", "#b4462b"), ("dan", "OGS, dan players", "#2b6c8f"),
            ("kyu", "OGS, kyu players", "#8fb3c9")],
           "Early 3-3 invasions: professionals and amateurs", "share of games",
           events=[(2016.2, "AlphaGo")], yformat=".0%")

# %% [markdown]
# ## Part 3: A go engine in a callback
#
# ## 13. Replaying the games
#
# The moves alone don't say what the board looks like at the end: stones get captured.
# To know, you have to play the game through, checking after every move whether a group
# has lost its last liberty. That is a loop with a flood fill inside, the kind of code no
# built-in expression covers, so it goes in a callback: a function called on each value.
#
# In Python this is `map_elements` with a function written in Python (it is in
# `goboard.py`, about forty lines), and it is slow, because Python runs the loop. In
# the Nim tab the same forty lines are Nim, compiled, and Nanuq 0.6 hands the bytes over
# through the Arrow C Data Interface without copying them.
#
# We replay the 3,997 complete games we kept (AlphaGo's, and all professional games
# since 2025) and count the stones left and the stones captured.

# %%
# id: s13_replay
import goboard

def final_counts(moves: bytes) -> dict:
    board, captured_by_black, captured_by_white = goboard.replay(moves)
    return {"black_stones": board.count(1), "white_stones": board.count(2),
            "captured": captured_by_black + captured_by_white}

full = pl.read_parquet("data/pro_full_moves.parquet")
replayed = full.with_columns(
    final=pl.col("moves").map_elements(final_counts, return_dtype=pl.Struct(
        {"black_stones": pl.Int64, "white_stones": pl.Int64, "captured": pl.Int64}))
).unnest("final")
replayed.select("file", "PB", "PW", "RE", n_moves=pl.col("moves").bin.size() // 2,
                black_stones="black_stones", white_stones="white_stones", captured="captured").sort(
    "captured", descending=True).head(5)

# %% [markdown]
# AlphaGo Zero playing itself leads the table: programs don't resign early, so their
# games go on until every last group is settled. On a laptop the Python callback takes
# about 3 seconds for these games, and the Nim one a few hundredths of a second. Here is
# the bloodiest game between humans, at the end.

# %%
# id: fig_bloodiest
bloodiest = replayed.filter(~pl.col("file").str.starts_with("AlphaGo/")).sort("captured", descending=True).head(1)
board_bytes = goboard.replay(bloodiest["moves"][0])[0]
final_stones = pl.DataFrame({"cell": list(board_bytes)}).with_row_index("p").filter(pl.col("cell") > 0).select(
    x=pl.col("p").cast(pl.Int64) % 19, y=pl.col("p").cast(pl.Int64) // 19,
    color=pl.when(pl.col("cell") == 1).then(pl.lit("B")).otherwise(pl.lit("W")))
figs.board(final_stones, f"{bloodiest['PB'][0]} (B) vs {bloodiest['PW'][0]} (W), {bloodiest['DT'][0]}: final position")

# %% [markdown]
# And a sanity check across all games: the more moves a game has, the more stones get
# captured, but the board never holds more than 361.

# %%
# id: s13_check
replayed.select(
    games=pl.len(),
    mean_moves=(pl.col("moves").bin.size() // 2).mean(),
    mean_captured=pl.col("captured").mean(),
    max_on_board=(pl.col("black_stones") + pl.col("white_stones")).max(),
    corr_moves_captured=pl.corr(pl.col("moves").bin.size(), pl.col("captured")),
)

# %% [markdown]
# ## Part 4: Italian go
#
# ## 14. Champions, in a database
#
# Italy has played go seriously since the 1970s. The Italian Go Federation (FIGG) has
# held a national championship every year since 1980; since 1992 the two best Italian
# players of the championship tournament meet in a final. The federation's roll of honour
# lists every winner, the score of the final and the runner-up. (2024 is missing from it;
# the 2025 result comes from the federation's news.)
#
# New in 0.6, frames go to and from **databases**: `write_database` creates a table,
# `read_database` runs a SQL query and returns a frame. Here we use SQLite, a database in
# a single file.

# %%
# id: s14_db
champions = pl.read_csv("data/champions.csv")
champions.write_database("champions", "sqlite:///italian_go.db", if_table_exists="replace")
titles = pl.read_database_uri(
    """
    SELECT winner AS player, COUNT(*) AS titles, MIN(year) AS first, MAX(year) AS last
    FROM champions GROUP BY winner ORDER BY titles DESC, first
    """,
    "sqlite://italian_go.db",
)
with pl.Config(tbl_rows=-1):  # all fourteen
    print(titles)

# %% [markdown]
# Fourteen champions in 45 championships, and the first six hold 34 titles between them.
# The finals are long-running rivalries: some pairs met again and again.

# %%
# id: s14_finals
pl.read_database_uri(
    """
    SELECT winner, runner_up, COUNT(*) AS finals, GROUP_CONCAT(year, ' ') AS years
    FROM champions WHERE runner_up IS NOT NULL AND runner_up <> ''
    GROUP BY winner, runner_up HAVING COUNT(*) >= 2 ORDER BY finals DESC
    """,
    "sqlite://italian_go.db",
)

# %% [markdown]
# ## 15. Fifty-six thousand players in a text file
#
# The European Go Database records every rated tournament game in Europe. Its player list
# is a plain text table with fixed-width columns: the PIN, the name (last name first),
# country, club, grade, a suggested promotion, the rating (GoR), the number of
# tournaments and the code of the last one (a letter, then the date as YYMMDD). We read each line as one string, keep the
# lines that start with a PIN, and cut them at fixed positions.

# %%
# id: s15_egd
lines = pl.read_csv("data/egd_players.txt", has_header=False, new_columns=["line"], separator="\x01").filter(
    pl.col("line").str.contains(r"^ \d{8} "))
def cut(start, length):
    return pl.col("line").str.slice(start, length).str.strip_chars()

egd = lines.select(
    pin=cut(0, 10).cast(pl.Int64),
    name=cut(11, 38).str.replace_all("_", " "),
    country=cut(49, 2),
    club=cut(53, 4),
    grade=cut(57, 6),
    gor=cut(68, 7).cast(pl.Int64),
    tournaments=cut(75, 6).cast(pl.Int64),
    last=cut(83, 8),
).with_columns(yy=pl.col("last").str.slice(1, 2).str.to_integer(strict=False)).with_columns(
    last_year=pl.when(pl.col("yy") > 50).then(1900 + pl.col("yy")).otherwise(2000 + pl.col("yy"))
).drop("yy")
egd.filter(pl.col("country") == "IT").sort("gor", descending=True).head(5)

# %% [markdown]
# How does Italy compare? Ratings work like chess Elo: 2100 is about 1 dan, and every 100
# points is one grade. Among players active in the last five years:

# %%
# id: s15_countries
egd.filter(pl.col("last_year") >= 2021).group_by("country").agg(
    players=pl.len(), dan=(pl.col("gor") >= 2050).sum(), median_gor=pl.col("gor").median(),
).filter(pl.col("players") >= 300).sort("players", descending=True).head(10)

# %% [markdown]
# ## 16. The champions today, in a spreadsheet
#
# Joining the roll of honour with the database gives each champion's current rating and
# the number of tournaments they have played: some won the title and then stopped, others
# are still playing forty years later. EGD writes names last name first, so we flip ours.

# %%
# id: s16_join
champion_cards = (
    titles.with_columns(name=pl.col("player").str.replace(r"^(\S+) (.+)$", "$2 $1"))
    .join(egd.filter(pl.col("country").is_in(["IT", "DE"])), on="name", how="left", maintain_order="left")
    .select("player", "titles", "first", "last", "grade", "gor", "tournaments", "last_year")
)
champion_cards

# %% [markdown]
# Spreadsheets are where results like this end up, so 0.6 also writes and reads **Excel**
# files. `write_excel` makes a real `.xlsx` with a header row and autofit columns, and
# `read_excel` reads a sheet back.

# %%
# id: s16_excel
champion_cards.write_excel("italian_champions.xlsx", worksheet="champions", autofit=True)
back = pl.read_excel("italian_champions.xlsx", sheet_name="champions")
assert_frame_equal(back, champion_cards, check_dtypes=False)
back.shape

# %% [markdown]
# ## Afterword
#
# Go players say that the board holds more positions than there are atoms in the
# universe; a laptop with Polars can still hold every game humans have played on it. In
# this post Nanuq streamed an 8 GB file it could not read at once, saved a query and used
# it again on other data, counted komi in exact half points, searched moves stored as
# bytes, hashed positions with XOR, replayed four thousand games in a Nim callback, and
# moved tables in and out of SQLite and Excel.
#
# AlphaGo retired in 2017. Its move 37 is still being played.

docs/blog/go/go.py

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

SAVE_PATH = None
KAYA = "#dcb468"
STARS = [3, 9, 15]
COLS = "ABCDEFGHJKLMNOPQRST"  # go boards skip the letter I

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

def _grid(fig, size=19, row=None, col=None, xref="x", yref="y"):
    """Board lines and star points; x = column 0..18 left to right, y = row 0..18 top down."""
    fig.add_shape(type="rect", x0=-0.8, x1=size - 0.2, y0=-0.8, y1=size - 0.2, xref=xref, yref=yref,
                  fillcolor=KAYA, line=dict(width=0), layer="below")
    for i in range(size):
        fig.add_shape(type="line", x0=0, x1=size - 1, y0=i, y1=i, xref=xref, yref=yref,
                      line=dict(color="#3b2f1e", width=1), layer="below")
        fig.add_shape(type="line", x0=i, x1=i, y0=0, y1=size - 1, xref=xref, yref=yref,
                      line=dict(color="#3b2f1e", width=1), layer="below")
    stars = [(x, y) for x in STARS for y in STARS] if size == 19 else []
    return go.Scatter(x=[p[0] for p in stars], y=[p[1] for p in stars], mode="markers",
                      marker=dict(size=6, color="#3b2f1e"), hoverinfo="skip", showlegend=False)

def _axes(fig, size=19, **kw):
    fig.update_xaxes(range=[-1, size], showgrid=False, zeroline=False, tickvals=list(range(size)),
                     ticktext=list(COLS[:size]), side="top", constrain="domain", **kw)
    fig.update_yaxes(range=[size, -1], showgrid=False, zeroline=False, tickvals=list(range(size)),
                     ticktext=[str(size - i) for i in range(size)], scaleanchor="x" if not kw else None,
                     constrain="domain", **kw)

def board(stones, title, labels=None, size=19, height=560):
    """stones: frame with x, y, color ("B"/"W"); labels: optional frame x, y, text."""
    fig = go.Figure()
    fig.add_trace(_grid(fig, size))
    for c, fill, line in [("B", "#111111", "#000000"), ("W", "#f8f8f4", "#555555")]:
        s = stones.filter(stones["color"] == c)
        fig.add_trace(go.Scatter(x=s["x"], y=s["y"], mode="markers", name="black" if c == "B" else "white",
                                 marker=dict(size=height / (size + 2) * 0.9, color=fill, line=dict(width=1, color=line)),
                                 hoverinfo="skip", showlegend=False))
    if labels is not None:
        fig.add_trace(go.Scatter(x=labels["x"], y=labels["y"], text=labels["text"], mode="text",
                                 textfont=dict(color=labels["fg"].to_list(), size=11), hoverinfo="skip", showlegend=False))
    fig.update_layout(title=title, height=height, width=height - 20, plot_bgcolor="white")
    _axes(fig, size)
    _out(fig)

def heat_boards(freq, panels, title, height=330):
    """freq: frame with panel, x, y, share; one 19x19 heatmap per panel, side by side."""
    fig = make_subplots(rows=1, cols=len(panels), subplot_titles=panels, horizontal_spacing=0.03)
    zmax = freq["share"].max()
    for i, p in enumerate(panels):
        f = freq.filter(freq["panel"] == p)
        z = [[0.0] * 19 for _ in range(19)]
        for x, y, s in zip(f["x"], f["y"], f["share"]):
            z[y][x] = s
        fig.add_trace(go.Heatmap(z=z, x=list(range(19)), y=list(range(19)), zmin=0, zmax=zmax,
                                 colorscale=[[0, "#f3e3bd"], [0.25, "#e0a84f"], [0.6, "#b4462b"], [1, "#3a0f12"]],
                                 showscale=(i == len(panels) - 1), hovertemplate="%{z:.1%}<extra></extra>",
                                 colorbar=dict(tickformat=".0%", len=0.8)), row=1, col=i + 1)
        fig.update_xaxes(range=[-0.5, 18.5], showticklabels=False, showgrid=False, zeroline=False,
                         constrain="domain", row=1, col=i + 1)
        fig.update_yaxes(range=[18.5, -0.5], showticklabels=False, showgrid=False, zeroline=False,
                         constrain="domain", scaleanchor=f"x{i + 1 if i else ''}", row=1, col=i + 1)
    fig.update_layout(title=title, height=height, plot_bgcolor="#f3e3bd")
    _out(fig)

def lines(df, x, ys, title, ytitle, events=(), yformat=None, height=420, mode="lines+markers"):
    fig = go.Figure()
    for y, name, color in ys:
        fig.add_trace(go.Scatter(x=df[x], y=df[y], name=name, mode=mode, line=dict(color=color)))
    for ex, text in events:
        fig.add_shape(type="line", x0=ex, x1=ex, y0=0, y1=1, yref="paper", line=dict(color="#999", dash="dot"))
        fig.add_annotation(x=ex, y=1, yref="paper", text=text, showarrow=False, yanchor="bottom",
                           font=dict(size=11, color="#555"))
    fig.update_layout(title=title, height=height, yaxis_title=ytitle, legend=dict(orientation="h", y=-0.15))
    if yformat:
        fig.update_yaxes(tickformat=yformat)
    _out(fig)

def bars(df, x, y, title, ytitle, color="#8c5a2b", text=None, height=400, yformat=None):
    fig = go.Figure(go.Bar(x=df[x], y=df[y], marker_color=color,
                           text=df[text] if text else None, textposition="outside"))
    fig.update_layout(title=title, height=height, yaxis_title=ytitle)
    if yformat:
        fig.update_yaxes(tickformat=yformat)
    _out(fig)

docs/blog/go/figs.py

docs/blog/go/goboard.nim 52 lines
## A tiny go board: play the main line of a game, with captures, and return the final
## position. The twin of goboard.py; in the post it is the callback.

proc neighbours(p, size: int): seq[int] =
  let (x, y) = (p mod size, p div size)
  if x > 0: result.add p - 1
  if x < size - 1: result.add p + 1
  if y > 0: result.add p - size
  if y < size - 1: result.add p + size

proc group(board: string, p, size: int): (seq[int], bool) =
  ## The stones connected to `p`, and whether the group has a liberty.
  let color = board[p]
  var stack = @[p]
  var seen = @[p]
  var libs = false
  while stack.len > 0:
    let q = stack.pop
    for r in neighbours(q, size):
      if board[r] == '\0': libs = true
      elif board[r] == color and r notin seen:
        seen.add r
        stack.add r
  (seen, libs)

proc replay*(moves: string, size = 19): (string, int, int) =
  ## moves: two SGF letters per move ("aa" is the top-left point, "tt" a pass).
  ## Returns the board (size*size chars: '\0' empty, '\1' black, '\2' white) and the
  ## stones captured by Black and by White.
  var board = newString(size * size)
  var caps = [0, 0, 0]
  var color = '\1'
  var i = 0
  while i + 1 < moves.len:
    let (x, y) = (ord(moves[i]) - 97, ord(moves[i + 1]) - 97)
    if x in 0 ..< size and y in 0 ..< size:
      let p = y * size + x
      board[p] = color
      let other = if color == '\1': '\2' else: '\1'
      for q in neighbours(p, size):
        if board[q] == other:
          let (stones, libs) = group(board, q, size)
          if not libs:
            for g in stones: board[g] = '\0'
            caps[ord(color)] += stones.len
      let (own, libs) = group(board, p, size)
      if not libs:  # suicide: remove own group (allowed in some rules)
        for g in own: board[g] = '\0'
        caps[ord(other)] += own.len
    color = if color == '\1': '\2' else: '\1'
    i += 2
  (board, caps[1], caps[2])

docs/blog/go/goboard.nim

docs/blog/go/goboard.py 47 lines
"""A tiny go board: play the main line of a game, with captures, and return the final
position. Pure Python on purpose: in the post it is the callback the Nim version beats."""

def replay(moves: bytes, size: int = 19):
    """moves: two SGF letters per move ("aa" is the top-left point, "tt" a pass).
    Returns (board, captured_by_black, captured_by_white); board is a bytes object of
    size*size cells: 0 empty, 1 black, 2 white."""
    board = bytearray(size * size)
    caps = [0, 0, 0]
    color = 1
    for i in range(0, len(moves) - 1, 2):
        x, y = moves[i] - 97, moves[i + 1] - 97
        if 0 <= x < size and 0 <= y < size:
            p = y * size + x
            board[p] = color
            other = 3 - color
            for q in _nbrs(p, size):
                if board[q] == other:
                    group, libs = _group(board, q, size)
                    if not libs:
                        for g in group: board[g] = 0
                        caps[color] += len(group)
            group, libs = _group(board, p, size)
            if not libs:  # suicide: remove own group (allowed in some rules)
                for g in group: board[g] = 0
                caps[other] += len(group)
        color = 3 - color
    return bytes(board), caps[1], caps[2]

def _nbrs(p, size):
    x, y = p % size, p // size
    if x > 0: yield p - 1
    if x < size - 1: yield p + 1
    if y > 0: yield p - size
    if y < size - 1: yield p + size

def _group(board, p, size):
    color = board[p]
    stack, seen, libs = [p], {p}, False
    while stack:
        q = stack.pop()
        for r in _nbrs(q, size):
            c = board[r]
            if c == 0: libs = True
            elif c == color and r not in seen:
                seen.add(r); stack.append(r)
    return seen, libs

docs/blog/go/goboard.py

docs/blog/go/plots.nim 153 lines
## Plotly figures for "Move 37", with nim-plotly. The twin of figs.py: same traces,
## colours and layout (without Plotly's "plotly_white" template, which only Python
## ships). nim-plotly builds the traces (type, data, mode, name, marker, text) and the
## basic layout (title, size); what it has no field for (board lines as shapes, colour
## scales as stops, several heatmaps side by side, axis ranges and aspect ratio) is
## added to the JSON it produces.
import std/[json, sequtils]
import plotly except Color
import nanuq

const
  Kaya = "#dcb468"
  Ink = "#3b2f1e"
  Stars = [3, 9, 15]
  Cols = "ABCDEFGHJKLMNOPQRST"  # go boards skip the letter I

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

proc floats(df: DataFrame, column: string): seq[float] =
  df.select(col(column).cast(Float64)).toList(column, float)

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

proc gridShapes(size: int, xref = "x", yref = "y"): seq[JsonNode] =
  ## The wooden board, then its lines (x = column 0..18 left to right, y = row 0..18 top down).
  result.add %*{"type": "rect", "x0": -0.8, "x1": size.float - 0.2, "y0": -0.8, "y1": size.float - 0.2,
                "xref": xref, "yref": yref, "fillcolor": Kaya, "line": {"width": 0}, "layer": "below"}
  for i in 0 ..< size:
    result.add %*{"type": "line", "x0": 0, "x1": size - 1, "y0": i, "y1": i, "xref": xref, "yref": yref,
                  "line": {"color": Ink, "width": 1}, "layer": "below"}
    result.add %*{"type": "line", "x0": i, "x1": i, "y0": 0, "y1": size - 1, "xref": xref, "yref": yref,
                  "line": {"color": Ink, "width": 1}, "layer": "below"}

proc board*(stones: DataFrame, title: string, labels = DataFrame(), size = 19, height = 560): PlotJson =
  ## stones: x, y, color ("B"/"W"); labels: optional x, y, text, fg.
  var stars: seq[(float, float)]
  for x in Stars:
    for y in Stars: stars.add (x.float, y.float)
  var traces = @[Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                              xs: stars.mapIt(it[0]), ys: stars.mapIt(it[1]))]
  for c in ["B", "W"]:
    let s = stones.filter(col.color == c)
    traces.add Trace[float](`type`: PlotType.Scatter, mode: PlotMode.Markers,
                            name: (if c == "B": "black" else: "white"),
                            xs: s.floats("x"), ys: s.floats("y"))
  result = finish(traces, title, height)
  result.withStyle(0, %*{"marker": {"size": 6, "color": Ink}, "hoverinfo": "skip", "showlegend": false})
  let stoneSize = height.float / (size + 2).float * 0.9
  result.withStyle(1, %*{"marker": {"size": stoneSize, "color": "#111111", "line": {"width": 1, "color": "#000000"}},
                         "hoverinfo": "skip", "showlegend": false})
  result.withStyle(2, %*{"marker": {"size": stoneSize, "color": "#f8f8f4", "line": {"width": 1, "color": "#555555"}},
                         "hoverinfo": "skip", "showlegend": false})
  if labels.width > 0:
    result.traces.add %*{"type": "scatter", "mode": "text", "x": labels.floats("x"), "y": labels.floats("y"),
                         "text": labels.toList("text", string),
                         "textfont": {"color": labels.toList("fg", string), "size": 11},
                         "hoverinfo": "skip", "showlegend": false}
  result.layout["width"] = %(height - 20)
  result.layout["shapes"] = %gridShapes(size)
  result.layout["xaxis"] = %*{"range": [-1, size], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(Cols[0 ..< size]).mapIt($it), "side": "top",
    "constrain": "domain"}
  result.layout["yaxis"] = %*{"range": [size, -1], "showgrid": false, "zeroline": false,
    "tickvals": toSeq(0 ..< size), "ticktext": toSeq(0 ..< size).mapIt($(size - it)),
    "scaleanchor": "x", "constrain": "domain"}

proc heatBoards*(freq: DataFrame, panels: openArray[string], title: string, height = 330): PlotJson =
  ## freq: panel, x, y, share; one 19x19 heatmap per panel, side by side.
  let zmax = freq.select(col.share.max).toList("share", float)[0]
  var traces: seq[Trace[float]]
  for p in panels:
    let f = freq.filter(col.panel == p)
    var z = newSeqWith(19, newSeq[float](19))
    for r in f.select(col.x, col.y, col.share).rows(tuple[x, y: int, share: float]):
      z[r.y][r.x] = r.share
    traces.add Trace[float](`type`: PlotType.HeatMap, xs: toSeq(0 .. 18).mapIt(it.float),
                            ys: toSeq(0 .. 18).mapIt(it.float), zs: z)
  result = finish(traces, title, height)
  let n = panels.len
  let gap = 0.03
  let w = (1.0 - gap * float(n - 1)) / float(n)
  var notes = newJArray()
  for i, p in panels:
    let suffix = if i == 0: "" else: $(i + 1)
    result.withStyle(i, %*{"zmin": 0, "zmax": zmax,
      "colorscale": [[0, "#f3e3bd"], [0.25, "#e0a84f"], [0.6, "#b4462b"], [1, "#3a0f12"]],
      "showscale": i == n - 1, "hovertemplate": "%{z:.1%}<extra></extra>",
      "colorbar": {"tickformat": ".0%", "len": 0.8}, "xaxis": "x" & suffix, "yaxis": "y" & suffix})
    let x0 = float(i) * (w + gap)
    result.layout["xaxis" & suffix] = %*{"domain": [x0, x0 + w], "anchor": "y" & suffix,
      "range": [-0.5, 18.5], "showticklabels": false, "showgrid": false, "zeroline": false, "constrain": "domain"}
    result.layout["yaxis" & suffix] = %*{"domain": [0, 1], "anchor": "x" & suffix,
      "range": [18.5, -0.5], "showticklabels": false, "showgrid": false, "zeroline": false,
      "constrain": "domain", "scaleanchor": "x" & suffix}
    notes.add %*{"text": p, "x": x0 + w / 2, "y": 1.0, "xref": "paper", "yref": "paper",
                 "xanchor": "center", "yanchor": "bottom", "showarrow": false, "font": {"size": 16}}
  result.layout["annotations"] = notes
  result.layout["plot_bgcolor"] = %"#f3e3bd"

proc linesAt[T](df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
                events: openArray[(T, string)], yformat: string, height: int, mode: string): PlotJson =
  ## One line per (column, name, colour); dotted vertical lines with a label for events.
  result = finish(@[], title, height)
  let xs = if df.schema[x] == Date: %df.select(col(x).cast(String)).toList(x, string) else: %df.floats(x)
  for (y, name, color) in ys:
    var jy = newJArray()
    for v in df.select(col(y).cast(Float64)).toList(y, Option[float]):
      jy.add(if v.isSome: %v.get else: newJNull())
    result.traces.add %*{"type": "scatter", "mode": mode, "name": name, "x": xs, "y": jy,
                         "line": {"color": color}}
  var shapes = newJArray()
  var notes = newJArray()
  for (ex, text) in events:
    shapes.add %*{"type": "line", "x0": ex, "x1": ex, "y0": 0, "y1": 1, "yref": "paper",
                  "line": {"color": "#999", "dash": "dot"}}
    notes.add %*{"x": ex, "y": 1, "yref": "paper", "text": text, "showarrow": false,
                 "yanchor": "bottom", "font": {"size": 11, "color": "#555"}}
  if shapes.len > 0:
    result.layout["shapes"] = shapes
    result.layout["annotations"] = notes
  result.layout["yaxis"] = %*{"title": {"text": ytitle}, "automargin": true}
  if yformat.len > 0: result.layout["yaxis"]["tickformat"] = %yformat
  result.layout["legend"] = %*{"orientation": "h", "y": -0.15}

proc bars*(df: DataFrame, x, y: string, title, ytitle: string, color = "#8c5a2b",
           height = 400, yformat = ""): PlotJson =
  result = finish(@[Trace[float](`type`: PlotType.Bar, xs: @[], ys: df.floats(y))], title, height)
  result.traces[0]["x"] = %df.toList(x, string)
  result.withStyle(0, %*{"marker": {"color": color}})
  result.layout["yaxis"] = %*{"title": {"text": ytitle}, "automargin": true}
  if yformat.len > 0: result.layout["yaxis"]["tickformat"] = %yformat


proc lines*[T](df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
               events: openArray[(T, string)], yformat = "", height = 420,
               mode = "lines+markers"): PlotJson =
  linesAt(df, x, ys, title, ytitle, events, yformat, height, mode)

proc lines*(df: DataFrame, x: string, ys: openArray[(string, string, string)], title, ytitle: string,
            yformat = "", height = 420, mode = "lines+markers"): PlotJson =
  ## Lines without event markers.
  linesAt(df, x, ys, title, ytitle, newSeq[(int, string)](), yformat, height, mode)

docs/blog/go/plots.nim

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

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

docs/blog/go/expected.py

docs/blog/go/src/ogs_prep.py 26 lines
"""Run the post's own OGS query (cells s07_schema and s08_query of go.py) on the full
2.8M-game sample and sink it to data/ogs_games.parquet with the streaming engine.
Usage, from the draft folder: python3 -I src/ogs_prep.py /tmp/godata/ogs/ogs_5pct.ndjson"""
import re, sys, time
import polars as pl
src = open("go.py").read()
cells = {re.match(r"\n# id: (\S+)", c).group(1): c for c in src.split("\n# %%")[1:] if not c.startswith(" [markdown]")}
ns = {"pl": pl}
for cid in ["s07_schema", "s08_query"]:
    exec(cells[cid].replace("data/ogs_slice.ndjson", sys.argv[1]), ns)
t = time.time()
ns["ogs"].sink_parquet("/tmp/ogs_games_full.parquet", engine="streaming")
print(f"{time.time() - t:.0f} s")
# What ships with the post: every fifth game (a 1% sample of OGS), fewer digits, and the
# first moves only for the even 19x19 games that section 12 looks at.
(pl.scan_parquet("/tmp/ogs_games_full.parquet").gather_every(5).select(
    "size", "handicap", "komi", "speed", "winner",
    started=pl.col("started").dt.date(),
    black_rank=pl.col("black_rank").round(1).cast(pl.Float32),
    white_rank=pl.col("white_rank").round(1).cast(pl.Float32),
    n_moves=pl.col("n_moves").cast(pl.UInt16),
    moves=pl.when((pl.col("size") == 19) & (pl.col("handicap") == 0)).then("moves"),
).sink_parquet("data/ogs_games.parquet", compression="zstd", compression_level=19))
print(pl.scan_parquet("data/ogs_games.parquet").select(pl.len()).collect())
# memory: see /home/user/scratch/memtest.py in the session; on 1 Nov 2026 (4-core, 15 GB VM)
# streaming sink 75 s, 0.13 GB anonymous memory; in-memory collect 89 s, 11.8 GB

docs/blog/go/src/ogs_prep.py

docs/blog/go/src/prep_pro.py 30 lines
"""Pack the 97k Japanese pro games (homepages.cwi.nl/~aeb/go/games/games.tgz, extracted to
/tmp/godata/cwi) into one Parquet file: SGF header fields as strings plus the main line of
moves as one Binary value (two SGF letters per move, "tt" or "" for a pass)."""
import glob, re, sys, polars as pl
root = sys.argv[1] if len(sys.argv) > 1 else "/tmp/godata/cwi"
out = sys.argv[2] if len(sys.argv) > 2 else "data/pro_games.parquet"
maxmoves = int(sys.argv[3]) if len(sys.argv) > 3 else 10_000
PROPS = ["DT", "PB", "PW", "BR", "WR", "KM", "HA", "RE", "SZ", "EV", "RU"]
rows = []
for f in sorted(glob.glob(f"{root}/**/*.sgf", recursive=True)):
    raw = open(f, "rb").read()
    try: s = raw.decode("utf-8")
    except UnicodeDecodeError: s = raw.decode("latin-1")
    head = s.split(";B[", 1)[0].split(";W[", 1)[0]
    r = {"file": f.split("/games/", 1)[-1]}
    for p in PROPS:
        m = re.search(rf"(?<![A-Z]){p}\[((?:[^\]\\]|\\.)*)\]", head)
        r[p] = m.group(1).strip() if m else None
    # main line only: stop at the first variation
    main = s.split("(;", 2)
    body = main[1] if len(main) > 1 else s
    body = body.split("(", 1)[0]
    mv = re.findall(r";\s*([BW])\[([a-s]{0,2})\]", body)
    r["moves"] = "".join((c if len(c) == 2 else "tt") for _, c in mv[:maxmoves]).encode()
    r["first_color"] = mv[0][0] if mv else None
    rows.append(r)
df = pl.DataFrame(rows, schema={"file": pl.String, **{p: pl.String for p in PROPS},
                                "moves": pl.Binary, "first_color": pl.String})
df.write_parquet(out, compression="zstd", compression_level=19)
print(df.shape, df.select(pl.col("moves").bin.size().sum()))

docs/blog/go/src/prep_pro.py

docs/blog/go/src/prep_small.py 22 lines
"""Small inputs for the post: pro games (first 80 moves, plus full games for a subset),
Zobrist keys, the FIGG roll of Italian champions, the EGD player list."""
import csv, html, json, random, re, shutil, polars as pl
# pro games
full = pl.read_parquet("/tmp/godata/pro_full.parquet")
pl.read_parquet("/tmp/godata/pro_80.parquet").write_parquet("data/pro_games.parquet", compression="zstd", compression_level=19)
recent = full.filter(pl.col("file").str.starts_with("AlphaGo/") | (pl.col("DT").str.slice(0, 4) >= "2025"))
recent.write_parquet("data/pro_full_moves.parquet", compression="zstd", compression_level=19)
print("full subset", recent.shape)
# Zobrist keys: one random 64-bit number per point and colour (19*19*2)
rng = random.Random(19)
pl.DataFrame({"point": [p for p in range(361) for _ in (1, 2)],
              "color": ["B", "W"] * 361,
              "key": [rng.getrandbits(64) for _ in range(722)]},
             schema={"point": pl.UInt16, "color": pl.String, "key": pl.UInt64}).write_csv("data/zobrist.csv")
# champions
shutil.copy("/tmp/godata/raw/champions_raw.csv", "data/champions.csv")
# EGD list (fixed width), as downloaded; strip the HTML wrapper lines
txt = open("/tmp/godata/raw/allworld_lp.html", encoding="latin-1").read()
body = txt.split("</b>\n", 2)[2].split("</pre>")[0]
open("data/egd_players.txt", "w", encoding="utf-8").write(body)
print(body[:300])

docs/blog/go/src/prep_small.py

docs/blog/go/src/stream_ogs.py 22 lines
import sys, zlib, urllib.request, time
URL = "https://za3k.com/ogs/ogs_games_2013_to_2025-05.json.gz"
out = open(sys.argv[1], "wb"); every = int(sys.argv[2])
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
pos = 0; n = 0; buf = b""; fails = 0
while True:
    try:
        req = urllib.request.Request(URL, headers={"Range": f"bytes={pos}-"})
        with urllib.request.urlopen(req, timeout=60) as r:
            while True:
                chunk = r.read(1 << 20)
                if not chunk: break
                pos += len(chunk)
                buf += d.decompress(chunk)
                lines = buf.split(b"\n"); buf = lines.pop()
                for l in lines:
                    if n % every == every - 1: out.write(l + b"\n")
                    n += 1
        if d.eof or pos >= 45847026468: break
    except Exception as e:
        fails += 1; print("retry", pos, n, e, flush=True); time.sleep(min(30, 2 ** min(fails, 5)))
print("done", pos, n, flush=True)

docs/blog/go/src/stream_ogs.py