the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
compare csd: like for like note by note, in place of the coverage counts
Jameson Hodge70b935b91d3a
diff --git a/crates/chimera-cli/src/compare.rs b/crates/chimera-cli/src/compare.rsindex 0d205ae..9fbada6 100644--- a/crates/chimera-cli/src/compare.rs+++ b/crates/chimera-cli/src/compare.rs@@ -796,66 +796,22 @@ fn r2(x: f64) -> Value {}}-/// One voice's song-level values for the score (in `score::TERMS` order), from its measures on-/// these notes. Each is NaN when no note gives it.-fn song_values(notes: &[&Note], meas: &[&NoteMeas]) -> [f64; score::N_TERMS] {- let col = |f: &dyn Fn(&NoteMeas) -> f64| meas.iter().map(|m| f(m)).collect::<Vec<_>>();- let eligible: Vec<&&NoteMeas> = meas.iter().filter(|m| m.vib_eligible).collect();- let vib_share = if eligible.is_empty() {- f64::NAN- } else {- eligible.iter().filter(|m| m.vib_depth.is_finite()).count() as f64 / eligible.len() as f64- };- let onset = |start: Start| {- median(- ¬es- .iter()- .zip(meas)- .filter(|(n, _)| n.phrase_start && n.starts_with() == start)- .map(|(_, m)| m.onset)- .collect::<Vec<_>>(),- )- };- [- mean(&col(&|m| m.bands[0])),- mean(&col(&|m| m.bands[1])),- mean(&col(&|m| m.bands[2])),- mean(&col(&|m| m.bands[3])),- mean(&col(&|m| m.bands[4])),- median(&col(&|m| m.h1h2)),- vib_share,- median(&col(&|m| m.vib_depth)),- median(&col(&|m| m.vib_rate)),- mean(&col(&|m| m.voiced)),- onset(Start::Vowel),- onset(Start::Voiceless),- median(&col(&|m| m.aperiodicity)),- ]-}--/// On how many of these notes the synth gives each guarded measure (`score::COVERAGE` order):-/// a value that goes missing must not take its note out of the score unnoticed.-fn coverage(notes: &[&Note], meas: &[&NoteMeas]) -> [u64; score::N_COVERAGE] {- let count = |f: &dyn Fn(&Note, &NoteMeas) -> bool| {- notes.iter().zip(meas).filter(|(n, m)| f(n, m)).count() as u64- };- let onset = |start: Start| {- count(&|n, m| n.phrase_start && n.starts_with() == start && m.onset.is_finite())- };+/// One voice's measures on a note, as the score keeps them (`score::NoteRow`).+fn note_row(m: &NoteMeas) -> score::NoteRow {[- notes.len() as u64,- count(&|_, m| m.bands[0].is_finite()),- count(&|_, m| m.bands[1].is_finite()),- count(&|_, m| m.bands[2].is_finite()),- count(&|_, m| m.bands[3].is_finite()),- count(&|_, m| m.bands[4].is_finite()),- count(&|_, m| m.h1h2.is_finite()),- count(&|_, m| m.vib_eligible),- count(&|_, m| m.voiced.is_finite()),- onset(Start::Vowel),- onset(Start::Voiceless),- count(&|_, m| m.aperiodicity.is_finite()),- count(&|_, m| m.cents.is_finite()),+ m.bands[0],+ m.bands[1],+ m.bands[2],+ m.bands[3],+ m.bands[4],+ m.h1h2,+ if m.vib_eligible { 1.0 } else { 0.0 },+ m.vib_depth,+ m.vib_rate,+ m.voiced,+ m.onset,+ m.aperiodicity,+ m.cents,]}@@ -903,15 +859,27 @@ fn compare_song(// notes measured on both sides; those the planner could not place on time are reported// but left out of every statistic (their windows would hold the wrong sound)let mut kept: Vec<&Note> = Vec::new();- // the singer on every note, aligned or not: the score's units come from these- let mut human_all: Vec<NoteMeas> = Vec::with_capacity(notes.len());+ // every note's measures on both voices, compared or not, for the score+ let (mut singer_rows, mut synth_rows) = (Vec::new(), Vec::new());+ let (mut starts, mut aligned_all) = (Vec::new(), Vec::new());for (n, &vt0) in notes.iter().zip(&vowel_t0) {let h = ha.note(&human, n);- human_all.push(h.clone());let s = sa.note(&synth, n);let d = mcd(&h.cep, &s.cep);let bd: [f64; 5] = std::array::from_fn(|k| s.bands[k] - h.bands[k]);let aligned = (vt0 - n.start).abs() <= MAX_MISALIGN;+ singer_rows.push(note_row(&h));+ synth_rows.push(note_row(&s));+ starts.push(if !n.phrase_start {+ 0+ } else {+ match n.starts_with() {+ Start::Vowel => score::PHRASE_VOWEL,+ Start::Voiceless => score::PHRASE_VOICELESS,+ Start::Voiced => score::PHRASE_VOICED,+ }+ });+ aligned_all.push(aligned);rows.push(json!({"start": n.start, "end": n.end, "midi": n.midi, "csd": n.csd,"ipa": format!("{}{}{}",@@ -990,21 +958,15 @@ fn compare_song("envelopeLagSec": r2(lag), "envelopeCorr": r2(lag_r),"bandDiffDb": BAND_NAMES.iter().zip(&band_mean).map(|(n, v)| (n.to_string(), r2(*v))).collect::<serde_json::Map<_, _>>(),});- let all_notes: Vec<&Note> = notes.iter().collect();- let singer: Vec<&NoteMeas> = per.iter().map(|p| &p.0).collect();- let synth_m: Vec<&NoteMeas> = per.iter().map(|p| &p.1).collect();- let (h_vals, s_vals) = (song_values(&kept, &singer), song_values(&kept, &synth_m));let song_score = score::SongScore {id: id.to_string(),- singer_all: song_values(&all_notes, &human_all.iter().collect::<Vec<_>>()),- pairs: std::array::from_fn(|k| (h_vals[k], s_vals[k])),- coverage: coverage(&kept, &synth_m),- notes: notes.len(),- misaligned,+ starts,+ aligned: aligned_all,+ singer: singer_rows,+ synth: synth_rows,dropped,mcd: mean(&mcds),env_corr: lag_r,- synth_pitch: median(&abs_cents(1)),};let line = format!("{id} {:>3} notes ({misaligned:>2} off-time) pitch |c| H {:>5} S {:>5} vib H {:>4}c/{:>3}Hz S {:>4}c/{:>3}Hz aper H {} S {} H1-H2 H {:>5} S {:>5} MCD {:>4} lag {:+.2}s r {} bands {}",diff --git a/crates/chimera-cli/src/compare/score.rs b/crates/chimera-cli/src/compare/score.rsindex 35ac1ac..195bb21 100644--- a/crates/chimera-cli/src/compare/score.rs+++ b/crates/chimera-cli/src/compare/score.rs@@ -4,10 +4,10 @@//! synth's in the same song, her share of voiced frames against the synth's, and so on. A term's//! gap is the mean over songs of |synth − singer|, divided by the spread of her own values over//! the training songs (median absolute deviation, scaled to a standard deviation; taken from all-//! her notes, so nothing the synth does can move it). A gap within-//! one spread is about as close as two of her own songs are to each other and costs nothing;-//! beyond that, the excess is the term's cost. The score is the weighted mean of the costs:-//! lower is better, and 0 means every term is within her own variation.+//! her notes, so nothing the synth does can move it). A gap within one spread is about as close+//! as two of her own songs are to each other and costs nothing; beyond that, the excess is the+//! term's cost. The score is the weighted mean of the costs: lower is better, and 0 means every+//! term is within her own variation.//!//! Every fifth song (en005, en010, …, in both keys) is held out. The spreads and the verdict use//! the training songs only; the held-out songs are scored with the same spreads, as a check that@@ -15,11 +15,11 @@//!//! `--against <score.json>` compares the training score with an earlier run's. A change is//! better when the score falls by at least `MARGIN`, no term's cost rises by more than-//! `TERM_SLACK`, and no guard breaks. The verdict compares like for like: each term's cost is-//! recomputed for both runs over the songs both runs measure, so a song that stops being-//! measured (say, its vibrato no longer reads as vibrato) can't take its gap out of the-//! comparison. Within a song, a measure that the synth gave on a note before and doesn't now-//! breaks a guard, since it would otherwise leave the song's median quietly.+//! `TERM_SLACK`, and no guard breaks. The verdict compares like for like, note by note: each+//! song's value of each term is recomputed for both runs over the notes on which both runs give+//! it. A note that stops being measured (a stray voiced frame gone, a vibrato that no longer+//! reads as vibrato) leaves both runs alike, so it can neither lower nor raise the score; making+//! notes unmeasurable by not voicing them still costs, through the voiced share.use super::{mean, median};use serde_json::{Value, json};@@ -58,27 +58,24 @@ const MCD_SLACK: f64 = 0.1;const PITCH_SLACK: f64 = 2.0;const CORR_SLACK: f64 = 0.01;-/// What `coverage` counts per song: the notes compared, and the notes on which the synth gives each-/// guarded measure. Vibrato depth and rate are not counted: they exist only on notes with-/// vibrato, and the vibrato share term already scores how many have it.-pub const N_COVERAGE: usize = 13;-pub const COVERAGE: [&str; N_COVERAGE] = [- "notes compared",- "level 0-.5k",- "level .5-1k",- "level 1-2k",- "level 2-4k",- "level 4-8k",- "H1-H2",- "notes long enough for vibrato",- "voiced share",- "onset, vowel-initial",- "onset, voiceless-initial",- "aperiodicity",- "pitch",-];-/// at most this many coverage losses are listed in a verdict-const MAX_LISTED: usize = 6;+/// One voice's measures on one note, in this order: the five band levels, H1−H2, long enough+/// to look for vibrato (1 or 0), vibrato depth and rate (NaN without vibrato), voiced share,+/// voice onset (NaN unless phrase-initial), aperiodicity, cents off the score.+pub const N_NOTE: usize = 13;+pub type NoteRow = [f64; N_NOTE];+const H1H2: usize = 5;+const ELIGIBLE: usize = 6;+const DEPTH: usize = 7;+const RATE: usize = 8;+const VOICED: usize = 9;+const ONSET: usize = 10;+const APER: usize = 11;+const CENTS: usize = 12;++/// What a note opens: 0 not a phrase, else a phrase on a vowel, a voiceless or a voiced consonant.+pub const PHRASE_VOWEL: u8 = 1;+pub const PHRASE_VOICELESS: u8 = 2;+pub const PHRASE_VOICED: u8 = 3;/// Held out of tuning: every fifth song number, in both keys.pub fn held_out(id: &str) -> bool {@@ -86,23 +83,95 @@ pub fn held_out(id: &str) -> bool {digits.parse::<u32>().is_ok_and(|n| n % 5 == 0)}-/// One song's inputs to the score.+/// Whether a voice's note gives term `k` a value.+fn gives(k: usize, row: &NoteRow, start: u8) -> bool {+ match k {+ 6 => row[ELIGIBLE] == 1.0,+ 7 | 8 => row[DEPTH].is_finite() && row[RATE].is_finite(),+ 10 => start == PHRASE_VOWEL && row[ONSET].is_finite(),+ 11 => start == PHRASE_VOICELESS && row[ONSET].is_finite(),+ _ => row[column(k)].is_finite(),+ }+}++fn column(k: usize) -> usize {+ match k {+ 0..=4 => k,+ 5 => H1H2,+ 7 => DEPTH,+ 8 => RATE,+ 9 => VOICED,+ 10 | 11 => ONSET,+ 12 => APER,+ _ => unreachable!("term {k} has no single column"),+ }+}++/// A voice's value of term `k` in one song, over the notes `keep` admits (and that give it).+fn song_value(k: usize, rows: &[NoteRow], starts: &[u8], keep: &dyn Fn(usize) -> bool) -> f64 {+ let kept: Vec<usize> = (0..rows.len())+ .filter(|&i| keep(i) && gives(k, &rows[i], starts[i]))+ .collect();+ match k {+ // the share of the notes long enough for vibrato that have it+ 6 => {+ if kept.is_empty() {+ f64::NAN+ } else {+ kept.iter().filter(|&&i| rows[i][DEPTH].is_finite()).count() as f64+ / kept.len() as f64+ }+ }+ 0..=4 | 9 => mean(&kept.iter().map(|&i| rows[i][column(k)]).collect::<Vec<_>>()),+ _ => median(&kept.iter().map(|&i| rows[i][column(k)]).collect::<Vec<_>>()),+ }+}++/// One song's inputs to the score: every annotated note, measured on both voices.pub struct SongScore {pub id: String,- /// per term, the singer's value over all her notes: the spreads are taken from these- pub singer_all: [f64; N_TERMS],- /// per term (singer, synth) over the notes compared; NaN where that side has no value- pub pairs: [(f64, f64); N_TERMS],- /// per `COVERAGE` entry, how many notes- pub coverage: [u64; N_COVERAGE],- pub notes: usize,- pub misaligned: usize,+ /// per note: PHRASE_* or 0+ pub starts: Vec<u8>,+ /// per note: the planner placed its vowel on time, so it is compared+ pub aligned: Vec<bool>,+ pub singer: Vec<NoteRow>,+ pub synth: Vec<NoteRow>,pub dropped: u64,- /// mean note MCD (dB)+ /// mean note MCD (dB) over the notes comparedpub mcd: f64,pub env_corr: f64,- /// the synth's median |cents| off the score- pub synth_pitch: f64,+}++impl SongScore {+ fn misaligned(&self) -> usize {+ self.aligned.iter().filter(|a| !**a).count()+ }++ /// per term (singer, synth) over the notes compared+ fn pairs(&self) -> [(f64, f64); N_TERMS] {+ let keep = |i: usize| self.aligned[i];+ std::array::from_fn(|k| {+ (+ song_value(k, &self.singer, &self.starts, &keep),+ song_value(k, &self.synth, &self.starts, &keep),+ )+ })+ }++ /// per term, the singer's value over all her notes: the spreads are taken from these+ fn singer_all(&self) -> [f64; N_TERMS] {+ std::array::from_fn(|k| song_value(k, &self.singer, &self.starts, &|_| true))+ }++ /// the synth's median |cents| off the score over the notes compared that `keep` admits+ fn synth_pitch(&self, keep: &dyn Fn(usize) -> bool) -> f64 {+ median(+ &(0..self.synth.len())+ .filter(|&i| self.aligned[i] && keep(i))+ .map(|i| self.synth[i][CENTS].abs())+ .collect::<Vec<_>>(),+ )+ }}fn mad_sd(xs: &[f64]) -> f64 {@@ -112,12 +181,9 @@ fn mad_sd(xs: &[f64]) -> f64 {/// The singer's spread of each term over these songs; NaN with too few songs or none at all.fn spreads(train: &[&SongScore]) -> [f64; N_TERMS] {+ let all: Vec<[f64; N_TERMS]> = train.iter().map(|s| s.singer_all()).collect();std::array::from_fn(|k| {- let h: Vec<f64> = train- .iter()- .map(|s| s.singer_all[k])- .filter(|v| v.is_finite())- .collect();+ let h: Vec<f64> = all.iter().map(|v| v[k]).filter(|v| v.is_finite()).collect();let sd = mad_sd(&h);if h.len() >= MIN_SPREAD_SONGS && sd > 0.0 {sd@@ -143,6 +209,11 @@ fn r4(x: f64) -> Value {}}+/// A number, or null when it isn't finite (full precision: the verdict recomputes from these).+fn fin(x: f64) -> Value {+ if x.is_finite() { json!(x) } else { Value::Null }+}+/// A term's cost from its per-song gaps |synth − singer|: the mean gap in units, less one unit./// NaN with too few songs or no unit (`f64::max` would turn that into a cost of 0).fn term_cost(gaps: &[f64], unit: f64) -> f64 {@@ -158,19 +229,16 @@ fn term_cost(gaps: &[f64], unit: f64) -> f64 {}}-/// A number, or null when it isn't finite (full precision: the verdict recomputes from these).-fn fin(x: f64) -> Value {- if x.is_finite() { json!(x) } else { Value::Null }-}--/// Score and guards of a set of songs, with the spreads of the training songs.-fn score_set(songs: &[&SongScore], spread: &[f64; N_TERMS]) -> Value {+/// Score and guards of a set of songs, with the spreads of the training songs; with `notes`,+/// every note's measures too, for a later verdict to compare against.+fn score_set(songs: &[&SongScore], spread: &[f64; N_TERMS], notes: bool) -> Value {+ let all_pairs: Vec<[(f64, f64); N_TERMS]> = songs.iter().map(|s| s.pairs()).collect();let mut terms = Vec::new();let (mut cost, mut weight) = (0.0, 0.0);for (k, (name, w)) in TERMS.iter().enumerate() {- let pairs: Vec<(f64, f64)> = songs+ let pairs: Vec<(f64, f64)> = all_pairs.iter()- .map(|s| s.pairs[k])+ .map(|p| p[k]).filter(|(h, s)| h.is_finite() && s.is_finite()).collect();let gaps: Vec<f64> = pairs.iter().map(|(h, s)| (s - h).abs()).collect();@@ -179,7 +247,6 @@ fn score_set(songs: &[&SongScore], spread: &[f64; N_TERMS]) -> Value {} else {f64::NAN};- let z = gap / spread[k];let excess = term_cost(&gaps, spread[k]);if excess.is_finite() {cost += w * excess;@@ -189,26 +256,87 @@ fn score_set(songs: &[&SongScore], spread: &[f64; N_TERMS]) -> Value {"name": name, "weight": r3(*w), "songs": pairs.len(),"singer": r4(median(&pairs.iter().map(|p| p.0).collect::<Vec<_>>())),"synth": r4(median(&pairs.iter().map(|p| p.1).collect::<Vec<_>>())),- "gap": r4(gap), "spread": r4(spread[k]), "z": r3(z), "cost": r3(excess),+ "gap": r4(gap), "spread": r4(spread[k]), "z": r3(gap / spread[k]), "cost": r3(excess),}));}- let total = |f: &dyn Fn(&SongScore) -> u64| songs.iter().map(|s| f(s)).sum::<u64>();let avg = |f: &dyn Fn(&SongScore) -> f64| mean(&songs.iter().map(|s| f(s)).collect::<Vec<_>>());- json!({+ let mut out = json!({"songs": songs.iter().map(|s| s.id.clone()).collect::<Vec<_>>(),- "coverageNames": COVERAGE,"score": r3(if weight > 0.0 { cost / weight } else { f64::NAN }),"terms": terms,- "coverage": songs.iter().map(|s| (s.id.clone(), json!(s.coverage))).collect::<serde_json::Map<_, _>>(),- "pairs": songs.iter().map(|s| (s.id.clone(), json!(s.pairs.iter().map(|(h, y)| json!([fin(*h), fin(*y)])).collect::<Vec<_>>()))).collect::<serde_json::Map<_, _>>(),"guards": {- "notes": total(&|s| s.notes as u64),- "notesMisaligned": total(&|s| s.misaligned as u64),- "droppedGestures": total(&|s| s.dropped),+ "notes": songs.iter().map(|s| s.aligned.len()).sum::<usize>(),+ "notesMisaligned": songs.iter().map(|s| s.misaligned()).sum::<usize>(),+ "droppedGestures": songs.iter().map(|s| s.dropped).sum::<u64>(),"noteMcdDb": r3(avg(&|s| s.mcd)),"envelopeCorr": r3(avg(&|s| s.env_corr)),- "synthPitchAbsCents": r3(avg(&|s| s.synth_pitch)),+ "synthPitchAbsCents": r3(avg(&|s| s.synth_pitch(&|_| true))),},+ });+ if notes {+ let rows = |r: &[NoteRow]| {+ r.iter()+ .map(|n| n.iter().map(|v| fin(*v)).collect::<Vec<_>>())+ .collect::<Vec<_>>()+ };+ out["notes"] = songs+ .iter()+ .map(|s| {+ (+ s.id.clone(),+ json!({+ "starts": s.starts, "aligned": s.aligned,+ "singer": rows(&s.singer), "synth": rows(&s.synth),+ "dropped": s.dropped, "mcd": fin(s.mcd), "envCorr": fin(s.env_corr),+ }),+ )+ })+ .collect::<serde_json::Map<_, _>>()+ .into();+ }+ out+}++/// A song back from `score.json`'s notes.+fn song_from(id: &str, v: &Value) -> Result<SongScore, String> {+ let bad = || format!("score.json: no notes for {id}; rescore the baseline with this build");+ let rows = |side: &str| -> Result<Vec<NoteRow>, String> {+ v[side]+ .as_array()+ .ok_or_else(bad)?+ .iter()+ .map(|r| {+ let r = r.as_array().filter(|r| r.len() == N_NOTE).ok_or_else(bad)?;+ Ok(std::array::from_fn(|k| num(&r[k])))+ })+ .collect()+ };+ let starts: Vec<u8> = v["starts"]+ .as_array()+ .ok_or_else(bad)?+ .iter()+ .map(|x| x.as_u64().unwrap_or(0) as u8)+ .collect();+ let aligned: Vec<bool> = v["aligned"]+ .as_array()+ .ok_or_else(bad)?+ .iter()+ .map(|x| x.as_bool().unwrap_or(false))+ .collect();+ let (singer, synth) = (rows("singer")?, rows("synth")?);+ if singer.len() != starts.len() || synth.len() != starts.len() || aligned.len() != starts.len()+ {+ return Err(bad());+ }+ Ok(SongScore {+ id: id.to_string(),+ starts,+ aligned,+ singer,+ synth,+ dropped: v["dropped"].as_u64().unwrap_or(0),+ mcd: num(&v["mcd"]),+ env_corr: num(&v["envCorr"]),})}@@ -224,7 +352,7 @@ fn num(v: &Value) -> f64 {}/// The verdict on a change in score (like for like) once the guards are checked: the change is-/// taken in the thousandths `score.json` gives, so 1.001 → 0.991 is a fall of exactly 0.010.+/// taken in thousandths, so 1.001 → 0.991 is a fall of exactly 0.010.fn decide(change: f64, mut why: Vec<String>) -> (Verdict, Vec<String>) {let milli = |x: f64| (x * 1000.0).round() as i64;let (d, margin) = (milli(change), milli(MARGIN));@@ -241,7 +369,7 @@ fn decide(change: f64, mut why: Vec<String>) -> (Verdict, Vec<String>) {}/// The training score of `new` against `old` (both as written to `score.json`): the verdict,-/// why when worse, and the change in score over the songs both runs measure.+/// why when worse, and the change in score, like for like.pub fn verdict(old: &Value, new: &Value) -> Result<(Verdict, Vec<String>, f64), String> {let (o, n) = (&old["train"], &new["train"]);if o["songs"] != n["songs"] || old["body"] != new["body"] {@@ -253,8 +381,12 @@ pub fn verdict(old: &Value, new: &Value) -> Result<(Verdict, Vec<String>, f64),.into(),);}+ let ids: Vec<&str> = o["songs"]+ .as_array()+ .map(|a| a.iter().filter_map(|v| v.as_str()).collect())+ .unwrap_or_default();let mut why = Vec::new();- // (old, new) of a guard; a guard that had a value and lost it breaks+ // run-level guards: a guard that had a value and lost it breakslet mut guard = |k: &str, broken: &dyn Fn(f64, f64) -> bool, what: &str| {let (a, b) = (num(&o["guards"][k]), num(&n["guards"][k]));if a.is_finite() && !b.is_finite() {@@ -271,82 +403,48 @@ pub fn verdict(old: &Value, new: &Value) -> Result<(Verdict, Vec<String>, f64),&|a, b| b < a - CORR_SLACK,"envelope correlation down",);- guard(- "synthPitchAbsCents",- &|a, b| b > a + PITCH_SLACK,- "pitch error up (cents)",- );- // no song may lose a note from any guarded measure- if o["coverageNames"] != n["coverageNames"] {- return Err(- "the earlier score counts other measures; rescore the baseline with this build".into(),+ // like for like, note by note+ let mut gaps: Vec<(Vec<f64>, Vec<f64>)> = vec![(Vec::new(), Vec::new()); N_TERMS];+ let (mut pitch_o, mut pitch_n) = (Vec::new(), Vec::new());+ for id in &ids {+ let (so, sn) = (+ song_from(id, &o["notes"][id])?,+ song_from(id, &n["notes"][id])?,);- }- let mut lost = Vec::new();- if let (Some(co), Some(cn)) = (o["coverage"].as_object(), n["coverage"].as_object()) {- for (song, a) in co {- let (a, b) = (a.as_array(), cn.get(song).and_then(|b| b.as_array()));- let (Some(a), Some(b)) = (a, b) else { continue };- for (k, (x, y)) in a.iter().zip(b).enumerate() {- let (x, y) = (x.as_u64().unwrap_or(0), y.as_u64().unwrap_or(0));- if y < x {- lost.push(format!("{song} {}: {x} → {y} notes", COVERAGE[k]));- }- }+ if so.starts != sn.starts {+ return Err(format!("{id}: the two runs have different notes"));}- }- if !lost.is_empty() {- let more = lost.len().saturating_sub(MAX_LISTED);- lost.truncate(MAX_LISTED);- why.push(format!(- "measured on fewer notes: {}{}",- lost.join(", "),- if more > 0 {- format!(" and {more} more")- } else {- String::new()+ let both = |i: usize| so.aligned[i] && sn.aligned[i];+ for (k, (go, gn)) in gaps.iter_mut().enumerate() {+ let synth = |i: usize| {+ both(i)+ && gives(k, &so.synth[i], so.starts[i])+ && gives(k, &sn.synth[i], sn.starts[i])+ };+ let h = song_value(k, &sn.singer, &sn.starts, &both);+ let (vo, vn) = (+ song_value(k, &so.synth, &so.starts, &synth),+ song_value(k, &sn.synth, &sn.starts, &synth),+ );+ if [h, vo, vn].iter().all(|v| v.is_finite()) {+ go.push((vo - h).abs());+ gn.push((vn - h).abs());}- ));+ }+ let pitched =+ |i: usize| both(i) && so.synth[i][CENTS].is_finite() && sn.synth[i][CENTS].is_finite();+ pitch_o.push(so.synth_pitch(&pitched));+ pitch_n.push(sn.synth_pitch(&pitched));}- let empty = vec![];- let (to, tn) = (- o["terms"].as_array().unwrap_or(&empty),- n["terms"].as_array().unwrap_or(&empty),- );- if to.len() != N_TERMS- || tn.len() != N_TERMS- || to.iter().zip(tn).any(|(a, b)| a["name"] != b["name"])- {- return Err(- "the earlier score has other terms; rescore the baseline with this build".into(),- );+ let (po, pn) = (mean(&pitch_o), mean(&pitch_n));+ if pn > po + PITCH_SLACK {+ why.push(format!("pitch error up (cents): {po:.2} → {pn:.2}"));}- // each term's cost in both runs over the songs both measure- let songs: Vec<&str> = o["songs"]- .as_array()- .unwrap_or(&empty)- .iter()- .filter_map(|v| v.as_str())- .collect();- let pair = |run: &Value, song: &str, k: usize| {- let p = &run["pairs"][song][k];- (num(&p[0]), num(&p[1]))- };let (mut change, mut weight) = (0.0, 0.0);for (k, (name, w)) in TERMS.iter().enumerate() {let unit = num(&old["units"][k]);- let (mut go, mut gn) = (Vec::new(), Vec::new());- for song in &songs {- let ((ho, so), (hn, sn)) = (pair(o, song, k), pair(n, song, k));- if [ho, so, hn, sn].iter().all(|v| v.is_finite()) {- go.push((so - ho).abs());- gn.push((sn - hn).abs());- }- }- let (co, cn) = (term_cost(&go, unit), term_cost(&gn, unit));- if num(&to[k]["cost"]).is_finite() && !num(&tn[k]["cost"]).is_finite() {- why.push(format!("{name} has no value any more"));- } else if co.is_finite() && cn.is_finite() {+ let (co, cn) = (term_cost(&gaps[k].0, unit), term_cost(&gaps[k].1, unit));+ if co.is_finite() && cn.is_finite() {if cn > co + TERM_SLACK {why.push(format!("{name} cost up: {co:.3} → {cn:.3}"));}@@ -381,10 +479,10 @@ pub fn report(let mut out = json!({"body": body,"units": spread.iter().map(|u| fin(*u)).collect::<Vec<_>>(),- "train": score_set(&train, &spread),+ "train": score_set(&train, &spread, true),});if !held.is_empty() {- out["heldout"] = score_set(&held, &spread);+ out["heldout"] = score_set(&held, &spread, false);}let t = &out["train"];let fmt = |v: &Value, d: usize| v.as_f64().map_or("—".to_string(), |x| format!("{x:.d$}"));@@ -460,77 +558,41 @@ pub fn report(mod tests {use super::*;+ /// A song of ten notes, all compared and long enough for vibrato; the first opens a phrase on+ /// a vowel and the sixth one on a voiceless consonant. Every measure of a voice is its value.fn song(id: &str, singer: f64, synth: f64) -> SongScore {+ let row = |v: f64| -> NoteRow {+ let mut r = [v; N_NOTE];+ r[ELIGIBLE] = 1.0;+ r+ };+ let mut starts = vec![0; 10];+ starts[0] = PHRASE_VOWEL;+ starts[5] = PHRASE_VOICELESS;SongScore {id: id.into(),- singer_all: [singer; N_TERMS],- pairs: [(singer, synth); N_TERMS],- coverage: [10; N_COVERAGE],- notes: 10,- misaligned: 0,+ starts,+ aligned: vec![true; 10],+ singer: vec![row(singer); 10],+ synth: vec![row(synth); 10],dropped: 0,mcd: 9.0,env_corr: 0.8,- synth_pitch: 5.0,}}- #[test]- fn a_bad_song_that_stops_being_measured_does_not_improve_the_score() {- // nine songs one spread (3.7065) apart from her, one far off: a cost the outlier carries- let mk = |worst_missing: bool| {- let mut songs: Vec<SongScore> = (1..=9)- .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + 3.7))- .collect();- songs[0].pairs[5].1 = 1.0 + 60.0;- if worst_missing {- // its H1−H2 can no longer be measured on any note- songs[0].pairs[5].1 = f64::NAN;- songs[0].coverage[6] = 0;- }- let refs: Vec<&SongScore> = songs.iter().collect();- report("female", &refs, None).unwrap().0- };- let (base, gone) = (mk(false), mk(true));- assert!(num(&gone["train"]["score"]) < num(&base["train"]["score"]));- let (v, why, _) = verdict(&base, &gone).unwrap();- assert_eq!(v, Verdict::Worse);- assert!(why[0].contains("en001a H1-H2: 10 → 0 notes"), "{why:?}");- // losing pitch on a few notes of one song is caught the same way- let mut fewer = base.clone();- fewer["train"]["coverage"]["en002a"][12] = json!(7);- let (v, why, _) = verdict(&base, &fewer).unwrap();- assert_eq!(v, Verdict::Worse);- assert!(why[0].contains("en002a pitch: 10 → 7 notes"), "{why:?}");- }-- #[test]- fn the_margin_is_exact_in_thousandths() {- // 0.991 − 1.001 is −0.0099999… in floating point, and still a fall of 0.010- assert_eq!(decide(0.991 - 1.001, vec![]).0, Verdict::Better);- assert_eq!(decide(1.001 - 0.991, vec![]).0, Verdict::Worse);- assert_eq!(decide(0.992 - 1.001, vec![]).0, Verdict::Same);- assert_eq!(decide(-0.5, vec!["a guard".into()]).0, Verdict::Worse);+ fn report_of(songs: &[SongScore]) -> Value {+ let refs: Vec<&SongScore> = songs.iter().collect();+ report("female", &refs, None).unwrap().0}- #[test]- fn a_song_whose_vibrato_stops_reading_as_vibrato_takes_no_gap_with_it() {- // vibrato rate (term 8) is far off in en001a; then its modulation leaves the vibrato- // range, so it has no rate at all. Depth and rate keep no coverage (fewer notes with- // vibrato can be right), so only the like-for-like comparison stops this from passing.- let mk = |gone: bool| {- let mut songs: Vec<SongScore> = (1..=9)- .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + 3.7))- .collect();- songs[0].pairs[8].1 = if gone { f64::NAN } else { 1.0 + 40.0 };- let refs: Vec<&SongScore> = songs.iter().collect();- report("female", &refs, None).unwrap().0- };- let (base, gone) = (mk(false), mk(true));- assert!(num(&gone["train"]["score"]) < num(&base["train"]["score"]) - 0.01);- let (v, _, change) = verdict(&base, &gone).unwrap();- assert_eq!(v, Verdict::Same);- assert_eq!(change, 0.0);+ /// Nine songs, the synth `gap` above her on every measure, then `f` applied to each song.+ fn scored(gap: f64, f: impl Fn(&mut SongScore)) -> Value {+ let mut songs: Vec<SongScore> = (1..=9)+ .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + gap))+ .collect();+ songs.iter_mut().for_each(&f);+ report_of(&songs)}#[test]@@ -552,8 +614,7 @@ mod tests {)}).collect();- let refs: Vec<&SongScore> = songs.iter().collect();- let (out, _, _) = report("female", &refs, None).unwrap();+ let out = report_of(&songs);let t = &out["train"]["terms"][0];assert_eq!(out["train"]["songs"].as_array().unwrap().len(), 8);assert!((num(&t["spread"]) - 3.7065).abs() < 1e-3, "{t}");@@ -565,18 +626,16 @@ mod tests {let close: Vec<SongScore> = (1..=9).map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + 1.0)).collect();- let refs: Vec<&SongScore> = close.iter().collect();- let (out, _, _) = report("female", &refs, None).unwrap();- assert_eq!(num(&out["train"]["score"]), 0.0);+ assert_eq!(num(&report_of(&close)["train"]["score"]), 0.0);}- fn scored(gap: f64, f: impl Fn(&mut SongScore)) -> Value {- let mut songs: Vec<SongScore> = (1..=9)- .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + gap))- .collect();- songs.iter_mut().for_each(&f);- let refs: Vec<&SongScore> = songs.iter().collect();- report("female", &refs, None).unwrap().0+ #[test]+ fn the_margin_is_exact_in_thousandths() {+ // 0.991 − 1.001 is −0.0099999… in floating point, and still a fall of 0.010+ assert_eq!(decide(0.991 - 1.001, vec![]).0, Verdict::Better);+ assert_eq!(decide(1.001 - 0.991, vec![]).0, Verdict::Worse);+ assert_eq!(decide(0.992 - 1.001, vec![]).0, Verdict::Same);+ assert_eq!(decide(-0.5, vec!["a guard".into()]).0, Verdict::Worse);}#[test]@@ -594,26 +653,85 @@ mod tests {Verdict::Worse);// better on the score, but a note leaves its time: worse- let (v, why, _) = verdict(&base, &scored(6.0, |s| s.misaligned = 1)).unwrap();+ let (v, why, _) = verdict(&base, &scored(6.0, |s| s.aligned[3] = false)).unwrap();assert_eq!(v, Verdict::Worse);assert!(why[0].contains("off time"), "{why:?}");let (v, _, _) = verdict(&base, &scored(6.0, |s| s.mcd = 9.5)).unwrap();assert_eq!(v, Verdict::Worse);+ let (v, why, _) = verdict(&base, &scored(6.0, |s| s.mcd = f64::NAN)).unwrap();+ assert_eq!(v, Verdict::Worse);+ assert!(why[0].contains("note MCD up (dB): no value"), "{why:?}");// one term much worse while the rest improve: worse- let one_worse = scored(6.0, |s| s.pairs[5].1 = s.pairs[5].0 + 30.0);+ let one_worse = scored(6.0, |s| s.synth.iter_mut().for_each(|r| r[H1H2] += 30.0));let (v, why, _) = verdict(&base, &one_worse).unwrap();assert_eq!(v, Verdict::Worse);- assert!(why[0].contains("H1-H2"), "{why:?}");- // a guard that loses its value breaks- let (v, why, _) = verdict(&base, &scored(6.0, |s| s.synth_pitch = f64::NAN)).unwrap();+ assert!(why.iter().any(|w| w.contains("H1-H2")), "{why:?}");+ // the synth further off the score: worse+ let off_key = scored(6.0, |s| s.synth.iter_mut().for_each(|r| r[CENTS] += 10.0));+ let (v, why, _) = verdict(&base, &off_key).unwrap();assert_eq!(v, Verdict::Worse);- assert!(- why[0].contains("pitch error up (cents): no value"),- "{why:?}"- );+ assert!(why.iter().any(|w| w.contains("pitch error up")), "{why:?}");// different songs are not comparablelet mut other = scored(6.0, |_| {});other["train"]["songs"] = json!(["en001a"]);assert!(verdict(&base, &other).is_err());}++ #[test]+ fn notes_that_stop_being_measured_take_nothing_with_them() {+ // in en001a, six of ten notes have the synth's H1−H2 60 off: they carry its median+ let mk = |gone: bool| {+ let mut songs: Vec<SongScore> = (1..=9)+ .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + 3.7))+ .collect();+ for r in songs[0].synth.iter_mut().take(6) {+ r[H1H2] = if gone { f64::NAN } else { 61.0 };+ }+ report_of(&songs)+ };+ let (base, gone) = (mk(false), mk(true));+ // counted plainly, losing them looks like a gain+ assert!(num(&gone["train"]["score"]) < num(&base["train"]["score"]) - 0.01);+ // like for like, both runs are judged on the four notes both measure+ let (v, _, change) = verdict(&base, &gone).unwrap();+ assert_eq!(v, Verdict::Same);+ assert_eq!(change, 0.0);+ }++ #[test]+ fn a_vibrato_that_stops_reading_as_vibrato_takes_no_gap_with_it() {+ // en001a's vibrato rate is far off; then its modulation leaves the vibrato range on+ // every note, so the synth has no rate there at all+ let mk = |gone: bool| {+ let mut songs: Vec<SongScore> = (1..=9)+ .map(|i| song(&format!("en{i:03}a"), i as f64, i as f64 + 3.7))+ .collect();+ for r in songs[0].synth.iter_mut() {+ (r[DEPTH], r[RATE]) = if gone {+ (f64::NAN, f64::NAN)+ } else {+ (4.7, 41.0)+ };+ }+ report_of(&songs)+ };+ let (base, gone) = (mk(false), mk(true));+ assert!(num(&gone["train"]["score"]) < num(&base["train"]["score"]) - 0.01);+ let (v, _, change) = verdict(&base, &gone).unwrap();+ assert_eq!(v, Verdict::Same);+ assert_eq!(change, 0.0);+ }++ #[test]+ fn a_song_reads_back_from_score_json_as_it_was() {+ let mut s = song("en001a", 2.0, 3.0);+ s.synth[4][ONSET] = f64::NAN;+ s.aligned[7] = false;+ let out = report_of(&[s, song("en002a", 1.0, 2.0)]);+ let back = song_from("en001a", &out["train"]["notes"]["en001a"]).unwrap();+ assert!(back.synth[4][ONSET].is_nan());+ assert!(!back.aligned[7]);+ assert_eq!(back.starts[5], PHRASE_VOICELESS);+ assert_eq!(back.singer[0][0], 2.0);+ }}diff --git a/docs/csd-comparison.md b/docs/csd-comparison.mdindex 9d573b7..db9db68 100644--- a/docs/csd-comparison.md+++ b/docs/csd-comparison.md@@ -116,10 +116,12 @@ convention with real timing errors. Pitch is not scored either: the synth singsdeviations from it can't be predicted from the score.**The verdict.** `--against <earlier score.json>` compares the training scores of two runs over-the same songs and body. It compares like for like: each term's cost is recomputed for both runs-over the songs both runs measure, from the per-song values in `score.json`. A song that stops-being measured, for example because its vibrato no longer reads as vibrato, can't take its gap-out of the comparison.+the same songs and body. It compares like for like, note by note. `score.json` keeps every note's+measures on both voices, and the verdict recomputes each song's value of each term for both runs+over the notes on which both runs give that term. A measure that stops being measurable on a+note leaves both runs alike, so it can neither help nor hurt. That covers a stray voiced frame+that comes or goes in a note the synth barely voices, and a vibrato that no longer reads as+vibrato. Not voicing a note still costs, through the voiced share, which every note has.- **Better:** the like-for-like score falls by at least 0.01 (in thousandths), no term's costrises by more than 0.25, and every guard holds.@@ -128,14 +130,7 @@ out of the comparison.- no more dropped gestures- note MCD up by no more than 0.1 dB- envelope correlation down by no more than 0.01- - the synth's pitch error up by no more than 2 cents- - no song measured on fewer notes. For each song, `score.json` counts the notes compared and- the notes on which the synth gives each measure: band levels, H1−H2, voicing, onsets,- aperiodicity and pitch, and the notes long enough to look for vibrato. A song's value is a- median over its notes, and a measure that stops being measurable on a note would otherwise- drop that note, maybe a bad one, from the median. Vibrato depth and rate are not counted:- they exist only on notes with vibrato, giving fewer notes vibrato can be right, and the share- term scores how many have it.+ - the synth's pitch error up by no more than 2 cents, over the notes both runs pitch- a guard that had a value and has none now breaks too.- **Worse:** any guard or term breaks, or the score rises by 0.01 or more.- **No clear change:** anything else.