kshana 0.27.1

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
// SPDX-License-Identifier: AGPL-3.0-only
//! Result reporting: assembling a run's figures of merit, samples and provenance
//! into the structured result returned to callers.
use crate::fom::{FoMScores, Sample};
use crate::scenario::Scenario;
use crate::types::ModelSpec;
use serde::Serialize;
use sha2::{Digest, Sha256};

/// Unit and provenance class for every numeric field the single-run `clock` report
/// ([`RunResult`]) emits.
///
/// `quantum` and `classical` are the same [`ClockRun`] shape, so every column is
/// stated once and carried under both roots — a units entry describes the column, not
/// the row, and the two suites differ only in which sensor configuration filled it.
///
/// The sensor-model parameters under `spec.params` are the raw arguments of
/// [`crate::models::ClockModel`]: `q_wf` is the intensity of the phase random walk
/// (`Var[dx] = q_wf*dt` with `dx` in seconds, hence `s^2/s`) and `q_rw` the intensity
/// of the fractional-frequency random walk (`Var[dy] = q_rw*dt` with `y`
/// dimensionless, hence `1/s`). [`crate::security::monitor_sigma_s`] carries the same
/// convention: `sigma^2 = r/m + q_wf*tau + q_rw*tau^3/3`, in `s^2`.
pub const UNITS: &[crate::field_schema::FieldUnit] = {
    use crate::field_schema::{FieldUnit, ProvenanceClass::*};
    macro_rules! clock_units {
        ($($s:literal),+ $(,)?) => {
            &[
                FieldUnit {
                    path: "seed",
                    unit: "1",
                    provenance: Input,
                    definition: "RNG seed of the quantum realisation; the classical \
                                 realisation runs at seed + 0x9e3779b97f4a7c15",
                },
                FieldUnit {
                    path: "threshold_ns",
                    unit: "ns",
                    provenance: Input,
                    definition: "timing spec: a sample whose absolute timing error is at \
                                 or below this is in spec",
                },
                FieldUnit {
                    path: "eci_track[][]",
                    unit: "km",
                    provenance: Computed,
                    definition: "one Earth-centred-inertial [x, y, z] component of the \
                                 propagated user spacecraft at one sampled time; emitted \
                                 only by the orbit pack, absent from a clock run",
                },
                $(
                FieldUnit {
                    path: concat!($s, ".spec.params.y0"),
                    unit: "1",
                    provenance: Input,
                    definition: "deterministic fractional-frequency offset of the clock \
                                 model (dimensionless df/f)",
                },
                FieldUnit {
                    path: concat!($s, ".spec.params.q_wf"),
                    unit: "s^2/s",
                    provenance: Input,
                    definition: "white-FM process-noise intensity: the clock phase gains \
                                 variance q_wf*dt over a step dt, so q_wf is numerically \
                                 sigma_y(1 s)^2",
                },
                FieldUnit {
                    path: concat!($s, ".spec.params.q_rw"),
                    unit: "1/s",
                    provenance: Input,
                    definition: "random-walk-FM process-noise intensity: the fractional \
                                 frequency gains variance q_rw*dt over a step dt",
                },
                FieldUnit {
                    path: concat!($s, ".spec.params.drift"),
                    unit: "1/s",
                    provenance: Input,
                    definition: "linear fractional-frequency aging rate: the deterministic \
                                 frequency is y0 + drift*t",
                },
                FieldUnit {
                    path: concat!($s, ".spec.params.flicker_floor"),
                    unit: "1",
                    provenance: Input,
                    definition: "flat flicker-FM Allan-deviation floor sigma_y of the clock \
                                 model; null when no flicker component is configured",
                },
                FieldUnit {
                    path: concat!($s, ".series[].t"),
                    unit: "s",
                    provenance: Computed,
                    definition: "sample time on the uniform run grid, i*time.step_s",
                },
                FieldUnit {
                    path: concat!($s, ".series[].error_ns"),
                    unit: "ns",
                    provenance: Computed,
                    definition: "timing error at t: the true clock phase minus the coasted \
                                 prediction; zero while GNSS is nominal",
                },
                FieldUnit {
                    path: concat!($s, ".fom.timing_rms_ns"),
                    unit: "ns",
                    provenance: Computed,
                    definition: "root mean square of the timing error over the outage \
                                 samples",
                },
                FieldUnit {
                    path: concat!($s, ".fom.timing_p95_ns"),
                    unit: "ns",
                    provenance: Computed,
                    definition: "95th percentile (nearest-rank) of the absolute timing \
                                 error over the outage samples",
                },
                FieldUnit {
                    path: concat!($s, ".fom.holdover_s"),
                    unit: "s",
                    provenance: Computed,
                    definition: "worst-case (shortest) in-spec coast across the outage \
                                 segments; grid-bounded at time.step_s",
                },
                FieldUnit {
                    path: concat!($s, ".fom.resilience_slope_ns_per_s"),
                    unit: "ns/s",
                    provenance: Computed,
                    definition: "least-squares slope of the absolute timing error against \
                                 time over the outage",
                },
                FieldUnit {
                    path: concat!($s, ".fom.availability"),
                    unit: "1",
                    provenance: Computed,
                    definition: "fraction of all samples in the run whose absolute timing \
                                 error is within threshold_ns",
                },
                FieldUnit {
                    path: concat!($s, ".fom.integrity"),
                    unit: "1",
                    provenance: Computed,
                    definition: "filter self-consistency: the fraction of outage samples \
                                 whose true error stays inside the Kalman 3-sigma phase \
                                 bound; not an aviation HPL/VPL/RAIM integrity figure",
                },
                FieldUnit {
                    path: concat!($s, ".fom.security"),
                    unit: "1",
                    provenance: Computed,
                    definition: "analytic spoof-detectability bound from clock stability, \
                                 clamp(1 - smallest detectable offset / threshold_ns, 0, \
                                 1); meaningful only against a configured attack, and not \
                                 a multi-satellite RAIM detector",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].tau_s"),
                    unit: "s",
                    provenance: Computed,
                    definition: "averaging time of this overlapping-Allan point, \
                                 m*time.step_s at octave-spaced m",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].adev"),
                    unit: "1",
                    provenance: Computed,
                    definition: "overlapping Allan deviation sigma_y(tau) of the clock \
                                 phase — a dimensionless fractional-frequency stability",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].n_samples"),
                    unit: "count",
                    provenance: Computed,
                    definition: "number of overlapping second differences averaged into \
                                 this point",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].edf"),
                    unit: "1",
                    provenance: Computed,
                    definition: "effective degrees of freedom of this point for the \
                                 power-law noise type identified over the whole record",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].ci_lo"),
                    unit: "1",
                    provenance: Computed,
                    definition: "lower end of the chi-squared 95% confidence interval on \
                                 adev at this tau",
                },
                FieldUnit {
                    path: concat!($s, ".adev_curve[].ci_hi"),
                    unit: "1",
                    provenance: Computed,
                    definition: "upper end of the chi-squared 95% confidence interval on \
                                 adev at this tau",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nis_mean"),
                    unit: "1",
                    provenance: InternalConsistency,
                    definition: "pooled mean normalised innovation squared over the \
                                 consistency ensemble; a matched filter gives 1",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nis_chi2_lower_95"),
                    unit: "1",
                    provenance: ClosedForm,
                    definition: "lower 95% chi-squared acceptance bound on the NIS mean, \
                                 chi2_0.025(K)/K over K pooled innovations",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nis_chi2_upper_95"),
                    unit: "1",
                    provenance: ClosedForm,
                    definition: "upper 95% chi-squared acceptance bound on the NIS mean, \
                                 chi2_0.975(K)/K over K pooled innovations",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nees_mean"),
                    unit: "1",
                    provenance: InternalConsistency,
                    definition: "pooled mean normalised estimation error squared; a \
                                 matched two-state filter gives 2",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nees_chi2_lower_95"),
                    unit: "1",
                    provenance: ClosedForm,
                    definition: "lower 95% chi-squared acceptance bound on the NEES mean, \
                                 chi2_0.025(2*seeds)/seeds",
                },
                FieldUnit {
                    path: concat!($s, ".filter_health.nees_chi2_upper_95"),
                    unit: "1",
                    provenance: ClosedForm,
                    definition: "upper 95% chi-squared acceptance bound on the NEES mean, \
                                 chi2_0.975(2*seeds)/seeds",
                },
                )+
            ]
        };
    }
    clock_units!("quantum", "classical")
};

