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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! A bar the rules leave unread, solved from where its notes stand. An engraver sets what
//! sounds together in one column through all the staves of a system and what starts later
//! further right, and a program that hides a voice's rests still sets its notes in their
//! columns. So each note and rest of an unread staff's bar has a start to be found, and only a
//! few starts it may have by what is printed:
//!
//! - the start of the column of a read staff it stands in (then no other);
//! - the bar's start, if it stands where the read staves' bar starts;
//! - the start of a note of the unread staves it stands in a column with;
//! - the end of a note or rest left of it on its part's staves (it follows it: in its voice, or
//!   as a line that passes from one staff to the other).
//!
//! Every choice of starts is tried, under what the page says of any reading: nothing runs past
//! the bar's end; what stands further right starts no earlier, and later if it stands clear;
//! what starts together stands together; a beam's notes follow one another; two notes of one
//! staff stemmed the same way do not start together (they would be one chord); each staff's
//! notes go into four voices at most, and the time between a voice's notes is of a length
//! rests can be written in. A bar is solved only where one choice of starts is left. With two
//! or none it stays unread: a second reading is a guess, and none means something printed was
//! not read as it is (a tuplet not seen, a length mistaken).

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

/// A note stands in a column of another staff when no further from it than this (staff
/// spaces), as `columns::retimed` has it.
const IN_COLUMN: f64 = 0.7;
/// Columns of two staves at one start stand no further apart than this.
const APART: f64 = 1.8;
/// Two voices' notes of one staff at one start: the second no further right than this,
const BESIDE: f64 = 2.2;
/// or this past a dotted or flagged note,
const BESIDE_PAST: f64 = 3.3;
/// and this much more for its own accidental.
const ACCIDENTAL: f64 = 1.3;
/// What starts later stands at least this far right.
const ON: f64 = 0.3;
/// A staff's voices at most.
const VOICES: usize = 4;
/// Choices tried before the bar is given up.
const BUDGET: usize = 20_000;

/// Each staff's voices, for those solved (the staves that were read have none here).
pub type Solved = Vec<Option<Vec<Vec<Ev>>>>;

/// Why a bar was not solved.
pub const UNSURE: &str = "a length or a note of it is not sure as seen";
pub const NO_NOTES: &str = "no notes";
pub const NO_COLUMNS: &str = "no read staff's columns to stand by";
pub const TOO_MANY: &str = "too many choices to try";
pub const NO_START: &str = "a note with no start it may have";
pub const TWO_READINGS: &str = "more than one reading";
pub const NO_VOICES: &str = "starts that make no voices that can be written";
pub const OFF_COLUMNS: &str = "starts the columns contradict";
pub const UNEVEN: &str = "starts the bar's spacing contradicts";

/// One staff of the bar to solve.
pub struct StaffIn<'a> {
    /// Its part: a line passes only between staves of one part.
    pub part: &'a str,
    /// What was seen in its bar.
    pub events: &'a [Ev],
    /// Its voices, if it was read.
    pub read: Option<&'a [Vec<Ev>]>,
}

/// A note or rest of an unread staff whose start is sought.
struct Item {
    staff: usize,
    /// Its index among its staff's events.
    k: usize,
    x: f64,
    dur: Q,
    note: bool,
    up: Option<bool>,
    wide: bool,
    sign: bool,
    play: f64,
}

fn item(staff: usize, k: usize, e: &Ev) -> Item {
    let lefts = || e.heads.iter().map(|h| h.x0);
    let play = match (e.is_note(), e.stem) {
        (true, None) => lefts().fold(f64::MIN, f64::max) - lefts().fold(f64::MAX, f64::min),
        _ => 0.0,
    };
    let written = e.written();
    Item {
        staff,
        k,
        x: if e.is_note() {
            columns::column_x(e)
        } else {
            e.x
        },
        dur: e.takes(),
        note: e.is_note(),
        up: if e.is_note() { e.up } else { None },
        wide: (written < Q::ONE && e.beam_polys.is_empty()) || !written.is_power_of_two(),
        sign: !e.accs.is_empty(),
        play: play.max(0.0),
    }
}

