Skip to main content

sva_samples/measure/harmony/
mod.rs

1// Concern: the partials a harmonic reading starts from, per instant or frame, and their floor | Non-concern: what a reading makes of them (siblings) | IO: (lines) -> partials
2
3pub mod chords;
4pub mod dissonance;
5pub mod inharmonicity;
6pub mod measured;
7pub mod tonnetz;
8pub mod voice_leading;
9
10use std::collections::HashMap;
11
12use sva_formula::C64;
13
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct Partial {
16    pub hz: f64,
17    pub amplitude: f64,
18    /// Where the true values lie, `(lo, hi)`; a point where the partial is exact.
19    pub hz_bounds: (f64, f64),
20    pub amplitude_bounds: (f64, f64),
21}
22
23#[derive(Clone, Debug, PartialEq)]
24pub struct Moment {
25    pub t_secs: f64,
26    pub partials: Vec<Partial>,
27}
28
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct Framing {
31    pub hop_secs: f64,
32    pub window: Option<Window>,
33}
34
35impl Framing {
36    pub fn method(&self) -> &'static str {
37        match self.window {
38            None => EXACT_METHOD,
39            Some(_) => measured::METHOD,
40        }
41    }
42}
43
44pub const EXACT_METHOD: &str = "exact: at each instant every atom of the closed form's first \
45                                component is a partial at its carrier frequency, its value \
46                                there summed with the others at that frequency, and a cosine's \
47                                two conjugate lines one partial";
48
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct Window {
51    pub size: usize,
52    pub secs: f64,
53    pub resolution_hz: f64,
54}
55
56/// Lines at one frequency sum as complex amplitudes, so a cancelled pair is no partial; a
57/// real wave's amplitude is its two conjugate lines' moduli summed.
58pub fn partials(lines: impl IntoIterator<Item = (f64, C64)>) -> Vec<Partial> {
59    let mut at: HashMap<u64, C64> = HashMap::new();
60    let mut order: Vec<f64> = Vec::new();
61    for (hz, amp) in lines {
62        let summed = at.entry(hz.to_bits()).or_insert_with(|| {
63            order.push(hz);
64            C64::ZERO
65        });
66        *summed = *summed + amp;
67    }
68    let modulus = |hz: f64| at.get(&hz.to_bits()).map_or(0.0, |c| c.abs());
69    order
70        .into_iter()
71        .filter(|hz| *hz > 0.0)
72        .map(|hz| {
73            let amplitude = modulus(hz) + modulus(-hz);
74            Partial {
75                hz,
76                amplitude,
77                hz_bounds: (hz, hz),
78                amplitude_bounds: (amplitude, amplitude),
79            }
80        })
81        .filter(|p| p.amplitude > 0.0)
82        .collect()
83}
84
85pub fn above(moment: &Moment, floor_db: f64) -> Vec<Partial> {
86    let floor = 10f64.powf(floor_db / 20.0);
87    moment
88        .partials
89        .iter()
90        .filter(|p| p.amplitude >= floor)
91        .copied()
92        .collect()
93}