/// One clock's run: its spec, full error series, scored FoMs, and the
/// overlapping Allan-deviation curve of the clock's phase over the run.
#[derive(Clone, Debug, Serialize)]
pub struct ClockRun {
    pub spec: ModelSpec,
    pub series: Vec<Sample>,
    pub fom: FoMScores,
    #[serde(default)]
    pub adev_curve: Vec<crate::allan::AdevPoint>,
    /// Kalman filter-consistency health (NIS/NEES vs χ² bands). `None` for runs
    /// that do not assess it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter_health: Option<crate::filter_health::FilterHealth>,
}

/// Optional, additive study metadata for a productized report: a title, a
/// caller-supplied generation timestamp, and an optional author/disclaimer. Every
/// field is omitted from the serialized output when absent, so a `RunResult` that
/// carries no metadata is byte-identical to one produced before this struct
/// existed (reproducibility/golden tests stay green). This describes the *report*,
/// not the scenario inputs, so it never enters [`hash_scenario`].
#[derive(Clone, Debug, Serialize)]
pub struct StudyMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub study_title: Option<String>,
    /// Caller-supplied UTC ISO-8601 stamp. Stamped by the CLI, never read from a
    /// clock inside the engine/api, so the library stays pure/deterministic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generated_utc: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disclaimer: Option<String>,
}

