lichtung-plot 0.1.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
//! Native coordinate panels. Parents allocate the frame; this common producer
//! selects its axes once and hands the resulting projection to retained marks.

use super::{InteriorRoute, OneCategoricalAxis, StandardCoordinate};
use crate::builder::PlotDescription;
use crate::layout::fit::{self, FitKind, PlanError};
use crate::layout::{Axis, AxisSide, CoordinateLayoutInputs, Layout, Projection};
use crate::spec::{AxisDomain, PlotMeasureContext, PlotRenderResult};
use crate::Error;

/// Foundational axis text contributes hard requirements independently from
/// the prepared mark and annotation intrinsics of each family.
#[derive(Debug)]
pub(crate) struct Intrinsics {
    standard: CoordinateLayoutInputs,
    titles: [Option<crate::Text>; 2],
    formats: [Option<std::sync::Arc<crate::numeric::format::NumericFormat>>; 2],
    category_labels: [crate::CategoryLabelSelection; 2],
    base_ranges: [(u64, u64); 2],
    logarithmic: bool,
    minimum_body: (f64, f64),
    without_y_categories: f64,
    y_labels_analyzed: bool,
}

impl Intrinsics {
    /// The prepared axis scope is the owner identity. Parent widths, domain
    /// feedback, and hidden shared-axis labels cannot invalidate its analysis.
    pub(crate) fn prepare<'a>(
        intrinsic: &'a crate::orchestrator::root::PlotIntrinsics,
        input: &crate::orchestrator::root::PlotIntrinsicInputs<'_, '_>,
    ) -> Result<&'a Self, Error> {
        let axes = input.registered.axes.coordinate().ok_or_else(|| {
            Error::Render("native coordinate panel requires root-prepared axes".into())
        })?;
        let theme = &input.request;
        let crate::orchestrator::root::PlotIntrinsics::Coordinate { value } = intrinsic else {
            unreachable!("coordinate intrinsic slot")
        };
        if value.get().is_none() {
            let summary = Self::analyze(axes, input)?;

            let _ = value.set(summary);
        }
        let summary = value.get().expect("initialized panel intrinsics");
        if input.y_visible && !summary.y_labels_analyzed {
            return Err(Error::Render(
                "previously suppressed axis text cannot become active in prepared intrinsics"
                    .into(),
            ));
        }
        let pair = [
            axes.axis(input.registered.source, 0),
            axes.axis(input.registered.source, 1),
        ];
        if summary.formats
            != pair.map(|axis| {
                axis.authored()
                    .expect("coordinate authored intent")
                    .format
                    .clone()
            })
            || summary.category_labels
                != pair.map(|axis| {
                    axis.authored()
                        .expect("coordinate authored intent")
                        .category_labels
                        .clone()
                })
            || summary.base_ranges != axes.ranges().map(|(lo, hi)| (lo.to_bits(), hi.to_bits()))
            || summary.logarithmic != axes.logarithmic()
        {
            return Err(Error::Render(
                "prepared panel intrinsic numeric context changed".into(),
            ));
        }
        if summary.titles.each_ref().map(Option::as_ref)
            != [
                axes.label(input.registered, 0),
                axes.label(input.registered, 1),
            ]
            || !summary.standard.matches(theme)?
        {
            return Err(Error::Render(
                "prepared panel intrinsic typography changed".into(),
            ));
        }
        Ok(summary)
    }

    pub(crate) fn minimum(&self, y_visible: bool) -> (f64, f64) {
        (
            self.minimum_body.0,
            if y_visible {
                self.minimum_body.1
            } else {
                self.without_y_categories
            },
        )
    }

    #[expect(
        clippy::too_many_lines,
        reason = "one traversal owns title, category and formatted terminal intrinsics"
    )]
    fn analyze(
        axes: &crate::orchestrator::registration::PreparedAxesOwner,
        input: &crate::orchestrator::root::PlotIntrinsicInputs<'_, '_>,
    ) -> Result<Self, Error> {
        let theme = &input.request;
        let diagnostic_scope = input.diagnostic_scope;
        let y_labels_visible = input.y_visible;
        let windows = input.registered.raw_windows();
        let pair = [
            axes.axis(input.registered.source, 0),
            axes.axis(input.registered.source, 1),
        ];
        let _ = diagnostic_scope;
        let standard = CoordinateLayoutInputs::new(theme)?;
        let mut minimum_body = (
            crate::layout::canvas::MINIMUM_PANEL_SPAN,
            crate::layout::canvas::MINIMUM_PANEL_SPAN,
        );
        let mut without_y_categories = minimum_body.1;
        for side in 0..2 {
            if let Some(label) = axes.label(input.registered, side) {
                let (hard, _) = fit::intrinsic_widths(
                    theme,
                    label.as_str(),
                    label.appearance(&standard.axis_title),
                    "standard panel axis title intrinsic",
                )?;
                if side == 0 {
                    minimum_body.0 = minimum_body.0.max(hard);
                } else {
                    minimum_body.1 = minimum_body.1.max(hard);
                    without_y_categories = minimum_body.1;
                }
            }
            let appearance = theme.tick_text_appearance(if side == 0 {
                AxisSide::Bottom
            } else {
                AxisSide::Left
            });
            if appearance.hidden()
                || appearance.layout.is_some_and(|request| {
                    request.instructions().overlap == Some(crate::TextOverlap::Allow)
                        || request
                            .instructions()
                            .visibility
                            .as_ref()
                            .is_some_and(crate::TextVisibility::reduces)
                })
            {
                continue;
            }
            if let Some(categories) = axes.categories(side) {
                let labels = &categories.ticks;
                if side == 1 && !y_labels_visible {
                    continue;
                }
                let span = crate::layout::category_label_span(
                    &pair[side]
                        .authored()
                        .expect("coordinate authored intent")
                        .category_labels,
                    labels.len(),
                    |index| {
                        let label = &labels[index].label;
                        let parallel = if side == 0 {
                            fit::intrinsic_widths(
                                theme,
                                label,
                                appearance,
                                "coordinate panel tick label intrinsic",
                            )?
                            .0
                        } else {
                            // Mandatory lines and actual font metrics, not a
                            // nominal single-line height, constrain row slots.
                            theme
                                .measure_appearance_text(
                                    label,
                                    appearance,
                                    crate::layout::PhysicalTextAlignment::Center,
                                    "coordinate panel tick label intrinsic",
                                )?
                                .occupied_size()
                                .1
                        };
                        Ok(parallel + 2.0 * crate::layout::panel::LABEL_CLEARANCE)
                    },
                )?;
                if side == 0 {
                    minimum_body.0 = minimum_body.0.max(span);
                } else {
                    minimum_body.1 = minimum_body.1.max(span);
                }
            } else if pair[side].exact_ticks()?.is_none()
                && !pair[side].empty_numeric_source(windows[side].map(|window| window.pair()))?
            {
                // The terminal source is derived from this scientific domain,
                // using the same indivisible numeric formatter as tick selection.
                let value = f64::midpoint(axes.ranges()[side].0, axes.ranges()[side].1);
                let power = axes.logarithmic() && side == 0;
                let label = if let Some(probe) = pair[side]
                    .numeric_probe(input.registered.axis_numeric_binding(input.operation)?)?
                {
                    crate::data::source::copy_source_string(&probe.labels[1])?
                } else {
                    crate::layout::panel::format_label(value, power, false, 0)?
                };
                let plan = theme.measure_appearance_text(
                    &label,
                    appearance,
                    crate::layout::PhysicalTextAlignment::Center,
                    "numeric terminal source intrinsic",
                )?;
                let parallel = terminal_parallel_minimum(
                    &plan,
                    if side == 0 {
                        AxisSide::Bottom
                    } else {
                        AxisSide::Left
                    },
                )?;
                if side == 0 {
                    minimum_body.0 = minimum_body.0.max(parallel);
                } else {
                    minimum_body.1 = minimum_body.1.max(parallel);
                    without_y_categories = minimum_body.1;
                }
            }
        }
        Ok(Self {
            standard,
            titles: [
                axes.copy_label(input.registered, 0)?,
                axes.copy_label(input.registered, 1)?,
            ],
            formats: pair.map(|axis| {
                axis.authored()
                    .expect("coordinate authored intent")
                    .format
                    .clone()
            }),
            category_labels: pair.map(|axis| {
                axis.authored()
                    .expect("coordinate authored intent")
                    .category_labels
                    .clone()
            }),
            base_ranges: axes.ranges().map(|(lo, hi)| (lo.to_bits(), hi.to_bits())),
            logarithmic: axes.logarithmic(),
            minimum_body,
            without_y_categories,
            y_labels_analyzed: y_labels_visible,
        })
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "text plans and their half extents retain canonical i64 CSS quanta"
)]
fn terminal_parallel_minimum(
    plan: &crate::layout::ResolvedTextPlan,
    side: AxisSide,
) -> Result<f64, Error> {
    use crate::render::backend::{PlannedTextPlacement, Point2D, TextAnchor};
    let (length, half, anchor) = match side {
        AxisSide::Bottom => (plan.width(), plan.width_quanta, TextAnchor::Middle),
        AxisSide::Left => (plan.height(), plan.height_quanta, TextAnchor::End),
    };
    let half = crate::render::backend::nearest_even_text_half(half)
        .ok_or_else(|| Error::Render("numeric intrinsic half extent overflow".into()))?
        as f64
        / 1024.0;
    let (mut lower, mut upper) = match side {
        AxisSide::Bottom => (-half, length - half),
        AxisSide::Left => (half - length, half),
    };
    let placement = PlannedTextPlacement::middle(Point2D::new(0.0, 0.0), anchor, 0.0);
    if let Some(ink) = crate::render::geometry::planned_text_ink_bounds(
        plan,
        placement.position,
        placement.anchor,
        placement.rotation,
        placement.origin,
        placement.reverse_lines,
    ) {
        let (start, end) = match side {
            AxisSide::Bottom => (ink.left, ink.right),
            AxisSide::Left => (ink.bottom, ink.top),
        };
        lower = lower.min(start);
        upper = upper.max(end);
    }
    let parallel = match side {
        AxisSide::Bottom => (upper - lower).max(plan.fit_width()),
        AxisSide::Left => upper - lower,
    };
    crate::layout::kernel::required_length(parallel + 2.0 * crate::layout::panel::LABEL_CLEARANCE)
}

