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
use crate::types::{Matrix, Note, PitchGroup};
use std::{cmp::Ordering, fmt};
#[derive(Debug)]
pub struct Analysis {
notes: Vec<Note>,
records: Vec<AnalysisRecord>,
enharmonic: bool,
natural: bool,
sharp: bool,
flat: bool,
}
#[derive(Debug)]
pub struct AnalysisRecord {
pitch_group: PitchGroup,
probability: f64,
members: Vec<Note>,
offnotes: Vec<Note>,
}
pub struct Analyzer;
impl Analyzer {
#[rustfmt::skip]
pub fn score(notes: &[Note]) -> Result<Analysis, &'static str> {
let mut a = Analysis {
notes: notes.to_vec(),
records: Vec::with_capacity(12),
enharmonic: notes.iter().any(|n| n.enharmonic()),
natural: notes.iter().all(|n| n.natural()),
sharp: notes.iter().any(|n| n.sharp()),
flat: notes.iter().any(|n| n.flat()),
};
for pitch_group in PitchGroup::all().iter() {
let mut found = Vec::new();
let mut missing = Vec::new();
for note in notes {
if let Some(matrix_note) = match (a.natural, a.sharp, a.flat) {
(true, false, false) => Matrix::natural(¬e.pitch_class(), pitch_group),
(false, true, false) => Matrix::sharp(¬e.pitch_class(), pitch_group),
(false, false, true) => Matrix::flat(¬e.pitch_class(), pitch_group),
(_, _, _) => None
} {
if matrix_note == *note {
found.push(*note);
} else {
missing.push(*note);
}
} else {
missing.push(*note);
}
}
let p = found.len() as f64 / notes.len() as f64;
a.records.push(AnalysisRecord {
pitch_group: pitch_group.clone(),
probability: p,
members: found,
offnotes: missing,
});
}
a.records.sort_by(|a, b| b.probability.partial_cmp(&a.probability).unwrap());
Ok(a)
}
}
#[cfg(test)]
mod tests {
use super::PitchGroup;
use crate::analysis::Analyzer;
use crate::types::{Accidental::*, Note::*, PitchClass::*};
#[test]
fn test_score_pitchgroup() {
let notes0 = [C(Sharp), D(Sharp), F(Sharp), A(Natural), A(Sharp)];
let result0 = Analyzer::score(¬es0);
println!("Result 0: {:#?}\n", &result0);
let notes1 = [C(Sharp), D(Natural), D(Sharp), F(Sharp), B(Natural)];
let result1 = Analyzer::score(¬es1);
println!("Result 1: {:#?}\n", &result1);
let notes2 = [
C(Natural),
C(Sharp),
D(Sharp),
G(Natural),
E(Sharp),
F(Natural),
];
let result2 = Analyzer::score(¬es2);
println!("Result 2: {:#?}\n", &result2);
let notes3 = [C(Sharp), E(Natural), E(Sharp), F(Sharp), A(Sharp)];
let result3 = Analyzer::score(¬es3);
println!("Result 3: {:#?}\n", &result3);
let notes4 = [
C(Natural),
C(Sharp),
D(Natural),
E(Natural),
F(Natural),
F(Sharp),
G(Natural),
A(Natural),
B(Natural),
];
let result4 = Analyzer::score(¬es4);
println!("Result 4: {:#?}\n", &result4);
}
}