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
//! A dot two voices' notes share (one head with a stem up and a stem down, and a dot: a dotted
//! quarter and a quarter in unison) belongs to one of them or to both, and the page does not
//! say which. The rules try each way where a staff's voices alone must fill the bar
//! (`staff::dots_of_one_voice`); the spacing solver, which times a bar from the other staves'
//! columns, left such a staff alone as not sure. Here it is solved once for each way the dots
//! may be given out. Where more than one way solves it, the way whose voices are fewest is
//! taken, if one way alone is: the dot given to both notes makes the note it lengthens sound on
//! under the next note stemmed its way, which then needs a voice of its own that nothing on
//! the page asks for. Where two ways are as few, the bar stays unread.
//!
//! A chord whose dots stand by some of its heads only is parted here too (`part_by_dots`).

use crate::frac::Q;
use crate::spacing::{self, Solved, StaffIn};
use crate::staff::Ev;

/// Pairs of notes at one place that share their dots, at most this many in a bar.
const PAIRS: usize = 4;
/// Ways tried in all, across the bar's staves.
const WAYS: usize = 81;

/// The notes in a staff's bar that share their dots, paired: up-stemmed with down-stemmed at
/// one place.
fn pairs(events: &[Ev], sp: f64) -> Vec<(usize, usize)> {
    let mut out: Vec<(usize, usize)> = Vec::new();
    for i in 0..events.len() {
        for j in i + 1..events.len() {
            let (a, b) = (&events[i], &events[j]);
            let free = |k: usize| !out.iter().any(|p| p.0 == k || p.1 == k);
            if a.dots_shared > 0
                && b.dots_shared > 0
                && a.up != b.up
                && (a.x - b.x).abs() < 1.5 * sp
                && free(i)
                && free(j)
            {
                out.push((i, j));
            }
        }
    }
    out
}

/// A note's length without the dots it shares.
fn undotted(e: &Ev) -> Q {
    match e.dots_shared {
        2 => e.dur * Q::new(4, 7),
        _ => e.dur * Q::new(2, 3),
    }
}

/// Each way of giving out a staff's shared dots: both notes of a pair dotted, the first alone,
/// or the second alone; the notes no longer marked as sharing. None where nothing is shared, or
/// a note shares its dot with no partner found.
pub(crate) fn ways(events: &[Ev], sp: f64) -> Option<Vec<Vec<Ev>>> {
    let pairs = pairs(events, sp);
    let shared = events.iter().filter(|e| e.dots_shared > 0).count();
    if pairs.is_empty() || pairs.len() > PAIRS || shared != 2 * pairs.len() {
        return None;
    }
    let n = 3usize.pow(pairs.len() as u32);
    let mut out = Vec::with_capacity(n);
    for way in 0..n {
        let mut evs = events.to_vec();
        let mut w = way;
        for &(i, j) in &pairs {
            match w % 3 {
                1 => evs[j].dur = undotted(&events[j]),
                2 => evs[i].dur = undotted(&events[i]),
                _ => {}
            }
            (evs[i].dots_shared, evs[j].dots_shared) = (0, 0);
            w /= 3;
        }
        out.push(evs);
    }
    Some(out)
}