/// Whether what the reader saw of a staff's bar is sure enough to solve from: every length as
/// printed (no dot that may be another note's, no whole rest that may be the bar's).
fn sure(events: &[Ev], sp: f64) -> bool {
    // a grace note in a note's column is the note's or its own, which is not told
    let in_column = |g: &Ev| {
        (events.iter()).any(|e| {
            e.grace.is_none() && e.rest != Rest::Blank && (e.x - g.x).abs() <= IN_COLUMN * sp
        })
    };
    let with_small = |e: &Ev| {
        e.grace.is_none()
            && events
                .iter()
                .any(|g| g.grace.is_some() && !g.beam_polys.is_disjoint(&e.beam_polys))
    };
    !events.iter().any(|e| {
        e.rest == Rest::Bar
            || e.dots_shared > 0
            || e.dots_partial
            || e.on_staff.is_some()
            || e.tremolo.is_some()
            || !e.loose.is_empty()
            || with_small(e)
            || (e.grace.is_some() && in_column(e))
            || (e.rest != Rest::Blank && e.grace.is_none() && e.takes() <= Q::ZERO)
    })
}

struct Search<'a> {
    staves: &'a [StaffIn<'a>],
    items: &'a [Item],
    /// The read staves' columns.
    marks: &'a [Mark],
    /// Where the bar starts, by the read staves.
    x0: Option<f64>,
    sp: f64,
    len: Q,
    /// The bar's right barline.
    right: f64,
    starts: Vec<Q>,
    found: Vec<Vec<Q>>,
    budget: usize,
    /// How many items were given a start, at most.
    reached: usize,
    /// Why the last full choice of starts did not hold.
    failed: Option<&'static str>,
    /// The search stops at this many readings (2: one is sure, two are not).
    want: usize,
    /// Readings the bar's spacing or columns speak against are kept too, with why (`options.rs`).
    lax: bool,
    found_why: Vec<Option<&'static str>>,
}