impl InteriorRoute {
    #[expect(
        clippy::too_many_lines,
        reason = "one native boundary freezes both sibling axes before projecting retained marks"
    )]
    pub(crate) fn measure(
        self,
        plot: &PlotDescription,
        context: &PlotMeasureContext<'_, '_>,
        request: &crate::text::TextRequestContext<'_, '_>,
    ) -> Result<PlotRenderResult, PlanError> {
        self.validate(plot)?;
        let inputs = context.registered.axes.coordinate().ok_or_else(|| {
            Error::Render("native coordinate panel requires root-prepared axes".into())
        })?;
        let valid = match self {
            Self::StandardCoordinate(family) => {
                !inputs.logarithmic()
                    && inputs.categories(1).is_none()
                    && (inputs.categories(0).is_none() || family == StandardCoordinate::Trajectory)
            }
            Self::OneCategoricalAxis(family) => {
                // The prepared source owns orientation and midpoint order. New
                // categorical clusters reuse this boundary without rebuilding it.
                let category_side = match family {
                    OneCategoricalAxis::Bar
                    | OneCategoricalAxis::StackedBar
                    | OneCategoricalAxis::Boxplot
                    | OneCategoricalAxis::Violin
                    | OneCategoricalAxis::Raincloud
                    | OneCategoricalAxis::Interaction => 0,
                    OneCategoricalAxis::PointInterval
                    | OneCategoricalAxis::Coefficient
                    | OneCategoricalAxis::Forest
                    | OneCategoricalAxis::Dumbbell
                    | OneCategoricalAxis::HorizontalBar
                    | OneCategoricalAxis::StackedHorizontalBar => 1,
                };
                inputs.categories(category_side).is_some()
                    && inputs.categories(1 - category_side).is_none()
                    && (!inputs.logarithmic()
                        || (family == OneCategoricalAxis::Forest && inputs.categories(0).is_none()))
            }
            Self::SpecializedGrid(_) => false,
        };
        if !valid {
            return Err(Error::Render("invalid native coordinate axis orientation".into()).into());
        }
        let minimum = plot.intrinsic_body_minimum(
            Some(context.registered),
            context.intrinsic(),
            context.operation,
            request,
            context.assignment.local.ranges(),
        )?;
        let panel = context.assignment.local.body;
        if ![panel.x0, panel.x1, panel.y0, panel.y1]
            .into_iter()
            .all(f64::is_finite)
        {
            return Err(Error::Render("native panel assignment must be finite".into()).into());
        }
        if panel.width() < minimum.0 || panel.height() < minimum.1 {
            return Err(context
                .fit_scope()
                .failure(
                    FitKind::TrackOrResidual,
                    "assigned coordinate panel is smaller than its foundational intrinsics",
                )
                .into());
        }
        let [x_range, y_range] = [AxisSide::Bottom, AxisSide::Left].map(|side| {
            let index = usize::from(side == AxisSide::Left);
            if inputs.categories(index).is_some() {
                Ok(inputs.ranges()[index])
            } else {
                context.axis_range(side)
            }
        });
        let projection = Projection::new(x_range?, y_range?, panel.as_tuple()).with_categories(
            [inputs.categories(0), inputs.categories(1)]
                .map(|categories| categories.map(|categories| categories.raw.len())),
        );

        let mut keys = [None, None];
        let domains = [inputs.categories(0), inputs.categories(1)].map(|categories| {
            if categories.is_some() {
                AxisDomain::Categorical
            } else {
                AxisDomain::Continuous
            }
        });
        let assigned = context
            .axis_pair(crate::orchestrator::assignment::AxisPairScope::Pair)?
            .axes;
        let mut axes = fit::collect(
            "native coordinate axes",
            (0..2).map(|side| {
                let base = inputs.axis(context.registered.source, side);
                let supplied = if let Some(categories) = inputs.categories(side) {
                    let display = &categories.ticks;
                    if display.len() != categories.raw.len() {
                        return Err(Error::Render(
                            "native category sources are not aligned".into(),
                        )
                        .into());
                    }
                    keys[side] = Some(crate::data::source::collect_source(
                        categories
                            .raw
                            .iter()
                            .map(|label| crate::data::source::copy_source_string(label)),
                    )?);
                    crate::data::source::collect_source(display.iter().map(|tick| {
                        Ok(crate::layout::AxisTick {
                            position: tick.position,
                            label: crate::data::source::copy_source_string(&tick.label)?,
                        })
                    }))?
                } else {
                    Vec::new()
                };
                let assigned = assigned[side];
                let ticks = if side == 0 && inputs.logarithmic() && base.exact_ticks()?.is_none() {
                    crate::plots::interval_estimate::log_tick_plan(
                        projection.x_range(),
                        assigned,
                        panel,
                        request,
                        context.fit_scope(),
                        context.registered.axis_numeric_binding(context.operation)?,
                    )?
                } else {
                    assigned.layout_ticks(
                        supplied,
                        &projection,
                        if side == 0 {
                            AxisSide::Bottom
                        } else {
                            AxisSide::Left
                        },
                        request,
                        context.fit_scope(),
                        context.registered.axis_numeric_binding(context.operation)?,
                    )?
                };
                Ok(Axis {
                    label: inputs.copy_label(context.registered, side)?,
                    ticks: ticks.ticks,
                    tick_labels_visible: side == 0
                        || crate::orchestrator::registration::axis_tick_labels_visible(
                            Some(context.registered),
                            1,
                        ),
                    category_labels: base
                        .authored()
                        .expect("coordinate authored intent")
                        .category_labels
                        .clone(),
                    explicit_ticks: base.exact_ticks()?.is_some(),
                    assigned_tick_width: None,
                    assigned_cells: None,
                    source: ticks.source,
                    numeric: ticks.numeric,
                })
            }),
        )?;
        let y_axis = axes.pop().expect("two measured axes");
        let x_axis = axes.pop().expect("two measured axes");
        let layout = Layout {
            projection,
            x_axis,
            y_axis,
        };
        let frozen = layout.measure_axes_with_inputs(
            request,
            context.fit_scope(),
            std::array::from_fn(|side| {
                let mut input = assigned[side].semantic_inputs();
                input
                    .text_layout
                    .clone_from(&request.text_layouts.ticks[side]);
                input
            }),
            || CoordinateLayoutInputs::new(request),
        )?;
        let marks = super::measure_selected_interior(context, &layout, request)?;
        let mut result = PlotRenderResult::new(
            layout,
            crate::orchestrator::registration::guide_descriptor(Some(context.registered))?,
        );
        result.marks = Some(marks.marks);
        result.significance = marks.significance;
        result.deferred_annotation_text = marks.deferred_annotation_text;
        result.numeric_presentation = marks.numeric_presentation;
        result.axes = Some(frozen);
        [result.x_tick_keys, result.y_tick_keys] = keys;
        result.x_domain = domains[0];
        result.y_domain = domains[1];
        Ok(result)
    }
}