1use num::BigInt;
10use num::integer::Integer;
11
12use crate::common::numbertools::{float_ratio, limit_denominator};
13use crate::common::stringtools::get_num_from_str;
14use crate::defaults::{FloatType, UnsignedIntegerType};
15
16pub const VALID_DENOMINATORS: [UnsignedIntegerType; 8] = [1, 2, 4, 8, 16, 32, 64, 128];
19
20#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
23pub enum MeterDivision {
24 Fast,
26 Slow,
28 #[default]
30 None,
31}
32
33impl MeterDivision {
34 #[must_use]
36 pub fn music21_name(self) -> &'static str {
37 match self {
38 Self::Fast => "FAST",
39 Self::Slow => "SLOW",
40 Self::None => "NONE",
41 }
42 }
43}
44
45#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
47pub struct SlashMeter {
48 pub numerator: UnsignedIntegerType,
50 pub denominator: UnsignedIntegerType,
52 pub division: MeterDivision,
54}
55
56#[derive(Clone, Debug, Eq, PartialEq)]
59pub enum SlashError {
60 Meter(String),
63 TimeSignature(String),
66 Unreadable(String),
69}
70
71impl std::fmt::Display for SlashError {
72 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 match self {
74 Self::Meter(message) | Self::TimeSignature(message) | Self::Unreadable(message) => {
75 formatter.write_str(message)
76 }
77 }
78 }
79}
80
81impl std::error::Error for SlashError {}
82
83fn leading_ratio(text: &str) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
86 let (numerator, rest) = text.split_at(text.find(|c: char| !c.is_ascii_digit())?);
87 let rest = rest.strip_prefix('/')?;
88 let end = rest
89 .find(|c: char| !c.is_ascii_digit())
90 .unwrap_or(rest.len());
91 let denominator = &rest[..end];
92 if numerator.is_empty() || denominator.is_empty() {
93 return None;
94 }
95 Some((numerator.parse().ok()?, denominator.parse().ok()?))
96}
97
98pub fn slash_to_tuple(value: &str) -> Result<SlashMeter, SlashError> {
113 let (numbers, words) = get_num_from_str(value, "0123456789/.");
114 let words = words.to_lowercase();
115 let division = if words.contains("slow") {
116 MeterDivision::Slow
117 } else if words.contains("fast") {
118 MeterDivision::Fast
119 } else {
120 MeterDivision::None
121 };
122 let Some((numerator, denominator)) = leading_ratio(numbers.trim()) else {
123 return Err(SlashError::Meter(format!(
124 "slashToTuple() cannot find two part fraction for {value}"
125 )));
126 };
127 Ok(SlashMeter {
128 numerator,
129 denominator,
130 division,
131 })
132}
133
134#[must_use]
143pub fn slash_compound_to_fraction(value: &str) -> Vec<(UnsignedIntegerType, UnsignedIntegerType)> {
144 value
145 .trim()
146 .split('+')
147 .filter_map(|part| slash_to_tuple(part).ok())
148 .map(|read| (read.numerator, read.denominator))
149 .collect()
150}
151
152pub fn slash_mixed_to_fraction(
170 value: &str,
171) -> Result<(Vec<(UnsignedIntegerType, UnsignedIntegerType)>, bool), SlashError> {
172 let mut read: Vec<(UnsignedIntegerType, Option<UnsignedIntegerType>)> = Vec::new();
173 let mut summed = false;
174 for part in value.trim().split('+') {
175 if part.contains('/') {
176 let ratio = slash_to_tuple(part).map_err(|_| {
177 SlashError::TimeSignature(format!("Cannot create time signature from \"{value}\""))
178 })?;
179 read.push((ratio.numerator, Some(ratio.denominator)));
180 continue;
181 }
182 let numerator = part.trim().parse().map_err(|_| {
183 SlashError::Unreadable(format!(
184 "Cannot parse this file -- this error often comes up if the musicxml \
185 pickled file is out of date after a change in musicxml/__init__.py . \
186 Clear your temp directory of .p and .p.gz files and try again. \
187 Time Signature: {value} "
188 ))
189 })?;
190 read.push((numerator, None));
191 summed = true;
192 }
193
194 let mut parts = Vec::with_capacity(read.len());
195 for (index, (numerator, denominator)) in read.iter().enumerate() {
196 let denominator = denominator
198 .or_else(|| read[index + 1..].iter().find_map(|(_, later)| *later))
199 .ok_or_else(|| {
200 SlashError::Meter(format!("cannot match denominator to numerator in: {value}"))
201 })?;
202 parts.push((*numerator, denominator));
203 }
204 Ok((parts, summed))
205}
206
207#[must_use]
217pub fn fraction_to_slash_mixed(
218 fractions: &[(UnsignedIntegerType, UnsignedIntegerType)],
219) -> Vec<(String, UnsignedIntegerType)> {
220 let mut runs: Vec<(Vec<String>, UnsignedIntegerType)> = Vec::new();
221 for (numerator, denominator) in fractions {
222 match runs.last_mut() {
223 Some((numerators, shared)) if shared == denominator => {
224 numerators.push(numerator.to_string());
225 }
226 _ => runs.push((vec![numerator.to_string()], *denominator)),
227 }
228 }
229 runs.into_iter()
230 .map(|(numerators, denominator)| (numerators.join("+"), denominator))
231 .collect()
232}
233
234#[must_use]
249pub fn fraction_sum(fractions: &[(BigInt, BigInt)]) -> (BigInt, BigInt) {
250 let Some((_, first)) = fractions.first() else {
251 return (BigInt::from(0), BigInt::from(1));
252 };
253 if fractions
254 .iter()
255 .all(|(_, denominator)| denominator == first)
256 {
257 let numerator = fractions.iter().map(|(numerator, _)| numerator).sum();
258 return (numerator, first.clone());
259 }
260 let common = fractions
261 .iter()
262 .fold(BigInt::from(1), |common, (_, denominator)| {
263 common.lcm(denominator)
264 });
265 let numerator = fractions
266 .iter()
267 .map(|(numerator, denominator)| numerator * (&common / denominator))
268 .sum();
269 (numerator, common)
270}
271
272#[must_use]
283pub fn proportion_to_fraction(value: FloatType) -> Option<(BigInt, BigInt)> {
284 let (numerator, denominator) = float_ratio(value)?;
285 limit_denominator(&numerator, &denominator, &BigInt::from(16)).ok()
286}
287
288#[must_use]
291pub fn fractions_upward(
292 numerator: UnsignedIntegerType,
293 denominator: UnsignedIntegerType,
294) -> Vec<String> {
295 let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
296 let mut out = Vec::new();
297 if denominator >= largest {
298 return out;
299 }
300 let (mut numerator, mut denominator) = (numerator * 2, denominator * 2);
301 while denominator <= largest {
302 out.push(format!("{numerator}/{denominator}"));
303 numerator *= 2;
304 denominator *= 2;
305 }
306 out
307}
308
309#[must_use]
312pub fn fractions_downward(
313 numerator: UnsignedIntegerType,
314 denominator: UnsignedIntegerType,
315) -> Vec<String> {
316 let smallest = VALID_DENOMINATORS[0];
317 let mut out = Vec::new();
318 if denominator <= smallest || !numerator.is_multiple_of(2) {
319 return out;
320 }
321 let (mut numerator, mut denominator) = (numerator / 2, denominator / 2);
322 loop {
323 out.push(format!("{numerator}/{denominator}"));
324 if !numerator.is_multiple_of(2) || denominator <= smallest {
325 break;
326 }
327 numerator /= 2;
328 denominator /= 2;
329 }
330 out
331}
332
333#[must_use]
337pub fn additive_multiples_upward(
338 numerator: UnsignedIntegerType,
339 denominator: UnsignedIntegerType,
340) -> Vec<Vec<String>> {
341 let mut out = Vec::new();
342 if numerator <= 1 {
343 return out;
344 }
345 let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
346 let limit = if numerator > 16 { numerator } else { 16 };
347 let (mut denominator, mut count) = (denominator, numerator);
348 while denominator <= largest && count <= limit {
349 out.push(vec![format!("1/{denominator}"); count as usize]);
350 denominator *= 2;
351 count *= 2;
352 }
353 out
354}
355
356#[must_use]
360pub fn additive_multiples_halved(
361 numerator: UnsignedIntegerType,
362 denominator: UnsignedIntegerType,
363) -> Vec<Vec<String>> {
364 let mut out = Vec::new();
365 if !numerator.is_multiple_of(2) || denominator < 2 {
366 return out;
367 }
368 let (mut count, mut denominator) = (numerator / 2, denominator / 2);
369 while denominator >= 1 && count > 1 {
370 out.push(vec![format!("1/{denominator}"); count as usize]);
371 if !count.is_multiple_of(2) || denominator == 1 {
372 break;
373 }
374 denominator /= 2;
375 count /= 2;
376 }
377 out
378}
379
380#[must_use]
383pub fn additive_multiples(
384 numerator: UnsignedIntegerType,
385 denominator: UnsignedIntegerType,
386) -> Vec<Vec<String>> {
387 let mut out = Vec::new();
388 if numerator <= 3 || !numerator.is_multiple_of(2) {
389 return out;
390 }
391 let mut divisor = 2;
392 while numerator.is_multiple_of(divisor) {
393 let count = numerator / divisor;
394 if count <= 1 {
395 break;
396 }
397 out.push(vec![format!("{count}/{denominator}"); divisor as usize]);
398 divisor *= 2;
399 }
400 out
401}
402
403#[must_use]
407pub fn additive_multiples_downward(
408 numerator: UnsignedIntegerType,
409 denominator: UnsignedIntegerType,
410) -> Vec<Vec<String>> {
411 let largest = VALID_DENOMINATORS[VALID_DENOMINATORS.len() - 1];
412 let mut out = Vec::new();
413 if denominator >= largest || numerator != 1 {
414 return out;
415 }
416 let (mut count, mut denominator) = (2usize, denominator * 2);
417 while denominator <= largest {
418 out.push(vec![format!("{numerator}/{denominator}"); count]);
419 denominator *= 2;
420 count *= 2;
421 }
422 out
423}
424
425#[must_use]
433pub fn division_options_algo(
434 numerator: UnsignedIntegerType,
435 denominator: UnsignedIntegerType,
436) -> Vec<Vec<String>> {
437 let mut options: Vec<Vec<String>> = Vec::new();
438
439 if numerator > 3 && numerator.is_multiple_of(3) {
441 options.push(vec![format!("3/{denominator}"); (numerator / 3) as usize]);
442 }
443 let groupings: &[&[UnsignedIntegerType]] = match numerator {
445 5 => &[&[2, 3], &[3, 2]],
446 7 => &[&[2, 2, 3], &[3, 2, 2], &[2, 3, 2]],
447 10 => &[&[2, 2, 3, 3]],
448 _ => &[],
449 };
450 for grouping in groupings {
451 options.push(
452 grouping
453 .iter()
454 .map(|count| format!("{count}/{denominator}"))
455 .collect(),
456 );
457 }
458 options.extend(additive_multiples_upward(numerator, denominator));
459 options.extend(additive_multiples_halved(numerator, denominator));
460 options.push(vec![format!("{numerator}/{denominator}")]);
461 options.extend(additive_multiples(numerator, denominator));
462 options.extend(additive_multiples_downward(numerator, denominator));
463 for written in fractions_downward(numerator, denominator) {
464 options.push(vec![written]);
465 }
466 for written in fractions_upward(numerator, denominator) {
467 options.push(vec![written]);
468 }
469 let mut seen: Vec<Vec<String>> = Vec::new();
471 options.retain(|option| {
472 if seen.contains(option) {
473 return false;
474 }
475 seen.push(option.clone());
476 true
477 });
478 options
479}
480
481#[must_use]
484pub fn division_options_preset(
485 numerator: UnsignedIntegerType,
486 denominator: UnsignedIntegerType,
487) -> Vec<Vec<String>> {
488 if numerator != 5 {
489 return Vec::new();
490 }
491 vec![
492 vec![
493 format!("2/{denominator}"),
494 format!("2/{denominator}"),
495 format!("1/{denominator}"),
496 ],
497 vec![
498 format!("2/{denominator}"),
499 format!("1/{denominator}"),
500 format!("2/{denominator}"),
501 ],
502 ]
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508
509 fn strings(options: &[Vec<String>]) -> Vec<String> {
510 options.iter().map(|option| option.join(",")).collect()
511 }
512
513 #[test]
514 fn a_meter_is_read_with_its_word() {
515 let read = slash_to_tuple("7/32").unwrap();
516 assert_eq!((read.numerator, read.denominator), (7, 32));
517 assert_eq!(read.division, MeterDivision::None);
518 assert_eq!(
519 slash_to_tuple("Fast 6/8").unwrap().division,
520 MeterDivision::Fast
521 );
522 assert_eq!(
523 slash_to_tuple("3.0/4.0").unwrap_err(),
524 SlashError::Meter("slashToTuple() cannot find two part fraction for 3.0/4.0".into())
525 );
526 }
527
528 #[test]
529 fn a_mixed_meter_fails_as_music21_fails() {
530 let (parts, summed) = slash_mixed_to_fraction("3+2+5/8+3/4+2+1+4/16").unwrap();
531 assert_eq!(
532 parts,
533 [(3, 8), (2, 8), (5, 8), (3, 4), (2, 16), (1, 16), (4, 16)]
534 );
535 assert!(summed);
536 assert_eq!(
537 slash_mixed_to_fraction("4/4").unwrap(),
538 (vec![(4, 4)], false)
539 );
540 assert_eq!(
541 slash_mixed_to_fraction("3+2+5/8+3/4+2+1+4").unwrap_err(),
542 SlashError::Meter("cannot match denominator to numerator in: 3+2+5/8+3/4+2+1+4".into())
543 );
544 assert_eq!(
545 slash_mixed_to_fraction("3.0/4.0").unwrap_err(),
546 SlashError::TimeSignature("Cannot create time signature from \"3.0/4.0\"".into())
547 );
548 assert!(matches!(
549 slash_mixed_to_fraction("x+3/4"),
550 Err(SlashError::Unreadable(_))
551 ));
552 }
553
554 #[test]
555 fn fractions_sum_without_reducing() {
556 let big = |pairs: &[(i32, i32)]| -> Vec<(BigInt, BigInt)> {
557 pairs
558 .iter()
559 .map(|(n, d)| (BigInt::from(*n), BigInt::from(*d)))
560 .collect()
561 };
562 let sum = |pairs: &[(i32, i32)]| fraction_sum(&big(pairs));
563 assert_eq!(
564 sum(&[(1, 13), (2, 17)]),
565 (BigInt::from(43), BigInt::from(221))
566 );
567 assert_eq!(sum(&[(3, 4), (1, 2)]), (BigInt::from(5), BigInt::from(4)));
568 assert_eq!(sum(&[]), (BigInt::from(0), BigInt::from(1)));
569 assert_eq!(
570 proportion_to_fraction(0.83333),
571 Some((BigInt::from(5), BigInt::from(6)))
572 );
573 assert_eq!(proportion_to_fraction(FloatType::NAN), None);
574 }
575
576 #[test]
577 fn the_options_are_music21s() {
578 assert_eq!(
579 strings(&division_options_algo(12, 8)),
580 [
581 "3/8,3/8,3/8,3/8",
582 "1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8,1/8",
583 "1/4,1/4,1/4,1/4,1/4,1/4",
584 "1/2,1/2,1/2",
585 "12/8",
586 "6/8,6/8",
587 "6/4",
588 "3/2",
589 "24/16",
590 "48/32",
591 "96/64",
592 "192/128",
593 ]
594 );
595 assert_eq!(
596 strings(&division_options_algo(3, 128)),
597 ["1/128,1/128,1/128", "3/128"]
598 );
599 assert_eq!(fractions_downward(12, 16), ["6/8", "3/4"]);
600 assert_eq!(strings(&additive_multiples(6, 4)), ["3/4,3/4"]);
601 assert!(additive_multiples_halved(3, 4).is_empty());
602 }
603}