impl Search<'_> {
    /// The starts item `n` may have, those before it given.
    fn candidates(&self, n: usize) -> Vec<Q> {
        let (it, sp) = (&self.items[n], self.sp);
        let near = (self.marks.iter())
            .filter(|m| (m.x - it.x).abs() <= IN_COLUMN * sp + m.play)
            .min_by(|a, b| (a.x - it.x).abs().total_cmp(&(b.x - it.x).abs()));
        let mut out: Vec<Q> = Vec::new();
        if let Some(m) = near {
            out.push(m.at);
        } else {
            if self.x0.is_some_and(|x0| (it.x - x0).abs() <= APART * sp) {
                out.push(Q::ZERO);
            }
            for f in 0..n {
                let (o, s) = (&self.items[f], self.starts[f]);
                if self.together(o, it) {
                    out.push(s);
                }
                let one_part = self.staves[o.staff].part == self.staves[it.staff].part;
                if one_part && it.x - o.x >= ON * sp {
                    out.push(s + o.dur);
                }
            }
        }
        // (for a person's choices: any start on the bar's finest grid between the columns it
        // stands between, the spacing then to say how likely it is)
        if self.lax && near.is_none() && !self.marks.is_empty() {
            let step = (self.items.iter().map(|o| o.dur))
                .filter(|d| !d.is_zero())
                .min()
                .unwrap_or(Q::ONE);
            let before = (self.marks.iter().filter(|m| m.x < it.x).map(|m| m.at)).max();
            let after = (self.marks.iter().filter(|m| m.x > it.x).map(|m| m.at)).min();
            let (from, to) = (before.unwrap_or(Q::ZERO), after.unwrap_or(self.len));
            let mut t = from;
            while t < to && out.len() < 64 {
                out.push(t);
                t += step;
            }
        }
        out.sort();
        out.dedup();
        out.retain(|&t| self.may(n, t));
        out
    }

    /// Whether two of the unread staves' notes may start together by where they stand (`a` no
    /// further right than `b`).
    fn together(&self, a: &Item, b: &Item) -> bool {
        let dx = b.x - a.x;
        if a.staff != b.staff {
            return dx <= APART * self.sp + a.play;
        }
        // (a rest is set off its column more freely than a note)
        let reach = if a.wide || !a.note || !b.note {
            BESIDE_PAST
        } else {
            BESIDE
        };
        let sign = if b.sign { ACCIDENTAL } else { 0.0 };
        dx <= (reach + sign) * self.sp + a.play
    }

    /// Whether item `n` may start at `t` by the bar's end, the read staves' columns, the items
    /// before it and its beam.
    fn may(&self, n: usize, t: Q) -> bool {
        let (it, sp) = (&self.items[n], self.sp);
        if t < Q::ZERO || t + it.dur > self.len {
            return false;
        }
        let ordered = self.marks.iter().all(|m| {
            let dx = it.x - m.x;
            if dx > IN_COLUMN * sp + m.play {
                t > m.at || (t == m.at && dx <= APART * sp + m.play)
            } else if dx < -IN_COLUMN * sp {
                t < m.at || (t == m.at && -dx <= APART * sp + it.play)
            } else {
                true
            }
        });
        if !ordered {
            return false;
        }
        let e = self.event(it);
        for f in 0..n {
            let (o, s) = (&self.items[f], self.starts[f]);
            if t < s {
                return false;
            }
            if t == s {
                if !self.together(o, it) {
                    return false;
                }
                // (two notes of one staff stemmed the same way would be one chord, but where
                // they stand in one column: two voices' heads set on one side)
                let one_column = (it.x - o.x).abs() <= IN_COLUMN * sp;
                if o.staff == it.staff && o.note && it.note && o.up == it.up && !one_column {
                    return false;
                }
            } else if it.x - o.x < ON * sp {
                return false;
            }
        }
        // a beam's notes follow one another, but for a rest printed under the beam
        let mate = (0..n).rev().find(|&f| {
            let o = &self.items[f];
            o.staff == it.staff && !self.event(o).beam_polys.is_disjoint(&e.beam_polys)
        });
        if let Some(f) = mate {
            let o = &self.items[f];
            let end = self.starts[f] + o.dur;
            let rest_between = self.items[f + 1..n]
                .iter()
                .any(|r| r.staff == it.staff && !r.note);
            if t < end || (t > end && !rest_between) {
                return false;
            }
        }
        true
    }

    fn event(&self, it: &Item) -> &Ev {
        &self.staves[it.staff].events[it.k]
    }

    fn walk(&mut self, n: usize) {
        if self.found.len() >= self.want || self.budget == 0 {
            return;
        }
        self.budget -= 1;
        self.reached = self.reached.max(n);
        if n == self.items.len() {
            if !self.found.contains(&self.starts) {
                match self.voices(&self.starts) {
                    Ok(_) => {
                        self.found.push(self.starts.clone());
                        self.found_why.push(None);
                    }
                    Err(why @ (UNEVEN | OFF_COLUMNS)) if self.lax => {
                        self.found.push(self.starts.clone());
                        self.found_why.push(Some(why));
                    }
                    Err(why) => self.failed = Some(why),
                }
            }
            return;
        }
        for t in self.candidates(n) {
            self.starts.push(t);
            self.walk(n + 1);
            self.starts.pop();
        }
    }

    /// Each unread staff's voices by the starts given, if they can be written and their columns
    /// contradict neither themselves nor the other staves'.
    fn voices(&self, starts: &[Q]) -> Result<Solved, &'static str> {
        let mut out: Vec<Option<Vec<Vec<Ev>>>> = Vec::new();
        for (i, st) in self.staves.iter().enumerate() {
            if st.read.is_some() {
                out.push(None);
                continue;
            }
            let mine: Vec<(&Ev, Q)> = (self.items.iter().zip(starts))
                .filter(|(it, _)| it.staff == i)
                .map(|(it, &s)| (self.event(it), s))
                .collect();
            if three_one_way(&mine) {
                return Err(NO_VOICES);
            }
            out.push(Some(
                voices_of(&mine, st.events, self.len).ok_or(NO_VOICES)?,
            ));
        }
        let cols: Vec<Vec<Mark>> = (self.staves.iter().zip(&out))
            .map(|(st, v)| match (st.read, v) {
                (Some(vs), _) => columns::marks(vs),
                (None, Some(vs)) => columns::marks(vs),
                (None, None) => Vec::new(),
            })
            .collect();
        for (i, st) in self.staves.iter().enumerate() {
            if st.read.is_some() {
                continue;
            }
            if columns::contradicts_itself(&cols[i], self.sp) {
                return Err(OFF_COLUMNS);
            }
            let mine = columns::columns(&cols[i]);
            for (j, other) in cols.iter().enumerate() {
                if j != i && columns::contradict(&mine, &columns::columns(other), self.sp) {
                    return Err(OFF_COLUMNS);
                }
            }
        }
        let all: Vec<Mark> = cols.into_iter().flatten().collect();
        match evenly_spaced(&all, self.len, self.right) {
            true => Ok(out),
            false => Err(UNEVEN),
        }
    }
}

/// A step between two of the bar's columns that is `ratio` times as long as another stands at
/// least this many times as wide (the middle of each length's steps): an engraver gives a longer
/// note more room, about half as much again for twice the length.
fn wider(ratio: f64) -> f64 {
    match ratio {
        r if r < 4.0 => 1.1,
        r if r < 8.0 => 1.3,
        _ => 1.6,
    }
}

