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::closed_form::Edge;
4use sva_formula::spectral_sum::atom::{Singular, SpectralAtom};
5use sva_formula::{C64, Line, SpectralSum, Var, d_dt, envelope_read, line_atoms_read};
6use sva_samples::measure::harmony::dissonance::Crowded;
7use sva_samples::measure::harmony::{
8    self, Framing, Moment, chords, dissonance, inharmonicity, measured as framed, tonnetz,
9    voice_leading,
10};
11use sva_samples::measure::{modulation, periodicity, self_similarity, sliding};
12use sva_samples::{
13    Buffer, Consumes, Extent, Peak, PitchFrame, Profile, Source, measure::bands, measure::crest,
14    measure::envelope, measure::formants, measure::loudness, measure::onsets, measure::pitch,
15    measure::spectrum, measure::stereo, measure_alias,
16};
17
18use crate::error::{Diagnostic, EngineError, Located};
19use crate::query::{Answer, Atom, DEFAULT_FRAME_SECS, Harmonic, Output, Representation};
20use crate::refs;
21use crate::render::Render;
22use crate::typing::Value;
23
24/// A closed form answers off its spectral sum and a buffer off its samples; its own `Ty`
25/// decides which, never a flag on the observation.
26pub fn answer(
27    render: &Render,
28    node: sva_formula::NodeId,
29    representation: Representation,
30) -> Result<Answer, EngineError> {
31    let closed = render.tys.ty(node).is_closed_form();
32    let profile = render.config.profile.name;
33    if representation == Representation::Arguments {
34        return Ok(Answer::whole(
35            Output::Arguments(arguments_under(render, node)),
36            Source::Exact,
37            profile,
38            None,
39        ));
40    }
41    if representation == Representation::Bindings {
42        return Ok(Answer::whole(
43            Output::Bindings(render.bindings.get(&node).cloned().unwrap_or_default()),
44            Source::Exact,
45            profile,
46            None,
47        ));
48    }
49    match representation.consumes(closed) {
50        Consumes::ClosedForm => {
51            let found;
52            let sum = match render.symbolic.get(&node) {
53                Some(held) => held,
54                None => match refs::spectral_sum_of(&render.tys, node, render.tys.var(node)) {
55                    Ok(held) => {
56                        found = held;
57                        &found
58                    }
59                    Err(left) => return Err(unsummed(representation, left)),
60                },
61            };
62            let (value, listed, source) = exact(render, node, representation, sum)
63                .map_err(|left| not_exact(representation, left))?;
64            Ok(Answer {
65                value,
66                source,
67                profile,
68                rate: None,
69                tail_db: listed.tail_db(),
70                dropped: listed.dropped,
71            })
72        }
73        _ => {
74            if render.buffer(node).is_none() {
75                return Err(unmaterialized(render, node, representation));
76            }
77            let buffer = render.output(node)?;
78            Ok(Answer::whole(
79                measured(render, node, representation, &buffer)?,
80                Source::Measured,
81                profile,
82                Some(render.config.rate),
83            ))
84        }
85    }
86}
87
88fn exact(
89    render: &Render,
90    node: sva_formula::NodeId,
91    representation: Representation,
92    sum: &SpectralSum,
93) -> Result<(Output, Listed, Source), EngineError> {
94    let source = Source::Exact;
95    let enumerated = || listed(render, node, sum, &render.config.profile);
96    let (value, listed) = match representation {
97        Representation::Lines => {
98            let listed = enumerated()?;
99            let held = lines(render, node, sum.var, &listed.atoms)?;
100            (Output::Lines(held), listed)
101        }
102        Representation::Spectrum {
103            frame_secs: Some(_),
104            ..
105        } => return Err(unframed(render, node, "spectrum is its lines", "the lines")),
106        Representation::Envelope {
107            frame_secs: Some(_),
108        } => {
109            return Err(unframed(
110                render,
111                node,
112                "envelope is its exact squared magnitude",
113                "the exact envelope",
114            ));
115        }
116        // A pair's spectrum is its whole line list; no estimate, no peaks.
117        Representation::Spectrum {
118            frame_secs: None, ..
119        } => {
120            let each = per_channel(render, node, sum)?;
121            let mut held = match each.as_slice() {
122                [one] => lines(render, node, sum.var, &one.atoms)?,
123                _ => in_power(
124                    each.iter()
125                        .map(|one| lines(render, node, sum.var, &one.atoms))
126                        .collect::<Result<_, _>>()?,
127                ),
128            };
129            held.sort_by(|a, b| a.hz.total_cmp(&b.hz));
130            (Output::Lines(held), Listed::joined(each))
131        }
132        Representation::Atoms => {
133            let each = per_channel(render, node, sum)?;
134            let found = each
135                .iter()
136                .enumerate()
137                .flat_map(|(c, one)| one.atoms.iter().map(move |a| atom_of(sum.var, a, c)))
138                .collect();
139            (Output::Atoms(found), Listed::joined(each))
140        }
141        // A pair states its partials; `max_notes` is the question, not a cut answer.
142        Representation::Pitch { max_notes, .. } => {
143            let each = per_channel(render, node, sum)?;
144            let partials = each
145                .iter()
146                .map(|one| {
147                    let held = lines(render, node, sum.var, &one.atoms)?;
148                    Ok(harmony::partials(held.iter().map(|l| (l.hz, l.amp))))
149                })
150                .collect::<Result<_, EngineError>>()?;
151            let mut found: Vec<Peak> = harmony::averaged(partials)
152                .into_iter()
153                .map(|p| Peak {
154                    hz: p.hz,
155                    db: 20.0 * p.amplitude.log10(),
156                })
157                .collect();
158            found.sort_by(|a, b| b.db.total_cmp(&a.db));
159            let start = render.read_from.ok_or_else(|| {
160                refused(
161                    render,
162                    node,
163                    "engine.not_materialized",
164                    "an exact `pitch` frame starts at the sample the render reads its root \
165                     from, and this render, not asked for `pitch`, decided none"
166                        .to_string(),
167                )
168            })?;
169            let frame = PitchFrame {
170                t_secs: start as f64 / f64::from(render.config.rate),
171                notes: pitch::name_peaks(&found, max_notes),
172            };
173            (Output::Pitch(vec![frame]), Listed::joined(each))
174        }
175        // Each series is listed first, as `atoms` lists it, so no term is differentiated away.
176        Representation::Derivative => {
177            let each = per_channel(render, node, sum)?;
178            let series_free = SpectralSum::of(
179                sum.var,
180                each.iter()
181                    .map(|one| sva_formula::Lane::of(one.atoms.clone()))
182                    .collect(),
183            );
184            let slope = d_dt(&series_free).map_err(|left| {
185                EngineError::of_closed_form(
186                    &left.refusal(),
187                    render.tys.locate(left.origin),
188                    "read the derivative of a lower order or degree",
189                )
190            })?;
191            let dropped = Listed::joined(each).dropped.into_iter().map(|l| Line {
192                amp: l.amp * C64::new(0.0, std::f64::consts::TAU * l.hz),
193                ..l
194            });
195            let differentiated = Listed {
196                atoms: slope.atoms().copied().collect(),
197                dropped: dropped.collect(),
198            };
199            (Output::Symbolic(Box::new(slope)), differentiated)
200        }
201        Representation::Envelope { frame_secs: None } => {
202            let held =
203                refs::read_through(&render.tys, |t| envelope_read(sum, t)).map_err(|left| {
204                    EngineError::of_closed_form(
205                        &left.refusal(),
206                        render.tys.locate(left.origin),
207                        "read the envelope off sample(...) for a measured one",
208                    )
209                })?;
210            (Output::Symbolic(Box::new(held.squared)), Listed::NONE)
211        }
212        Representation::Harmony {
213            reading,
214            frame_secs,
215            floor_db,
216        } => {
217            let (moments, framing, listed, end_secs) =
218                exact_moments(render, node, sum, frame_secs)?;
219            let value = harmonic(reading, &moments, (framing, end_secs), floor_db)
220                .map_err(|held| crowded(render.tys.name(node), representation, held))?;
221            (value, listed)
222        }
223        other => return Err(not_a_closed_form(render, node, other)),
224    };
225    Ok((value, listed, source))
226}
227
228/// Each instant on the frame grid over the range, each channel's partials exactly: every atom
229/// a partial at its carrier, `omega/2pi`, its complex value there merged with the channel's
230/// others at that carrier, so a decay, polynomial, Gaussian or window weighs it as it stands;
231/// then every channel in power.
232fn exact_moments(
233    render: &Render,
234    node: sva_formula::NodeId,
235    sum: &SpectralSum,
236    frame_secs: f64,
237) -> Result<(Vec<Moment>, Framing, Listed, f64), EngineError> {
238    let range = match (render.range, &render.unranged) {
239        (Some(range), _) => range,
240        (None, Some(refused)) => return Err(refused.clone()),
241        (None, None) => unreachable!("a harmonic reading decides its range before it answers"),
242    };
243    let rate = f64::from(render.config.rate);
244    let hop = ((frame_secs * rate).round() as usize).max(1);
245    let each = per_channel(render, node, sum)?;
246    let instants: Vec<f64> = (range.start..range.end)
247        .step_by(hop)
248        .map(|n| n as f64 / rate)
249        .collect();
250    let moments = match sum.var {
251        Var::F => {
252            let partials = harmony::averaged(
253                each.iter()
254                    .map(|one| {
255                        let held = lines(render, node, Var::F, &one.atoms)?;
256                        Ok(harmony::partials(held.iter().map(|l| (l.hz, l.amp))))
257                    })
258                    .collect::<Result<_, EngineError>>()?,
259            );
260            instants
261                .iter()
262                .map(|t| Moment {
263                    t_secs: *t,
264                    partials: partials.clone(),
265                })
266                .collect()
267        }
268        Var::T => instants
269            .iter()
270            .map(|t| {
271                let at = |one: &Listed| {
272                    let carried = one.atoms.iter().map(|a| {
273                        let value = (!a.is_delta()).then(|| a.smooth_at(*t)).flatten();
274                        let hz = a.exp.map_or(0.0, |e| e.omega / std::f64::consts::TAU);
275                        value
276                            .map(|v| (hz, v))
277                            .ok_or_else(|| no_partial(render, node, a, *t))
278                    });
279                    Ok(harmony::partials(carried.collect::<Result<Vec<_>, _>>()?))
280                };
281                Ok(Moment {
282                    t_secs: *t,
283                    partials: harmony::averaged(each.iter().map(at).collect::<Result<_, _>>()?),
284                })
285            })
286            .collect::<Result<_, EngineError>>()?,
287    };
288    let framing = Framing {
289        hop_secs: hop as f64 / rate,
290        window: None,
291    };
292    let end_secs = range.end as f64 / rate;
293    Ok((moments, framing, Listed::joined(each), end_secs))
294}
295
296/// One harmonic reading off a curve of partials, whichever source took them, over a render
297/// ending at `end_secs`.
298fn harmonic(
299    reading: Harmonic,
300    moments: &[Moment],
301    (framing, end_secs): (Framing, f64),
302    floor_db: f64,
303) -> Result<Output, Crowded> {
304    let chords = || chords::segment(moments, framing.hop_secs, end_secs, floor_db);
305    Ok(match reading {
306        Harmonic::Dissonance { max_pairs } => Output::Dissonance(Box::new(dissonance::measure(
307            moments, framing, floor_db, max_pairs,
308        )?)),
309        Harmonic::VoiceLeading { norm } => Output::VoiceLeading(Box::new(voice_leading::analyze(
310            chords(),
311            framing,
312            floor_db,
313            norm,
314        ))),
315        Harmonic::TonalDistance => {
316            Output::TonalDistance(Box::new(tonnetz::analyze(chords(), framing, floor_db)))
317        }
318        Harmonic::Inharmonicity => {
319            Output::Inharmonicity(Box::new(inharmonicity::measure(moments, framing, floor_db)))
320        }
321    })
322}
323
324/// An impulse stands at no frequency, and a pole has no value at its own instant.
325fn no_partial(
326    render: &Render,
327    node: sva_formula::NodeId,
328    atom: &SpectralAtom,
329    t: f64,
330) -> EngineError {
331    let mut at = render.tys.locate(atom.origin);
332    if at.node.is_empty() {
333        at = Located::at(render.tys.name(node), None);
334    }
335    let message = match atom.is_delta() {
336        true => "this term is an impulse in `t`, which stands at no one frequency, so it is \
337                 no partial"
338            .to_string(),
339        false => {
340            format!("this term has a pole at {t}s, an instant of the curve, where it has no value")
341        }
342    };
343    EngineError::refused(Diagnostic {
344        code: "read.no_partial_at_instant".to_string(),
345        message,
346        location: at,
347        help: "a harmonic reading of `sample(...)` of it, as `sample(@x([0, 1s]))`, is \
348               measured off frames of its samples instead"
349            .to_string(),
350    })
351}
352
353fn crowded(name: &str, representation: Representation, held: Crowded) -> EngineError {
354    let reading = representation.name();
355    EngineError::refused(Diagnostic {
356        code: "read.too_many_partial_pairs".to_string(),
357        message: format!(
358            "at {}s, {} partials may stand over the floor, {} pairs, past the {} asked for",
359            held.t_secs, held.partials, held.pairs, held.cap
360        ),
361        location: Located::at(name, None),
362        help: format!(
363            "ask for more pairs, as `{reading}(pairs={})`, or raise the floor so fewer partials \
364             pair, as `{reading}(floor=-30db)`",
365            held.pairs
366        ),
367    })
368}
369
370/// Each names the window or rate that would read, `longer` how to hand it a target that
371/// long and `faster` how to hand it samples at a rate over that.
372fn unread(
373    name: &str,
374    representation: Representation,
375    why: sliding::Unread,
376    longer: impl Fn(f64) -> String,
377    faster: impl Fn(f64) -> String,
378) -> EngineError {
379    let reading = representation.name();
380    let (code, message, help) = match why {
381        sliding::Unread::RateUnderBands { rate_hz, least_hz } => {
382            under_bands(reading, rate_hz, least_hz, faster)
383        }
384        sliding::Unread::WindowUnderTwoPeriods {
385            window_secs,
386            least_secs,
387        } => (
388            "read.window_under_two_periods",
389            format!(
390                "a {window_secs}s window holds under two of the shortest period `{reading}` \
391                 reads, {}s",
392                least_secs / 2.0
393            ),
394            format!(
395                "ask a window of {least_secs}s or longer, as `{reading}(window={least_secs}s)`"
396            ),
397        ),
398        sliding::Unread::TargetShorterThanWindow {
399            held_secs,
400            window_secs,
401            least_secs,
402        } => (
403            "read.target_under_window",
404            format!("the target holds {held_secs}s, under the {window_secs}s window"),
405            match least_secs <= held_secs {
406                true => format!(
407                    "{}, or ask a window as long as the target, as \
408                     `{reading}(window={held_secs}s)`",
409                    longer(window_secs)
410                ),
411                false => format!(
412                    "{}; no window under {least_secs}s holds two of the shortest period",
413                    longer(window_secs)
414                ),
415            },
416        ),
417    };
418    EngineError::refused(Diagnostic {
419        code: code.to_string(),
420        message,
421        location: Located::at(name, None),
422        help,
423    })
424}
425
426/// `faster` says how to hand a reading of ERB bands samples at the least rate that places one.
427fn under_bands(
428    reading: &str,
429    rate_hz: f64,
430    least_hz: f64,
431    faster: impl Fn(f64) -> String,
432) -> (&'static str, String, String) {
433    (
434        "read.rate_under_bands",
435        format!(
436            "`{reading}` reads ERB bands, and {rate_hz} Hz samples place none: the first band's \
437             centre stands at {:.2} Hz, over {} of the rate",
438            least_hz * bands::HIGHEST_CENTRE_OF_RATE,
439            bands::HIGHEST_CENTRE_OF_RATE
440        ),
441        faster((least_hz * 100.0).ceil() / 100.0),
442    )
443}
444
445/// Names the least rate and, through `faster`, how to hand it samples at one.
446fn rate_under(
447    name: &str,
448    held: sva_samples::RateUnderWeighting,
449    faster: impl Fn(f64) -> String,
450) -> EngineError {
451    EngineError::refused(Diagnostic {
452        code: "read.rate_under_weighting".to_string(),
453        message: format!(
454            "BS.1770's K-weighting shelf stands at {} Hz, at or past the Nyquist of {} Hz \
455             samples, where its bilinear design has no filter",
456            held.least_hz / 2.0,
457            held.rate_hz
458        ),
459        location: Located::at(name, None),
460        help: faster(held.least_hz),
461    })
462}
463
464/// Names the least frame or target an all-pole fit of the order reads, `longer` how to hand
465/// it a target that long.
466fn under_order(
467    name: &str,
468    why: formants::UnderOrder,
469    longer: impl Fn(f64) -> String,
470) -> EngineError {
471    let (code, message, help) = match why {
472        formants::UnderOrder::Frame {
473            frame_secs,
474            held,
475            order,
476            least_secs,
477        } => (
478            "read.frame_under_order",
479            format!(
480                "a {frame_secs}s frame holds {held} samples, and an order-{order} all-pole fit \
481                 reads {} lags",
482                order + 1
483            ),
484            format!("ask a frame of {least_secs}s or longer, as `formants(frame={least_secs}s)`"),
485        ),
486        formants::UnderOrder::Target {
487            held,
488            order,
489            least_secs,
490        } => (
491            "read.target_under_order",
492            format!(
493                "the target holds {held} samples, and an order-{order} all-pole fit reads {} \
494                 lags",
495                order + 1
496            ),
497            longer(least_secs),
498        ),
499    };
500    EngineError::refused(Diagnostic {
501        code: code.to_string(),
502        message,
503        location: Located::at(name, None),
504        help,
505    })
506}
507
508/// Names the rate, cell or window that fits and, through `shorter` and `faster`, how to hand
509/// it a target that short or samples that fast.
510fn unfit(
511    name: &str,
512    why: self_similarity::Unfit,
513    shorter: impl Fn(f64) -> String,
514    faster: impl Fn(f64) -> String,
515) -> EngineError {
516    let (code, message, help) = match why {
517        self_similarity::Unfit::RateUnderBands { rate_hz, least_hz } => {
518            under_bands("self_similarity", rate_hz, least_hz, faster)
519        }
520        self_similarity::Unfit::TooManyCells(held) => (
521            "read.too_many_cells",
522            format!(
523                "the target's {}s at cell={}s is {} cells a side, past the {} a matrix holds",
524                held.held_secs, held.cell_secs, held.cells, held.cap
525            ),
526            format!(
527                "ask a coarser cell, as `self_similarity(cell={}s)`, or {}",
528                held.least_cell_secs,
529                shorter(held.most_secs)
530            ),
531        ),
532        self_similarity::Unfit::CellUnderBandStep {
533            cell_secs,
534            least_cell_secs,
535            band_hz,
536        } => (
537            "read.cell_under_band_step",
538            format!(
539                "a {cell_secs}s cell holds no sample of the {band_hz} Hz band envelopes its \
540                 band levels are read off"
541            ),
542            format!(
543                "ask a cell of {least_cell_secs}s or coarser, as \
544                 `self_similarity(cell={least_cell_secs}s)`"
545            ),
546        ),
547        self_similarity::Unfit::KernelPastCap {
548            window_secs,
549            kernel_cells,
550            cap,
551            cell_secs,
552            widest_secs,
553        } => (
554            "read.kernel_past_cap",
555            format!(
556                "a {window_secs}s novelty window at cell={cell_secs}s is {kernel_cells} cells \
557                 a side, past the {cap} a matrix holds"
558            ),
559            format!(
560                "ask a window of at most {widest_secs}s, as \
561                 `self_similarity(window={widest_secs}s)`, or a coarser cell"
562            ),
563        ),
564    };
565    EngineError::refused(Diagnostic {
566        code: code.to_string(),
567        message,
568        location: Located::at(name, None),
569        help,
570    })
571}
572
573/// A closed form's envelope is exact or refused, never measured unasked: a refusal of its
574/// sum says so, and names `sample(...)` as the way to ask for the measured one.
575fn not_exact(representation: Representation, left: EngineError) -> EngineError {
576    match (representation, left) {
577        (Representation::Envelope { frame_secs: None }, EngineError::Refused(cause)) => {
578            EngineError::refused(Diagnostic {
579                message: format!("this closed form has no exact envelope: {}", cause.message),
580                help: "a measured envelope is asked for explicitly: read `envelope` of \
581                       `sample(...)` of it, as `sample(@x([0, 1s]))`"
582                    .to_string(),
583                ..*cause
584            })
585        }
586        (_, left) => left,
587    }
588}
589
590/// A closed form with no atom sum has no exact partials; the measured ones are asked for
591/// explicitly, never taken in their place.
592fn unsummed(representation: Representation, left: EngineError) -> EngineError {
593    match (representation, left) {
594        (Representation::Harmony { .. }, EngineError::Refused(cause)) => {
595            EngineError::refused(Diagnostic {
596                message: format!(
597                    "`{}` of a closed form reads its exact partials, and it has none: {}",
598                    representation.name(),
599                    cause.message
600                ),
601                help: format!(
602                    "a measured `{}` is asked for explicitly: read it of `sample(...)` of it, as \
603                     `sample(@x([0, 1s]))`",
604                    representation.name()
605                ),
606                ..*cause
607            })
608        }
609        (_, left) => not_exact(representation, left),
610    }
611}
612
613/// A closed form holds no frames, so a written `frame` is refused rather than ignored.
614fn unframed(render: &Render, node: sva_formula::NodeId, is: &str, bare: &str) -> EngineError {
615    EngineError::refused(Diagnostic {
616        code: "engine.observation_needs_samples".to_string(),
617        message: format!("a closed form's {is}, and it has no frames to take it across"),
618        location: Located::at(render.tys.name(node), None),
619        help: format!("drop `frame` for {bare}, or read `sample(...)` of it to measure frames"),
620    })
621}
622
623/// Every atom the spectral sum stands for, beside the terms its series truncated away or left
624/// above the ceiling: `atoms` alone holds only the terms already written out.
625struct Listed {
626    atoms: Vec<SpectralAtom>,
627    dropped: Vec<Line>,
628}
629
630impl Listed {
631    /// A reading that enumerates no series leaves nothing out.
632    const NONE: Listed = Listed {
633        atoms: Vec::new(),
634        dropped: Vec::new(),
635    };
636
637    fn joined(each: Vec<Listed>) -> Listed {
638        let mut held = Listed::NONE;
639        for one in each {
640            held.atoms.extend(one.atoms);
641            held.dropped.extend(one.dropped);
642        }
643        held
644    }
645
646    /// The tail is the loudest line left out against the loudest one kept, so
647    /// it is one ratio over the whole answer, never a per-series one carried upward.
648    fn tail_db(&self) -> Option<f64> {
649        let loudest = |set: &mut dyn Iterator<Item = f64>| set.fold(0.0f64, f64::max);
650        let gone = loudest(&mut self.dropped.iter().map(|l| l.amp.abs()));
651        let kept = loudest(&mut self.atoms.iter().map(|a| a.c.abs()));
652        (gone > 0.0 && kept > 0.0).then(|| 20.0 * (gone / kept).log10())
653    }
654}
655
656/// Each lane's series enumerated under the band a rate-free reading is taken in. A series
657/// whose term no line closed form reads yields nothing, and nothing is not an exact empty answer.
658fn listed(
659    render: &Render,
660    node: sva_formula::NodeId,
661    sum: &SpectralSum,
662    profile: &Profile,
663) -> Result<Listed, EngineError> {
664    let ceiling = profile.ceiling_hz;
665    let band = (ceiling, profile.floor(ceiling), profile.half_lsb());
666    let mut held = Listed::NONE;
667    for lane in &sum.lanes {
668        held.atoms.extend(lane.clone().expanded().atoms);
669        for series in &lane.series {
670            let found = refs::read_through(&render.tys, |t| line_atoms_read(series, band, t));
671            let Some(found) = found else {
672                return Err(unenumerable(render, node));
673            };
674            held.atoms.extend(found.atoms);
675            held.dropped.extend(found.dropped);
676        }
677    }
678    Ok(held)
679}
680
681/// Each channel's lane listed on its own, in channel order.
682fn per_channel(
683    render: &Render,
684    node: sva_formula::NodeId,
685    sum: &SpectralSum,
686) -> Result<Vec<Listed>, EngineError> {
687    sum.lanes
688        .iter()
689        .map(|lane| {
690            let one = SpectralSum::of(sum.var, vec![lane.clone()]);
691            listed(render, node, &one, &render.config.profile)
692        })
693        .collect()
694}
695
696/// Every channel in power, as a measured spectrum reads them: a channel's lines at one
697/// frequency summed, their squared modulus summed over the channels, divided by the count.
698/// Channels share no phase, so each line is that power's root, real.
699fn in_power(per_channel: Vec<Vec<Line>>) -> Vec<Line> {
700    let count = per_channel.len() as f64;
701    let mut power: Vec<(Line, f64)> = Vec::new();
702    for lines in per_channel {
703        let mut channel: Vec<Line> = Vec::new();
704        for line in lines {
705            match channel
706                .iter_mut()
707                .find(|l| l.hz.to_bits() == line.hz.to_bits())
708            {
709                Some(held) => held.amp = held.amp + line.amp,
710                None => channel.push(line),
711            }
712        }
713        for line in channel {
714            let squared = line.amp.abs() * line.amp.abs();
715            match power
716                .iter_mut()
717                .find(|(l, _)| l.hz.to_bits() == line.hz.to_bits())
718            {
719                Some((_, sum)) => *sum += squared,
720                None => power.push((line, squared)),
721            }
722        }
723    }
724    power
725        .into_iter()
726        .filter(|(_, sum)| *sum > 0.0)
727        .map(|(line, sum)| Line {
728            amp: C64::real((sum / count).sqrt()),
729            ..line
730        })
731        .collect()
732}
733
734/// The exact line list of a pair: in `t` a bare turning exponential, in `f` the delta it
735/// duals to. A list every other atom was dropped from answers a spectrum this node has not.
736fn lines(
737    render: &Render,
738    node: sva_formula::NodeId,
739    var: Var,
740    atoms: &[SpectralAtom],
741) -> Result<Vec<Line>, EngineError> {
742    atoms
743        .iter()
744        .map(|a| line_of(var, a).ok_or_else(|| not_a_line(render, node, var, a)))
745        .collect()
746}
747
748fn line_of(var: Var, a: &SpectralAtom) -> Option<Line> {
749    match (var, a.sing) {
750        (Var::F, Singular::Delta { at, order: 0 }) => Some(Line::bare(at, a.c)),
751        (Var::T, Singular::Regular) => {
752            if !a.poly.is_one() || a.gauss.is_some() || a.ind.is_some() || a.pole.is_some() {
753                return None;
754            }
755            match a.exp {
756                // A constant turns at no rate, which is the line at zero hertz.
757                None => Some(Line::bare(0.0, a.c)),
758                Some(e) if e.sigma == 0.0 => Some(Line::bare(e.omega / std::f64::consts::TAU, a.c)),
759                Some(_) => None,
760            }
761        }
762        _ => None,
763    }
764}
765
766/// What gave this atom a width; a turning exponential is the line itself and never among it.
767fn widening(a: &SpectralAtom) -> Vec<&'static str> {
768    let mut held = Vec::new();
769    if !a.poly.is_one() {
770        held.push("a polynomial");
771    }
772    if a.exp.is_some_and(|e| e.sigma != 0.0) {
773        held.push("a decaying exponential");
774    }
775    if a.gauss.is_some() {
776        held.push("a Gaussian");
777    }
778    if a.pole.is_some() {
779        held.push("a pole");
780    }
781    if held.is_empty() {
782        held.push("a delta");
783    }
784    held
785}
786
787/// Convolved into a line, each shape beside the turning exponential answers a band.
788fn not_a_line(
789    render: &Render,
790    node: sva_formula::NodeId,
791    var: Var,
792    atom: &SpectralAtom,
793) -> EngineError {
794    let mut at = render.tys.locate(atom.origin);
795    if at.node.is_empty() {
796        at = Located::at(render.tys.name(node), None);
797    }
798    let message = match atom.ind {
799        _ if var == Var::F => "this term spreads over `f` rather than standing at one \
800                               frequency, and a line in `f` is a delta"
801            .to_string(),
802        Some(window) => format!(
803            "this term is windowed to [{}s, {}s), and a windowed line is that line convolved \
804             with the window's transform, which has a width and is no line",
805            window.l.value(),
806            window.r.value()
807        ),
808        None => format!(
809            "this term carries {}, and a line is a bare turning exponential: each of those \
810             convolves the line with a shape of its own width",
811            widening(atom).join(", ")
812        ),
813    };
814    EngineError::refused(Diagnostic {
815        code: "read.lines_need_unwindowed_lines".to_string(),
816        message,
817        location: at,
818        help: "`atoms` states each term as it stands, `lines` of the node under the window \
819               or envelope lists the lines it multiplies, and `pitch` or `spectrum` of \
820               `sample(...)` of it measures it frame by frame"
821            .to_string(),
822    })
823}
824
825/// One atom as the six factors it is present in, which is what `atoms` answers with.
826fn sketch_atom(a: &SpectralAtom) -> String {
827    let factors: Vec<&'static str> = a.present().iter().map(|f| f.as_str()).collect();
828    format!("{} x {}", a.c.abs(), factors.join(" times "))
829}
830
831/// Each atom of every lane as `atoms` answers it, the lane its channel.
832pub fn atoms_of(sum: &SpectralSum) -> Vec<Atom> {
833    sum.lanes
834        .iter()
835        .enumerate()
836        .flat_map(|(c, lane)| lane.atoms.iter().map(move |a| atom_of(sum.var, a, c)))
837        .collect()
838}
839
840/// The atom's own fields, read off as it holds them; a constant turns at zero and decays at
841/// none. Adding zero writes a negative zero as the zero it equals.
842fn atom_of(var: Var, a: &SpectralAtom, channel: usize) -> Atom {
843    let (sigma, omega, mu) = a.exp.map_or((0.0, 0.0, 0.0), |e| (e.sigma, e.omega, e.mu));
844    let bounded = |edge: Edge| Some(edge.value() + 0.0).filter(|x| x.is_finite());
845    Atom {
846        var,
847        channel,
848        sketch: sketch_atom(a),
849        amp: a.c,
850        turns: omega / std::f64::consts::TAU + 0.0,
851        decay: 0.0 - sigma,
852        decay_from: mu + 0.0,
853        degree: a.poly.degree,
854        polynomial_at: a.poly.at + 0.0,
855        start: a.ind.and_then(|i| bounded(i.l)),
856        end: a.ind.and_then(|i| bounded(i.r)),
857    }
858}
859
860fn measured(
861    render: &Render,
862    node: sva_formula::NodeId,
863    representation: Representation,
864    buffer: &Buffer,
865) -> Result<Output, EngineError> {
866    Ok(match representation {
867        Representation::Alias { oversample } => {
868            let reference = oversampled(render, behind(render, node)?, oversample)?;
869            Output::Alias(Box::new(worst_alias(
870                render, node, buffer, &reference, oversample,
871            )?))
872        }
873        Representation::Ledger { depth } => Output::Ledger(attributed(render, node, depth)?),
874        other => {
875            let name = render.tys.name(node);
876            let longer = |secs: f64| {
877                format!("render an interval of at least {secs}s, as `@x([0, {secs}s])` writes one")
878            };
879            let shorter = |secs: f64| {
880                format!("render an interval of at most {secs}s, as `@x([0, {secs}s])` writes one")
881            };
882            let faster = |hz: f64| format!("render at a rate over {hz} Hz, as `--rate 48000` asks");
883            return off_buffer(buffer, other).map_err(|fault| match fault {
884                NoReading::NeedsAGraph => not_a_reading(render, node, other),
885                NoReading::WidthMismatch { need, held } => width_mismatch(render, node, need, held),
886                NoReading::Crowded(held) => crowded(name, other, held),
887                NoReading::Unread(why) => unread(name, other, why, longer, faster),
888                NoReading::RateUnder(held) => rate_under(name, held, faster),
889                NoReading::UnderOrder(why) => under_order(name, why, longer),
890                NoReading::Unfit(why) => unfit(name, why, shorter, faster),
891            });
892        }
893    })
894}
895
896/// Why a buffer answered nothing: the reading needs the tree the node was built from, or
897/// the buffer holds other than the components the reading needs.
898#[derive(Clone, Copy, Debug, PartialEq)]
899pub enum NoReading {
900    NeedsAGraph,
901    WidthMismatch { need: usize, held: usize },
902    Crowded(Crowded),
903    Unread(sliding::Unread),
904    Unfit(self_similarity::Unfit),
905    RateUnder(sva_samples::RateUnderWeighting),
906    UnderOrder(formants::UnderOrder),
907}
908
909/// Every reading a buffer answers on its own, with no graph behind it.
910pub fn off_buffer(buffer: &Buffer, representation: Representation) -> Result<Output, NoReading> {
911    let sr = f64::from(buffer.rate);
912    let start = buffer.origin_secs();
913    let planes = buffer.slices();
914    Ok(match representation {
915        Representation::Samples => Output::Samples(Box::new(buffer.clone())),
916        Representation::Spectrum {
917            max_peaks,
918            frame_secs,
919        } => Output::Spectrum(Box::new(spectrum::analyze(
920            &planes, sr, max_peaks, frame_secs,
921        ))),
922        Representation::Envelope { frame_secs } => Output::Envelope(envelope::trace(
923            &buffer.slices(),
924            sr,
925            start,
926            frame_secs.unwrap_or(DEFAULT_FRAME_SECS),
927        )),
928        Representation::Derivative => Output::Samples(Box::new(difference(buffer))),
929        Representation::Pitch {
930            max_notes,
931            frame_secs,
932        } => Output::Pitch(pitch::track(&planes, sr, start, frame_secs, max_notes)),
933        Representation::Formants {
934            max_formants,
935            frame_secs,
936        } => Output::Formants(
937            formants::track(
938                &planes,
939                sr,
940                start,
941                frame_secs,
942                formants::default_order(sr),
943                max_formants,
944            )
945            .map_err(NoReading::UnderOrder)?,
946        ),
947        Representation::Stereo { frame_secs } => {
948            if buffer.width() != 2 {
949                return Err(NoReading::WidthMismatch {
950                    need: 2,
951                    held: buffer.width(),
952                });
953            }
954            Output::Stereo(Box::new(stereo::analyze(
955                &planes,
956                buffer.width(),
957                sr,
958                start,
959                frame_secs,
960            )))
961        }
962        Representation::Bands => Output::Bands(Box::new(bands::analyze(&planes, sr, start))),
963        Representation::Crest => Output::Crest(Box::new(crest::analyze(&planes, sr))),
964        Representation::Onsets => Output::Onsets(Box::new(onsets::detect(&planes, sr, start))),
965        Representation::Loudness => Output::Loudness(Box::new(
966            loudness::analyze(&planes, sr, start).map_err(NoReading::RateUnder)?,
967        )),
968        Representation::Harmony {
969            reading,
970            frame_secs,
971            floor_db,
972        } => {
973            let (moments, framing) = framed::moments(&planes, sr, start, frame_secs);
974            let end_secs = buffer.end() as f64 / sr;
975            harmonic(reading, &moments, (framing, end_secs), floor_db)
976                .map_err(NoReading::Crowded)?
977        }
978        Representation::Periodicity {
979            frame_secs,
980            window_secs,
981            curve,
982        } => Output::Periodicity(Box::new(
983            periodicity::measure(&planes, sr, start, frame_secs, window_secs, curve)
984                .map_err(NoReading::Unread)?,
985        )),
986        Representation::Modulation {
987            frame_secs,
988            window_secs,
989            bpm,
990        } => Output::Modulation(Box::new(
991            modulation::measure(&planes, sr, start, frame_secs, window_secs, bpm)
992                .map_err(NoReading::Unread)?,
993        )),
994        Representation::SelfSimilarity {
995            frame_secs,
996            cell_secs,
997            smooth_secs,
998            window_secs,
999            floor_db,
1000            listed,
1001            curve,
1002        } => {
1003            let asked = self_similarity::Asked {
1004                hop_secs: frame_secs,
1005                cell_secs,
1006                smooth_secs,
1007                window_secs,
1008                floor_db,
1009                listed,
1010                curve,
1011            };
1012            Output::SelfSimilarity(Box::new(
1013                self_similarity::measure(&planes, sr, start, asked).map_err(NoReading::Unfit)?,
1014            ))
1015        }
1016        _ => return Err(NoReading::NeedsAGraph),
1017    })
1018}
1019
1020/// The ledger the pull tallied of `node`, refused where none was.
1021fn attributed(
1022    render: &Render,
1023    node: sva_formula::NodeId,
1024    depth: usize,
1025) -> Result<Vec<sva_samples::LedgerEntry>, EngineError> {
1026    super::ledger::entries(render, node, depth).unwrap_or_else(|| {
1027        Err(EngineError::refused(Diagnostic {
1028            code: "engine.not_materialized".to_string(),
1029            message: format!(
1030                "a ledger is tallied block by block as the render pulls, and this render was \
1031                 not asked for `ledger` of `{}` to depth {depth}",
1032                render.tys.name(node)
1033            ),
1034            location: Located::at(render.tys.name(node), None),
1035            help: "ask for the ledger with the render it reads, as `--representation ledger`"
1036                .to_string(),
1037        }))
1038    })
1039}
1040
1041/// What every instance under `node` was lowered with, `node` first, then breadth first. The
1042/// walk is over what each node was lowered to, so it needs no buffer.
1043fn arguments_under(render: &Render, node: sva_formula::NodeId) -> Vec<crate::Arguments> {
1044    let under = |id: sva_formula::NodeId| -> Vec<sva_formula::NodeId> {
1045        match render.tys.value(id) {
1046            Value::ClosedForm(form) => refs::nodes_in(&form.body),
1047            Value::Read { source, .. } | Value::Cast(_, source) => vec![*source],
1048            Value::Op { args, .. } => args.clone(),
1049            Value::Filter {
1050                x, cutoff, q, gain, ..
1051            } => vec![*x, *cutoff, *q, *gain],
1052            Value::Solver { varying, .. } => varying.iter().map(|(_, a)| *a).collect(),
1053            Value::SelfAt { .. } | Value::Noise(_) => Vec::new(),
1054        }
1055    };
1056    let mut names: Vec<&str> = Vec::new();
1057    let mut seen = std::collections::BTreeSet::from([node]);
1058    let mut level = vec![node];
1059    while !level.is_empty() {
1060        let mut next = Vec::new();
1061        for at in level {
1062            let name = render.tys.name(at);
1063            if !names.contains(&name) {
1064                names.push(name);
1065            }
1066            next.extend(under(at).into_iter().filter(|c| seen.insert(*c)));
1067        }
1068        level = next;
1069    }
1070    names
1071        .into_iter()
1072        .filter_map(|name| render.tys.arguments(name).cloned())
1073        .collect()
1074}
1075
1076/// The closed form an alias score oversamples: the node itself where it is one, and the operand of
1077/// the `sample(...)` that collapsed it where it is not.
1078fn behind(render: &Render, node: sva_formula::NodeId) -> Result<sva_formula::NodeId, EngineError> {
1079    if render.tys.ty(node).is_closed_form() {
1080        return Ok(node);
1081    }
1082    match render.tys.value(node) {
1083        crate::typing::Value::Cast(crate::cast::Cast::Sample, source) => Ok(*source),
1084        _ => Err(refused(
1085            render,
1086            node,
1087            "engine.alias_needs_a_closed_form",
1088            "an alias score is a render against the same closed form oversampled, and this node \
1089             is samples with no closed form behind it"
1090                .to_string(),
1091        )),
1092    }
1093}
1094
1095/// The score a point sampling's label carries where a reading asks for one, at its multiple.
1096pub(super) fn alias_db(
1097    render: &Render,
1098    node: sva_formula::NodeId,
1099    buffer: &Buffer,
1100    oversample: u32,
1101) -> Result<f64, EngineError> {
1102    let reference = oversampled(render, behind(render, node)?, oversample)?;
1103    Ok(worst_alias(render, node, buffer, &reference, oversample)?.asr_db)
1104}
1105
1106/// Each component scored against its own reference; the worst answers.
1107fn worst_alias(
1108    render: &Render,
1109    node: sva_formula::NodeId,
1110    buffer: &Buffer,
1111    reference: &Buffer,
1112    oversample: u32,
1113) -> Result<sva_samples::Alias, EngineError> {
1114    debug_assert_eq!(
1115        buffer.width(),
1116        reference.width(),
1117        "the reference is the same form at another rate"
1118    );
1119    let sr = f64::from(buffer.rate);
1120    let width = buffer.width().min(reference.width());
1121    let scored = (0..width).map(|c| {
1122        measure_alias(
1123            buffer.plane(c),
1124            reference.plane(c),
1125            oversample as usize,
1126            sr,
1127            buffer.origin_secs(),
1128        )
1129    });
1130    let scored = scored.collect::<Result<Vec<_>, _>>().map_err(|short| {
1131        let secs = (short.frame as f64 / sr * 1000.0).ceil() / 1000.0;
1132        EngineError::refused(Diagnostic {
1133            code: "read.target_under_frame".to_string(),
1134            message: format!(
1135                "the target holds {} samples, fewer than the {}-sample frame an alias score reads",
1136                short.held, short.frame
1137            ),
1138            location: Located::at(render.tys.name(node), None),
1139            help: format!(
1140                "render an interval of at least {secs}s, as `@x([0, {secs}s])` writes one"
1141            ),
1142        })
1143    })?;
1144    Ok(sva_samples::worst_alias(scored).expect("a buffer holds at least one component"))
1145}
1146
1147/// The node read at a multiple of the rate by its own route: what an alias score is against.
1148fn oversampled(
1149    render: &Render,
1150    node: sva_formula::NodeId,
1151    oversample: u32,
1152) -> Result<Buffer, EngineError> {
1153    let range = render.range.expect("an alias score reads a decided range");
1154    let k = i64::from(oversample);
1155    let extent = Extent::new(range.start * k, range.end * k);
1156    super::finer(render, node, oversample, extent)
1157}
1158
1159/// A first difference on the grid, which is what a derivative is once the closed form is gone:
1160/// `(x[n] - x[n-1]) * rate` at each sample from the second, as the first has no sample before it.
1161fn difference(buffer: &Buffer) -> Buffer {
1162    let step = f64::from(buffer.rate);
1163    let planes = (0..buffer.width())
1164        .map(|c| {
1165            let plane = buffer.plane(c);
1166            plane.windows(2).map(|x| (x[1] - x[0]) * step).collect()
1167        })
1168        .collect();
1169    let mut out = Buffer::of_planes(buffer.rate, planes);
1170    out.start = buffer.start + buffer.plane(0).len().min(1) as i64;
1171    out
1172}
1173
1174fn refused(render: &Render, node: sva_formula::NodeId, code: &str, message: String) -> EngineError {
1175    EngineError::refused(Diagnostic {
1176        code: code.to_string(),
1177        message,
1178        location: Located::at(render.tys.name(node), None),
1179        help: "ask for a reading this representation answers".to_string(),
1180    })
1181}
1182
1183fn unenumerable(render: &Render, node: sva_formula::NodeId) -> EngineError {
1184    refused(
1185        render,
1186        node,
1187        "read.series_not_enumerable",
1188        "a series whose term is no line lists no lines, and an empty list would read as \
1189         a node with none"
1190            .to_string(),
1191    )
1192}
1193
1194fn not_a_closed_form(render: &Render, node: sva_formula::NodeId, r: Representation) -> EngineError {
1195    refused(
1196        render,
1197        node,
1198        "engine.observation_needs_samples",
1199        format!(
1200            "`{}` reads samples, and this node is a closed form",
1201            r.name()
1202        ),
1203    )
1204}
1205
1206fn not_a_reading(render: &Render, node: sva_formula::NodeId, r: Representation) -> EngineError {
1207    refused(
1208        render,
1209        node,
1210        "engine.observation_not_wired",
1211        format!("`{}` takes no reading off a buffer here", r.name()),
1212    )
1213}
1214
1215fn width_mismatch(
1216    render: &Render,
1217    node: sva_formula::NodeId,
1218    need: usize,
1219    held: usize,
1220) -> EngineError {
1221    EngineError::refused(Diagnostic {
1222        code: "type.width_mismatch".to_string(),
1223        message: width_message(need, held, "node"),
1224        location: Located::at(render.tys.name(node), None),
1225        help: format!("read a node of exactly {need} components, as `join(@a, @b)` writes one"),
1226    })
1227}
1228
1229/// More components than a reading reads refuse too, so none goes unread under its answer.
1230fn width_message(need: usize, held: usize, holder: &str) -> String {
1231    format!("this reading needs exactly {need} components and the {holder} holds {held}")
1232}
1233
1234pub(super) fn unheld(render: &Render, node: sva_formula::NodeId) -> EngineError {
1235    refused(
1236        render,
1237        node,
1238        "engine.not_materialized",
1239        "this render held no samples of it".to_string(),
1240    )
1241}
1242
1243pub(super) fn unmaterialized(
1244    render: &Render,
1245    node: sva_formula::NodeId,
1246    r: Representation,
1247) -> EngineError {
1248    refused(
1249        render,
1250        node,
1251        "engine.not_materialized",
1252        format!("`{}` reads samples this render never held", r.name()),
1253    )
1254}
1255
1256/// One reading off a buffer nothing rendered — an external file, say — under the profile the
1257/// caller names. Every representation needing the graph behind it refuses here.
1258pub fn answer_buffer(
1259    name: &str,
1260    buffer: &Buffer,
1261    representation: Representation,
1262    profile: &'static str,
1263) -> Result<Answer, EngineError> {
1264    let refused = |code: &str, message: String| {
1265        EngineError::refused(Diagnostic {
1266            code: code.to_string(),
1267            message,
1268            location: Located::at(name, None),
1269            help: "ask for a reading a buffer answers on its own".to_string(),
1270        })
1271    };
1272    let longer = |secs: f64| format!("analyze a file holding at least {secs}s");
1273    let shorter = |secs: f64| format!("analyze a file holding at most {secs}s");
1274    let faster = |hz: f64| format!("analyze a file sampled over {hz} Hz");
1275    let value = off_buffer(buffer, representation).map_err(|fault| match fault {
1276        NoReading::NeedsAGraph => refused(
1277            "engine.observation_needs_a_graph",
1278            format!(
1279                "`{}` reads the tree a node was built from, and a file has none",
1280                representation.name()
1281            ),
1282        ),
1283        NoReading::WidthMismatch { need, held } => EngineError::refused(Diagnostic {
1284            code: "type.width_mismatch".to_string(),
1285            message: width_message(need, held, "file"),
1286            location: Located::at(name, None),
1287            help: format!("analyze a file of exactly {need} channels"),
1288        }),
1289        NoReading::Crowded(held) => crowded(name, representation, held),
1290        NoReading::Unread(why) => unread(name, representation, why, longer, faster),
1291        NoReading::Unfit(why) => unfit(name, why, shorter, faster),
1292        NoReading::RateUnder(held) => rate_under(name, held, faster),
1293        NoReading::UnderOrder(why) => under_order(name, why, longer),
1294    })?;
1295    Ok(Answer::whole(
1296        value,
1297        Source::Measured,
1298        profile,
1299        Some(buffer.rate),
1300    ))
1301}