Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

compare csd: one score against the singer, held-out songs, and a verdict

Jameson Hodge37d217cd9888
diff --git a/crates/chimera-cli/src/compare.rs b/crates/chimera-cli/src/compare.rs
index 146737b..504f156 100644
--- a/crates/chimera-cli/src/compare.rs
+++ b/crates/chimera-cli/src/compare.rs
@@ -22,6 +22,10 @@
//!
//! "Voiced" means YIN finds a period and the frame is within 35 dB of the signal's loud level.
//!
+//! `score.json` (see `score.rs`) folds the measures into one number, how far the synth is from the
+//! singer in units of her own song-to-song spread, over training songs and held-out songs; with
+//! `--against <earlier score.json>` it also gives the verdict on a change.
+//!
//! The band and cepstral measures compare averaged spectra, so they see vowel colour, spectral
//! tilt and noise, not frame-level detail. At this singer's pitch (C4–C6) harmonics are 260 Hz+
//! apart, which is why there are no LPC formants here.
@@ -41,6 +45,8 @@ use std::collections::BTreeMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
+mod score;
+
/// A gap between notes longer than this (s) ends a phrase: the synth stops and breathes.
const PHRASE_GAP: f64 = 0.08;
/// Two notes this close (s) with a vowel-only second syllable on the same vowel are a melisma.
@@ -114,6 +120,20 @@ fn csd_ipa(sym: &str) -> Option<(&'static str, bool)> {
})
}
+/// IPA onsets with no voicing of their own: after them, the first voiced frame is the vowel's.
+const VOICELESS: [&str; 9] = ["p", "t", "k", "f", "θ", "s", "ʃ", "h", "tʃ"];
+
+/// What a phrase starts with, which decides what its first voiced frame belongs to.
+#[derive(Clone, Copy, PartialEq)]
+enum Start {
+ Vowel,
+ /// a voiceless consonant: the voicing starts with the vowel, whichever convention places it
+ Voiceless,
+ /// a voiced consonant: the voicing starts with the consonant, which `plan_song` sings before
+ /// the note while CSD's note starts mark the start of the syllable
+ Voiced,
+}
+
struct Note {
start: f64,
end: f64,
@@ -127,6 +147,16 @@ struct Note {
prev_end: f64,
}
+impl Note {
+ fn starts_with(&self) -> Start {
+ match self.syl.onset.first() {
+ None => Start::Vowel,
+ Some(c) if VOICELESS.contains(&c.ipa.as_str()) => Start::Voiceless,
+ Some(_) => Start::Voiced,
+ }
+ }
+}
+
/// Read `csv/<id>.csv` into notes with engine syllables, melismas and phrase ends.
fn load_notes(path: &str) -> Result<Vec<Note>, String> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
@@ -755,6 +785,7 @@ struct SongResult {
/// (vowel IPA, mcd, band diffs synth − human)
vowels: Vec<(String, f64, [f64; 5])>,
line: String,
+ score: score::SongScore,
}
fn r2(x: f64) -> Value {
@@ -765,6 +796,14 @@ fn r2(x: f64) -> Value {
}
}
+fn r3(x: f64) -> Value {
+ if x.is_finite() {
+ json!((x * 1000.0).round() / 1000.0)
+ } else {
+ Value::Null
+ }
+}
+
fn compare_song(
ctx: &Ctx,
csd: &str,
@@ -849,12 +888,11 @@ fn compare_song(
let abs_cents = |side| col(&|m: &NoteMeas| m.cents.abs(), side);
let vs_human: Vec<f64> = per.iter().map(|p| (p.1.cents - p.0.cents).abs()).collect();
let mcds: Vec<f64> = per.iter().map(|p| p.2).collect();
- // phrase starts, split by whether voicing means the vowel (vowel-initial) or the onset
- // consonant (or the vowel after a voiceless one) has begun
- let onset_of = |side: usize, vowel_initial: bool| -> Vec<f64> {
+ // phrase starts, by what the first voiced frame belongs to
+ let onset_of = |side: usize, start: Start| -> Vec<f64> {
kept.iter()
.zip(&per)
- .filter(|(n, _)| n.phrase_start && n.syl.onset.is_empty() == vowel_initial)
+ .filter(|(n, _)| n.phrase_start && n.starts_with() == start)
.map(|(_, p)| if side == 0 { p.0.onset } else { p.1.onset })
.collect()
};
@@ -879,12 +917,56 @@ fn compare_song(
"aperiodicity": {"human": r2(median(&col(&|m| m.aperiodicity, 0))), "synth": r2(median(&col(&|m| m.aperiodicity, 1)))},
"h1h2Db": {"human": r2(median(&col(&|m| m.h1h2, 0))), "synth": r2(median(&col(&|m| m.h1h2, 1)))},
"voicedShare": {"human": r2(mean(&col(&|m| m.voiced, 0))), "synth": r2(mean(&col(&|m| m.voiced, 1)))},
- "vowelOnsetSec": {"human": r2(median(&onset_of(0, true))), "synth": r2(median(&onset_of(1, true)))},
- "consonantOnsetSec": {"human": r2(median(&onset_of(0, false))), "synth": r2(median(&onset_of(1, false)))},
+ "vowelOnsetSec": {"human": r3(median(&onset_of(0, Start::Vowel))), "synth": r3(median(&onset_of(1, Start::Vowel)))},
+ "voicelessOnsetSec": {"human": r3(median(&onset_of(0, Start::Voiceless))), "synth": r3(median(&onset_of(1, Start::Voiceless)))},
+ "voicedOnsetSec": {"human": r3(median(&onset_of(0, Start::Voiced))), "synth": r3(median(&onset_of(1, Start::Voiced)))},
"noteMcdDb": r2(mean(&mcds)),
"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<_, _>>(),
});
+ // the score's song-level values (singer, synth), unrounded, in score::TERMS order
+ fn side(p: &(NoteMeas, NoteMeas, f64), s: usize) -> &NoteMeas {
+ if s == 0 { &p.0 } else { &p.1 }
+ }
+ let with_bands: Vec<&(NoteMeas, NoteMeas, f64)> = per
+ .iter()
+ .filter(|p| p.0.bands[0].is_finite() && p.1.bands[0].is_finite())
+ .collect();
+ let level = |s: usize, k: usize| {
+ mean(
+ &with_bands
+ .iter()
+ .map(|p| side(p, s).bands[k])
+ .collect::<Vec<_>>(),
+ )
+ };
+ let med_of = |f: &dyn Fn(&NoteMeas) -> f64, s: usize| median(&col(f, s));
+ let pair = |f: &dyn Fn(usize) -> f64| (f(0), f(1));
+ let pairs: [(f64, f64); score::N_TERMS] = [
+ pair(&|s| level(s, 0)),
+ pair(&|s| level(s, 1)),
+ pair(&|s| level(s, 2)),
+ pair(&|s| level(s, 3)),
+ pair(&|s| level(s, 4)),
+ pair(&|s| med_of(&|m| m.h1h2, s)),
+ pair(&vib_share),
+ pair(&|s| med_of(&|m| m.vib_depth, s)),
+ pair(&|s| med_of(&|m| m.vib_rate, s)),
+ pair(&|s| mean(&col(&|m| m.voiced, s))),
+ pair(&|s| median(&onset_of(s, Start::Vowel))),
+ pair(&|s| median(&onset_of(s, Start::Voiceless))),
+ pair(&|s| med_of(&|m| m.aperiodicity, s)),
+ ];
+ let song_score = score::SongScore {
+ id: id.to_string(),
+ pairs,
+ notes: notes.len(),
+ misaligned,
+ 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 {}",
notes.len(),
@@ -913,6 +995,7 @@ fn compare_song(
notes: rows,
vowels,
line,
+ score: song_score,
})
}
@@ -925,12 +1008,14 @@ fn meas_json(m: &NoteMeas) -> Value {
})
}
-/// `compare csd [csd-dir] [outdir] [--songs en001a,en002b|all|a|b] [--body female] [--jobs n]`
+/// `compare csd [csd-dir] [outdir] [--songs en001a,en002b|all|a|b] [--body female] [--jobs n]
+/// [--against earlier/score.json]`
pub fn csd(ctx: &Ctx, a: &[String]) -> Result<(), String> {
let mut pos: Vec<&str> = Vec::new();
let mut songs = "a".to_string();
let mut body_name = "female".to_string();
let mut jobs = std::thread::available_parallelism().map_or(4, |n| n.get());
+ let mut against: Option<String> = None;
let mut it = a.iter();
while let Some(x) = it.next() {
let mut val = |name: &str| it.next().cloned().ok_or(format!("{name} needs a value"));
@@ -938,6 +1023,7 @@ pub fn csd(ctx: &Ctx, a: &[String]) -> Result<(), String> {
"--songs" => songs = val("--songs")?,
"--body" => body_name = val("--body")?,
"--jobs" => jobs = val("--jobs")?.parse().map_err(|e| format!("--jobs: {e}"))?,
+ "--against" => against = Some(val("--against")?),
_ => pos.push(x),
}
}
@@ -1057,6 +1143,13 @@ pub fn csd(ctx: &Ctx, a: &[String]) -> Result<(), String> {
.sum::<u64>(),
MAX_MISALIGN * 1000.0,
);
+ let (score_json, score_md, verdict) = score::report(
+ &body_name,
+ &results.iter().map(|r| &r.score).collect::<Vec<_>>(),
+ against.as_deref(),
+ )?;
+ md += &score_md;
+ md += "## Measures\n\n";
md += "| measure | human | synth |\n|---|---|---|\n";
for (label, key) in [
("pitch error vs score (|cents|)", "pitchAbsCentsVsScore"),
@@ -1071,14 +1164,19 @@ pub fn csd(ctx: &Ctx, a: &[String]) -> Result<(), String> {
"vowelOnsetSec",
),
(
- "voice onset re note start, consonant-initial phrases (s)",
- "consonantOnsetSec",
+ "voice onset re note start, phrases opening on a voiceless consonant (s)",
+ "voicelessOnsetSec",
+ ),
+ (
+ "voice onset re note start, phrases opening on a voiced consonant (s; not scored)",
+ "voicedOnsetSec",
),
] {
+ let d = if key.ends_with("OnsetSec") { 3 } else { 2 };
md += &format!(
"| {label} | {} | {} |\n",
- fx(overall(key, Some("human")), 2),
- fx(overall(key, Some("synth")), 2)
+ fx(overall(key, Some("human")), d),
+ fx(overall(key, Some("synth")), d)
);
}
md += &format!(
@@ -1156,8 +1254,15 @@ pub fn csd(ctx: &Ctx, a: &[String]) -> Result<(), String> {
"report.json",
serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?,
)?;
+ write(
+ "score.json",
+ serde_json::to_string_pretty(&score_json).map_err(|e| e.to_string())?,
+ )?;
println!("\n{md}");
- println!("wrote {out_dir}/report.md, {out_dir}/report.json");
+ println!("wrote {out_dir}/report.md, {out_dir}/report.json, {out_dir}/score.json");
+ if let Some(v) = verdict {
+ println!("{v}");
+ }
Ok(())
}
diff --git a/crates/chimera-cli/src/compare/score.rs b/crates/chimera-cli/src/compare/score.rs
new file mode 100644
index 0000000..d1d24c1
--- /dev/null
+++ b/crates/chimera-cli/src/compare/score.rs
@@ -0,0 +1,425 @@
+//! The CSD comparison as one number, and the verdict on a change.
+//!
+//! Each term is a song-level measure both voices have: her median H1−H2 in a song against the
+//! 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). 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
+//! a change carries over to songs it was not tuned on.
+//!
+//! `--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.
+
+use super::{mean, median};
+use serde_json::{Value, json};
+
+pub const N_TERMS: usize = 13;
+
+/// (name, weight). The weights give each group one share: spectrum, H1−H2, vibrato, voicing,
+/// onsets and noise.
+pub const TERMS: [(&str, f64); N_TERMS] = [
+ ("level 0-.5k", 0.2),
+ ("level .5-1k", 0.2),
+ ("level 1-2k", 0.2),
+ ("level 2-4k", 0.2),
+ ("level 4-8k", 0.2),
+ ("H1-H2", 1.0),
+ ("vibrato share", 1.0 / 3.0),
+ ("vibrato depth", 1.0 / 3.0),
+ ("vibrato rate", 1.0 / 3.0),
+ ("voiced share", 1.0),
+ ("onset, vowel-initial", 0.5),
+ ("onset, voiceless-initial", 0.5),
+ ("aperiodicity", 1.0),
+];
+
+/// fewest training songs a spread is taken over
+const MIN_SPREAD_SONGS: usize = 5;
+/// fewest songs a gap is averaged over
+const MIN_GAP_SONGS: usize = 3;
+/// a change must lower the training score by this much to be better
+pub const MARGIN: f64 = 0.01;
+/// no term's cost may rise by more than this, whatever the score does
+const TERM_SLACK: f64 = 0.25;
+/// guards: largest rise in note MCD (dB) and synth pitch error (cents), largest fall in envelope
+/// correlation
+const MCD_SLACK: f64 = 0.1;
+const PITCH_SLACK: f64 = 2.0;
+const CORR_SLACK: f64 = 0.01;
+
+/// Held out of tuning: every fifth song number, in both keys.
+pub fn held_out(id: &str) -> bool {
+ let digits: String = id.chars().filter(|c| c.is_ascii_digit()).collect();
+ digits.parse::<u32>().is_ok_and(|n| n % 5 == 0)
+}
+
+/// One song's inputs to the score.
+pub struct SongScore {
+ pub id: String,
+ /// per term (singer, synth); NaN where that side has no value in this song
+ pub pairs: [(f64, f64); N_TERMS],
+ pub notes: usize,
+ pub misaligned: usize,
+ pub dropped: u64,
+ /// mean note MCD (dB)
+ pub mcd: f64,
+ pub env_corr: f64,
+ /// the synth's median |cents| off the score
+ pub synth_pitch: f64,
+}
+
+fn mad_sd(xs: &[f64]) -> f64 {
+ let m = median(xs);
+ 1.4826 * median(&xs.iter().map(|x| (x - m).abs()).collect::<Vec<_>>())
+}
+
+/// 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] {
+ std::array::from_fn(|k| {
+ let h: Vec<f64> = train
+ .iter()
+ .map(|s| s.pairs[k].0)
+ .filter(|v| v.is_finite())
+ .collect();
+ let sd = mad_sd(&h);
+ if h.len() >= MIN_SPREAD_SONGS && sd > 0.0 {
+ sd
+ } else {
+ f64::NAN
+ }
+ })
+}
+
+fn r3(x: f64) -> Value {
+ if x.is_finite() {
+ json!((x * 1000.0).round() / 1000.0)
+ } else {
+ Value::Null
+ }
+}
+
+fn r4(x: f64) -> Value {
+ if x.is_finite() {
+ json!((x * 10000.0).round() / 10000.0)
+ } 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 {
+ 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
+ .iter()
+ .map(|s| s.pairs[k])
+ .filter(|(h, s)| h.is_finite() && s.is_finite())
+ .collect();
+ let gap = if pairs.len() >= MIN_GAP_SONGS {
+ mean(&pairs.iter().map(|(h, s)| (s - h).abs()).collect::<Vec<_>>())
+ } else {
+ f64::NAN
+ };
+ let z = gap / spread[k];
+ // f64::max would turn a missing z into a cost of 0
+ let excess = if z.is_finite() {
+ (z - 1.0).max(0.0)
+ } else {
+ f64::NAN
+ };
+ if excess.is_finite() {
+ cost += w * excess;
+ weight += w;
+ }
+ terms.push(json!({
+ "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),
+ }));
+ }
+ 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!({
+ "songs": songs.iter().map(|s| s.id.clone()).collect::<Vec<_>>(),
+ "score": r3(if weight > 0.0 { cost / weight } else { f64::NAN }),
+ "terms": terms,
+ "guards": {
+ "notes": total(&|s| s.notes as u64),
+ "notesMisaligned": total(&|s| s.misaligned as u64),
+ "droppedGestures": total(&|s| s.dropped),
+ "noteMcdDb": r3(avg(&|s| s.mcd)),
+ "envelopeCorr": r3(avg(&|s| s.env_corr)),
+ "synthPitchAbsCents": r3(avg(&|s| s.synth_pitch)),
+ },
+ })
+}
+
+#[derive(Debug, PartialEq)]
+pub enum Verdict {
+ Better,
+ Worse,
+ Same,
+}
+
+fn num(v: &Value) -> f64 {
+ v.as_f64().unwrap_or(f64::NAN)
+}
+
+/// The training score of `new` against `old` (both as written to `score.json`): the verdict and,
+/// when worse, why.
+pub fn verdict(old: &Value, new: &Value) -> Result<(Verdict, Vec<String>), String> {
+ let (o, n) = (&old["train"], &new["train"]);
+ if o["songs"] != n["songs"] || old["body"] != new["body"] {
+ return Err("the earlier score covers other songs or another body; score both runs with the same --songs and --body".into());
+ }
+ let (so, sn) = (num(&o["score"]), num(&n["score"]));
+ if !so.is_finite() || !sn.is_finite() {
+ return Err("one of the two runs has no training score".into());
+ }
+ let mut why = Vec::new();
+ let g = |k: &str| (num(&o["guards"][k]), num(&n["guards"][k]));
+ let (a, b) = g("notesMisaligned");
+ if b > a {
+ why.push(format!("more notes off time: {a} → {b}"));
+ }
+ let (a, b) = g("droppedGestures");
+ if b > a {
+ why.push(format!("more dropped gestures: {a} → {b}"));
+ }
+ let (a, b) = g("noteMcdDb");
+ if b > a + MCD_SLACK {
+ why.push(format!("note MCD up: {a} → {b} dB"));
+ }
+ let (a, b) = g("envelopeCorr");
+ if b < a - CORR_SLACK {
+ why.push(format!("envelope correlation down: {a} → {b}"));
+ }
+ let (a, b) = g("synthPitchAbsCents");
+ if b > a + PITCH_SLACK {
+ why.push(format!("pitch error up: {a} → {b} cents"));
+ }
+ let empty = vec![];
+ let (to, tn) = (
+ o["terms"].as_array().unwrap_or(&empty),
+ n["terms"].as_array().unwrap_or(&empty),
+ );
+ if to.len() != tn.len() || 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(),
+ );
+ }
+ for (a, b) in to.iter().zip(tn) {
+ let (ca, cb) = (num(&a["cost"]), num(&b["cost"]));
+ let name = b["name"].as_str().unwrap_or("?");
+ if ca.is_finite() && !cb.is_finite() {
+ why.push(format!("{name} has no value any more"));
+ } else if cb > ca + TERM_SLACK {
+ why.push(format!("{name} cost up: {ca} → {cb}"));
+ }
+ }
+ let d = sn - so;
+ Ok(if !why.is_empty() {
+ (Verdict::Worse, why)
+ } else if d <= -MARGIN {
+ (Verdict::Better, why)
+ } else if d >= MARGIN {
+ (Verdict::Worse, vec![format!("score up: {so} → {sn}")])
+ } else {
+ (Verdict::Same, why)
+ })
+}
+
+/// `score.json` and the report's score section for these songs, with the verdict against an
+/// earlier `score.json` if one is given.
+pub fn report(
+ body: &str,
+ songs: &[&SongScore],
+ against: Option<&str>,
+) -> Result<(Value, String, Option<String>), String> {
+ let (held, train): (Vec<&SongScore>, Vec<&SongScore>) =
+ songs.iter().copied().partition(|s| held_out(&s.id));
+ if train.is_empty() {
+ if against.is_some() {
+ return Err("--against: this run has no training song to score".into());
+ }
+ let md = "## Score\n\nNo score: the run has no training song to take the singer's spreads from.\n\n";
+ return Ok((json!({ "body": body, "train": null }), md.to_string(), None));
+ }
+ let spread = spreads(&train);
+ let mut out = json!({ "body": body, "train": score_set(&train, &spread) });
+ if !held.is_empty() {
+ out["heldout"] = score_set(&held, &spread);
+ }
+ let t = &out["train"];
+ let fmt = |v: &Value, d: usize| v.as_f64().map_or("—".to_string(), |x| format!("{x:.d$}"));
+ let mut md = format!(
+ "## Score\n\nTraining songs ({}): **{}**. Held out ({}): {}. Lower is better; 0 means \
+ every term is within the singer's own song-to-song spread (see docs/csd-comparison.md).\n\n\
+ | term | weight | singer | synth | mean gap | her spread | gap/spread | cost | held-out cost |\n\
+ |---|---|---|---|---|---|---|---|---|\n",
+ train.len(),
+ fmt(&t["score"], 3),
+ held.len(),
+ out.get("heldout")
+ .map_or("—".to_string(), |h| fmt(&h["score"], 3)),
+ );
+ for (k, term) in t["terms"].as_array().unwrap().iter().enumerate() {
+ let held_cost = out
+ .get("heldout")
+ .map_or("—".to_string(), |h| fmt(&h["terms"][k]["cost"], 2));
+ md += &format!(
+ "| {} | {} | {} | {} | {} | {} | {} | {} | {held_cost} |\n",
+ term["name"].as_str().unwrap_or("?"),
+ fmt(&term["weight"], 2),
+ fmt(&term["singer"], 3),
+ fmt(&term["synth"], 3),
+ fmt(&term["gap"], 3),
+ fmt(&term["spread"], 3),
+ fmt(&term["z"], 2),
+ fmt(&term["cost"], 2),
+ );
+ }
+ let g = &t["guards"];
+ md += &format!(
+ "\nGuards (training songs): {} of {} notes off time, {} dropped gestures, note MCD {} dB, \
+ envelope correlation {}, synth pitch error {} cents.\n\n",
+ g["notesMisaligned"],
+ g["notes"],
+ g["droppedGestures"],
+ fmt(&g["noteMcdDb"], 3),
+ fmt(&g["envelopeCorr"], 3),
+ fmt(&g["synthPitchAbsCents"], 2),
+ );
+ let mut line = None;
+ if let Some(path) = against {
+ let old: Value = serde_json::from_str(
+ &std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?,
+ )
+ .map_err(|e| format!("{path}: {e}"))?;
+ let (v, why) = verdict(&old, &out)?;
+ let word = match v {
+ Verdict::Better => "BETTER",
+ Verdict::Worse => "WORSE",
+ Verdict::Same => "NO CLEAR CHANGE",
+ };
+ let text = format!(
+ "Verdict against {path}: {word} (training score {} → {}){}",
+ fmt(&old["train"]["score"], 3),
+ fmt(&t["score"], 3),
+ if why.is_empty() {
+ String::new()
+ } else {
+ format!(": {}", why.join("; "))
+ }
+ );
+ md += &format!("{text}\n\n");
+ out["verdict"] = json!({ "against": path, "result": word, "reasons": why });
+ line = Some(text);
+ }
+ Ok((out, md, line))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn song(id: &str, singer: f64, synth: f64) -> SongScore {
+ SongScore {
+ id: id.into(),
+ pairs: [(singer, synth); N_TERMS],
+ notes: 10,
+ misaligned: 0,
+ dropped: 0,
+ mcd: 9.0,
+ env_corr: 0.8,
+ synth_pitch: 5.0,
+ }
+ }
+
+ #[test]
+ fn every_fifth_song_is_held_out_in_both_keys() {
+ assert!(held_out("en005a") && held_out("en005b") && held_out("en050a"));
+ assert!(!held_out("en001a") && !held_out("en049b") && !held_out("x"));
+ }
+
+ #[test]
+ fn a_gap_costs_its_excess_over_one_singer_spread() {
+ // eight training songs (en005 and en010 are held out); her values 0 1 2 3 5 6 7 8 have
+ // median 4 and MAD 2.5, a spread of 3.7065, so a gap of two spreads costs 1
+ let songs: Vec<SongScore> = (1..=10)
+ .map(|i| {
+ song(
+ &format!("en{i:03}a"),
+ (i - 1) as f64,
+ (i - 1) as f64 + 7.413,
+ )
+ })
+ .collect();
+ let refs: Vec<&SongScore> = songs.iter().collect();
+ let (out, _, _) = report("female", &refs, None).unwrap();
+ 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}");
+ assert!((num(&t["z"]) - 2.0).abs() < 1e-3, "{t}");
+ assert!((num(&out["train"]["score"]) - 1.0).abs() < 1e-3);
+ // two held-out songs are too few to average a gap over
+ assert!(out["heldout"]["score"].is_null());
+ // within one spread costs nothing
+ 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);
+ }
+
+ 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_verdict_wants_a_lower_score_and_every_guard_kept() {
+ let base = scored(8.0, |_| {});
+ assert_eq!(
+ verdict(&base, &scored(6.0, |_| {})).unwrap().0,
+ Verdict::Better
+ );
+ assert_eq!(
+ verdict(&base, &scored(8.0, |_| {})).unwrap().0,
+ Verdict::Same
+ );
+ assert_eq!(
+ verdict(&base, &scored(9.0, |_| {})).unwrap().0,
+ 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();
+ 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);
+ // one term much worse while the rest improve: worse
+ let mut one_worse = scored(6.0, |_| {});
+ one_worse["train"]["terms"][5]["cost"] = json!(99.0);
+ let (v, why) = verdict(&base, &one_worse).unwrap();
+ assert_eq!(v, Verdict::Worse);
+ assert!(why[0].contains("H1-H2"), "{why:?}");
+ // different songs are not comparable
+ let mut other = scored(6.0, |_| {});
+ other["train"]["songs"] = json!(["en001a"]);
+ assert!(verdict(&base, &other).is_err());
+ }
+}
diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rs
index 7237a9e..c81342d 100644
--- a/crates/chimera-cli/src/main.rs
+++ b/crates/chimera-cli/src/main.rs
@@ -26,6 +26,7 @@ usage: chimera <command> [args] [--float]
render vowels [male|female|child] [out]
diagnose [outdir]
compare csd [csd-dir] [outdir] [--songs a|b|all|en001a,…] [--body female] [--jobs n]
+ [--against earlier/score.json] (score.json: distance to the singer, and the verdict)
calibrate vowels [male|female|child|all] [--out file]
calibrate consonants [--out file]
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
index 3f3ee79..1ae73a6 100644
--- a/crates/chimera-cli/tests/cli.rs
+++ b/crates/chimera-cli/tests/cli.rs
@@ -155,6 +155,11 @@ fn calibrate_vowels_reproduces_the_committed_table() {
/// A tiny dataset in CSD's layout: two phrases (a gap between) and a melisma, with a stereo
/// 16-bit 44.1 kHz "singer" that is a pure tone at each note's pitch.
fn mini_csd(dir: &str, syllables: [&str; 4]) {
+ mini_song(dir, "x01a", syllables, 0.0);
+}
+
+/// One song of the tiny dataset; the singer's second harmonic has amplitude `h2` (re the first).
+fn mini_song(dir: &str, id: &str, syllables: [&str; 4], h2: f64) {
let notes = [
(0.3, 0.8, 69.0),
(0.8, 1.3, 69.0),
@@ -167,7 +172,7 @@ fn mini_csd(dir: &str, syllables: [&str; 4]) {
for ((a, b, m), s) in notes.iter().zip(syllables) {
csv += &format!("{a:.4},{b:.4},{m},{s}\r\n");
}
- std::fs::write(format!("{dir}/english/csv/x01a.csv"), csv).unwrap();
+ std::fs::write(format!("{dir}/english/csv/{id}.csv"), csv).unwrap();
let fs = 44100.0;
let n = (3.0 * fs) as usize;
let mut data = Vec::with_capacity(n * 4);
@@ -177,8 +182,8 @@ fn mini_csd(dir: &str, syllables: [&str; 4]) {
.iter()
.find(|(a, b, _)| t >= *a && t < *b)
.map_or(0.0, |(_, _, m)| {
- let hz = 440.0 * 2f64.powf((m - 69.0) / 12.0);
- 0.3 * (2.0 * std::f64::consts::PI * hz * t).sin()
+ let ph = 2.0 * std::f64::consts::PI * 440.0 * 2f64.powf((m - 69.0) / 12.0) * t;
+ 0.3 * (ph.sin() + h2 * (2.0 * ph).sin())
});
let s = ((v * 32767.0).round() as i16).to_le_bytes();
data.extend_from_slice(&s);
@@ -200,7 +205,7 @@ fn mini_csd(dir: &str, syllables: [&str; 4]) {
b.extend_from_slice(b"data");
b.extend_from_slice(&(data.len() as u32).to_le_bytes());
b.extend_from_slice(&data);
- std::fs::write(format!("{dir}/english/wav/x01a.wav"), b).unwrap();
+ std::fs::write(format!("{dir}/english/wav/{id}.wav"), b).unwrap();
}
#[test]
@@ -250,6 +255,77 @@ fn compare_csd_sings_the_annotation_on_the_recordings_timeline() {
);
}
+#[test]
+fn compare_csd_scores_training_and_held_out_songs_and_judges_a_rerun() {
+ // six songs whose singer differs in H1−H2, so that term has a spread; x05a is held out
+ let dir = tmp("csd-score");
+ let ids = ["x01a", "x02a", "x03a", "x04a", "x05a", "x06a"];
+ for (i, id) in ids.iter().enumerate() {
+ mini_song(
+ &dir,
+ id,
+ ["l_ii", "ii", "d_ou", "m_ai_n"],
+ 0.1 + 0.15 * i as f64,
+ );
+ }
+ let songs = ids.join(",");
+ let (first, second) = (tmp("csd-score-1"), tmp("csd-score-2"));
+ chimera(&[
+ "compare", "csd", &dir, &first, "--songs", &songs, "--jobs", "3",
+ ]);
+ let score: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(format!("{first}/score.json")).unwrap())
+ .unwrap();
+ let names = |v: &serde_json::Value| -> Vec<String> {
+ v.as_array()
+ .unwrap()
+ .iter()
+ .map(|s| s.as_str().unwrap().to_string())
+ .collect()
+ };
+ assert_eq!(
+ names(&score["train"]["songs"]),
+ ["x01a", "x02a", "x03a", "x04a", "x06a"]
+ );
+ assert_eq!(names(&score["heldout"]["songs"]), ["x05a"]);
+ let h1h2 = &score["train"]["terms"][5];
+ assert_eq!(h1h2["name"], "H1-H2");
+ assert!(h1h2["spread"].as_f64().unwrap() > 0.0, "{h1h2}");
+ assert!(score["train"]["score"].is_number(), "{score}");
+ assert_eq!(score["train"]["guards"]["notes"], 20);
+
+ // the engine is deterministic: the same build scored again is no change
+ let stdout = chimera(&[
+ "compare",
+ "csd",
+ &dir,
+ &second,
+ "--songs",
+ &songs,
+ "--jobs",
+ "3",
+ "--against",
+ &format!("{first}/score.json"),
+ ]);
+ assert!(stdout.contains("NO CLEAR CHANGE"), "{stdout}");
+ // a run over other songs can't be judged against it
+ let other = Command::new(env!("CARGO_BIN_EXE_chimera"))
+ .args([
+ "compare",
+ "csd",
+ &dir,
+ &tmp("csd-score-3"),
+ "--songs",
+ "x01a,x02a,x03a,x04a,x05a",
+ "--against",
+ &format!("{first}/score.json"),
+ ])
+ .output()
+ .unwrap();
+ assert!(!other.status.success());
+ assert!(String::from_utf8_lossy(&other.stderr).contains("other songs"));
+}
+
#[test]
fn compare_csd_refuses_an_unmapped_phoneme() {
let dir = tmp("csd-bad");
diff --git a/docs/csd-comparison.md b/docs/csd-comparison.md
index a729beb..2204810 100644
--- a/docs/csd-comparison.md
+++ b/docs/csd-comparison.md
@@ -24,14 +24,18 @@ tools/fetch-csd.sh # 1.85 GB to ~/datasets/csd; unpacks CSD/english
cargo run --release -p chimera-cli -- compare csd # the 50 `a` songs, female body, all cores (~2 min)
cargo run --release -p chimera-cli -- compare csd ~/datasets/csd/CSD out/csd --songs en001a,en002a
# --songs a | b | all | <ids> --body female|male|child --jobs n --float
+cargo run --release -p chimera-cli -- compare csd ~/datasets/csd/CSD out/csd-new --against out/csd/score.json
+# score this build and give the verdict against an earlier run's score
```
It writes the following to the output directory (`out/csd` by default):
- `<id>-synth.wav`: the synth's render, on the same timeline as `english/wav/<id>.wav`. You can
load both into a DAW, or make spectrograms of the pair with `bun tools/spectrogram.ts`.
-- `report.md`: medians over songs, spectral balance per vowel, and one line per song.
+- `report.md`: the score, medians over songs, spectral balance per vowel, and one line per song.
- `report.json`: every note's measures for the singer and the synth.
+- `score.json`: the score, its terms and guards, for the training and held-out songs (below), and
+ the verdict when run with `--against`.
## Method
@@ -62,7 +66,7 @@ measurement window would hold the wrong sound. The report gives the count.
| aperiodicity | YIN's aperiodicity: noise and roughness in the voice |
| H1−H2 (dB) | first minus second harmonic, the standard voice-quality measure: high is breathy or lax, low is pressed. Measured in each voiced frame at that frame's own f0, then the median is taken |
| voiced share | share of steady frames the synth actually voices; a frame is voiced when YIN finds a period and it is within 35 dB of the signal's loud level |
-| voice onset (s) | first voiced frame of a phrase-initial note, relative to the note start; vowel-initial and consonant-initial phrases are reported separately |
+| voice onset (s) | first voiced frame of a phrase-initial note, relative to the note start, by what the phrase opens on: a vowel, a voiceless consonant (the voicing is the vowel's) or a voiced one (the voicing is the consonant's) |
| band levels, synth − singer (dB) | 0–0.5, 0.5–1, 1–2, 2–4 and 4–8 kHz, each relative to the 0–8 kHz total: spectral tilt and vowel colour, per vowel |
| note MCD (dB) | mel-cepstral distance between the note's averaged log-mel spectra (40 bands, 13 coefficients); on the usual MCD scale, but note-level, not frame-aligned |
| envelope lag and correlation | the shift (within ±0.3 s) that best lines up the two level envelopes: overall timing, and how much the loudness shape matches |
@@ -78,38 +82,95 @@ measurement window would hold the wrong sound. The report gives the count.
chain.
- **One singer.** Treat the numbers as directions to tune in, not as targets for every voice.
-## Baseline (2026-11-05, the 50 `a` songs, female body)
-
-7,032 of 7,220 notes are compared. The other 188 were too short for the planner to place on time:
-up to 25 in a song (en028a), mostly in fast passages.
-
-| measure | singer | synth |
-|---|---|---|
-| pitch error vs score (median \|cents\|) | 15.3 | 5.0 |
-| long notes with vibrato | 65 % | 100 % |
-| vibrato depth (peak cents) / rate (Hz) | 39 / 6.0 | 35 / 5.5 |
-| H1−H2 (dB) | +3.8 | −1.7 |
-| H1−H2 on notes ≤ C4 / notes ≥ G4 (dB) | +4.1 / 0.0 | −5.8 / +8.0 |
-| voiced share of steady frames | 0.94 | 0.88 (0.64 in en041a) |
-| voice onset, consonant-initial phrases (s) | +0.01 | −0.06 |
-
-- **Spectral balance.** Over all vowels, synth minus singer is −3.2, 0.0, +1.4, +4.5 and +8.0 dB
- in the five bands.
-- **Distance and timing.** Note MCD is 9.2 dB. The envelope lag is −0.02 s (between −0.06 and
- +0.04 s) with correlation 0.79.
+## The score
+
+`score.json` folds the measures into one number: how far the synth is from the singer, in units of
+her own variation. It is what an automated tuning loop climbs (lower is better), so it is built to
+be hard to improve without sounding closer to her.
+
+- **Terms.** Each term is a song-level value both voices have: her median H1−H2 in a song against
+ the synth's in that song, the two voiced shares, and so on. There are 13 terms: the five band
+ levels, H1−H2, vibrato share, depth and rate, voiced share, voice onset of vowel-initial phrases
+ and of phrases that open on a voiceless consonant, and aperiodicity.
+- **Gap.** A term's gap is the mean over songs of |synth − singer|. It is a mean rather than a
+ median so that every song's change counts, and one song gone badly wrong shows.
+- **Unit.** The gap is divided by her spread on that term over the training songs (median absolute
+ deviation, scaled to a standard deviation). The spread is a property of the singer, so a change
+ to the synth can't move it.
+- **Cost.** A gap within one spread is about as close as two of her songs are to each other, so it
+ costs nothing. Beyond that, the excess is the term's cost. Nothing is gained by matching her
+ medians more closely than her own variation, which keeps a tuning loop from overfitting one
+ singer.
+- **Score.** The score is the weighted mean of the costs. Each of six groups gets one share:
+ spectrum (the five bands), H1−H2, vibrato (its three terms), voicing, onsets (its two terms) and
+ noise (aperiodicity). 0 means every term is within her own variation.
+
+**Held-out songs.** Every fifth song (en005, en010, …, en050, in both keys) is held out. The
+spreads and the verdict use the other 40 songs only. The held-out songs are scored with the same
+spreads, to check that a change carries over to songs it wasn't tuned on.
+
+**Not scored.** Voice onsets of phrases that open on a voiced consonant are reported but not
+scored. CSD's note starts mark the start of the syllable, while `plan_song` sings onset consonants
+before the beat so that the vowel lands on it. Measured against CSD, those onsets mix that
+convention with real timing errors. Pitch is not scored either: the synth sings the score, and her
+deviations 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:
+
+- **Better:** the score falls by at least 0.01, no term's cost rises by more than 0.25, and every
+ guard holds.
+- **Guards:**
+ - no more notes off time (so a change can't drop hard notes from the statistics)
+ - 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
+- **Worse:** any guard or term breaks, or the score rises by 0.01 or more.
+- **No clear change:** anything else.
+
+## Baseline (2026-11-07, the 50 `a` songs, female body)
+
+All 7,220 notes are compared: the planner now places every vowel within 30 ms of its annotated
+start (on 2026-11-05, 188 notes were too short for their consonants and ran late).
+
+**Score: 1.433 on the 40 training songs, 1.590 on the 10 held-out songs.** The costs, largest
+first:
+
+| term | singer | synth | cost |
+|---|---|---|---|
+| level 4–8 kHz (dB re total) | −24.8 | −17.3 | 5.38 |
+| aperiodicity | 0.005 | 0.010 | 2.88 |
+| H1−H2 (dB) | +3.2 | −0.8 | 2.08 |
+| level 2–4 kHz | −18.4 | −14.0 | 1.43 |
+| level 0–0.5 kHz | −4.0 | −7.4 | 1.39 |
+| onset, vowel-initial (s) | +0.005 | −0.015 | 1.39 |
+| onset, voiceless-initial (s) | +0.018 | −0.024 | 1.11 |
+| vibrato rate (Hz) | 6.1 | 5.5 | 0.67 |
+| vibrato share | 0.64 | 1.00 | 0.62 |
+| level 0.5–1 kHz | −6.7 | −6.8 | 0.28 |
+| voiced share | 0.93 | 0.88 | 0.26 |
+| vibrato depth (peak cents) | 39 | 35 | 0.01 |
+| level 1–2 kHz | −15.1 | −13.4 | 0 |
+
+Singer and synth values are medians over the training songs. Note MCD is 9.24 dB and the envelope
+correlation 0.80.
What this points at:
-1. **Too much energy above 2 kHz**, about +8 dB at 4–8 kHz, for every vowel.
-2. **The fundamental is weak on low notes and too strong on high ones.** The singer's H1−H2 falls
- only about 4 dB from her low notes to her high ones. The synth's rises by 14 dB.
-3. **Consonants come too early.** For consonant-initial phrases the singer's voicing starts at
- the note's annotated start, but the synth sings its onset consonants about 60 ms before it.
- Either CSD annotates the syllable start rather than the vowel, or this singer puts consonants
- on the beat. Either way it is a timing difference to check by ear.
-4. **Vibrato is too uniform.** The synth puts 35-cent vibrato on every long note. The singer uses
- it on about two thirds of them, a little wider and faster.
-5. **Voicing gaps in the steady part of notes.** These are worst in en041a, en018a and en043a,
- which are worth listening to first.
-6. **Short notes don't fit.** When a note is too short for its consonants, the planner runs late,
- about 2.6 % of notes here. Fast lyrics will drift off the beat.
+1. **The spectrum tilts too little.** The synth has about 7.5 dB too much at 4–8 kHz and 4.4 dB too
+ much at 2–4 kHz, and 3.4 dB too little below 500 Hz, for every vowel.
+2. **The fundamental doesn't track pitch the way hers does.** H1−H2 on notes ≤ C4 is −5.8 dB
+ (singer +4.0), and on notes ≥ G4 it is +8.2 dB (singer +0.1). Her H1−H2 falls about 4 dB from
+ her low notes to her high ones; the synth's rises by 14 dB. Points 1 and 2 together sound like
+ a source that is too pressed on most notes.
+3. **The synth is less periodic than she is.** Its aperiodicity is about twice hers, which points
+ at jitter, shimmer or noise in the source.
+4. **Voicing starts early at phrase starts.** It starts 20 ms early before a vowel. Before a
+ voiceless consonant it starts about 40 ms early, where both voices should only start voicing at
+ the vowel. Before /s/, /f/ and /h/ the synth voices 100–130 ms before the note, so the voicing
+ runs into the fricative or comes before it.
+5. **Vibrato is too uniform.** The synth puts 35-cent vibrato on every long note. She uses it on
+ about two thirds of them, a little faster.
+6. **Voicing gaps in the steady part of notes.** These are worst in en018a, en041a and en043a
+ (0.65–0.70 voiced).