/// Whether the bar's columns stand as their starts say by the bar's own spacing: the steps of
/// a length twice another's or more are wider than its steps ([`wider`]), and so is what is left
/// of the bar after its last column (less strictly: the barline's own room is in it). Notes read
/// with too short a length, set end to end, stand as wide as the true ones and fail this.
fn evenly_spaced(marks: &[Mark], len: Q, right: f64) -> bool {
    let cols = columns::columns(marks);
    let mut steps: Vec<(f64, Vec<f64>)> = Vec::new();
    for w in cols.windows(2) {
        let (dt, dx) = ((w[1].at - w[0].at).to_f64(), w[1].x - w[0].x);
        match steps.iter_mut().find(|s| (s.0 - dt).abs() < 1e-9) {
            Some(s) => s.1.push(dx),
            None => steps.push((dt, vec![dx])),
        }
    }
    let middle = |v: &Vec<f64>| {
        let mut v = v.clone();
        v.sort_by(f64::total_cmp);
        (v[(v.len() - 1) / 2] + v[v.len() / 2]) / 2.0
    };
    let steps: Vec<(f64, f64)> = steps.iter().map(|(dt, v)| (*dt, middle(v))).collect();
    let among = steps.iter().all(|&(dt, dx)| {
        (steps.iter())
            .filter(|s| s.0 >= 2.0 * dt - 1e-9)
            .all(|s| s.1 >= wider(s.0 / dt) * dx)
    });
    let last = cols.last().map(|c| ((len - c.at).to_f64(), right - c.x));
    let at_end = last.is_none_or(|(dt, dx)| {
        (steps.iter())
            .filter(|s| dt >= 2.0 * s.0 - 1e-9)
            .all(|s| dx >= (wider(dt / s.0) - 0.1) * s.1)
    });
    among && at_end
}

/// Whether three notes of a staff stemmed one way sound at once: a staff's voices stemmed one
/// way are two at most.
fn three_one_way(timed: &[(&Ev, Q)]) -> bool {
    let stemmed = || (timed.iter()).filter(|(e, _)| e.is_note() && e.up.is_some());
    stemmed().any(|(e, s)| {
        let sounding = stemmed().filter(|(o, t)| o.up == e.up && *t <= *s && *s < *t + o.takes());
        sounding.count() > 2
    })
}

/// Whether blank time of `gap` may follow `before` in its voice: not a printed rest (a program
/// that prints a voice's rest prints the next), and not a note that a dot or two would lengthen
/// by as much (then a dot may have been missed, which is not told).
fn may_follow(before: Option<&Ev>, gap: Q) -> bool {
    match before {
        None => true,
        Some(p) if p.is_note() => {
            let dot = p.takes() / Q::int(2);
            gap != dot && gap != dot + dot / Q::int(2)
        }
        Some(_) => false,
    }
}

