use crate::columns::{column_x, Mark};
use crate::doubt;
use crate::frac::Q;
use crate::staff::{Ev, Rest};
pub const NAMES: [&str; N] = [
"d_dot_either",
"d_pad_unconfirmed",
"d_pad_beside",
"d_pad_any",
"d_pad_inner",
"d_small_timed",
"d_small_grace",
"d_pad_twice",
"d_small_apart",
"d_shared_head",
"d_number_loose",
"d_voices_many",
"d_tie_in_uncarried",
"d_tie_failed",
"d_tie_no_start",
"d_tie_dropped",
"d_tie_ends",
"d_tie_from_unread",
"d_tie_partial",
"d_ink_stem_left",
"d_ink_stem_bare",
"d_ink_beam",
"d_ink_flag",
"voices",
"notes",
"heads_most",
"blank_runs",
"blank_share",
"blank_first",
"blank_last",
"rests",
"graces",
"tuplet_notes",
"tuplets_odd",
"numbers_loose",
"shortest",
"lengths",
"dotted",
"other_staff",
"dots_shared",
"dots_partial",
"tied",
"landed",
"signs",
"beamed",
"unbeamed_short",
"stems_mixed",
"voices_close",
"small",
"staves",
"lower",
"upper",
"beside_unread",
"before_unread",
"after_unread",
"bar_first",
"bar_last",
"short_ok",
"rescued",
"retimed",
"retimed_by_columns",
"col_same",
"col_other",
"col_alone",
"col_margin",
"col_order",
"own_other",
"space_inverted",
"space_worst",
"space_squeezed",
"own_inverted",
"end_tight",
"width",
];
pub const N: usize = 73;
const DOUBTS: [&str; 23] = [
doubt::DOT_EITHER,
doubt::PAD_UNCONFIRMED,
doubt::PAD_BESIDE,
doubt::PAD_ANY,
doubt::PAD_INNER,
doubt::SMALL_TIMED,
doubt::SMALL_GRACE,
doubt::PAD_TWICE,
doubt::SMALL_APART,
doubt::SHARED_HEAD,
doubt::NUMBER_LOOSE,
doubt::VOICES_MANY,
doubt::TIE_IN_UNCARRIED,
doubt::TIE_FAILED,
doubt::TIE_NO_START,
doubt::TIE_DROPPED,
doubt::TIE_ENDS,
doubt::TIE_FROM_UNREAD,
doubt::TIE_PARTIAL,
doubt::INK_STEM_LEFT,
doubt::INK_STEM_BARE,
doubt::INK_BEAM,
doubt::INK_FLAG,
];
pub type Stamp = Option<Vec<Vec<(Q, u8)>>>;
pub fn stamps(all: &[crate::ties::BarVoices]) -> Vec<Vec<Stamp>> {
all.iter()
.map(|bar| {
bar.iter()
.map(|v| v.as_ref().ok().map(|v| stamp(v)))
.collect()
})
.collect()
}
fn stamp(voices: &[Vec<Ev>]) -> Vec<Vec<(Q, u8)>> {
let kind = |e: &Ev| match e.rest {
Rest::None => 0,
Rest::Printed(_) => 1,
Rest::Bar => 2,
Rest::Blank => 3,
};
voices
.iter()
.map(|v| v.iter().map(|e| (e.takes(), kind(e))).collect())
.collect()
}
pub struct Bar<'a> {
pub evs: &'a [Ev],
pub of_bar: &'a [&'static str],
pub read: &'a [Result<Vec<Vec<Ev>>, String>],
pub staff: usize,
pub names: &'a [String],
pub sp: f64,
pub len: Q,
pub edges: (f64, f64),
pub at: (usize, usize),
pub may_be_short: bool,
pub unread_about: (bool, bool),
pub first: &'a Stamp,
pub mid: &'a Stamp,
}
fn flag(b: bool) -> f32 {
f32::from(u8::from(b))
}
fn marks_of(voices: &[Vec<Ev>]) -> Vec<(Mark, usize)> {
let mut out = Vec::new();
for (vi, v) in voices.iter().enumerate() {
let mut t = Q::ZERO;
for e in v {
if e.is_note() && e.grace.is_none() && !e.heads.is_empty() {
let m = Mark {
x: column_x(e),
at: t,
play: 0.0,
wide: false,
sign: false,
};
out.push((m, vi));
}
t += e.takes();
}
}
out
}
fn gaps(marks: &[Mark], end: Option<(Q, f64)>) -> Vec<(f64, f64)> {
let mut cols = crate::columns::columns(marks);
if let Some((at, x)) = end {
cols.push(Mark {
x,
at,
play: 0.0,
wide: false,
sign: false,
});
}
cols.windows(2)
.map(|w| ((w[1].at - w[0].at).to_f64(), w[1].x - w[0].x))
.collect()
}
fn inverted(gaps: &[(f64, f64)], sp: f64) -> (f32, f32) {
let (mut n, mut worst) = (0.0, 0.0f64);
for a in gaps {
for b in gaps {
if a.0 > b.0 * 1.01 && a.1 < b.1 * 0.75 && b.1 > 0.5 * sp {
n += 1.0;
worst = worst.max((b.1 / a.1.max(0.2 * sp)).ln());
}
}
}
(n, worst.min(3.0) as f32)
}
pub fn features(bar: &Bar, voices: &[Vec<Ev>]) -> [f32; N] {
let sp = bar.sp;
let mut f = Vec::with_capacity(N);
let has = |d: &str| {
bar.of_bar.contains(&d)
|| (bar.evs.iter())
.chain(voices.iter().flatten())
.any(|e| e.doubts.contains(&d))
};
f.extend(DOUBTS.iter().map(|d| flag(has(d))));
let all = || voices.iter().flatten();
let notes = || all().filter(|e| e.is_note() && e.grace.is_none());
let noted = |v: &&Vec<Ev>| v.iter().any(|e| e.is_note());
let blank = |e: &Ev| e.rest == Rest::Blank;
f.push(voices.iter().filter(noted).count() as f32);
f.push(notes().count() as f32);
f.push(notes().map(|e| e.places.len()).max().unwrap_or(0) as f32);
let runs: usize = voices
.iter()
.map(|v| {
(0..v.len())
.filter(|&k| blank(&v[k]) && (k == 0 || !blank(&v[k - 1])))
.count()
})
.sum();
f.push(runs as f32);
let blanks: Q = all().filter(|e| blank(e)).map(|e| e.dur).sum();
f.push((blanks / bar.len).to_f64().min(4.0) as f32);
f.push(flag(
voices
.iter()
.any(|v| v.first().is_some_and(blank) && noted(&v)),
));
f.push(flag(
voices
.iter()
.any(|v| v.last().is_some_and(blank) && noted(&v)),
));
f.push(all().filter(|e| matches!(e.rest, Rest::Printed(_))).count() as f32);
f.push(all().filter(|e| e.grace.is_some()).count() as f32);
f.push(notes().filter(|e| !e.tuplets.is_empty()).count() as f32);
let odd = |e: &&Ev| e.tuplets.len() > 1 || e.tuplets.iter().any(|t| (t.0, t.1) != (3, 2));
f.push(flag(all().any(|e| odd(&e))));
f.push(bar.evs.iter().map(|e| e.loose.len()).sum::<usize>() as f32);
let shortest = notes().map(|e| e.dur.to_f64()).fold(f64::MAX, f64::min);
f.push(if shortest == f64::MAX {
0.0
} else {
-shortest.max(1.0 / 64.0).log2() as f32
});
let mut lengths: Vec<Q> = notes().map(|e| e.written()).collect();
lengths.sort_by(|a, b| a.to_f64().total_cmp(&b.to_f64()));
lengths.dedup();
f.push(lengths.len() as f32);
f.push(notes().filter(|e| !e.written().is_power_of_two()).count() as f32);
f.push(notes().filter(|e| e.on_staff.is_some()).count() as f32);
f.push(flag(all().any(|e| e.dots_shared > 0)));
f.push(flag(all().any(|e| e.dots_partial)));
f.push(notes().filter(|e| !e.tied.is_empty()).count() as f32);
f.push(notes().filter(|e| !e.landed.is_empty()).count() as f32);
f.push(notes().map(|e| e.accs.len()).sum::<usize>() as f32);
f.push(notes().filter(|e| !e.beam_polys.is_empty()).count() as f32);
let short = |e: &&Ev| e.written() < Q::ONE && e.beam_polys.is_empty();
f.push(notes().filter(short).count() as f32);
let mixed = |v: &Vec<Ev>| {
let ups = |up: bool| {
v.iter()
.any(|e| e.is_note() && e.grace.is_none() && e.up == Some(up))
};
ups(true) && ups(false)
};
f.push(flag(voices.iter().any(mixed)));
let mine = marks_of(voices);
let mut heads: Vec<(Q, usize, f64)> = Vec::new();
for (vi, v) in voices.iter().enumerate() {
let mut t = Q::ZERO;
for e in v {
if e.is_note() && e.grace.is_none() {
heads.extend(e.heads.iter().map(|h| (t, vi, h.y)));
}
t += e.takes();
}
}
let close = (0..heads.len()).any(|a| {
(0..a).any(|b| {
heads[a].0 == heads[b].0
&& heads[a].1 != heads[b].1
&& (heads[a].2 - heads[b].2).abs() < 0.6 * sp
})
});
f.push(flag(close));
let small = |e: &Ev| !e.heads.is_empty() && e.heads.iter().all(|h| h.size < 0.8 * 4.0 * sp);
f.push(bar.evs.iter().filter(|e| small(e)).count() as f32);
let part = |n: &str| n.split('.').next().unwrap_or(n).to_string();
let i = bar.staff;
let same_part = |j: usize| j < bar.names.len() && part(&bar.names[j]) == part(&bar.names[i]);
f.push(bar.read.len() as f32);
f.push(flag(i > 0 && same_part(i - 1)));
f.push(flag(same_part(i + 1)));
let beside = (0..bar.read.len()).filter(|&j| j != i && bar.read[j].is_err());
f.push(beside.count() as f32);
f.push(flag(bar.unread_about.0));
f.push(flag(bar.unread_about.1));
f.push(flag(bar.at.0 == 0));
f.push(flag(bar.at.0 + 1 == bar.at.1));
f.push(flag(bar.may_be_short));
let now = Some(stamp(voices));
f.push(flag(bar.first.is_none()));
f.push(flag(bar.first.is_some() && *bar.first != now));
f.push(flag(bar.mid.is_some() && *bar.mid != now));
let others: Vec<Mark> = (0..bar.read.len())
.filter(|&j| j != i)
.filter_map(|j| bar.read[j].as_ref().ok())
.flat_map(|vs| marks_of(vs).into_iter().map(|m| m.0))
.collect();
let (mut same, mut other, mut alone, mut order) = (0.0, 0.0, 0.0, 0.0);
let mut margin = 5.0f64;
for (m, _) in &mine {
let near = |o: &&Mark| (o.x - m.x).abs() <= 0.7 * sp;
same += flag(others.iter().filter(near).any(|o| o.at == m.at));
other += flag(others.iter().filter(near).any(|o| o.at != m.at));
alone += flag(!others.iter().any(|o| o.at == m.at));
for o in others.iter().filter(|o| o.at != m.at) {
margin = margin.min((o.x - m.x).abs() / sp);
let before = (o.at < m.at) == (o.x < m.x);
order += flag(!before && (o.x - m.x).abs() > 0.5 * sp);
}
}
f.extend([same, other, alone, margin as f32, order]);
let own = (0..mine.len())
.flat_map(|a| (0..a).map(move |b| (a, b)))
.filter(|&(a, b)| {
let (a, b) = (&mine[a], &mine[b]);
a.1 != b.1 && a.0.at != b.0.at && (a.0.x - b.0.x).abs() <= 0.7 * sp
});
f.push(own.count() as f32);
let my: Vec<Mark> = mine.iter().map(|m| m.0).collect();
let every: Vec<Mark> = my.iter().chain(&others).copied().collect();
let all_gaps = gaps(&every, None);
let (n, worst) = inverted(&all_gaps, sp);
f.extend([n, worst]);
f.push(all_gaps.iter().filter(|g| g.1 < 0.9 * sp).count() as f32);
f.push(inverted(&gaps(&my, None), sp).0);
let with_end = gaps(&every, Some((bar.len, bar.edges.1)));
let tight = match with_end.split_last() {
Some((last, rest)) => rest
.iter()
.any(|g| last.0 > g.0 * 1.01 && last.1 < g.1 * 0.6),
None => false,
};
f.push(flag(tight));
f.push(((bar.edges.1 - bar.edges.0) / sp / bar.len.to_f64().max(0.25)).min(60.0) as f32);
let mut out = [0.0; N];
out.copy_from_slice(&f);
out
}
pub fn traced() -> bool {
std::env::var("FMV_FEATS").is_ok()
}
pub fn trace(number: i64, staff: &str, f: &[f32; N]) {
let said: Vec<String> = (0..N)
.filter(|&k| f[k] != 0.0)
.map(|k| format!("{}={}", NAMES[k], f[k]))
.collect();
eprintln!("FEAT\t{number}\t{staff}\t{}", said.join(" "));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::page::Glyph;
const SP: f64 = 10.0;
fn note(x: f64, dur: Q) -> Ev {
let head = Glyph {
code: 0xE0A4,
x0: x,
x1: x + 12.0,
y: 20.0,
size: 40.0,
};
let mut e = Ev::new(vec![head], None, None);
e.dur = dur;
e.places = vec![4];
e.place_of = vec![4];
e
}
fn blank(x: f64, dur: Q) -> Ev {
let mut e = Ev::spacer(dur, x);
e.rest = Rest::Blank;
e
}
fn value(f: &[f32; N], name: &str) -> f32 {
f[NAMES.iter().position(|n| *n == name).unwrap()]
}
#[test]
fn a_bar_s_features_say_what_it_holds_and_how_its_notes_stand_by_the_other_staff_s() {
let q = Q::ONE;
let upper = vec![vec![
note(100.0, q),
note(200.0, q),
note(300.0, q),
note(400.0, q),
]];
let lower = vec![vec![
note(100.0, q),
blank(150.0, q),
note(200.0, Q::int(2)),
]];
let evs: Vec<Ev> = lower[0].iter().filter(|e| e.is_note()).cloned().collect();
let read = [Ok(upper), Ok(lower.clone())];
let names = ["P.1".to_string(), "P.2".to_string()];
let first = None;
let mid = Some(stamp(&lower));
let bar = Bar {
evs: &evs,
of_bar: &[doubt::PAD_ANY, doubt::PAD_INNER],
read: &read,
staff: 1,
names: &names,
sp: SP,
len: Q::int(4),
edges: (80.0, 500.0),
at: (0, 3),
may_be_short: false,
unread_about: (false, true),
first: &first,
mid: &mid,
};
let f = features(&bar, &lower);
for (name, v) in [
("d_pad_any", 1.0),
("d_pad_inner", 1.0),
("d_shared_head", 0.0),
("voices", 1.0),
("notes", 2.0),
("blank_runs", 1.0),
("blank_share", 0.25),
("lengths", 2.0),
("staves", 2.0),
("lower", 1.0),
("upper", 0.0),
("after_unread", 1.0),
("bar_first", 1.0),
("bar_last", 0.0),
("rescued", 1.0),
("retimed", 0.0),
("retimed_by_columns", 0.0),
("col_same", 1.0),
("col_other", 1.0),
("col_margin", 0.0),
("col_order", 0.0),
] {
assert_eq!(value(&f, name), v, "{name}");
}
}
#[test]
fn spacing_is_inverted_where_the_longer_gap_in_time_is_the_narrower_on_the_page() {
let gaps = [(2.0, 20.0), (1.0, 100.0)];
let (n, worst) = inverted(&gaps, SP);
assert_eq!(n, 1.0);
assert!(worst > 1.5);
assert_eq!(inverted(&[(2.0, 100.0), (1.0, 60.0)], SP).0, 0.0);
}
#[test]
fn a_reading_timed_again_has_another_stamp() {
let a = vec![vec![note(100.0, Q::ONE), note(200.0, Q::ONE)]];
let b = vec![vec![
note(100.0, Q::ONE),
blank(150.0, Q::ONE),
note(200.0, Q::ONE),
]];
assert_eq!(stamp(&a), stamp(&a.clone()));
assert_ne!(stamp(&a), stamp(&b));
assert_eq!(stamps(&[vec![Ok(a), Err(String::new())]])[0][1], None);
}
}