/// A chord on one stem with a dot by some of its heads and not by the others (`Ev::dots_partial`)
/// is two voices' notes hung from one stem: a dotted chord dots every head. Where each dot is
/// plainly one head's (at its height, a head in a space; or half a space off it, a head on a
/// line, with no other head as near) and no two heads are a second apart (whose dots may be
/// set as one), the chord is parted into the dotted notes and the others, one length each.
/// `partial`: the chords so marked (index into `out`) with the heights of their one column of
/// dots; the plain part is pushed at the end of `out`.
pub fn part_by_dots(out: &mut Vec<Ev>, partial: &[(usize, Vec<f64>)], sp: f64) {
    for (i, dots) in partial {
        let c = &out[*i];
        let fit = c.is_note()
            && c.stem.is_some()
            && c.grace.is_none()
            && c.beam_polys.is_empty()
            && c.dots_shared == 0
            && c.heads.len() >= 2;
        if !fit {
            continue;
        }
        let close = (0..c.heads.len()).any(|a| {
            (a + 1..c.heads.len()).any(|b| (c.heads[a].y - c.heads[b].y).abs() < 0.75 * sp)
        });
        if close {
            continue;
        }
        let mut dotted: Vec<usize> = Vec::new();
        let mut plain = true;
        for d in dots {
            let at = |lo: f64, hi: f64| -> Vec<usize> {
                (0..c.heads.len())
                    .filter(|&k| {
                        let off = (c.heads[k].y - d).abs();
                        lo <= off && off < hi
                    })
                    .collect()
            };
            let (level, off) = (at(0.0, 0.25 * sp), at(0.25 * sp, 0.75 * sp));
            let own = match (&level[..], &off[..]) {
                ([k], _) => Some(*k),
                ([], [k]) => Some(*k),
                _ => None,
            };
            match own {
                Some(k) if !dotted.contains(&k) => dotted.push(k),
                _ => plain = false,
            }
        }
        if !plain || dotted.is_empty() || dotted.len() == c.heads.len() {
            continue;
        }
        let part = |keep: bool| -> Vec<crate::page::Glyph> {
            (0..c.heads.len())
                .filter(|k| dotted.contains(k) == keep)
                .map(|k| c.heads[k])
                .collect()
        };
        let mut other = c.clone();
        other.heads = part(false);
        other.dur = c.dur * Q::new(2, 3);
        other.dots_partial = false;
        let mine = part(true);
        out[*i].heads = mine;
        out[*i].dots_partial = false;
        out.push(other);
    }
}

/// The bar solved (`spacing::solve`) with its unread staves' shared dots given out each way
/// they may be: the reading of the way with the fewest voices (and of those the fewest rests
/// made up), where one way alone is so. None
/// where no unread staff shares a dot, a way has two readings, or there are too many ways.
pub fn solve(staves: &[StaffIn], sp: f64, len: Q, right: f64) -> Option<Solved> {
    let mut each: Vec<Vec<Vec<Ev>>> = Vec::new();
    let mut any = false;
    for st in staves {
        let shares = st.read.is_none() && st.events.iter().any(|e| e.dots_shared > 0);
        if shares {
            each.push(ways(st.events, sp)?);
            any = true;
        } else {
            each.push(vec![st.events.to_vec()]);
        }
    }
    let total: usize = each.iter().map(|w| w.len()).product();
    if !any || total > WAYS {
        return None;
    }
    // of the ways that solve the bar, the one whose staves hold the fewest voices, and of those
    // the fewest rests made up: one way alone, or none
    let mut found: Option<((usize, usize), Solved)> = None;
    let mut tie = false;
    for way in 0..total {
        let mut w = way;
        let chosen: Vec<&Vec<Ev>> = each
            .iter()
            .map(|ws| {
                let k = w % ws.len();
                w /= ws.len();
                &ws[k]
            })
            .collect();
        let tried: Vec<StaffIn> = (staves.iter().zip(&chosen))
            .map(|(st, evs)| StaffIn {
                part: st.part,
                events: evs,
                read: st.read,
            })
            .collect();
        let r = spacing::solve(&tried, sp, len, right);
        match r {
            Ok(solved) => {
                let n = lines(&solved);
                match found.as_ref().map(|f| f.0) {
                    Some(m) if m < n => {}
                    Some(m) if m == n => tie = true,
                    _ => {
                        tie = false;
                        found = Some((n, solved));
                    }
                }
            }
            Err(spacing::TWO_READINGS) | Err(spacing::TOO_MANY) => return None,
            Err(_) => {}
        }
    }
    match tie {
        true => None,
        false => found.map(|(_, s)| s),
    }
}