/// A staff's notes and rests with their starts as voices: each goes on in the voice of the note
/// it is beamed with, else one stemmed its way that ends where it starts, else any that has
/// ended; the time between is blank. `None` where a beam's notes do not follow one another,
/// more than four voices are needed, a blank is of a length no rests have, or a grace note has
/// no note to lead to.
fn voices_of(timed: &[(&Ev, Q)], events: &[Ev], len: Q) -> Option<Vec<Vec<Ev>>> {
    let mut order: Vec<usize> = (0..timed.len()).collect();
    order.sort_by(|&a, &b| {
        (timed[a].1.cmp(&timed[b].1)).then(timed[a].0.x.total_cmp(&timed[b].0.x))
    });
    // each voice: the events' indices in `timed`
    let mut voices: Vec<Vec<usize>> = Vec::new();
    for n in order {
        let (e, s) = timed[n];
        let end = |v: &Vec<usize>| v.last().map(|&l| timed[l].1 + timed[l].0.takes());
        let last = |v: &Vec<usize>| v.last().map(|&l| timed[l].0);
        let beamed = |v: &Vec<usize>| {
            e.is_note()
                && v.iter()
                    .any(|&l| !timed[l].0.beam_polys.is_disjoint(&e.beam_polys))
        };
        if let Some(v) = voices.iter().position(beamed) {
            if end(&voices[v])? > s {
                return None;
            }
            voices[v].push(n);
            continue;
        }
        let dir = |v: &Vec<usize>| {
            v.iter()
                .rev()
                .map(|&l| timed[l].0)
                .find(|o| o.is_note() && o.up.is_some())
                .and_then(|o| o.up)
        };
        let best = (0..voices.len())
            .filter(|&v| end(&voices[v]).is_some_and(|t| t <= s))
            .min_by_key(|&v| {
                let same = e.is_note() && e.up.is_some() && dir(&voices[v]) == e.up;
                let other = e.is_note() && e.up.is_some() && dir(&voices[v]).is_some() && !same;
                let on = end(&voices[v]) == Some(s);
                let far = last(&voices[v]).map_or(0.0, |o| (o.y() - e.y()).abs());
                (other, !same, !on, (far * 100.0) as i64)
            });
        // (a note stemmed against a voice's own opens its own voice while it may)
        let opposed = best.is_some_and(|v| {
            e.is_note() && e.up.is_some() && dir(&voices[v]).is_some_and(|d| Some(d) != e.up)
        });
        match best {
            Some(v) if !opposed || voices.len() >= VOICES => voices[v].push(n),
            _ => voices.push(vec![n]),
        }
    }
    if voices.len() > VOICES {
        return None;
    }
    // the upper voice first: stems up, then by height
    let key = |v: &Vec<usize>| {
        let notes: Vec<&Ev> = (v.iter().map(|&l| timed[l].0))
            .filter(|e| e.is_note())
            .collect();
        let ups = notes.iter().filter(|e| e.up == Some(true)).count() as i64;
        let downs = notes.iter().filter(|e| e.up == Some(false)).count() as i64;
        let y = v.iter().map(|&l| timed[l].0.y()).sum::<f64>() / v.len().max(1) as f64;
        ((downs - ups).signum(), (y * 100.0) as i64)
    };
    voices.sort_by_key(key);
    let mut out: Vec<Vec<Ev>> = Vec::new();
    for v in &voices {
        let mut voice: Vec<Ev> = Vec::new();
        let mut t = Q::ZERO;
        for &l in v {
            let (e, s) = timed[l];
            if s > t {
                crate::write::plain_lengths(s - t).ok()?;
                if !may_follow(voice.last(), s - t) {
                    return None;
                }
                voice.push(Ev::spacer(s - t, e.x - 0.01));
            }
            voice.push(e.clone());
            t = s + e.takes();
        }
        if t < len {
            crate::write::plain_lengths(len - t).ok()?;
            if !may_follow(voice.last(), len - t) {
                return None;
            }
            voice.push(Ev::spacer(
                len - t,
                voice.last().map_or(0.0, |e| e.x + 0.01),
            ));
        }
        out.push(voice);
    }
    // each grace note before the note it leads to: the nearest right of it
    for g in events.iter().filter(|e| e.grace.is_some()) {
        let gy = g.y();
        let (v, k, _) = (0..out.len())
            .filter_map(|v| {
                out[v]
                    .iter()
                    .position(|e| e.x > g.x && e.rest != Rest::Blank && e.grace.is_none())
                    .map(|k| (v, k, (out[v][k].x - g.x) + (out[v][k].y() - gy).abs()))
            })
            .min_by(|a, b| a.2.total_cmp(&b.2))?;
        out[v].insert(k, g.clone());
    }
    Some(out)
}

/// The bar's unread staves solved: for each staff of `staves` that was not read, its voices,
/// where the starts of all their notes and rests are told one way by where they stand (the
/// module's rules); else why not: no reading or more than one is left, or what was seen is not
/// sure. `len`: the bar's length, which the caller knows to be the bar's (a read staff fills
/// it).
pub fn solve(staves: &[StaffIn], sp: f64, len: Q, right: f64) -> Result<Solved, &'static str> {
    let unread = || staves.iter().filter(|s| s.read.is_none());
    if unread().count() == 0 || unread().any(|s| !sure(s.events, sp)) {
        return Err(UNSURE);
    }
    let mut items: Vec<Item> = Vec::new();
    for (i, st) in staves.iter().enumerate().filter(|(_, s)| s.read.is_none()) {
        for (k, e) in st.events.iter().enumerate() {
            if e.rest != Rest::Blank && e.grace.is_none() {
                items.push(item(i, k, e));
            }
        }
    }
    if !items.iter().any(|it| it.note) {
        return Err(NO_NOTES);
    }
    items.sort_by(|a, b| a.x.total_cmp(&b.x));
    let marks: Vec<Mark> = (staves.iter().filter_map(|s| s.read))
        .flat_map(|vs| columns::columns(&columns::marks(vs)))
        .collect();
    if marks.is_empty() {
        return Err(NO_COLUMNS);
    }
    // where the bar starts: the leftmost of what the read staves' voices start with
    let x0 = (staves.iter().filter_map(|s| s.read))
        .flatten()
        .filter_map(|v| v.iter().find(|e| e.grace.is_none()))
        .filter(|e| e.is_note() || matches!(e.rest, Rest::Printed(_)))
        .map(|e| {
            if e.is_note() {
                columns::column_x(e)
            } else {
                e.x
            }
        })
        .min_by(|a, b| a.total_cmp(b));
    let mut search = Search {
        staves,
        items: &items,
        marks: &marks,
        x0,
        sp,
        len,
        right,
        starts: Vec::new(),
        found: Vec::new(),
        budget: BUDGET,
        reached: 0,
        failed: None,
        want: 2,
        lax: false,
        found_why: Vec::new(),
    };
    search.walk(0);
    if search.budget == 0 {
        return Err(TOO_MANY);
    }
    match &search.found[..] {
        [one] => search.voices(one),
        [] if search.reached < items.len() => Err(NO_START),
        [] => Err(search.failed.unwrap_or(NO_START)),
        _ => Err(TWO_READINGS),
    }
}

