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