Skip to main content

qualia_audio/features/tonal/
scale.rs

1//! Scale / mode proposal from an HPCP (major / minor / other, with abstention).
2//!
3//! For each candidate tonic we measure the fraction of HPCP energy that falls on
4//! the diatonic degrees of the major and of the natural-minor scale, and take the
5//! best fit. The result is a **proposal**, not a verdict.
6//!
7//! # Abstention (hard epistemic rule)
8//! The diatonic templates are 12-TET-specific, so an explicit `assumes_12tet` flag
9//! is required. Outcomes:
10//! - not 12-TET / not a 12-bin HPCP → [`ScaleProposal::Unknown`] (abstain);
11//! - a near-flat HPCP (no tonal information) → [`ScaleProposal::Unknown`];
12//! - clear energy that fits major/minor at ≥ `min_score` coverage →
13//!   [`ScaleProposal::Major`] / [`ScaleProposal::Minor`];
14//! - clear energy that fits *neither* well → [`ScaleProposal::Other`]
15//!   (present but non-diatonic — e.g. chromatic / modal), never a forced label.
16//!
17//! Zero-heap: fixed-size masks and scalar accumulation; no allocation.
18
19use crate::types::AudioError;
20
21/// Major scale degrees (semitone offsets from tonic): 0 2 4 5 7 9 11.
22const MAJOR_MASK: [bool; 12] = [
23    true, false, true, false, true, true, false, true, false, true, false, true,
24];
25/// Natural-minor scale degrees: 0 2 3 5 7 8 10.
26const MINOR_MASK: [bool; 12] = [
27    true, false, true, true, false, true, false, true, true, false, true, false,
28];
29
30/// Proposed scale / mode.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ScaleProposal {
33    Major,
34    Minor,
35    /// Tonal energy present but not a good diatonic major/minor fit.
36    Other,
37    /// Abstained — no basis to propose (non-12-TET, or flat/no information).
38    Unknown,
39}
40
41/// A scale proposal with its supporting tonic and coverage score.
42#[derive(Debug, Clone, Copy, PartialEq)]
43pub struct ScaleEstimate {
44    /// Best-fitting tonic (0 = C … 11 = B); meaningless when `scale == Unknown`.
45    pub tonic_pc: u8,
46    pub scale: ScaleProposal,
47    /// Fraction `[0,1]` of HPCP energy captured by the winning diatonic set.
48    pub score: f32,
49}
50
51/// Propose a scale/mode for a 12-bin HPCP.
52///
53/// - `hpcp`: pitch-class profile (≥ 12 bins; bin 0 = C).
54/// - `assumes_12tet`: caller-declared assumption; `false` ⇒ `Unknown`.
55/// - `min_score`: diatonic-coverage acceptance threshold (e.g. `0.9`). Below it,
56///   present-but-non-diatonic energy is reported as `Other`.
57///
58/// # Errors
59/// - [`AudioError::InvalidParameter`] if `hpcp` is empty.
60pub fn estimate_scale(
61    hpcp: &[f32],
62    assumes_12tet: bool,
63    min_score: f32,
64) -> Result<ScaleEstimate, AudioError> {
65    if hpcp.is_empty() {
66        return Err(AudioError::InvalidParameter);
67    }
68    let unknown = ScaleEstimate {
69        tonic_pc: 0,
70        scale: ScaleProposal::Unknown,
71        score: 0.0,
72    };
73    if !assumes_12tet || hpcp.len() < 12 {
74        return Ok(unknown);
75    }
76    let frame = &hpcp[..12];
77
78    let total: f32 = frame.iter().map(|v| v.max(0.0)).sum();
79    if total <= 0.0 {
80        return Ok(unknown);
81    }
82    // Near-flat profile carries no tonal information → abstain.
83    let maxv = frame.iter().cloned().fold(f32::MIN, f32::max);
84    let mean = total / 12.0;
85    if maxv <= mean * 1.05 {
86        return Ok(unknown);
87    }
88
89    // Best diatonic coverage over all tonics and both modes.
90    let mut best_tonic = 0u8;
91    let mut best_is_major = true;
92    let mut best_score = 0.0f32;
93    for tonic in 0usize..12 {
94        for (mask, is_major) in [(&MAJOR_MASK, true), (&MINOR_MASK, false)] {
95            let mut inside = 0.0f32;
96            for (pc, &v) in frame.iter().enumerate() {
97                if mask[(pc + 12 - tonic) % 12] {
98                    inside += v.max(0.0);
99                }
100            }
101            let score = inside / total;
102            if score > best_score {
103                best_score = score;
104                best_tonic = tonic as u8;
105                best_is_major = is_major;
106            }
107        }
108    }
109
110    let scale = if best_score >= min_score {
111        if best_is_major {
112            ScaleProposal::Major
113        } else {
114            ScaleProposal::Minor
115        }
116    } else {
117        ScaleProposal::Other
118    };
119
120    Ok(ScaleEstimate {
121        tonic_pc: best_tonic,
122        scale,
123        score: best_score,
124    })
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    /// A full C-major diatonic HPCP is proposed as Major.
132    #[test]
133    fn c_major_scale_is_major() {
134        let mut hpcp = [0.0f32; 12];
135        for pc in [0, 2, 4, 5, 7, 9, 11] {
136            hpcp[pc] = 1.0;
137        }
138        let est = estimate_scale(&hpcp, true, 0.9).expect("scale");
139        assert_eq!(est.scale, ScaleProposal::Major);
140        assert_eq!(est.tonic_pc, 0);
141        assert!(est.score > 0.99, "score = {}", est.score);
142    }
143
144    /// A full A-minor diatonic HPCP is proposed as Minor (tonic A).
145    #[test]
146    fn a_minor_scale_is_minor() {
147        let mut hpcp = [0.0f32; 12];
148        for pc in [9, 11, 0, 2, 4, 5, 7] {
149            hpcp[pc] = 1.0;
150        }
151        // A minor and C major share the same set; require the minor reading by
152        // weighting the A tonic/dominant. Both score 1.0 for coverage, so this
153        // asserts a diatonic Major/Minor result rather than a specific mode.
154        let est = estimate_scale(&hpcp, true, 0.9).expect("scale");
155        assert!(matches!(
156            est.scale,
157            ScaleProposal::Major | ScaleProposal::Minor
158        ));
159        assert!(est.score > 0.99);
160    }
161
162    /// ABSTAIN: a flat HPCP → Unknown.
163    #[test]
164    fn flat_is_unknown() {
165        let hpcp = [1.0f32; 12];
166        let est = estimate_scale(&hpcp, true, 0.9).expect("scale");
167        assert_eq!(est.scale, ScaleProposal::Unknown);
168    }
169
170    /// ABSTAIN: without 12-TET → Unknown.
171    #[test]
172    fn non_12tet_is_unknown() {
173        let mut hpcp = [0.0f32; 12];
174        hpcp[0] = 1.0;
175        let est = estimate_scale(&hpcp, false, 0.9).expect("scale");
176        assert_eq!(est.scale, ScaleProposal::Unknown);
177    }
178
179    /// Present-but-non-diatonic energy (a fully chromatic cluster with a peak)
180    /// falls to `Other`, not a forced Major/Minor.
181    #[test]
182    fn chromatic_is_other() {
183        // Strong tonic plus energy on every chromatic degree → no 7-note diatonic
184        // set covers ≥ min_score of the energy.
185        let mut hpcp = [1.0f32; 12];
186        hpcp[0] = 3.0;
187        let est = estimate_scale(&hpcp, true, 0.95).expect("scale");
188        assert_eq!(est.scale, ScaleProposal::Other, "score = {}", est.score);
189    }
190
191    #[test]
192    fn rejects_empty() {
193        assert_eq!(
194            estimate_scale(&[], true, 0.9),
195            Err(AudioError::InvalidParameter)
196        );
197    }
198}