/// Every reading of the unread staff `i` of `staves` (the others read, or left out) that the
/// solver's rules allow, up to `want` of them, for a person to choose from (`options.rs`): those
/// the bar's spacing or the columns speak against too, with why. Unlike [`solve`] it takes what
/// was seen as sure (the caller has given out what is not) and, with no read staff to stand by,
/// times the notes by where the staff's own first one stands.
pub fn all(
    staves: &[StaffIn],
    unread: &[usize],
    sp: f64,
    len: Q,
    right: f64,
    want: usize,
) -> Vec<(Vec<Vec<Ev>>, Option<&'static str>)> {
    let i = unread[0];
    let st = &staves[i];
    let mut items: Vec<Item> = Vec::new();
    for &u in unread {
        items.extend(
            (staves[u].events.iter().enumerate())
                .filter(|(_, e)| e.rest != Rest::Blank && e.grace.is_none())
                .map(|(k, e)| item(u, k, e)),
        );
    }
    if !items.iter().any(|it| it.note) || items.len() > 40 {
        return Vec::new();
    }
    items.sort_by(|a, b| a.x.total_cmp(&b.x));
    let marks: Vec<Mark> = (staves.iter().enumerate())
        .filter(|(j, _)| !unread.contains(j))
        .filter_map(|(_, s)| s.read)
        .flat_map(|vs| columns::columns(&columns::marks(vs)))
        .collect();
    let x0 = (staves.iter().enumerate())
        .filter(|(j, _)| !unread.contains(j))
        .filter_map(|(_, s)| s.read)
        .flatten()
        .filter_map(|v| v.iter().find(|e| e.grace.is_none()))
        .filter(|e| e.is_note() || matches!(e.rest, Rest::Printed(_)))
        .map(|e| match e.is_note() {
            true => columns::column_x(e),
            false => e.x,
        })
        .min_by(|a, b| a.total_cmp(b))
        .filter(|_| !marks.is_empty())
        .or(items.iter().map(|it| it.x).min_by(|a, b| a.total_cmp(b)));
    // (the staff alone, the others its columns only)
    let alone: Vec<StaffIn> = (staves.iter().enumerate())
        .map(|(j, s)| StaffIn {
            part: s.part,
            events: s.events,
            read: if unread.contains(&j) { None } else { s.read },
        })
        .collect();
    let mut search = Search {
        staves: &alone,
        items: &items,
        marks: &marks,
        x0,
        sp,
        len,
        right,
        starts: Vec::new(),
        found: Vec::new(),
        budget: BUDGET,
        reached: 0,
        failed: None,
        want,
        lax: true,
        found_why: Vec::new(),
    };
    search.walk(0);
    let found = std::mem::take(&mut search.found);
    let why = std::mem::take(&mut search.found_why);
    let mut out = Vec::new();
    for (starts, why) in found.iter().zip(why) {
        let mine: Vec<(&Ev, Q)> = (items.iter().zip(starts))
            .filter(|(it, _)| it.staff == i)
            .map(|(it, &s)| (&st.events[it.k], s))
            .collect();
        if let Some(vs) = voices_of(&mine, st.events, len) {
            out.push((vs, why));
        }
    }
    out
}