/// Top-level result artifact (versioned, self-describing, reproducible).
#[derive(Clone, Debug, Serialize)]
pub struct RunResult {
    pub schema_version: String,
    pub engine_version: String,
    pub scenario_hash: String,
    pub seed: u64,
    pub threshold_ns: f64,
    pub quantum: ClockRun,
    pub classical: ClockRun,
    /// Optional propagated Earth-centred-inertial track of the user spacecraft
    /// (km), one `[x, y, z]` per sampled time, populated only for the orbit pack
    /// so the playground can draw the 3D orbit. `None` for non-orbit runs; an
    /// output-only field, so it does not perturb [`hash_scenario`] (which hashes
    /// only the scenario *inputs*) or the shared-link reproducibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eci_track: Option<Vec<[f64; 3]>>,
    /// Optional, additive study metadata (title / generation stamp / author /
    /// disclaimer) for a productized report. An output-only field: omitted when
    /// absent (so meta-less runs are byte-identical to legacy output) and never
    /// part of [`hash_scenario`], which hashes only the scenario *inputs*.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<StudyMeta>,
}

/// Turn a free-text study name into a filesystem-friendly base name: lower-cased,
/// runs of non-alphanumeric characters collapsed to single hyphens, with leading
/// and trailing hyphens trimmed (e.g. `"My Study"` → `"my-study"`). Pure and
/// deterministic — the CLI uses it to derive the output file base when
/// `--study-name` is given. Falls back to `"study"` if the name has no
/// alphanumerics, so a base name always exists.
pub fn slugify(name: &str) -> String {
    let mut slug = String::with_capacity(name.len());
    let mut prev_hyphen = false;
    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() {
            slug.push(ch.to_ascii_lowercase());
            prev_hyphen = false;
        } else if !slug.is_empty() && !prev_hyphen {
            slug.push('-');
            prev_hyphen = true;
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    if slug.is_empty() {
        "study".to_string()
    } else {
        slug
    }
}

/// Build [`StudyMeta`] for a productized study from a title and a caller-supplied
/// UTC ISO-8601 timestamp. Pure: the timestamp is *passed in* (the CLI is the only
/// place allowed to read a clock), so this stays deterministic and the library
/// never reads wall-clock time. `author`/`disclaimer` are left unset here.
pub fn study_meta_with_title(study_title: &str, generated_utc: &str) -> StudyMeta {
    StudyMeta {
        study_title: Some(study_title.to_string()),
        generated_utc: Some(generated_utc.to_string()),
        author: None,
        disclaimer: None,
    }
}

/// sha256 hex over the canonical JSON of the scenario (field order is stable).
pub fn hash_scenario(scn: &Scenario) -> String {
    let canonical = serde_json::to_string(scn).unwrap_or_default();
    let mut h = Sha256::new();
    h.update(canonical.as_bytes());
    hex::encode(h.finalize())
}

/// Render the quantum-vs-classical timing-error divergence as a standalone SVG
/// (no dependencies). |error| in ns vs time, with the spec threshold line.
pub fn to_svg(result: &RunResult) -> String {
    use crate::fom::Sample;
    let (w, h) = (820.0_f64, 420.0_f64);
    let (ml, mr, mt, mb) = (70.0_f64, 20.0_f64, 30.0_f64, 50.0_f64);
    let pw = w - ml - mr;
    let ph = h - mt - mb;
    let c = &result.classical.series;
    let q = &result.quantum.series;
    let t_max = c.iter().map(|s| s.t).fold(1.0_f64, f64::max);
    let mut y_max = result.threshold_ns * 1.3;
    for s in c.iter().chain(q.iter()) {
        y_max = y_max.max(s.error_ns.abs());
    }
    if y_max <= 0.0 {
        y_max = 1.0;
    }
    let xof = |t: f64| ml + (t / t_max) * pw;
    let yof = |e: f64| mt + ph - (e.min(y_max) / y_max) * ph;
    let points = |series: &[Sample]| {
        series
            .iter()
            .map(|s| format!("{:.1},{:.1}", xof(s.t), yof(s.error_ns.abs())))
            .collect::<Vec<_>>()
            .join(" ")
    };
    let thr_y = yof(result.threshold_ns);
    let axis_y = mt + ph;
    let mut svg = String::new();
    svg.push_str(&format!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w:.0}\" height=\"{h:.0}\" font-family=\"sans-serif\" font-size=\"12\" fill=\"#bcb3a3\">"
    ));
    svg.push_str(&format!(
        "<rect width=\"{w:.0}\" height=\"{h:.0}\" fill=\"#0c0b08\"/>"
    ));
    svg.push_str(&format!(
        "<text x=\"{:.0}\" y=\"18\" font-size=\"15\" font-weight=\"bold\">Clock holdover: timing error during GNSS outage</text>",
        ml
    ));
    // The provenance footer is stamped centrally for every chart in `api::run_toml`.
    svg.push_str(&crate::chart::y_axis(
        ml,
        mt,
        pw,
        ph,
        y_max,
        "timing error (ns)",
    ));
    svg.push_str(&format!(
        "<line x1=\"{ml:.0}\" y1=\"{mt:.0}\" x2=\"{ml:.0}\" y2=\"{axis_y:.0}\" stroke=\"#342c21\"/>"
    ));
    svg.push_str(&format!(
        "<line x1=\"{ml:.0}\" y1=\"{axis_y:.0}\" x2=\"{:.0}\" y2=\"{axis_y:.0}\" stroke=\"#342c21\"/>",
        ml + pw
    ));
    svg.push_str(&format!(
        "<line x1=\"{ml:.0}\" y1=\"{thr_y:.1}\" x2=\"{:.0}\" y2=\"{thr_y:.1}\" stroke=\"#e5645a\" stroke-dasharray=\"6 4\"/>",
        ml + pw
    ));
    svg.push_str(&format!(
        "<text x=\"{:.0}\" y=\"{:.1}\" fill=\"#e5645a\">spec {:.0} ns</text>",
        ml + 4.0,
        thr_y - 4.0,
        result.threshold_ns
    ));
    svg.push_str(&format!(
        "<polyline fill=\"none\" stroke=\"#d2925e\" stroke-width=\"2\" points=\"{}\"/>",
        points(c)
    ));
    svg.push_str(&format!(
        "<polyline fill=\"none\" stroke=\"#e0bd84\" stroke-width=\"2\" points=\"{}\"/>",
        points(q)
    ));
    svg.push_str(&format!(
        "<text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\">time (s)</text>",
        ml + pw / 2.0,
        h - 12.0
    ));
    svg.push_str(&format!(
        "<text x=\"{:.0}\" y=\"44\" fill=\"#d2925e\">classical: {}</text>",
        ml + 10.0,
        result.classical.spec.id
    ));
    svg.push_str(&format!(
        "<text x=\"{:.0}\" y=\"60\" fill=\"#e0bd84\">quantum: {}</text>",
        ml + 10.0,
        result.quantum.spec.id
    ));
    svg.push_str("</svg>");
    svg
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scenario::*;

    fn demo() -> Scenario {
        Scenario {
            seed: 1,
            threshold_ns: 100.0,
            runs: 1,
            time: TimeCfg {
                step_s: 10.0,
                duration_s: 60.0,
            },
            gnss: GnssTimeline {
                windows: vec![
                    GnssWindow {
                        t0: 0.0,
                        t1: 30.0,
                        state: GnssState::Nominal,
                    },
                    GnssWindow {
                        t0: 30.0,
                        t1: 60.0,
                        state: GnssState::Denied,
                    },
                ],
            },
            clock_quantum: ClockCfg {
                id: "q".into(),
                provenance: "d".into(),
                y0: 1e-13,
                q_wf: 1e-26,
                q_rw: 1e-32,
                drift: 0.0,
                flicker_floor: 0.0,
            },
            clock_classical: ClockCfg {
                id: "c".into(),
                provenance: "d".into(),
                y0: 1e-11,
                q_wf: 1e-24,
                q_rw: 1e-30,
                drift: 0.0,
                flicker_floor: 0.0,
            },
        }
    }

    #[test]
    fn slugify_makes_filesystem_friendly_base_names() {
        assert_eq!(slugify("My Study"), "my-study");
        assert_eq!(slugify("  Trailing / Slashes -- "), "trailing-slashes");
        assert_eq!(slugify("Q1 2026: Holdover (v2)"), "q1-2026-holdover-v2");
        assert_eq!(slugify("already-slug"), "already-slug");
        // No alphanumerics → stable fallback so a base name always exists.
        assert_eq!(slugify("***"), "study");
        assert_eq!(slugify(""), "study");
    }

    #[test]
    fn study_meta_with_title_sets_title_and_passed_in_stamp() {
        // The builder is pure: the timestamp is supplied by the caller (the CLI),
        // never read from a clock here, keeping the library deterministic.
        let m = study_meta_with_title("My Study", "2026-06-23T00:00:00Z");
        assert_eq!(m.study_title.as_deref(), Some("My Study"));
        assert_eq!(m.generated_utc.as_deref(), Some("2026-06-23T00:00:00Z"));
        assert_eq!(m.author, None);
        assert_eq!(m.disclaimer, None);
    }

    #[test]
    fn scenario_hash_is_deterministic_and_sensitive() {
        let a = hash_scenario(&demo());
        let b = hash_scenario(&demo());
        assert_eq!(a, b);
        assert_eq!(a.len(), 64);
        let mut other = demo();
        other.seed = 2;
        assert_ne!(a, hash_scenario(&other));
    }
}

