kiddo 6.0.2

A high-performance, flexible, ergonomic k-d tree library. Ideal for geo- and astro- nearest-neighbour and k-nearest-neighbor queries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python3
"""Chart exact-NN Donnelly variant screening results."""

from __future__ import annotations

import argparse
import html
import json
import math
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path


STRATEGIES = {
    "eytzinger": "Eytzinger",
    "donnelly": "Donnelly scalar",
    "donnelly_unrolled": "Donnelly unrolled",
    "donnelly_unrolled_block_dim": "Donnelly unrolled/block-dim",
    "donnelly_simd_descent": "Donnelly SIMD descent",
    "donnelly_cyclic_simd_descent": "Donnelly cyclic SIMD descent",
    "donnelly_cyclic_simd_full": "Donnelly cyclic SIMD full",
    "donnelly_simd_initial_descent": "Donnelly initial-only SIMD",
    "donnelly_simd_full": "Donnelly full SIMD",
}
COLORS = {
    "eytzinger": "#3264a8",
    "donnelly": "#d35400",
    "donnelly_unrolled": "#b03a8f",
    "donnelly_unrolled_block_dim": "#298f75",
    "donnelly_simd_descent": "#8a6d1d",
    "donnelly_cyclic_simd_descent": "#16a085",
    "donnelly_cyclic_simd_full": "#c0392b",
    "donnelly_simd_initial_descent": "#7d5fff",
    "donnelly_simd_full": "#c0392b",
}


@dataclass(frozen=True)
class Point:
    axis: str
    point_count: int
    mode: str
    strategy: str
    pool_size: int
    query_ns: float
    low_ns: float
    high_ns: float


def arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=("charts", "all"))
    parser.add_argument("--result", type=Path, required=True)
    parser.add_argument("--result-label", required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--html-name", default="donnelly-variant-screen.html")
    return parser.parse_args()


def load(path: Path) -> tuple[list[Point], dict[tuple[str, int, int], float]]:
    payload = json.loads(path.read_text(encoding="utf-8"))
    points: list[Point] = []
    controls: dict[tuple[str, int, int], float] = {}
    for entry in payload.get("results", []):
        metadata = entry["metadata"]
        function = metadata.get("function_id", "")
        group = metadata["group_id"].split("/")
        axis = group[-2]
        point_count = int(group[-1])
        pool_size = int(metadata["value_str"])
        slope = entry["estimates"]["slope"]
        interval = slope["confidence_interval"]
        query_ns = float(slope["point_estimate"]) / pool_size
        if function == "generated_control":
            controls[(axis, point_count, pool_size)] = query_ns
            continue
        matched = next(
            (
                (mode, strategy)
                for mode in ("stored", "generated")
                for strategy in STRATEGIES
                if function == f"{mode}_{strategy}"
            ),
            None,
        )
        if matched is None:
            continue
        mode, strategy = matched
        points.append(
            Point(
                axis=axis,
                point_count=point_count,
                mode=mode,
                strategy=strategy,
                pool_size=pool_size,
                query_ns=query_ns,
                low_ns=float(interval["lower_bound"]) / pool_size,
                high_ns=float(interval["upper_bound"]) / pool_size,
            )
        )
    if not points:
        raise RuntimeError(f"{path} contains no Donnelly variant results")
    return points, controls


def render(
    points: list[Point],
    controls: dict[tuple[str, int, int], float],
    axis: str,
    point_count: int,
    output: Path,
) -> None:
    matplotlib_config = Path(tempfile.gettempdir()) / "kiddo-matplotlib"
    matplotlib_config.mkdir(exist_ok=True)
    os.environ.setdefault("MPLCONFIGDIR", str(matplotlib_config))
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter

    selected = [
        point
        for point in points
        if point.axis == axis and point.point_count == point_count
    ]
    modes = ("stored", "generated")
    figure, axes = plt.subplots(
        2,
        2,
        figsize=(14.0, 9.0),
        height_ratios=(2.0, 1.0),
        sharex="col",
        constrained_layout=True,
    )
    point_log2 = round(math.log2(point_count))

    for column, mode in enumerate(modes):
        timing = axes[0][column]
        advantage = axes[1][column]
        mode_points = [point for point in selected if point.mode == mode]
        sizes = sorted({point.pool_size for point in mode_points})
        x = [math.log2(size) for size in sizes]
        strategies = [
            strategy
            for strategy in STRATEGIES
            if any(point.strategy == strategy for point in mode_points)
        ]
        table = {
            (point.strategy, point.pool_size): point for point in mode_points
        }
        for strategy in strategies:
            samples = [table[(strategy, size)] for size in sizes]
            timing.plot(
                x,
                [sample.query_ns for sample in samples],
                label=STRATEGIES[strategy],
                color=COLORS[strategy],
                marker="o",
                linewidth=2.0,
            )
            timing.fill_between(
                x,
                [sample.low_ns for sample in samples],
                [sample.high_ns for sample in samples],
                color=COLORS[strategy],
                alpha=0.10,
            )

        timing.set_title(f"{mode.capitalize()} query pool")
        timing.set_ylabel("Criterion slope (ns/query)")
        timing.grid(True, color="#dfe3e8", linewidth=0.8)
        timing.legend(fontsize=8.5)

        advantage.axhline(0.0, color="#555", linewidth=1.0)
        eytzinger = [table[("eytzinger", size)].query_ns for size in sizes]
        if mode == "generated":
            eytzinger = [
                value - controls.get((axis, point_count, size), 0.0)
                for value, size in zip(eytzinger, sizes)
            ]
        for strategy in strategies:
            if strategy == "eytzinger":
                continue
            values = [table[(strategy, size)].query_ns for size in sizes]
            if mode == "generated":
                values = [
                    value - controls.get((axis, point_count, size), 0.0)
                    for value, size in zip(values, sizes)
                ]
            speedups = [
                (baseline / value - 1.0) * 100.0
                if baseline > 0.0 and value > 0.0
                else math.nan
                for baseline, value in zip(eytzinger, values)
            ]
            advantage.plot(
                x,
                speedups,
                label=STRATEGIES[strategy],
                color=COLORS[strategy],
                marker="o",
                linewidth=2.0,
            )
        advantage.set_ylabel("Advantage over Eytzinger")
        advantage.yaxis.set_major_formatter(
            FuncFormatter(lambda value, _: f"{value:+.0f}%")
        )
        advantage.set_xlabel("Distinct queries in pool")
        advantage.set_xticks(x, [f"{size:,}" for size in sizes])
        advantage.grid(True, color="#dfe3e8", linewidth=0.8)

    if "_k" in axis:
        scalar, dimension_text = axis.split("_k", 1)
        dimensions = int(dimension_text)
    else:
        scalar = axis
        dimensions = 3 if axis == "f64" else 4
    block_height = 3 if scalar == "f64" else 4
    padding = (-(point_log2 - 5)) % block_height
    height_role = "exact block height" if padding == 0 else f"+{padding} root padding"
    present = {point.strategy for point in selected}
    if (
        "donnelly_unrolled_block_dim" in present
        and "donnelly_cyclic_simd_descent" in present
    ):
        experiment = "balanced full-strategy screen"
    elif "donnelly_unrolled_block_dim" in present:
        experiment = "balanced UBD control"
    elif "donnelly_cyclic_simd_descent" in present:
        experiment = "cyclic-layout screen"
    else:
        experiment = "strategy screen"
    figure.suptitle(
        f"Exact nearest-one Donnelly variant screen — {dimensions}D {scalar}, "
        f"2^{point_log2} points ({height_role}) — {experiment}"
    )
    figure.savefig(output, dpi=180)
    plt.close(figure)


def render_height_sweep(
    points: list[Point],
    controls: dict[tuple[str, int, int], float],
    axis: str,
    pool_size: int,
    output: Path,
) -> None:
    matplotlib_config = Path(tempfile.gettempdir()) / "kiddo-matplotlib"
    matplotlib_config.mkdir(exist_ok=True)
    os.environ.setdefault("MPLCONFIGDIR", str(matplotlib_config))
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter

    selected = [
        point
        for point in points
        if point.axis == axis and point.pool_size == pool_size
    ]
    point_counts = sorted({point.point_count for point in selected})
    strategies = [
        strategy
        for strategy in STRATEGIES
        if any(point.strategy == strategy for point in selected)
    ]
    figure, axes = plt.subplots(2, 2, figsize=(14, 10), sharex=True)
    x = [round(math.log2(point_count)) for point_count in point_counts]

    for row, mode in enumerate(("stored", "generated")):
        timing = axes[row][0]
        advantage = axes[row][1]
        table = {
            (point.strategy, point.point_count): point
            for point in selected
            if point.mode == mode
        }
        for strategy in strategies:
            samples = [table[(strategy, point_count)] for point_count in point_counts]
            timing.plot(
                x,
                [sample.query_ns for sample in samples],
                label=STRATEGIES[strategy],
                color=COLORS[strategy],
                marker="o",
                linewidth=2.0,
            )
            timing.fill_between(
                x,
                [sample.low_ns for sample in samples],
                [sample.high_ns for sample in samples],
                color=COLORS[strategy],
                alpha=0.10,
            )

        timing.set_title(f"{mode.capitalize()} queries")
        timing.set_ylabel("Criterion slope (ns/query)")
        timing.grid(True, color="#dfe3e8", linewidth=0.8)
        timing.legend(fontsize=8.5)

        advantage.axhline(0.0, color="#555", linewidth=1.0)
        eytzinger = [
            table[("eytzinger", point_count)].query_ns
            for point_count in point_counts
        ]
        if mode == "generated":
            eytzinger = [
                value - controls.get((axis, point_count, pool_size), 0.0)
                for value, point_count in zip(eytzinger, point_counts)
            ]
        for strategy in strategies:
            if strategy == "eytzinger":
                continue
            values = [
                table[(strategy, point_count)].query_ns
                for point_count in point_counts
            ]
            if mode == "generated":
                values = [
                    value - controls.get((axis, point_count, pool_size), 0.0)
                    for value, point_count in zip(values, point_counts)
                ]
            advantage.plot(
                x,
                [
                    (baseline / value - 1.0) * 100.0
                    if baseline > 0.0 and value > 0.0
                    else math.nan
                    for baseline, value in zip(eytzinger, values)
                ],
                label=STRATEGIES[strategy],
                color=COLORS[strategy],
                marker="o",
                linewidth=2.0,
            )
        advantage.set_ylabel("Advantage over Eytzinger")
        advantage.yaxis.set_major_formatter(
            FuncFormatter(lambda value, _: f"{value:+.0f}%")
        )
        advantage.grid(True, color="#dfe3e8", linewidth=0.8)

    if "_k" in axis:
        scalar, dimension_text = axis.split("_k", 1)
        dimensions = int(dimension_text)
    else:
        scalar = axis
        dimensions = 3 if axis == "f64" else 4
    block_height = 3 if scalar == "f64" else 4
    tick_labels = []
    for height in x:
        padding = (-(height - 5)) % block_height
        role = "exact" if padding == 0 else f"+{padding} pad"
        tick_labels.append(f"2^{height}\n{role}")
    for row in axes:
        for chart in row:
            chart.set_xticks(x, tick_labels)
            chart.set_xlabel("Tree points")
    figure.suptitle(
        f"Exact nearest-one height sweep — {dimensions}D {scalar}, "
        f"{pool_size:,} distinct queries"
    )
    figure.tight_layout()
    figure.savefig(output, dpi=180)
    plt.close(figure)


def main() -> None:
    args = arguments()
    points, controls = load(args.result)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    chart_names: list[str] = []
    for axis in sorted({point.axis for point in points}):
        axis_point_counts = sorted(
            {point.point_count for point in points if point.axis == axis}
        )
        common_pool_sizes = set.intersection(
            *(
                {
                    point.pool_size
                    for point in points
                    if point.axis == axis and point.point_count == point_count
                }
                for point_count in axis_point_counts
            )
        )
        for pool_size in sorted(common_pool_sizes):
            name = f"donnelly-variant-height-sweep-{axis}-q{pool_size}.png"
            render_height_sweep(
                points, controls, axis, pool_size, args.output_dir / name
            )
            chart_names.append(name)

        for point_count in axis_point_counts:
            point_log2 = round(math.log2(point_count))
            name = f"donnelly-variant-screen-{axis}-2p{point_log2}.png"
            render(points, controls, axis, point_count, args.output_dir / name)
            chart_names.append(name)

    if args.mode == "all":
        images = "\n".join(
            f'<section><img src="{html.escape(name)}" alt="Donnelly variant chart"></section>'
            for name in chart_names
        )
        (args.output_dir / args.html_name).write_text(
            "<!doctype html><meta charset='utf-8'>"
            f"<title>{html.escape(args.result_label)}</title>"
            "<style>body{font:16px system-ui;margin:2rem;background:#f7f7f7}"
            "section{margin:1rem auto;max-width:1450px;background:white;padding:1rem}"
            "img{width:100%;height:auto}</style>"
            f"<h1>{html.escape(args.result_label)}</h1>{images}",
            encoding="utf-8",
        )


if __name__ == "__main__":
    main()