/// How well a staff's reading stands by where its notes are, for ordering a person's choices:
/// 0 where its columns agree with themselves and the other staves' (`others`) and the bar's
/// spacing, 1 where only the spacing speaks against it, 2 where the columns do.
pub fn fit(voices: &[Vec<Ev>], others: &[Mark], sp: f64, len: Q, right: f64) -> u8 {
    let mine = columns::marks(voices);
    if columns::contradicts_itself(&mine, sp)
        || columns::contradict(&columns::columns(&mine), others, sp)
    {
        return 2;
    }
    let all: Vec<Mark> = mine.iter().chain(others).copied().collect();
    match evenly_spaced(&all, len, right) {
        true => 0,
        false => 1,
    }
}

/// What the solver says of a staff's bar that was read, timed again from where its notes stand
/// among the other read staves' columns as if it were not read.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Check {
    /// It times the notes as they were read.
    Agrees,
    /// It times them one other way, and that way alone.
    Another,
    /// No way of timing them holds, though each note had a start it might have.
    None,
    /// It cannot tell (more than one way, not sure as seen, no columns to stand by).
    Untold,
}

/// Each note's start and length in a staff's voices, in order.
fn timing(vs: &[Vec<Ev>]) -> Vec<(Q, Q)> {
    let mut out = Vec::new();
    for v in vs {
        let mut t = Q::ZERO;
        for e in v {
            if e.is_note() && e.grace.is_none() {
                out.push((t, e.takes()));
            }
            t += e.takes();
        }
    }
    out.sort();
    out
}

/// Staff `i`'s bar, read as `read`, checked by the solver against the other staves of `staves`
/// (all of them read: the caller leaves out the unread).
pub fn check(staves: &[StaffIn], i: usize, sp: f64, len: Q, right: f64) -> Check {
    let Some(read) = staves[i].read else {
        return Check::Untold;
    };
    let alone: Vec<StaffIn> = (staves.iter().enumerate())
        .map(|(j, s)| StaffIn {
            part: s.part,
            events: s.events,
            read: if j == i { None } else { s.read },
        })
        .collect();
    match solve(&alone, sp, len, right) {
        Ok(solved) => match &solved[i] {
            Some(vs) if timing(vs) == timing(read) => Check::Agrees,
            Some(_) => Check::Another,
            None => Check::Untold,
        },
        Err(NO_VOICES | OFF_COLUMNS | UNEVEN) => Check::None,
        Err(_) => Check::Untold,
    }
}