#[cfg(test)]
mod svg_tests {
    use super::*;
    use crate::fom::{FoMScores, Sample};
    use crate::scenario::GnssState::Denied;
    use crate::types::ModelSpec;

    fn run_of(id: &str, errs: &[f64]) -> ClockRun {
        let series = errs
            .iter()
            .enumerate()
            .map(|(i, &e)| Sample {
                t: i as f64,
                error_ns: e,
                gnss: Denied,
            })
            .collect();
        ClockRun {
            spec: ModelSpec {
                id: id.into(),
                kind: "clock".into(),
                provenance: "x".into(),
                params: serde_json::json!({}),
            },
            series,
            fom: FoMScores {
                timing_rms_ns: 0.0,
                timing_p95_ns: 0.0,
                holdover_s: 0.0,
                resilience_slope_ns_per_s: 0.0,
                availability: 1.0,
                integrity: None,
                security: None,
            },
            adev_curve: vec![],
            filter_health: None,
        }
    }

    #[test]
    fn to_svg_produces_valid_chart() {
        let r = RunResult {
            schema_version: crate::interchange::SCHEMA_VERSION.into(),
            engine_version: "test".into(),
            scenario_hash: "abc".into(),
            seed: 1,
            threshold_ns: 20.0,
            quantum: run_of("optical", &[0.0, 0.0, 0.1]),
            classical: run_of("csac", &[0.0, 15.0, 40.0]),
            eci_track: None,
            meta: None,
        };
        let svg = to_svg(&r);
        assert!(svg.starts_with("<svg"));
        assert_eq!(svg.matches("<polyline").count(), 2);
        assert!(svg.contains("spec 20 ns"));
        assert!(svg.ends_with("</svg>"));
    }
}