/// How many voices a solved bar's staves hold, and how many of their events are time made up.
fn lines(solved: &Solved) -> (usize, usize) {
    let vs = solved.iter().flatten().flatten();
    let blank = |e: &&Ev| e.rest == crate::staff::Rest::Blank;
    (vs.clone().count(), vs.flatten().filter(blank).count())
}

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

    fn head(x: f64, y: f64) -> Glyph {
        Glyph {
            code: 0xE0A4,
            x0: x,
            x1: x + 1.2,
            y,
            size: 4.0,
        }
    }

    fn note(x: f64, dur: Q, up: bool) -> Ev {
        let mut e = Ev::new(vec![head(x, 10.0)], None, Some(up));
        e.dur = dur;
        e
    }

    fn chord(ys: &[f64]) -> Ev {
        let stem = VLine {
            x: 1.2,
            y0: 4.0,
            y1: 12.0,
            w: 0.1,
        };
        let mut e = Ev::new(
            ys.iter().map(|&y| head(0.0, y)).collect(),
            Some(stem),
            Some(true),
        );
        e.dur = Q::new(3, 2);
        e.dots_partial = true;
        e
    }

    #[test]
    fn a_chord_dotted_by_some_heads_is_parted_into_two_lengths() {
        // heads a third apart; the one dot at the lower head's height (a head in a space)
        let mut out = vec![chord(&[10.0, 9.0])];
        part_by_dots(&mut out, &[(0, vec![10.0])], 1.0);
        assert_eq!(out.len(), 2);
        assert_eq!(
            (out[0].heads.len(), out[0].heads[0].y, out[0].dur),
            (1, 10.0, Q::new(3, 2))
        );
        assert_eq!(
            (out[1].heads.len(), out[1].heads[0].y, out[1].dur),
            (1, 9.0, Q::ONE)
        );
        assert!(!out[0].dots_partial && !out[1].dots_partial);
        // a head on a line: its dot half a space above it
        let mut out = vec![chord(&[10.0, 9.0])];
        part_by_dots(&mut out, &[(0, vec![9.5])], 1.0);
        assert_eq!(
            out.len(),
            1,
            "half a space from both heads: not plainly one's"
        );
        let mut out = vec![chord(&[10.0, 8.5])];
        part_by_dots(&mut out, &[(0, vec![8.0])], 1.0);
        assert_eq!((out.len(), out[0].heads[0].y), (2, 8.5));
    }

    #[test]
    fn a_second_with_one_dot_is_not_parted() {
        // a line and the space above: one dot there may be either head's
        let mut out = vec![chord(&[10.0, 9.5])];
        part_by_dots(&mut out, &[(0, vec![9.5])], 1.0);
        assert_eq!(out.len(), 1);
    }

    #[test]
    fn a_shared_dot_goes_to_the_note_whose_voices_then_stay_two() {
        // read: quarters at 0, 4, 8, 12 in a bar of four. Unread: stems up, quarters at 0, 4,
        // the shared head at 8 and a quarter at 12; stem down, the shared head at 8 and an
        // eighth at 14. The dot is the lower voice's: dotted, the upper would sound on into the
        // quarter at 12, which then needs a voice of its own
        let read = vec![[0.0, 4.0, 8.0, 12.0]
            .map(|x| note(x, Q::ONE, true))
            .to_vec()];
        let mut shared_up = note(8.0, Q::new(3, 2), true);
        let mut shared_down = note(8.0, Q::new(3, 2), false);
        shared_up.dots_shared = 1;
        shared_down.dots_shared = 1;
        let unread = vec![
            note(0.0, Q::ONE, true),
            note(4.0, Q::ONE, true),
            shared_up,
            shared_down,
            note(12.0, Q::ONE, true),
            note(14.0, Q::new(1, 2), false),
        ];
        let staves = [
            StaffIn {
                part: "P1",
                events: &read[0],
                read: Some(&read),
            },
            StaffIn {
                part: "P2",
                events: &unread,
                read: None,
            },
        ];
        assert!(spacing::solve(&staves, 1.0, Q::int(4), 16.0).is_err());
        let solved = solve(&staves, 1.0, Q::int(4), 16.0).unwrap();
        let voices = solved[1].as_ref().unwrap();
        assert_eq!(voices.len(), 2);
        let at_8 = |e: &&Ev| e.is_note() && e.x == 8.0;
        let lens: Vec<(bool, Q)> = (voices.iter().flatten().filter(at_8))
            .map(|e| (e.up == Some(true), e.dur))
            .collect();
        assert!(lens.contains(&(true, Q::ONE)) && lens.contains(&(false, Q::new(3, 2))));
    }
}