Skip to main content

fm_vector/
audit.rs

1//! A reading checked against its own page, with no answer key (docs/quality.md, "The audit").
2//!
3//! The measure of notes says nothing of the marks that are not notes, and a PDF from the library
4//! has no key to score against. Two things can still be told from the PDF and its reading alone:
5//!
6//! - **What is printed is what is written.** Each pedal sign, dynamic, fermata, articulation,
7//!   ornament, breath and ottava sign is a glyph of the music font: they are counted where they
8//!   stand, a system at a time, and so are the marks the `.fmn` writes in that system's bars.
9//!   Three printed and five written is a mark written twice, three and one a mark lost.
10//! - **Readings that cannot be right.** A pedal written on two staves where one is printed, or on
11//!   a voice's staff; a pedal let up that was never down; the same dynamic in one bar on both
12//!   staves of a piano where one is printed; a slur or hairpin closed that was never opened, or
13//!   never closed; a pedal, dynamic or hairpin on a staff that has no note in that bar.
14//!
15//! Each finding has a weight, and a bar's, a system's and the PDF's suspicion are the sums: a
16//! person looks at the worst systems first (`tools/proof`).
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use crate::page::{Glyph, Page};
21use crate::read::{Reading, Refusal};
22use crate::review::BarPlace;
23use crate::smufl;
24
25/// The kinds counted, printed and written.
26pub const KINDS: [&str; 11] = [
27    "pedal down",
28    "pedal up",
29    "dynamic",
30    "fermata",
31    "staccato",
32    "accent",
33    "tenuto",
34    "marcato",
35    "ornament",
36    "breath",
37    "ottava",
38];
39
40/// A bar's findings.
41#[derive(Clone, Debug, Default, PartialEq)]
42pub struct BarAudit {
43    /// The bar's label, as in the `.fmn`.
44    pub bar: String,
45    /// `[x0, y0, x1, y1]` in page points from the top left.
46    pub frame: [f64; 4],
47    pub score: f64,
48    pub reasons: Vec<String>,
49}
50
51/// A system's findings: its bars', and the counts that do not agree over the whole system.
52#[derive(Clone, Debug, Default, PartialEq)]
53pub struct SystemAudit {
54    /// From 0.
55    pub system: usize,
56    /// From 0.
57    pub page: usize,
58    /// `[x0, y0, x1, y1]`: its bars' frames, joined.
59    pub frame: [f64; 4],
60    pub bars: Vec<BarAudit>,
61    /// Its bars' scores and its own reasons' weights.
62    pub score: f64,
63    pub reasons: Vec<String>,
64    /// Per kind (as [`KINDS`]): the marks printed in it, and written in its bars.
65    pub printed: [usize; 11],
66    pub written: [usize; 11],
67    /// Whether the counts were compared (not where a staff's bar of it was left unread).
68    pub counted: bool,
69}
70
71/// A PDF's reading and what is suspect in it.
72#[derive(Clone, Debug)]
73pub struct Audit {
74    pub reading: Reading,
75    pub systems: Vec<SystemAudit>,
76    /// The systems' scores, summed.
77    pub score: f64,
78    /// Each kind of finding and how many bars or systems have it.
79    pub findings: BTreeMap<String, usize>,
80    /// The pages' sizes, in points.
81    pub pages: Vec<[f64; 2]>,
82}
83
84/// Read a PDF and audit the reading.
85pub fn audit_pdf(bytes: &[u8]) -> Result<Audit, Refusal> {
86    let pages = crate::page::read_pages(bytes).map_err(|why| Refusal { system: None, why })?;
87    let review = crate::review::read_pdf_review(bytes)?;
88    Ok(audit(
89        &pages,
90        review.reading,
91        &review.bars,
92        review.pages.clone(),
93    ))
94}
95
96/// A mark printed: its kind (an index into [`KINDS`]) and where it stands.
97struct Printed {
98    kind: usize,
99    page: usize,
100    x: f64,
101    y: f64,
102}
103
104fn kind_of_glyph(code: u32) -> Option<usize> {
105    let k = |name: &str| KINDS.iter().position(|&n| n == name);
106    match code {
107        0xE650 | 0xE651 => k("pedal down"),
108        0xE655 => k("pedal up"),
109        0xE510..=0xE516 | 0xE51C | 0xE51D => k("ottava"),
110        0xE4CE | 0xE4CF => k("breath"),
111        0xE566 | 0xE567 | 0xE568 | 0xE56C | 0xE56D => k("ornament"),
112        _ if smufl::fermata(code).is_some() => k("fermata"),
113        _ => match smufl::articulation(code) {
114            Some("-.") => k("staccato"),
115            Some("->") => k("accent"),
116            Some("-_") => k("tenuto"),
117            Some("-^") => k("marcato"),
118            _ => None,
119        },
120    }
121}
122
123/// The marks printed on the pages. A dynamic's letters set side by side are one mark, and so
124/// are an ottava's `8` and its `va`.
125fn printed_marks(pages: &[Page]) -> Vec<Printed> {
126    let dynamic = KINDS.iter().position(|&n| n == "dynamic").unwrap_or(0);
127    let ottava = KINDS.iter().position(|&n| n == "ottava").unwrap_or(0);
128    let mut out = Vec::new();
129    for (pi, pg) in pages.iter().enumerate() {
130        // (`(Ped.)` in the pedal's parentheses is the pedal still down, shown again at a
131        // system's start: no mark of its own)
132        // (nor is a pedal's sign at the size of words, set in a line of them)
133        let again = |g: &Glyph| {
134            let pedal = matches!(g.code, 0xE650 | 0xE651 | 0xE655 | 0xE656);
135            (pedal && g.size <= 0.6 * pg.size)
136                || (matches!(g.code, 0xE650 | 0xE651)
137                    && pg.glyphs.iter().any(|p| {
138                        p.code == 0xE676
139                            && (p.y - g.y).abs() < 0.1 * g.size.max(4.0)
140                            && (g.x0 - p.x1).abs() < 0.25 * g.size.max(4.0)
141                    }))
142        };
143        let mut run: Vec<(&Glyph, usize)> = (pg.glyphs.iter())
144            .filter(|g| !again(g))
145            .filter_map(|g| {
146                if smufl::dynamic_text(g.code).is_some() {
147                    Some((g, dynamic))
148                } else {
149                    kind_of_glyph(g.code).map(|k| (g, k))
150                }
151            })
152            .collect();
153        run.sort_by(|a, b| (a.1, a.0.x0).partial_cmp(&(b.1, b.0.x0)).unwrap());
154        let mut last: Option<(&Glyph, usize)> = None;
155        for (g, k) in run {
156            let joined = (k == dynamic || k == ottava)
157                && last.is_some_and(|(p, pk)| {
158                    pk == k
159                        && g.x0 - p.x1 < 0.35 * g.size.max(4.0)
160                        && (g.y - p.y).abs() < 0.3 * g.size.max(4.0)
161                });
162            if !joined {
163                out.push(Printed {
164                    kind: k,
165                    page: pi,
166                    x: g.x0,
167                    y: g.y,
168                });
169            }
170            last = Some((g, k));
171        }
172    }
173    out
174}
175
176/// A staff's bar as written: its marks counted, and what its lines hold.
177#[derive(Clone, Debug, Default)]
178struct Written {
179    counts: [usize; 11],
180    /// The dynamics, as written (`p`, `mf`).
181    dynamics: Vec<String>,
182    notes: usize,
183    /// In order: the pedal's marks, the hairpins' and the slurs' opens and closes.
184    events: Vec<Event>,
185}
186
187#[derive(Clone, Debug, PartialEq)]
188enum Event {
189    PedalDown,
190    PedalChange,
191    PedalUp,
192    HairpinOpen(u8),
193    HairpinClose(u8),
194    SlurOpen,
195    SlurClose,
196}
197
198/// The tokens of a line of music: split at spaces, but not inside a chord's `<...>` or a
199/// quoted text.
200fn tokens(line: &str) -> Vec<&str> {
201    let mut out = Vec::new();
202    let (mut start, mut quote, mut chord) = (None, false, false);
203    let b = line.as_bytes();
204    for (i, &c) in b.iter().enumerate() {
205        if start.is_none() && !c.is_ascii_whitespace() {
206            start = Some(i);
207            chord = c == b'<';
208        }
209        match c {
210            b'"' => quote = !quote,
211            b'>' if chord && !quote => chord = false,
212            _ => {}
213        }
214        if c.is_ascii_whitespace() && !quote && !chord {
215            if let Some(s) = start.take() {
216                out.push(&line[s..i]);
217            }
218        }
219    }
220    if let Some(s) = start {
221        out.push(&line[s..]);
222    }
223    out
224}
225
226fn kind(name: &str) -> usize {
227    KINDS.iter().position(|&n| n == name).unwrap_or(0)
228}
229
230/// A line of music's tokens added to its staff's bar.
231fn write_line(w: &mut Written, line: &str) {
232    for tok in tokens(line) {
233        if let Some(body) = tok.strip_prefix('\\') {
234            let number = |s: &str| s.parse::<u8>().unwrap_or(1);
235            if body == "ped" {
236                w.counts[kind("pedal down")] += 1;
237                w.events.push(Event::PedalDown);
238            } else if body == "ped*" {
239                w.counts[kind("pedal up")] += 1;
240                w.events.push(Event::PedalUp);
241            } else if body == "ped^" {
242                w.events.push(Event::PedalChange);
243            } else if let Some(n) = body.strip_prefix('<').or(body.strip_prefix('>')) {
244                w.events.push(Event::HairpinOpen(number(n)));
245            } else if let Some(n) = body.strip_prefix('!') {
246                w.events.push(Event::HairpinClose(number(n)));
247            } else if ["8va", "8vb", "15ma", "15mb"]
248                .iter()
249                .any(|o| body == *o || body.strip_suffix(":voice") == Some(o))
250            {
251                w.counts[kind("ottava")] += 1;
252            } else if !body.is_empty() && body.chars().all(|c| "pmfszrn".contains(c)) {
253                w.counts[kind("dynamic")] += 1;
254                w.dynamics.push(body.to_string());
255            }
256            continue;
257        }
258        if tok.starts_with("^\"") || tok.starts_with("_\"") || tok.starts_with('"') {
259            continue;
260        }
261        let first = tok.chars().next().unwrap_or(' ');
262        if first == '<' || (('a'..='g').contains(&first) && tok.contains('/')) {
263            w.notes += 1;
264        }
265        // (the marks after the note: past a chord's own `>`)
266        let tail = match (first == '<', tok.find('>')) {
267            (true, Some(i)) => &tok[i + 1..],
268            _ => tok,
269        };
270        for c in tok.chars() {
271            match c {
272                '(' => w.events.push(Event::SlurOpen),
273                ')' => w.events.push(Event::SlurClose),
274                _ => {}
275            }
276        }
277        let mut rest = tail;
278        while let Some(i) = rest.find('-') {
279            rest = &rest[i + 1..];
280            let named = [
281                ("fermatabelow", "fermata"),
282                ("shortfermata", "fermata"),
283                ("longfermata", "fermata"),
284                ("fermata", "fermata"),
285                ("breath", "breath"),
286                ("turn", "ornament"),
287                ("tr", "ornament"),
288                ("prall", "ornament"),
289                ("mordent", "ornament"),
290                (".", "staccato"),
291                (">", "accent"),
292                ("_", "tenuto"),
293                ("^", "marcato"),
294            ];
295            if let Some((_, k)) = named
296                .iter()
297                .find(|(n, _)| rest.starts_with(n) && !(*n == "tr" && rest.starts_with("trem")))
298            {
299                w.counts[kind(k)] += 1;
300            }
301        }
302    }
303}
304
305/// The `.fmn` as the audit needs it: the parts that are a voice's and a piano's, and per bar
306/// (in order) each staff's marks.
307struct Fmn {
308    voices: BTreeSet<String>,
309    pianos: BTreeSet<String>,
310    bars: Vec<(String, BTreeMap<String, Written>)>,
311}
312
313fn parse_fmn(fmn: &str) -> Fmn {
314    let mut out = Fmn {
315        voices: BTreeSet::new(),
316        pianos: BTreeSet::new(),
317        bars: Vec::new(),
318    };
319    for line in fmn.lines() {
320        if let Some(rest) = line.strip_prefix("part ") {
321            let id = rest.split_whitespace().next().unwrap_or("").to_string();
322            if rest.ends_with(" voice") {
323                out.voices.insert(id);
324            } else if rest.ends_with(" piano") {
325                out.pianos.insert(id);
326            }
327        } else if let Some(rest) = line.strip_prefix("bar ") {
328            let label = rest.split_whitespace().next().unwrap_or("").to_string();
329            out.bars.push((label, BTreeMap::new()));
330        } else if let (Some((head, music)), Some(bar)) =
331            (line.split_once(": "), out.bars.last_mut())
332        {
333            // (`P.1/2: ...` is the staff P.1's second voice; `V lyrics: ...` is no music)
334            if head.contains(' ') || head.is_empty() {
335                continue;
336            }
337            let staff = head.split('/').next().unwrap_or(head).to_string();
338            write_line(bar.1.entry(staff).or_default(), music);
339        }
340    }
341    out
342}
343
344fn part_of(staff: &str) -> &str {
345    staff.split('.').next().unwrap_or(staff)
346}
347
348/// The audit of a reading: `pages` the PDF's, `places` where each bar of it stands.
349pub(crate) fn audit(
350    pages: &[Page],
351    reading: Reading,
352    places: &[BarPlace],
353    sizes: Vec<[f64; 2]>,
354) -> Audit {
355    let fmn = parse_fmn(&reading.fmn);
356    let unread: BTreeSet<String> = reading.unread.iter().map(|u| u.bar.to_string()).collect();
357    // the systems, each with its bars
358    let mut systems: Vec<SystemAudit> = Vec::new();
359    for p in places {
360        if systems.last().is_none_or(|s| s.system != p.system) {
361            systems.push(SystemAudit {
362                system: p.system,
363                page: p.page,
364                frame: p.frame,
365                counted: true,
366                ..Default::default()
367            });
368        }
369        let s = systems.last_mut().unwrap();
370        s.frame = [
371            s.frame[0].min(p.frame[0]),
372            s.frame[1].min(p.frame[1]),
373            s.frame[2].max(p.frame[2]),
374            s.frame[3].max(p.frame[3]),
375        ];
376        s.counted &= !unread.contains(&p.bar);
377        s.bars.push(BarAudit {
378            bar: p.bar.clone(),
379            frame: p.frame,
380            ..Default::default()
381        });
382    }
383    let at: BTreeMap<String, (usize, usize)> = (systems.iter().enumerate())
384        .flat_map(|(si, s)| {
385            (s.bars.iter().enumerate()).map(move |(bi, b)| (b.bar.clone(), (si, bi)))
386        })
387        .collect();
388    let mut found: Vec<(usize, Option<usize>, f64, String)> = Vec::new(); // system, bar, weight, why
389
390    // 1. what is printed, by system and bar
391    let mut printed_bar: BTreeMap<(usize, usize), [usize; 11]> = BTreeMap::new();
392    let pedal = |k: usize| KINDS[k].starts_with("pedal");
393    for m in printed_marks(pages) {
394        // the system it stands nearest (in, over or under), on its page; a mark far from every
395        // system (a title's, a legend's) is none's. A pedal's sign is the system's it stands
396        // under, however far under and however near the next
397        let near = (systems.iter().enumerate())
398            .filter(|(_, s)| s.page == m.page && s.frame[0] - 40.0 < m.x && m.x < s.frame[2] + 20.0)
399            .filter(|(_, s)| !pedal(m.kind) || s.frame[1] < m.y)
400            .map(|(i, s)| {
401                let d = if m.y < s.frame[1] {
402                    s.frame[1] - m.y
403                } else {
404                    (m.y - s.frame[3]).max(0.0)
405                };
406                (if pedal(m.kind) { m.y - s.frame[1] } else { d }, d, i)
407            })
408            .min_by(|a, b| a.0.total_cmp(&b.0));
409        let Some((_, d, si)) = near else { continue };
410        let s = &mut systems[si];
411        if !pedal(m.kind) && d > 0.6 * (s.frame[3] - s.frame[1]).max(60.0) {
412            continue;
413        }
414        s.printed[m.kind] += 1;
415        let bi = (s.bars.iter())
416            .position(|b| m.x < b.frame[2])
417            .unwrap_or(s.bars.len() - 1);
418        printed_bar.entry((si, bi)).or_insert([0; 11])[m.kind] += 1;
419    }
420
421    // 2. what is written, and the readings that cannot be right
422    let mut pedal_down: BTreeMap<String, bool> = BTreeMap::new();
423    let mut hairpins: BTreeMap<(String, u8), (usize, usize)> = BTreeMap::new();
424    let mut slurs: BTreeMap<String, Vec<(usize, usize)>> = BTreeMap::new();
425    let dynamic = kind("dynamic");
426    let down = kind("pedal down");
427    for (label, staves) in &fmn.bars {
428        let Some(&(si, bi)) = at.get(label) else {
429            continue;
430        };
431        let here = printed_bar.get(&(si, bi)).copied().unwrap_or([0; 11]);
432        let whole = systems[si].printed;
433        let mut written = [0usize; 11];
434        for w in staves.values() {
435            for (k, n) in w.counts.iter().enumerate() {
436                written[k] += n;
437                systems[si].written[k] += n;
438            }
439        }
440        // a pedal printed once and written on two staves
441        let with_pedal: Vec<&String> = (staves.iter())
442            .filter(|(_, w)| w.counts[down] > 0)
443            .map(|(s, _)| s)
444            .collect();
445        if with_pedal.len() > 1 && written[down] > here[down] {
446            found.push((
447                si,
448                Some(bi),
449                3.0,
450                format!(
451                    "pedal on {} staves ({}), {} printed in the bar",
452                    with_pedal.len(),
453                    with_pedal
454                        .iter()
455                        .map(|s| s.as_str())
456                        .collect::<Vec<_>>()
457                        .join(" "),
458                    here[down]
459                ),
460            ));
461        }
462        for (staff, w) in staves {
463            let pedal = w
464                .events
465                .iter()
466                .any(|e| matches!(e, Event::PedalDown | Event::PedalChange | Event::PedalUp));
467            if pedal && fmn.voices.contains(part_of(staff)) {
468                found.push((
469                    si,
470                    Some(bi),
471                    3.0,
472                    format!("pedal on a voice's staff ({staff})"),
473                ));
474            }
475            let opens = (w.events.iter()).any(|e| matches!(e, Event::HairpinOpen(_)));
476            if w.notes == 0 && (pedal || opens || !w.dynamics.is_empty()) {
477                let what = [
478                    (pedal, "pedal"),
479                    (!w.dynamics.is_empty(), "dynamic"),
480                    (opens, "hairpin"),
481                ];
482                let what: Vec<&str> = what.iter().filter(|x| x.0).map(|x| x.1).collect();
483                found.push((
484                    si,
485                    Some(bi),
486                    if pedal { 2.0 } else { 1.0 },
487                    format!(
488                        "{} on {staff}, which has no note in the bar",
489                        what.join(", ")
490                    ),
491                ));
492            }
493            // (a staff's voices are written a line each, so the order of a bar's marks across
494            // them is not known: the bar's opens and closes are balanced, not followed)
495            let n = |e: &Event| w.events.iter().filter(|x| *x == e).count();
496            let (downs, ups, changes) = (
497                n(&Event::PedalDown),
498                n(&Event::PedalUp),
499                n(&Event::PedalChange),
500            );
501            let was = usize::from(pedal_down.get(staff).copied().unwrap_or(false));
502            if ups > was + downs || (changes > 0 && was + downs == 0) {
503                found.push((
504                    si,
505                    Some(bi),
506                    2.0,
507                    format!("pedal let up on {staff}, which was never down"),
508                ));
509            }
510            let left = (was + downs).saturating_sub(ups);
511            if left > 1 {
512                found.push((
513                    si,
514                    Some(bi),
515                    1.0,
516                    format!("pedal down on {staff}, which was down already"),
517                ));
518            }
519            if downs + ups > 0 {
520                pedal_down.insert(staff.clone(), left > 0);
521            }
522            let numbers: BTreeSet<u8> = (w.events.iter())
523                .filter_map(|e| match e {
524                    Event::HairpinOpen(k) | Event::HairpinClose(k) => Some(*k),
525                    _ => None,
526                })
527                .collect();
528            for k in numbers {
529                let key = (staff.clone(), k);
530                let (opens, closes) = (n(&Event::HairpinOpen(k)), n(&Event::HairpinClose(k)));
531                let was = usize::from(hairpins.contains_key(&key));
532                if closes > was + opens {
533                    found.push((
534                        si,
535                        Some(bi),
536                        2.0,
537                        format!("hairpin closed on {staff} that was never opened"),
538                    ));
539                }
540                let left = (was + opens).saturating_sub(closes);
541                if left > 1 {
542                    found.push((
543                        si,
544                        Some(bi),
545                        2.0,
546                        format!("hairpin opened on {staff} with the one before never closed"),
547                    ));
548                }
549                if left == 0 {
550                    hairpins.remove(&key);
551                } else if opens > 0 {
552                    hairpins.insert(key, (si, bi));
553                }
554            }
555            let open = slurs.entry(staff.clone()).or_default();
556            for _ in 0..n(&Event::SlurOpen) {
557                open.push((si, bi));
558            }
559            for _ in 0..n(&Event::SlurClose) {
560                // (the oldest open one: a slur closes long before the piece ends)
561                if open.is_empty() {
562                    found.push((
563                        si,
564                        Some(bi),
565                        2.0,
566                        format!("slur closed on {staff} that was never opened"),
567                    ));
568                } else {
569                    open.remove(0);
570                }
571            }
572        }
573        // the same dynamic on both staves of a piano, printed once
574        let mut by_part: BTreeMap<(&str, &str), Vec<&str>> = BTreeMap::new();
575        for (staff, w) in staves {
576            let part = part_of(staff);
577            if fmn.pianos.contains(part) {
578                let seen: BTreeSet<&str> = w.dynamics.iter().map(|d| d.as_str()).collect();
579                for d in seen {
580                    by_part.entry((part, d)).or_default().push(staff);
581                }
582            }
583        }
584        for ((_, d), on) in by_part {
585            // (where the page has no dynamic as a glyph, its dynamics are text: not counted)
586            if on.len() > 1 && written[dynamic] > here[dynamic] && whole[dynamic] > 0 {
587                found.push((
588                    si,
589                    Some(bi),
590                    3.0,
591                    format!(
592                        "{d} on both staves of a piano ({}), {} dynamic(s) printed in the bar",
593                        on.join(" "),
594                        here[dynamic]
595                    ),
596                ));
597            }
598        }
599        // the bar's counts, kept for the system's
600        if systems[si].counted {
601            for k in 0..KINDS.len() {
602                if written[k] != here[k] {
603                    systems[si].bars[bi].reasons.push(format!(
604                        "\u{1}{k}\u{1}{} printed, {} written",
605                        here[k], written[k]
606                    ));
607                }
608            }
609        }
610    }
611    for ((staff, _), (si, bi)) in hairpins {
612        found.push((
613            si,
614            Some(bi),
615            2.0,
616            format!("hairpin on {staff} never closed"),
617        ));
618    }
619    for (staff, open) in slurs {
620        for (si, bi) in open {
621            found.push((si, Some(bi), 2.0, format!("slur on {staff} never closed")));
622        }
623    }
624
625    // 3. the counts: a system's printed marks against its written ones
626    let fonts_dynamics = systems.iter().any(|s| s.printed[dynamic] > 0);
627    for (si, s) in systems.iter_mut().enumerate() {
628        let mut off = [false; 11];
629        if s.counted {
630            for k in 0..KINDS.len() {
631                let (p, w) = (s.printed[k], s.written[k]);
632                // (a pedal's line ends in a hook, no glyph, and an ottava's sign is printed
633                // again where its line runs on: only a sign not written, only a sign written
634                // and not printed is told; dynamics set as text are not glyphs)
635                let skip = (KINDS[k] == "pedal up" && w >= p)
636                    || (KINDS[k] == "ottava" && w <= p)
637                    || (k == dynamic && !fonts_dynamics);
638                if p != w && !skip {
639                    off[k] = true;
640                    found.push((
641                        si,
642                        None,
643                        (p.abs_diff(w) as f64).min(4.0),
644                        format!("{}: {p} printed, {w} written", KINDS[k]),
645                    ));
646                }
647            }
648        }
649        // a bar's own count is told only where its system's is off (a mark at a barline may be
650        // counted in the bar beside it)
651        for b in &mut s.bars {
652            let notes = std::mem::take(&mut b.reasons);
653            for n in notes {
654                let mut it = n.split('\u{1}');
655                let (_, k, text) = (it.next(), it.next(), it.next());
656                let k: usize = k.and_then(|k| k.parse().ok()).unwrap_or(0);
657                if off[k] {
658                    b.reasons
659                        .push(format!("{}: {}", KINDS[k], text.unwrap_or("")));
660                    b.score += 0.5;
661                }
662            }
663        }
664    }
665
666    let mut findings: BTreeMap<String, usize> = BTreeMap::new();
667    for (si, bi, weight, why) in found {
668        let class = class_of(&why);
669        *findings.entry(class).or_default() += 1;
670        match bi {
671            Some(bi) => {
672                let b = &mut systems[si].bars[bi];
673                b.score += weight;
674                b.reasons.push(why);
675            }
676            None => {
677                systems[si].score += weight;
678                systems[si].reasons.push(why);
679            }
680        }
681    }
682    for s in &mut systems {
683        s.score += s.bars.iter().map(|b| b.score).sum::<f64>();
684    }
685    Audit {
686        score: systems.iter().map(|s| s.score).sum(),
687        reading,
688        systems,
689        findings,
690        pages: sizes,
691    }
692}
693
694/// A finding's kind, for the tally.
695fn class_of(why: &str) -> String {
696    let named = [
697        ("on a voice's staff", "pedal on a voice's staff"),
698        ("staves (", "pedal printed once, written on two staves"),
699        (
700            "which has no note",
701            "mark on a staff with no note in the bar",
702        ),
703        ("was down already", "pedal down twice"),
704        ("never down", "pedal up, never down"),
705        ("hairpin closed", "hairpin closed, never opened"),
706        ("hairpin", "hairpin never closed"),
707        ("slur closed", "slur closed, never opened"),
708        ("slur", "slur never closed"),
709        (
710            "both staves",
711            "dynamic printed once, written on both staves",
712        ),
713    ];
714    match why.split_once(": ") {
715        Some((k, _)) if KINDS.contains(&k) => format!("count: {k}"),
716        _ => (named.iter())
717            .find(|(has, _)| why.contains(has))
718            .map_or("other", |(_, name)| name)
719            .to_string(),
720    }
721}
722
723fn json_str(s: &str) -> String {
724    let mut out = String::from("\"");
725    for c in s.chars() {
726        match c {
727            '"' => out.push_str("\\\""),
728            '\\' => out.push_str("\\\\"),
729            '\n' => out.push_str("\\n"),
730            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
731            c => out.push(c),
732        }
733    }
734    out.push('"');
735    out
736}
737
738fn json_list(items: &[String]) -> String {
739    let quoted: Vec<String> = items.iter().map(|s| json_str(s)).collect();
740    format!("[{}]", quoted.join(","))
741}
742
743fn json_frame(f: &[f64; 4]) -> String {
744    format!("[{:.1},{:.1},{:.1},{:.1}]", f[0], f[1], f[2], f[3])
745}
746
747impl Audit {
748    /// The audit as JSON, the reading's `.fmn` and MusicXML left out: the PDF's score, its
749    /// bars and systems counted, the findings by kind, the marks printed and written by kind,
750    /// and every system (its page, frame, score, reasons, and its bars with theirs).
751    pub fn to_json(&self) -> String {
752        let bars: usize = self.systems.iter().map(|s| s.bars.len()).sum();
753        let findings: Vec<String> = (self.findings.iter())
754            .map(|(k, n)| format!("{}:{n}", json_str(k)))
755            .collect();
756        let counts: Vec<String> = (KINDS.iter().enumerate())
757            .map(|(k, name)| {
758                format!(
759                    "{}:[{},{}]",
760                    json_str(name),
761                    self.systems.iter().map(|s| s.printed[k]).sum::<usize>(),
762                    self.systems.iter().map(|s| s.written[k]).sum::<usize>()
763                )
764            })
765            .collect();
766        let systems: Vec<String> = (self.systems.iter())
767            .map(|s| {
768                let bars: Vec<String> = (s.bars.iter())
769                    .map(|b| {
770                        format!(
771                            "{{\"bar\":{},\"frame\":{},\"score\":{:.1},\"reasons\":{}}}",
772                            json_str(&b.bar),
773                            json_frame(&b.frame),
774                            b.score,
775                            json_list(&b.reasons)
776                        )
777                    })
778                    .collect();
779                format!(
780                    "{{\"system\":{},\"page\":{},\"frame\":{},\"score\":{:.1},\"counted\":{},\"reasons\":{},\"bars\":[{}]}}",
781                    s.system,
782                    s.page,
783                    json_frame(&s.frame),
784                    s.score,
785                    s.counted,
786                    json_list(&s.reasons),
787                    bars.join(",")
788                )
789            })
790            .collect();
791        let pages: Vec<String> = (self.pages.iter())
792            .map(|p| format!("[{:.1},{:.1}]", p[0], p[1]))
793            .collect();
794        format!(
795            "{{\"score\":{:.1},\"systems_n\":{},\"bars_n\":{bars},\"unread\":{},\"findings\":{{{}}},\"counts\":{{{}}},\"pages\":[{}],\"systems\":[\n{}\n]}}",
796            self.score,
797            self.systems.len(),
798            self.reading.unread.len(),
799            findings.join(","),
800            counts.join(","),
801            pages.join(","),
802            systems.join(",\n")
803        )
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810
811    #[test]
812    fn a_line_is_split_at_spaces_outside_chords_and_texts() {
813        assert_eq!(
814            tokens("^\"a tempo\" \\mf <c4 e4>/8-.-> r/4 \\ped e4/4("),
815            [
816                "^\"a tempo\"",
817                "\\mf",
818                "<c4 e4>/8-.->",
819                "r/4",
820                "\\ped",
821                "e4/4("
822            ]
823        );
824    }
825
826    #[test]
827    fn a_line_s_marks_are_counted() {
828        let mut w = Written::default();
829        write_line(
830            &mut w,
831            "\\mf <c4 e4>/8-.-> r/4-fermata \\ped e4/4(-tr \\ped* g4/8-trem2) \\< a4/4-_ \\! \\8va",
832        );
833        let n = |k: &str| w.counts[kind(k)];
834        assert_eq!(
835            (n("dynamic"), n("staccato"), n("accent"), n("fermata")),
836            (1, 1, 1, 1)
837        );
838        assert_eq!((n("pedal down"), n("pedal up"), n("ornament")), (1, 1, 1));
839        assert_eq!((n("tenuto"), n("ottava"), w.notes), (1, 1, 4));
840        assert_eq!(w.dynamics, ["mf"]);
841        assert!(w.events.contains(&Event::SlurOpen) && w.events.contains(&Event::SlurClose));
842    }
843
844    #[test]
845    fn a_voice_s_pedal_and_a_staff_with_no_note_are_told() {
846        let fmn = parse_fmn(
847            "part V \"Voice\" voice\npart P \"Piano\" piano\n\nbar 1 system\nV: R \\ped \\ped*\nV lyrics: la (la)\nP.1: c4/1\nP.2/2: c3/1\n",
848        );
849        assert!(fmn.voices.contains("V") && fmn.pianos.contains("P"));
850        let bar = &fmn.bars[0].1;
851        assert_eq!(
852            (bar["V"].notes, bar["V"].counts[kind("pedal down")]),
853            (0, 1)
854        );
855        assert_eq!((bar["P.1"].notes, bar["P.2"].notes), (1, 1));
856        assert!(bar["V"].events.iter().all(|e| *e != Event::SlurOpen));
857    }
858}