fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Judge: every sign of doubt about a staff's bar as read, taken together. `doubt.rs` acts on
//! single signs that were each measured to catch a wrong bar for every two right ones it costs
//! at most; the rest are too weak alone. Here they are all counted for a bar (`features`), with
//! cheap ones about how the bar was read and where its notes stand, and printed with
//! `FMV_FEATS` set (`trace`), so that a small model can be fitted to the measured right and
//! wrong bars of a set of scores (`tools/measure/judge`).

use crate::columns::{column_x, Mark};
use crate::doubt;
use crate::frac::Q;
use crate::staff::{Ev, Rest};

/// What a feature is called, in the order of `features`.
pub const NAMES: [&str; N] = [
    // the doubts found and not acted on
    "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",
    // ink: what is printed that nothing written uses
    "d_ink_stem_left",
    "d_ink_stem_bare",
    "d_ink_beam",
    "d_ink_flag",
    // what the bar holds
    "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",
    // where it is
    "staves",
    "lower",
    "upper",
    "beside_unread",
    "before_unread",
    "after_unread",
    "bar_first",
    "bar_last",
    "short_ok",
    // how it was read
    "rescued",
    "retimed",
    "retimed_by_columns",
    // its notes against the other staves' columns
    "col_same",
    "col_other",
    "col_alone",
    "col_margin",
    "col_order",
    "own_other",
    // its spacing: further apart in time, further apart on the page
    "space_inverted",
    "space_worst",
    "space_squeezed",
    "own_inverted",
    "end_tight",
    "width",
];

pub const N: usize = 73;

/// The doubts of `doubt.rs` in the order of the first features.
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,
];

/// A reading's rhythm in short: what each voice's notes and rests take, in order. None for a
/// staff's bar not read.
pub type Stamp = Option<Vec<Vec<(Q, u8)>>>;

/// The rhythm of each staff's bar of a system as read so far (`all[bar][staff]`).
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()
}

/// A staff's bar and what is about it.
pub struct Bar<'a> {
    /// The staff's notes and rests as found.
    pub evs: &'a [Ev],
    /// The doubts of the bar told with its other staves read (`doubt::of_bar`).
    pub of_bar: &'a [&'static str],
    /// Every staff's reading of the bar, this staff's among them.
    pub read: &'a [Result<Vec<Vec<Ev>>, String>],
    /// Which staff of the system.
    pub staff: usize,
    /// The staves' names (`P.1`, `P.2`: one part's staves share what is before the dot).
    pub names: &'a [String],
    pub sp: f64,
    /// The bar's length in quarters.
    pub len: Q,
    /// The bar's left and right edges.
    pub edges: (f64, f64),
    /// Which bar of the system, of how many.
    pub at: (usize, usize),
    /// The bar may be shorter than its time (a first or last bar).
    pub may_be_short: bool,
    /// The staff's bar before, and the one after, was not read.
    pub unread_about: (bool, bool),
    /// The staff's rhythm as the first pass read it, and as it stood before the columns timed
    /// it again.
    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
}

/// The gaps between the columns of some notes, in order of time: (time between, space between).
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()
}

/// How many pairs of gaps have the longer in time the narrower on the page by a quarter or
/// more, and the worst such pair's ratio (as a logarithm, 0 for none).
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)
}

/// The features of a staff's bar as read (`voices`), in the order of `NAMES`.
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))));

    // what the bar holds
    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)));
    // (two voices' notes at one start a second or less apart: one is set beside the other)
    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);

    // where it is
    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));

    // how it was read
    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));

    // its notes against the other staves' columns
    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);

    // its spacing
    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);
    // (the last note's room before the barline against the rest of the bar's notes')
    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
}

/// Whether the features are asked for (`FMV_FEATS` set).
pub fn traced() -> bool {
    std::env::var("FMV_FEATS").is_ok()
}

/// A staff's bar's features on a line: `FEAT`, the bar's number, the staff, `name=value` for
/// each feature that is not 0.
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() {
        // the upper staff: four quarters in their columns. The lower: a quarter, a quarter of
        // blank time, and a half note read as starting on the third quarter though it stands
        // in the second quarter's column
        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),
            // (not read by the first pass; as it stood before the columns)
            ("rescued", 1.0),
            ("retimed", 0.0),
            ("retimed_by_columns", 0.0),
            // (the first note in its column; the second in a column of another start)
            ("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() {
        // a half note given two spaces and a quarter after it given ten
        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);
    }
}