/// With `FMV_SPACING` set, what the solver says of each read staff's bar of a bar (`voices`, one
/// entry a staff), printed as `DOUBT` lines where it does not agree, for measuring.
#[allow(clippy::too_many_arguments)]
pub fn trace(
    number: i64,
    names: &[String],
    events: &[Vec<Ev>],
    voices: &[Result<Vec<Vec<Ev>>, String>],
    sp: f64,
    len: Q,
    right: f64,
) {
    if std::env::var("FMV_SPACING").is_err() {
        return;
    }
    let read: Vec<usize> = (0..voices.len()).filter(|&i| voices[i].is_ok()).collect();
    let staves: Vec<StaffIn> = (read.iter())
        .map(|&i| StaffIn {
            part: names[i].split('.').next().unwrap_or(&names[i]),
            events: &events[i],
            read: voices[i].as_ref().ok().map(|v| &v[..]),
        })
        .collect();
    // another staff whose notes fill the bar: its length is then sure
    let fills = |k: usize| {
        (staves[k].read).is_some_and(|vs| {
            vs.iter().flatten().any(|e| e.is_note())
                && !vs.iter().flatten().any(|e| e.rest == Rest::Blank)
        })
    };
    for k in 0..staves.len() {
        if !(0..staves.len()).any(|j| j != k && fills(j)) {
            continue;
        }
        let what = match check(&staves, k, sp, len, right) {
            Check::Agrees => "agrees",
            Check::Another => "another",
            Check::None => "none",
            Check::Untold => continue,
        };
        eprintln!("DOUBT\t{number}\t{}\tspacing: {what}", names[read[k]]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::page::Glyph;

    fn note(x: f64, dur: Q, up: bool) -> Ev {
        let g = Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y: 10.0,
            size: 4.0,
        };
        let mut e = Ev::new(vec![g], None, Some(up));
        e.dur = dur;
        e
    }

    /// A read staff of four quarters at 0, 4, 8 and 12 (a bar of four, its barline at 16).
    fn quarters() -> Vec<Vec<Ev>> {
        vec![[0.0, 4.0, 8.0, 12.0]
            .map(|x| note(x, Q::ONE, true))
            .to_vec()]
    }

    fn solve_one(unread: &[Ev]) -> Result<Solved, &'static str> {
        let read = quarters();
        let staves = [
            StaffIn {
                part: "P1",
                events: &read[0],
                read: Some(&read),
            },
            StaffIn {
                part: "P2",
                events: unread,
                read: None,
            },
        ];
        solve(&staves, 1.0, Q::int(4), 16.0)
    }

    /// Each voice's notes as (start, length).
    fn starts(vs: &[Vec<Ev>]) -> Vec<Vec<(Q, Q)>> {
        (vs.iter())
            .map(|v| {
                let mut t = Q::ZERO;
                let mut out = Vec::new();
                for e in v {
                    if e.is_note() {
                        out.push((t, e.dur));
                    }
                    t += e.takes();
                }
                out
            })
            .collect()
    }

    #[test]
    fn hidden_rests_are_found_by_the_columns_the_notes_stand_in() {
        // quarters on the second and fourth beats, their rests hidden
        let got = solve_one(&[note(4.0, Q::ONE, true), note(12.0, Q::ONE, true)]).unwrap();
        let vs = got[1].as_ref().unwrap();
        assert_eq!(
            starts(vs),
            vec![vec![(Q::ONE, Q::ONE), (Q::int(3), Q::ONE)]]
        );
    }

    #[test]
    fn two_voices_heads_in_one_column_stemmed_one_way_start_together() {
        // a half and a quarter set on one side of a stem, then a quarter that follows the quarter
        let got = solve_one(&[
            note(0.0, Q::int(2), true),
            note(0.0, Q::ONE, true),
            note(4.0, Q::ONE, true),
        ])
        .unwrap();
        let vs = got[1].as_ref().unwrap();
        let mut s = starts(vs);
        s.sort();
        assert_eq!(
            s,
            vec![
                vec![(Q::ZERO, Q::ONE), (Q::ONE, Q::ONE)],
                vec![(Q::ZERO, Q::int(2))]
            ]
        );
    }

    #[test]
    fn a_note_with_no_column_to_stand_by_is_left() {
        // an eighth halfway between two beats: its start is not told by any column
        let got = solve_one(&[note(6.0, Q::new(1, 2), true)]);
        assert!(got.is_err());
    }

    #[test]
    fn three_notes_stemmed_one_way_at_once_are_not_voices() {
        let (a, b, c) = (
            note(0.0, Q::int(2), true),
            note(0.0, Q::ONE, true),
            note(4.0, Q::ONE, true),
        );
        let two = [(&a, Q::ZERO), (&b, Q::ZERO), (&c, Q::ONE)];
        assert!(!three_one_way(&two));
        let three = [(&a, Q::ZERO), (&b, Q::ZERO), (&c, Q::ZERO)];
        assert!(three_one_way(&three));
    }

    #[test]
    fn a_grace_note_in_a_notes_column_is_not_sure() {
        let mut g = note(0.3, Q::new(1, 2), true);
        g.grace = Some(true);
        let n = note(0.0, Q::ONE, true);
        assert!(!sure(&[g.clone(), n.clone()], 1.0));
        g.x = -3.0;
        assert!(sure(&[g, n], 1.0));
    }

    #[test]
    fn all_readings_place_a_note_no_column_tells_on_the_beat_grid() {
        // the eighth halfway between two beats that `solve` leaves: the diagnostic's lax search
        // starts it on the grid of its own length between the columns either side
        let read = quarters();
        let unread = [note(6.0, Q::new(1, 2), true)];
        let staves = [
            StaffIn {
                part: "P1",
                events: &read[0],
                read: Some(&read),
            },
            StaffIn {
                part: "P2",
                events: &unread,
                read: None,
            },
        ];
        let got = all(&staves, &[1], 1.0, Q::int(4), 16.0, 6);
        assert!(!got.is_empty());
        assert!(got.len() <= 6);
        assert!(got
            .iter()
            .any(|(vs, _)| starts(vs) == vec![vec![(Q::new(3, 2), Q::new(1, 2))]]));
    }

    #[test]
    fn a_reading_on_the_columns_fits_and_one_off_them_does_not() {
        let read = quarters();
        let marks = crate::columns::columns(&crate::columns::marks(&read));
        assert_eq!(fit(&quarters(), &marks, 1.0, Q::int(4), 16.0), 0);
        // the same notes read a beat late
        let mut late = quarters();
        late[0].insert(0, {
            let mut r = note(0.0, Q::ONE, true);
            r.rest = Rest::Blank;
            r
        });
        late[0].pop();
        assert!(fit(&late, &marks, 1.0, Q::int(4), 16.0) > 0);
    }
}