Skip to main content

sva_engine/render/
answer.rs

1// Concern: takes one reading off the representation a node declares, a ledger edge by edge | Non-concern: naming the observations (query.rs), the arithmetic of one | IO: (&Render, node) -> Answer
2
3use sva_formula::spectral_sum::atom::{Singular, SpectralAtom};
4use sva_formula::{AUDIBLE_CEILING_HZ, Line, SpectralSum, Var, d_dt, envelope, line_atoms};
5use sva_samples::{
6    AliasScore, Buffer, Consumes, Extent, Peak, PitchFrame, Source, measure::bands, measure::crest,
7    measure::envelope, measure::formants, measure::loudness, measure::pitch, measure::spectrum,
8    measure::stereo, measure_alias,
9};
10
11use crate::error::{Diagnostic, EngineError, Located};
12use crate::query::{Answer, DEFAULT_FRAME_SECS, Output, Representation};
13use crate::refs;
14use crate::render::Render;
15use crate::typing::Value;
16
17/// A closed form answers off its spectral sum and a buffer off its samples; its own `Ty`
18/// decides which, never a flag on the observation.
19pub fn answer(
20    render: &Render,
21    node: sva_formula::NodeId,
22    representation: Representation,
23) -> Result<Answer, EngineError> {
24    let closed = render.tys.ty(node).is_closed_form();
25    let profile = render.config.profile.name;
26    if representation == Representation::Flops {
27        return Ok(Answer::whole(
28            Output::Flops(Box::new(crate::flops::tree_at(render, node))),
29            Source::Exact,
30            profile,
31            None,
32        ));
33    }
34    if representation == Representation::Arguments {
35        return Ok(Answer::whole(
36            Output::Arguments(arguments_under(render, node)),
37            Source::Exact,
38            profile,
39            None,
40        ));
41    }
42    if representation == Representation::Bindings {
43        return Ok(Answer::whole(
44            Output::Bindings(render.bindings.get(&node).cloned().unwrap_or_default()),
45            Source::Exact,
46            profile,
47            None,
48        ));
49    }
50    match representation.consumes(closed) {
51        Consumes::ClosedForm => {
52            let found;
53            let sum = match render.symbolic.get(&node) {
54                Some(held) => held,
55                None => match refs::spectral_sum_of(&render.tys, node, render.tys.var(node)) {
56                    Ok(held) => {
57                        found = held;
58                        &found
59                    }
60                    Err(left) => return measured_instead(render, node, representation, left),
61                },
62            };
63            let (value, listed, source) = match exact(render, node, representation, sum) {
64                Err(left) => return measured_instead(render, node, representation, left),
65                Ok(held) => held,
66            };
67            Ok(Answer {
68                value,
69                source,
70                profile,
71                rate: None,
72                tail_db: listed.tail_db(),
73                dropped: listed.dropped,
74            })
75        }
76        _ => {
77            if render.buffer(node).is_none() {
78                return Err(unmaterialized(render, node, representation));
79            }
80            let buffer = render.output(node)?;
81            Ok(Answer::whole(
82                measured(render, node, representation, &buffer)?,
83                Source::Measured,
84                profile,
85                Some(render.config.rate),
86            ))
87        }
88    }
89}
90
91/// A closed form no atom sum reaches answers no reading symbolically. An envelope is the one
92/// FORMAT 9.3 already names off `sample(...)`, so it is measured here rather than refused.
93fn measured_instead(
94    render: &Render,
95    node: sva_formula::NodeId,
96    representation: Representation,
97    left: EngineError,
98) -> Result<Answer, EngineError> {
99    match representation {
100        Representation::Envelope { frame_secs } if left.code() == "cast.left_algebra" => {
101            off_the_grid(render, node, frame_secs)
102        }
103        _ => Err(left),
104    }
105}
106
107/// The samples this node reaches: the buffer the render holds, or the collapse it would have run,
108/// down to FORMAT 9.1's row 4 over the written closed form.
109pub(super) fn on_the_grid(
110    render: &Render,
111    node: sva_formula::NodeId,
112) -> Result<Buffer, EngineError> {
113    if render.buffer(node).is_some() {
114        return render.output(node);
115    }
116    let extent = render.range.ok_or_else(|| {
117        render.unranged.clone().unwrap_or_else(|| {
118            refused(
119                render,
120                node,
121                "engine.not_materialized",
122                "a measured envelope reads samples, and this render read none".to_string(),
123            )
124        })
125    })?;
126    collapsed_over(render, node, extent)
127}
128
129fn collapsed_over(
130    render: &Render,
131    node: sva_formula::NodeId,
132    extent: sva_samples::Extent,
133) -> Result<Buffer, EngineError> {
134    super::sampled(render, node, extent)
135}
136
137fn off_the_grid(
138    render: &Render,
139    node: sva_formula::NodeId,
140    frame_secs: Option<f64>,
141) -> Result<Answer, EngineError> {
142    let rate = render.config.rate;
143    let buffer = on_the_grid(render, node)?;
144    Ok(Answer::whole(
145        Output::Envelope(envelope::trace(
146            &buffer.slices(),
147            f64::from(rate),
148            buffer.origin_secs(),
149            frame_secs.unwrap_or(DEFAULT_FRAME_SECS),
150        )),
151        Source::Measured,
152        render.config.profile.name,
153        Some(rate),
154    ))
155}
156
157fn exact(
158    render: &Render,
159    node: sva_formula::NodeId,
160    representation: Representation,
161    sum: &SpectralSum,
162) -> Result<(Output, Listed, Source), EngineError> {
163    let source = Source::Exact;
164    let enumerated = || {
165        listed(
166            render,
167            node,
168            sum,
169            render.config.profile.floor(AUDIBLE_CEILING_HZ),
170            render.config.profile.half_lsb(),
171        )
172    };
173    let (value, listed) = match representation {
174        Representation::Lines => {
175            let listed = enumerated()?;
176            let held = lines(render, node, sum.var, &listed.atoms)?;
177            (Output::Lines(held), listed)
178        }
179        Representation::Spectrum {
180            frame_secs: Some(_),
181            ..
182        } => {
183            return Err(EngineError::refused(Diagnostic {
184                code: "engine.observation_needs_samples".to_string(),
185                message: "a closed form's spectrum is its lines, and it has no frames to \
186                          take a spectrum across"
187                    .to_string(),
188                location: Located::at(render.tys.name(node), None),
189                help: "drop `frame` for the lines, or read `sample(...)` of it to measure \
190                       frames"
191                    .to_string(),
192            }));
193        }
194        // FORMAT 14.1: a pair's spectrum is its whole line list; no estimate, no peaks.
195        Representation::Spectrum {
196            frame_secs: None, ..
197        } => {
198            let listed = enumerated()?;
199            let mut held = lines(render, node, sum.var, &listed.atoms)?;
200            held.sort_by(|a, b| a.hz.total_cmp(&b.hz));
201            (Output::Lines(held), listed)
202        }
203        Representation::Atoms => {
204            let listed = enumerated()?;
205            let found = listed.atoms.iter().map(sketch_atom).collect();
206            (Output::Atoms(found), listed)
207        }
208        // A pair states its partials; `max_notes` is the question, not a cut answer.
209        Representation::Pitch { max_notes, .. } => {
210            let listed = enumerated()?;
211            let held = lines(render, node, sum.var, &listed.atoms)?;
212            let mut found: Vec<Peak> = held
213                .iter()
214                .filter(|l| l.hz > 0.0)
215                .map(|l| Peak {
216                    hz: l.hz,
217                    db: 20.0 * amplitude_at(&held, l.hz).log10(),
218                })
219                .collect();
220            found.sort_by(|a, b| b.db.total_cmp(&a.db));
221            let frame = PitchFrame {
222                t_secs: render
223                    .range
224                    .map_or(0.0, |range| range.start_secs(render.config.rate)),
225                notes: pitch::name_peaks(&found, max_notes),
226            };
227            (Output::Pitch(vec![frame]), listed)
228        }
229        Representation::Derivative => (Output::Symbolic(Box::new(d_dt(sum))), Listed::NONE),
230        Representation::Envelope { .. } => {
231            let held = envelope(sum).map_err(|left| {
232                EngineError::of_closed_form(
233                    &left.refusal(),
234                    render.tys.locate(left.origin),
235                    "read the envelope off sample(...) for a measured one",
236                )
237            })?;
238            (Output::Symbolic(Box::new(held.squared)), Listed::NONE)
239        }
240        other => return Err(not_a_closed_form(render, node, other)),
241    };
242    Ok((value, listed, source))
243}
244
245/// Every atom the spectral sum stands for, beside the terms its series truncated away or left
246/// above the ceiling: `atoms` alone holds only the terms already written out.
247struct Listed {
248    atoms: Vec<SpectralAtom>,
249    dropped: Vec<Line>,
250}
251
252impl Listed {
253    /// A reading that enumerates no series leaves nothing out.
254    const NONE: Listed = Listed {
255        atoms: Vec::new(),
256        dropped: Vec::new(),
257    };
258
259    /// FORMAT 9.3: the tail is the loudest line left out against the loudest one kept, so
260    /// it is one ratio over the whole answer, never a per-series one carried upward.
261    fn tail_db(&self) -> Option<f64> {
262        let loudest = |set: &mut dyn Iterator<Item = f64>| set.fold(0.0f64, f64::max);
263        let gone = loudest(&mut self.dropped.iter().map(|l| l.amp.abs()));
264        let kept = loudest(&mut self.atoms.iter().map(|a| a.c.abs()));
265        (gone > 0.0 && kept > 0.0).then(|| 20.0 * (gone / kept).log10())
266    }
267}
268
269/// Each lane's series enumerated under the band a rate-free reading is taken in. A series
270/// whose term no line closed form reads yields nothing, and nothing is not an exact empty answer.
271fn listed(
272    render: &Render,
273    node: sva_formula::NodeId,
274    sum: &SpectralSum,
275    floor_db: f64,
276    precision: f64,
277) -> Result<Listed, EngineError> {
278    let mut held = Listed::NONE;
279    for lane in &sum.lanes {
280        held.atoms.extend(lane.clone().expanded().atoms);
281        for series in &lane.series {
282            let Some(found) = line_atoms(series, AUDIBLE_CEILING_HZ, floor_db, precision) else {
283                return Err(unenumerable(render, node));
284            };
285            held.atoms.extend(found.atoms);
286            held.dropped.extend(found.dropped);
287        }
288    }
289    Ok(held)
290}
291
292/// The exact line list of a pair: in `t` a bare turning exponential, in `f` the delta it
293/// duals to. A list every other atom was dropped from answers a spectrum this node has not.
294fn lines(
295    render: &Render,
296    node: sva_formula::NodeId,
297    var: Var,
298    atoms: &[SpectralAtom],
299) -> Result<Vec<Line>, EngineError> {
300    atoms
301        .iter()
302        .map(|a| line_of(var, a).ok_or_else(|| not_a_line(render, node, var, a)))
303        .collect()
304}
305
306fn line_of(var: Var, a: &SpectralAtom) -> Option<Line> {
307    match (var, a.sing) {
308        (Var::F, Singular::Delta { at, order: 0 }) => Some(Line::bare(at, a.c)),
309        (Var::T, Singular::Regular) => {
310            if !a.poly.is_one() || a.gauss.is_some() || a.ind.is_some() || a.pole.is_some() {
311                return None;
312            }
313            match a.exp {
314                // A constant turns at no rate, which is the line at zero hertz.
315                None => Some(Line::bare(0.0, a.c)),
316                Some(e) if e.sigma == 0.0 => Some(Line::bare(e.omega / std::f64::consts::TAU, a.c)),
317                Some(_) => None,
318            }
319        }
320        _ => None,
321    }
322}
323
324/// What gave this atom a width; a turning exponential is the line itself and never among it.
325fn widening(a: &SpectralAtom) -> Vec<&'static str> {
326    let mut held = Vec::new();
327    if !a.poly.is_one() {
328        held.push("a polynomial");
329    }
330    if a.exp.is_some_and(|e| e.sigma != 0.0) {
331        held.push("a decaying exponential");
332    }
333    if a.gauss.is_some() {
334        held.push("a Gaussian");
335    }
336    if a.pole.is_some() {
337        held.push("a pole");
338    }
339    if held.is_empty() {
340        held.push("a delta");
341    }
342    held
343}
344
345/// Convolved into a line, each shape beside the turning exponential answers a band.
346fn not_a_line(
347    render: &Render,
348    node: sva_formula::NodeId,
349    var: Var,
350    atom: &SpectralAtom,
351) -> EngineError {
352    let mut at = render.tys.locate(atom.origin);
353    if at.node.is_empty() {
354        at = Located::at(render.tys.name(node), None);
355    }
356    let message = match atom.ind {
357        _ if var == Var::F => "this term spreads over `f` rather than standing at one \
358                               frequency, and a line in `f` is a delta"
359            .to_string(),
360        Some(window) => format!(
361            "this term is windowed to [{}s, {}s), and a windowed line is that line convolved \
362             with the window's transform, which has a width and is no line",
363            window.l.value(),
364            window.r.value()
365        ),
366        None => format!(
367            "this term carries {}, and a line is a bare turning exponential: each of those \
368             convolves the line with a shape of its own width",
369            widening(atom).join(", ")
370        ),
371    };
372    EngineError::refused(Diagnostic {
373        code: "read.lines_need_unwindowed_lines".to_string(),
374        message,
375        location: at,
376        help: "`atoms` states each term as it stands, `lines` of the node under the window \
377               or envelope lists the lines it multiplies, and `pitch` or `spectrum` of \
378               `sample(...)` of it measures it frame by frame"
379            .to_string(),
380    })
381}
382
383/// The amplitude a partial sounds at: a real wave carries it in a conjugate pair, half in
384/// each, and a measured peak reads the pair's sum.
385fn amplitude_at(held: &[Line], hz: f64) -> f64 {
386    held.iter()
387        .filter(|l| (l.hz - hz).abs() <= f64::EPSILON * hz.abs() || l.hz == -hz)
388        .map(|l| l.amp.abs())
389        .sum()
390}
391
392/// One atom as the six factors it is present in, which is what `atoms` answers with.
393pub fn sketch_atom(a: &SpectralAtom) -> String {
394    let factors: Vec<&'static str> = a.present().iter().map(|f| f.as_str()).collect();
395    format!("{} x {}", a.c.abs(), factors.join(" times "))
396}
397
398fn measured(
399    render: &Render,
400    node: sva_formula::NodeId,
401    representation: Representation,
402    buffer: &Buffer,
403) -> Result<Output, EngineError> {
404    Ok(match representation {
405        Representation::Alias { oversample } => {
406            let reference = oversampled(render, behind(render, node)?, oversample)?;
407            Output::Alias(Box::new(worst_alias(buffer, &reference, oversample)))
408        }
409        Representation::Ledger { depth } => Output::Ledger(attributed(render, node, depth)?),
410        other => {
411            return off_buffer(buffer, other).map_err(|fault| match fault {
412                NoReading::NeedsAGraph => not_a_reading(render, node, other),
413                NoReading::TooNarrow { need, held } => too_narrow(render, node, need, held),
414            });
415        }
416    })
417}
418
419/// Why a buffer answered nothing: the reading needs the tree the node was built from, or
420/// the buffer is narrower than the reading needs.
421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
422pub enum NoReading {
423    NeedsAGraph,
424    TooNarrow { need: usize, held: usize },
425}
426
427/// Every reading a buffer answers on its own, with no graph behind it.
428pub fn off_buffer(buffer: &Buffer, representation: Representation) -> Result<Output, NoReading> {
429    let sr = f64::from(buffer.rate);
430    let start = buffer.origin_secs();
431    let plane = buffer.plane(0);
432    Ok(match representation {
433        Representation::Samples => Output::Samples(Box::new(buffer.clone())),
434        Representation::Spectrum {
435            max_peaks,
436            frame_secs,
437        } => Output::Spectrum(Box::new(spectrum::analyze(
438            plane, sr, max_peaks, frame_secs,
439        ))),
440        Representation::Envelope { frame_secs } => Output::Envelope(envelope::trace(
441            &buffer.slices(),
442            sr,
443            start,
444            frame_secs.unwrap_or(DEFAULT_FRAME_SECS),
445        )),
446        Representation::Derivative => Output::Samples(Box::new(difference(buffer))),
447        Representation::Pitch {
448            max_notes,
449            frame_secs,
450        } => Output::Pitch(pitch::track(plane, sr, start, frame_secs, max_notes)),
451        Representation::Formants {
452            max_formants,
453            frame_secs,
454        } => Output::Formants(formants::track(
455            plane,
456            sr,
457            start,
458            frame_secs,
459            formants::default_order(sr),
460            max_formants,
461        )),
462        Representation::Stereo { frame_secs } => {
463            if buffer.width < 2 {
464                return Err(NoReading::TooNarrow {
465                    need: 2,
466                    held: buffer.width,
467                });
468            }
469            let planes: Vec<&[f64]> = (0..buffer.width).map(|c| buffer.plane(c)).collect();
470            Output::Stereo(Box::new(stereo::analyze(
471                &planes,
472                buffer.width,
473                sr,
474                start,
475                frame_secs,
476            )))
477        }
478        Representation::Bands => Output::Bands(Box::new(bands::analyze(plane, sr, start))),
479        Representation::Crest => Output::Crest(Box::new(crest::analyze(plane, sr))),
480        Representation::Loudness => {
481            let planes: Vec<&[f64]> = (0..buffer.width).map(|c| buffer.plane(c)).collect();
482            Output::Loudness(Box::new(loudness::analyze(&planes, sr, start)))
483        }
484        _ => return Err(NoReading::NeedsAGraph),
485    })
486}
487
488/// Every held buffer under the target over the root's range, its own refs beside it, so the
489/// reading can share the target's energy down the tree it was built from. A ref the closed form
490/// adds stands there as what it contributed to the node reading it; one no addend isolates is
491/// left unattributed.
492fn attributed(
493    render: &Render,
494    node: sva_formula::NodeId,
495    depth: usize,
496) -> Result<Vec<sva_samples::LedgerEntry>, EngineError> {
497    let holds = |id: sva_formula::NodeId| render.buffers.contains_key(&id);
498    let edges = edges_under(render, node, depth, &holds)?;
499    let under: std::collections::BTreeSet<sva_formula::NodeId> = std::iter::once(node)
500        .chain(edges.iter().map(|(_, child)| *child))
501        .collect();
502    let mut deps = std::collections::BTreeMap::new();
503    let mut kinds = std::collections::BTreeMap::new();
504    for id in render.buffers.keys().filter(|id| under.contains(id)) {
505        let name = render.tys.name(*id).to_string();
506        let read = refs_read(render, *id, &holds)?
507            .into_iter()
508            .map(|op| render.tys.name(op).to_string())
509            .collect();
510        deps.insert(name.clone(), read);
511        kinds.insert(name, sva_samples::SignalKind::Audio);
512    }
513    let mut contributed_by = std::collections::BTreeMap::new();
514    for (parent, child) in &edges {
515        if !crate::render::slots::reads_held(render, *parent)? {
516            return Err(unmaterialized(
517                render,
518                node,
519                Representation::Ledger { depth },
520            ));
521        }
522        if let Some(held) = contributed(render, *parent, *child)? {
523            contributed_by.insert(render.tys.name(*child).to_string(), held);
524        }
525    }
526    // A row's own samples are read where it reads rows itself or no addend isolates it.
527    let readers: std::collections::BTreeSet<_> = edges.iter().map(|(parent, _)| *parent).collect();
528    let mut buffers = std::collections::BTreeMap::new();
529    for id in render.buffers.keys().filter(|id| under.contains(id)) {
530        let name = render.tys.name(*id);
531        if *id == node || readers.contains(id) || !contributed_by.contains_key(name) {
532            buffers.insert(name.to_string(), own_samples(render, *id)?);
533        }
534    }
535    let len = render.range.map_or(0, |range| range.len());
536    Ok(sva_samples::measure::ledger::attribute(
537        &buffers,
538        &contributed_by,
539        &deps,
540        &kinds,
541        render.tys.name(node),
542        0..len,
543        depth,
544    ))
545}
546
547/// A row's own samples over the range, held or pulled.
548fn own_samples(render: &Render, id: sva_formula::NodeId) -> Result<Buffer, EngineError> {
549    let range = render.range.expect("a ledger reads a decided range");
550    match render.buffer(id) {
551        Some(_) => render.output(id),
552        None => collapsed_over(render, id, range),
553    }
554}
555
556/// What every instance under `node` was lowered with, `node` first, then breadth first. The
557/// walk is over what each node was lowered to, so it needs no buffer.
558fn arguments_under(render: &Render, node: sva_formula::NodeId) -> Vec<crate::Arguments> {
559    let under = |id: sva_formula::NodeId| -> Vec<sva_formula::NodeId> {
560        match render.tys.value(id) {
561            Value::ClosedForm(form) => refs::nodes_in(&form.body),
562            Value::Read { source, .. } | Value::Cast(_, source) => vec![*source],
563            Value::Op { args, .. } => args.clone(),
564            Value::Filter {
565                x, cutoff, q, gain, ..
566            } => vec![*x, *cutoff, *q, *gain],
567            Value::Solver { varying, .. } => varying.iter().map(|(_, a)| *a).collect(),
568            Value::SelfAt { .. } | Value::Noise(_) | Value::Stored(_) => Vec::new(),
569        }
570    };
571    let mut names: Vec<&str> = Vec::new();
572    let mut seen = std::collections::BTreeSet::from([node]);
573    let mut level = vec![node];
574    while !level.is_empty() {
575        let mut next = Vec::new();
576        for at in level {
577            let name = render.tys.name(at);
578            if !names.contains(&name) {
579                names.push(name);
580            }
581            next.extend(under(at).into_iter().filter(|c| seen.insert(*c)));
582        }
583        level = next;
584    }
585    names
586        .into_iter()
587        .filter_map(|name| render.tys.arguments(name).cloned())
588        .collect()
589}
590
591/// The tree a ledger walks; a node several read is attributed to the first to reach it.
592fn edges_under(
593    render: &Render,
594    node: sva_formula::NodeId,
595    depth: usize,
596    holds: &dyn Fn(sva_formula::NodeId) -> bool,
597) -> Result<Vec<(sva_formula::NodeId, sva_formula::NodeId)>, EngineError> {
598    let mut seen = std::collections::BTreeSet::from([node]);
599    let (mut level, mut out) = (vec![node], Vec::new());
600    for _ in 0..depth {
601        let mut next = Vec::new();
602        for parent in level {
603            for child in refs_read(render, parent, holds)? {
604                if seen.insert(child) {
605                    out.push((parent, child));
606                    next.push(child);
607                }
608            }
609        }
610        level = next;
611    }
612    Ok(out)
613}
614
615/// Every ref one node's program reads, one row per name.
616fn refs_read(
617    render: &Render,
618    node: sva_formula::NodeId,
619    holds: &dyn Fn(sva_formula::NodeId) -> bool,
620) -> Result<Vec<sva_formula::NodeId>, EngineError> {
621    crate::render::slots::refs_read(render, node, holds)
622}
623
624/// What one ref contributed to the node reading it, at that node's own offset and window: its
625/// program with every other slot silenced. Two under one product have no addend apiece and no
626/// share either, so that edge is left unattributed.
627fn contributed(
628    render: &Render,
629    parent: sva_formula::NodeId,
630    child: sva_formula::NodeId,
631) -> Result<Option<Buffer>, EngineError> {
632    let range = render.range.expect("a ledger reads a decided range");
633    Ok(crate::render::slots::contributed(render, parent, child)?
634        .map(|held| held.over(range, held.extent())))
635}
636
637/// The closed form an alias score oversamples: the node itself where it is one, and the operand of
638/// the `sample(...)` that collapsed it where it is not.
639fn behind(render: &Render, node: sva_formula::NodeId) -> Result<sva_formula::NodeId, EngineError> {
640    if render.tys.ty(node).is_closed_form() {
641        return Ok(node);
642    }
643    match render.tys.value(node) {
644        crate::typing::Value::Cast(crate::cast::Cast::Sample, source) => Ok(*source),
645        _ => Err(refused(
646            render,
647            node,
648            "engine.alias_needs_a_closed_form",
649            "an alias score is a render against the same closed form oversampled, and this node \
650             is samples with no closed form behind it"
651                .to_string(),
652        )),
653    }
654}
655
656/// The score a point sampling's label carries where a reading asks for one: the node against
657/// its own closed form oversampled.
658pub(super) fn alias_db(
659    render: &Render,
660    node: sva_formula::NodeId,
661    buffer: &Buffer,
662) -> Result<f64, EngineError> {
663    let oversample = sva_samples::ALIAS_OVERSAMPLE as u32;
664    let reference = oversampled(render, behind(render, node)?, oversample)?;
665    Ok(worst_alias(buffer, &reference, oversample).asr_db)
666}
667
668/// Each component scored against its own reference, and `worst` says which one answers.
669fn worst_alias(buffer: &Buffer, reference: &Buffer, oversample: u32) -> sva_samples::Alias {
670    debug_assert_eq!(
671        buffer.width, reference.width,
672        "the reference is the same form at another rate"
673    );
674    let sr = f64::from(buffer.rate);
675    let width = buffer.width.min(reference.width);
676    sva_samples::worst_alias((0..width).map(|c| {
677        measure_alias(
678            buffer.plane(c),
679            reference.plane(c),
680            oversample as usize,
681            sr,
682            buffer.origin_secs(),
683        )
684    }))
685    .expect("a buffer holds at least one component")
686}
687
688/// The same closed form read at a multiple of the rate, which is what an alias score is against.
689fn oversampled(
690    render: &Render,
691    node: sva_formula::NodeId,
692    oversample: u32,
693) -> Result<Buffer, EngineError> {
694    let rate = render.config.rate * oversample;
695    let range = render.range.expect("an alias score reads a decided range");
696    let k = i64::from(oversample);
697    let extent = Extent::new(range.start * k, range.end * k);
698    let taken = match refs::spectral_sum_of(&render.tys, node, Var::T) {
699        Ok(sum) => sva_samples::of_spectral_sum(
700            &sum,
701            rate,
702            extent,
703            &render.config.profile,
704            AliasScore::NotAsked,
705        ),
706        Err(_) => return super::finer(render, node, oversample, extent),
707    };
708    taken.map(|(buffer, _)| buffer).map_err(|e| {
709        EngineError::refused(Diagnostic {
710            code: e.code().to_string(),
711            message: e.to_string(),
712            location: Located::at(render.tys.name(node), None),
713            help: "an alias score needs a closed form to oversample".to_string(),
714        })
715    })
716}
717
718/// A first difference on the grid, which is what a derivative is once the closed form is gone.
719fn difference(buffer: &Buffer) -> Buffer {
720    let step = f64::from(buffer.rate);
721    let planes = (0..buffer.width)
722        .map(|c| {
723            let plane = buffer.plane(c);
724            plane
725                .iter()
726                .enumerate()
727                .map(|(i, x)| match i {
728                    0 => 0.0,
729                    _ => (x - plane[i - 1]) * step,
730                })
731                .collect()
732        })
733        .collect();
734    let mut out = Buffer::of_planes(buffer.rate, planes);
735    out.start = buffer.start;
736    out
737}
738
739fn refused(render: &Render, node: sva_formula::NodeId, code: &str, message: String) -> EngineError {
740    EngineError::refused(Diagnostic {
741        code: code.to_string(),
742        message,
743        location: Located::at(render.tys.name(node), None),
744        help: "ask for a reading this representation answers".to_string(),
745    })
746}
747
748fn unenumerable(render: &Render, node: sva_formula::NodeId) -> EngineError {
749    refused(
750        render,
751        node,
752        "read.series_not_enumerable",
753        "a series whose term is no line lists no lines, and an empty list would read as \
754         a node with none"
755            .to_string(),
756    )
757}
758
759fn not_a_closed_form(render: &Render, node: sva_formula::NodeId, r: Representation) -> EngineError {
760    refused(
761        render,
762        node,
763        "engine.observation_needs_samples",
764        format!(
765            "`{}` reads samples, and this node is a closed form",
766            r.name()
767        ),
768    )
769}
770
771fn not_a_reading(render: &Render, node: sva_formula::NodeId, r: Representation) -> EngineError {
772    refused(
773        render,
774        node,
775        "engine.observation_not_wired",
776        format!("`{}` takes no reading off a buffer here", r.name()),
777    )
778}
779
780fn too_narrow(render: &Render, node: sva_formula::NodeId, need: usize, held: usize) -> EngineError {
781    refused(
782        render,
783        node,
784        "type.width_mismatch",
785        format!("this reading needs {need} components and the node holds {held}"),
786    )
787}
788
789pub(super) fn unheld(render: &Render, node: sva_formula::NodeId) -> EngineError {
790    refused(
791        render,
792        node,
793        "engine.not_materialized",
794        "this render held no samples of it".to_string(),
795    )
796}
797
798fn unmaterialized(render: &Render, node: sva_formula::NodeId, r: Representation) -> EngineError {
799    refused(
800        render,
801        node,
802        "engine.not_materialized",
803        format!("`{}` reads samples this render never held", r.name()),
804    )
805}
806
807/// One reading off a buffer nothing rendered — an external file, say — under the profile the
808/// caller names. Every representation needing the graph behind it refuses here.
809pub fn answer_buffer(
810    name: &str,
811    buffer: &Buffer,
812    representation: Representation,
813    profile: &'static str,
814) -> Result<Answer, EngineError> {
815    let refused = |code: &str, message: String| {
816        EngineError::refused(Diagnostic {
817            code: code.to_string(),
818            message,
819            location: Located::at(name, None),
820            help: "ask for a reading a buffer answers on its own".to_string(),
821        })
822    };
823    let value = off_buffer(buffer, representation).map_err(|fault| match fault {
824        NoReading::NeedsAGraph => refused(
825            "engine.observation_needs_a_graph",
826            format!(
827                "`{}` reads the tree a node was built from, and a file has none",
828                representation.name()
829            ),
830        ),
831        NoReading::TooNarrow { need, held } => refused(
832            "type.width_mismatch",
833            format!("this reading needs {need} components and the file holds {held}"),
834        ),
835    })?;
836    Ok(Answer::whole(
837        value,
838        Source::Measured,
839        profile,
840        Some(buffer.rate),
841    ))
842}