1use super::chords::named;
4use super::dissonance::Extreme;
5use super::{Framing, Moment, Partial};
6use crate::measure::stiff::{Weights, dot, weights};
7
8pub const MODEL: &str = "per moment, the series `pitch` names: the partial with the greatest \
9 subharmonic sum (Hermes, D. J. (1988), Measurement of pitch by \
10 subharmonic summation, J. Acoust. Soc. Am. 83(1) 257-264, the k-th \
11 multiple's amplitude weighted 0.84^(k-1)) roots a series, a partial left \
12 at a ratio over a louder member from 0.04 under a whole number q from 2 \
13 to 8 to 0.04 over where the stiff string the series' members so far fit \
14 (Fletcher, below, B floored at 0) puts its partial q n over its partial \
15 n joins it, or over the root if the pair's sum at the root is at \
16 least that partial's amplitude, and the rest go round again (Klapuri, A. (2006), Multiple \
17 fundamental frequency estimation by summing harmonic amplitudes, ISMIR); \
18 a member's harmonic number n = round(f / f1) over the root f1; only \
19 partials from 25 Hz to 5 kHz at or above the floor are read. That \
20 window bounds how stretched a member may be, and a partial stretched \
21 past it, or a harmonic past the 8th with no member at a divisor (a saw's \
22 11th), roots a series of its own; a fundamental quieter than its 2nd \
23 harmonic roots their series if its subharmonic sum is the greater and \
24 it is within 16 dB of that harmonic, else the two split; and \
25 a noise's many peaks fall within the tolerance by chance, so noise reads \
26 partly grouped, with many series. \
27 cents = 1200 log2(f / (n f1)); a series' and the moment's `cents` are \
28 the amplitude-weighted mean of |cents| over members n >= 2, null with \
29 none. fit: Fletcher, H. (1964), Normal vibration frequencies of a stiff \
30 piano string, J. Acoust. Soc. Am. 36(1) 203-209, f_n = n f0 sqrt(1 + B \
31 n^2), by unweighted least squares of (f_n / n)^2 = f0^2 + f0^2 B n^2 \
32 over a series' members, null under two distinct n or with no positive \
33 f0^2; B is the model's coefficient for a stiff string and only a fitted \
34 slope for any other body. unexplained: the share of the read partials' \
35 energy, sum of amplitude^2, in series of one partial, which hold no \
36 evidence of a harmonic series, so a lone sinusoid reads 1. Every bound \
37 holds over the box of the partials' frequency and amplitude bounds, \
38 with the series and each n as named at the estimates; b_bounds is null \
39 where that box admits no positive f0^2";
40
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct Member {
43 pub n: u32,
44 pub partial: Partial,
45 pub cents: f64,
46 pub cents_bounds: (f64, f64),
47}
48
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct Fit {
51 pub b: f64,
52 pub f0_hz: f64,
53 pub b_bounds: Option<(f64, f64)>,
55 pub f0_bounds: Option<(f64, f64)>,
56}
57
58#[derive(Clone, Debug, PartialEq)]
60pub struct Series {
61 pub members: Vec<Member>,
62 pub cents: Option<Weighted>,
63 pub fit: Option<Fit>,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct Weighted {
68 pub value: f64,
69 pub bounds: (f64, f64),
70}
71
72#[derive(Clone, Debug, PartialEq)]
73pub struct InharmonicFrame {
74 pub t_secs: f64,
75 pub series: Vec<Series>,
76 pub cents: Option<Weighted>,
77 pub unexplained: Option<Weighted>,
79}
80
81#[derive(Clone, Debug, PartialEq)]
82pub struct Inharmonicity {
83 pub framing: Framing,
84 pub floor_db: f64,
85 pub frames: Vec<InharmonicFrame>,
86 pub cents_mean: Option<f64>,
88 pub cents_max: Option<Extreme>,
89 pub unexplained_mean: Option<f64>,
90}
91
92fn cents(ratio: f64) -> f64 {
93 1200.0 * ratio.log2()
94}
95
96fn member(p: &Partial, n: u32, root: &Partial) -> Member {
98 let k = f64::from(n);
99 let cents_bounds = match n {
100 1 => (0.0, 0.0),
101 _ => (
102 cents(p.hz_bounds.0 / (k * root.hz_bounds.1)),
103 cents(p.hz_bounds.1 / (k * root.hz_bounds.0)),
104 ),
105 };
106 Member {
107 n,
108 partial: *p,
109 cents: cents(p.hz / (k * root.hz)),
110 cents_bounds,
111 }
112}
113
114#[derive(Clone, Copy)]
116struct Term {
117 value: f64,
118 value_bounds: (f64, f64),
119 weight: f64,
120 weight_bounds: (f64, f64),
121}
122
123fn weighted(terms: &[Term]) -> Option<Weighted> {
128 let weight: f64 = terms.iter().map(|t| t.weight).sum();
129 if weight <= 0.0 {
130 return None;
131 }
132 let value = terms.iter().map(|t| t.weight * t.value).sum::<f64>() / weight;
133 let extreme = |least: bool| {
134 let mut held: Vec<(f64, (f64, f64))> = terms
135 .iter()
136 .map(|t| match least {
137 true => (t.value_bounds.0, t.weight_bounds),
138 false => (-t.value_bounds.1, t.weight_bounds),
139 })
140 .collect();
141 held.sort_by(|a, b| a.0.total_cmp(&b.0));
142 let lowest = (0..=held.len())
143 .filter_map(|split| {
144 let (num, den) = held
145 .iter()
146 .enumerate()
147 .fold((0.0, 0.0), |(n, d), (i, (v, w))| {
148 let w = if i < split { w.1 } else { w.0 };
149 (n + w * v, d + w)
150 });
151 (den > 0.0).then_some(num / den)
152 })
153 .fold(f64::INFINITY, f64::min);
154 match least {
155 true => lowest,
156 false => -lowest,
157 }
158 };
159 Some(Weighted {
161 value,
162 bounds: (extreme(true).min(value), extreme(false).max(value)),
163 })
164}
165
166fn magnitude(bounds: (f64, f64)) -> (f64, f64) {
168 let (lo, hi) = bounds;
169 let least = match lo <= 0.0 && hi >= 0.0 {
170 true => 0.0,
171 false => lo.abs().min(hi.abs()),
172 };
173 (least, lo.abs().max(hi.abs()))
174}
175
176fn fit(points: &[(u32, Partial)]) -> Option<Fit> {
179 let ns: Vec<u32> = points.iter().map(|(n, _)| *n).collect();
180 let Weights { slope, intercept } = weights(&ns)?;
181 let y = |at: fn(&Partial) -> f64| -> Vec<f64> {
182 points
183 .iter()
184 .map(|(n, p)| (at(p) / f64::from(*n)).powi(2))
185 .collect()
186 };
187 let (y_lo, y_hi, y_at) = (y(|p| p.hz_bounds.0), y(|p| p.hz_bounds.1), y(|p| p.hz));
188 let a = dot(&intercept, &y_at);
189 if a <= 0.0 {
190 return None;
191 }
192 let b = dot(&slope, &y_at) / a;
193 let a_end = |pick: fn(f64, f64) -> f64| -> f64 {
194 intercept
195 .iter()
196 .zip(y_lo.iter().zip(&y_hi))
197 .map(|(w, (lo, hi))| pick(w * lo, w * hi))
198 .sum()
199 };
200 let (least_a, most_a) = (a_end(f64::min), a_end(f64::max));
201 let ratio_bound = |sign: f64| {
203 let mut l = b;
204 loop {
205 let y: Vec<f64> = slope
206 .iter()
207 .zip(&intercept)
208 .enumerate()
209 .map(|(i, (s, w))| match sign * (s - l * w) > 0.0 {
210 true => y_hi[i],
211 false => y_lo[i],
212 })
213 .collect();
214 let next = dot(&slope, &y) / dot(&intercept, &y);
215 if sign * (next - l) <= 0.0 {
216 return l;
217 }
218 l = next;
219 }
220 };
221 Some(Fit {
222 b,
223 f0_hz: a.sqrt(),
224 b_bounds: (least_a > 0.0).then(|| (ratio_bound(-1.0), ratio_bound(1.0))),
225 f0_bounds: (least_a > 0.0).then(|| (least_a.min(a).sqrt(), most_a.max(a).sqrt())),
226 })
227}
228
229fn series_of(moment: &Moment, floor_db: f64) -> Vec<(Partial, Vec<(u32, Partial)>)> {
230 let named = named(moment, floor_db);
231 let mut roots: Vec<(Partial, Vec<(u32, Partial)>)> = named
232 .iter()
233 .filter(|(_, note)| note.harmonic_of.is_none())
234 .map(|(partial, _)| (*partial, vec![(1, *partial)]))
235 .collect();
236 let mut by_hz: Vec<_> = named.iter().collect();
237 by_hz.sort_by(|a, b| a.0.hz.total_cmp(&b.0.hz));
238 let mut root_of: Vec<(f64, usize)> = Vec::with_capacity(named.len());
239 for (partial, note) in by_hz {
240 let at = match note.harmonic_of {
241 None => roots
242 .iter()
243 .position(|(root, _)| root.hz == partial.hz)
244 .expect("a note naming no harmonic heads a series"),
245 Some(hz) => {
246 let at = root_of
247 .iter()
248 .find(|(lower, _)| *lower == hz)
249 .map(|(_, at)| *at)
250 .expect("a harmonic names a lower note of its series");
251 let n = (partial.hz / roots[at].0.hz).round() as u32;
252 roots[at].1.push((n, *partial));
253 at
254 }
255 };
256 root_of.push((partial.hz, at));
257 }
258 for (_, members) in &mut roots {
259 members.sort_by(|a, b| a.1.hz.total_cmp(&b.1.hz));
260 }
261 roots
262}
263
264fn energy(p: &Partial) -> (f64, (f64, f64)) {
265 (
266 p.amplitude.powi(2),
267 (p.amplitude_bounds.0.powi(2), p.amplitude_bounds.1.powi(2)),
268 )
269}
270
271fn unexplained(lone: (f64, (f64, f64)), grouped: (f64, (f64, f64))) -> Option<Weighted> {
273 let share = |u: f64, e: f64| match u + e > 0.0 {
274 true => u / (u + e),
275 false => 0.0,
276 };
277 (lone.0 + grouped.0 > 0.0).then(|| Weighted {
278 value: share(lone.0, grouped.0),
279 bounds: (share(lone.1.0, grouped.1.1), share(lone.1.1, grouped.1.0)),
280 })
281}
282
283fn frame(moment: &Moment, floor_db: f64) -> InharmonicFrame {
284 let add =
285 |a: (f64, (f64, f64)), b: (f64, (f64, f64))| (a.0 + b.0, (a.1.0 + b.1.0, a.1.1 + b.1.1));
286 let none = (0.0, (0.0, 0.0));
287 let (mut lone, mut grouped) = (none, none);
288 let mut every = Vec::new();
289 let mut series = Vec::new();
290 for (root, points) in series_of(moment, floor_db) {
291 let held = points.iter().map(|(_, p)| energy(p)).fold(none, add);
292 match points.len() {
293 1 => lone = add(lone, held),
294 _ => grouped = add(grouped, held),
295 }
296 let members: Vec<Member> = points.iter().map(|(n, p)| member(p, *n, &root)).collect();
297 let deviations: Vec<Term> = members
298 .iter()
299 .zip(&points)
300 .filter(|(m, _)| m.n >= 2)
301 .map(|(m, (_, p))| Term {
302 value: m.cents.abs(),
303 value_bounds: magnitude(m.cents_bounds),
304 weight: p.amplitude,
305 weight_bounds: p.amplitude_bounds,
306 })
307 .collect();
308 every.extend(&deviations);
309 series.push(Series {
310 cents: weighted(&deviations),
311 fit: fit(&points),
312 members,
313 });
314 }
315 InharmonicFrame {
316 t_secs: moment.t_secs,
317 series,
318 cents: weighted(&every),
319 unexplained: unexplained(lone, grouped),
320 }
321}
322
323pub fn measure(moments: &[Moment], framing: Framing, floor_db: f64) -> Inharmonicity {
324 let frames: Vec<InharmonicFrame> = moments.iter().map(|m| frame(m, floor_db)).collect();
325 let mean = |of: fn(&InharmonicFrame) -> Option<f64>| {
326 let held: Vec<f64> = frames.iter().filter_map(of).collect();
327 (!held.is_empty()).then(|| held.iter().sum::<f64>() / held.len() as f64)
328 };
329 let cents_max = frames
330 .iter()
331 .filter_map(|f| f.cents.map(|c| (c.value, f.t_secs)))
332 .fold(None, |held: Option<Extreme>, (value, t_secs)| match held {
333 Some(e) if e.value >= value => Some(e),
334 _ => Some(Extreme { value, t_secs }),
335 });
336 Inharmonicity {
337 framing,
338 floor_db,
339 cents_mean: mean(|f| f.cents.map(|c| c.value)),
340 cents_max,
341 unexplained_mean: mean(|f| f.unexplained.map(|u| u.value)),
342 frames,
343 }
344}