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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use crate::{
    libr::{ ModeObj, get_all_scale_objs, ionian },
    theory::{
        traits::{
            VecWrapper, ToChord, ToRootedChord, ToPCs, ModeIteratorSpawner, ToScaleTry, ToNote,
            AsScaleTry, AsRelativeIntervals, ScaleIteratorSpawner
        },
        Steps, Chord, Scale, Note, RootedChord, PC, Interval
    },
};

use fnrs::Sequence;

/// Given a scale in the form of [Steps][Steps], find all the chords build from each scale degree.
/// `chord_size` determines the size of the chord, so 4 will result in chords with 4 notes.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::*, libr };
/// let chords = find_scale_chords(&libr::ionian::steps(), 3);
/// assert_eq!(
///     (&chords[0], &chords[6]),
///     (&Chord::new(MAJOR), &Chord::new(MINOR_DIMINISHED))
/// );
/// ```
pub fn find_scale_chords(steps: &Steps, chord_size: usize) -> Vec<Chord>{
    let len = steps.len();
    let mut chords = Vec::new();
    for (i, _) in steps.scale_iter(Note::ZERO).enumerate().take(len){
        let mut chord = Vec::new();
        for note in steps.scale_iter(Note::ZERO).skip(i).step_by(2).take(chord_size){
            chord.push(note);
        }
        chords.push(Scale(chord).to_chord());
    }
    chords
}

/// Given a scale in the form of [Steps][Steps], find all the rooted chord build from each scale
/// degree.
/// `tonic` determines the tonic/root/first note of the scale.
/// `chord_size` determines the size of the chord, so 4 will result in chords with 4 notes.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::*, libr };
/// let chords = find_rooted_scale_chords(&libr::ionian::steps(), Note::C1, 3);
/// assert_eq!(
///     (&chords[0], &chords[6]),
///     (
///         &RootedChord{ root: Note::C1, chord: Chord::new(MAJOR) },
///         &RootedChord{ root: Note::B2, chord: Chord::new(MINOR_DIMINISHED) }
///     )
/// );
/// ```
pub fn find_rooted_scale_chords(steps: &Steps, tonic: Note, chord_size: usize) -> Vec<RootedChord>{
    let len = steps.len();
    let mut chords = Vec::new();
    for (i, _) in steps.scale_iter(tonic).enumerate().take(len){
        let mut chord = Vec::new();
        for note in steps.scale_iter(tonic).skip(i).step_by(2).take(chord_size){
            chord.push(note);
        }
        chords.push(Scale(chord).to_rooted_chord());
    }
    chords
}

/// Given a [Scale][Scale], try to find a matching [ModeObj][ModeObj].
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::*, libr::* };
/// let mo = find_scale(&Scale::wrap(vec![
///     Note::A1, Note::B1, Note::C1, Note::D1, Note::E1, Note::F1, Note::G1
/// ]).unwrap()).unwrap();
/// assert_eq!(&mo.fam_name, "Ionian");
/// assert_eq!(&mo.mode_name, "Aeolian");
/// assert_eq!(mo.mode_nr, 5);
/// ```
pub fn find_scale(scale: &Scale) -> Option<ModeObj>{
    let steps = scale.as_octave_steps()?;
    let scales = get_all_scale_objs();
    for sc in scales{
        if let Some((mode, msteps)) = sc.steps.clone().mode_nr_of_this(&steps){
            return Option::Some(ModeObj{
                steps: msteps,
                fam_name: sc.family_name(),
                mode_name: sc.get_mode_name(mode),
                mode_nr: mode,
            });
        }
    }
    Option::None
}

/// Given an [Scale][Scale], try to find all super strings.
/// A super string is a super sequence that contains the sub string uninterrupted.
/// For example "abcd" is a super string of "bc" but not of "bd".
/// Output does not come in [Scale][Scale] form but as pairs of [PC][PC] and [ModeObj][ModeObj].
/// The relevant [Scale][Scale] can be constructed from this if needed.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::* };
/// let scale = Scale::wrap(vec![Note::C1, Note::D1, Note::E1, Note::F1, Note::G1]).unwrap();
/// let mut res = find_scale_superstring(&scale)
///     .into_iter().map(|(pc, mo)| (pc, mo.fam_name, mo.mode_nr));
/// assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 0)));
/// assert_eq!(res.next(), Some((PC::A, "Ionian".to_string(), 2)));
/// assert_eq!(res.next(), Some((PC::As, "Ionian".to_string(), 3)));
/// ```
pub fn find_scale_superstring(scale: &Scale) -> Vec<(PC, ModeObj)>{
    let pcs = scale.clone().to_pcs();
    let scales = get_all_scale_objs();
    let mut res = Vec::new();
    for sc in scales{
        for (i, mode) in sc.steps.clone().mode_iter().enumerate(){
            for j in 0..12{
                let tonic = Note(j);
                // shouldn't be able to fail as it does not depend on input
                let modescale = mode.clone().to_scale_try(tonic).unwrap().to_pcs();
                if modescale.has_seq(&pcs){
                    res.push((modescale[0],
                        ModeObj{
                            steps: mode.clone(),
                            fam_name: sc.family_name(),
                            mode_name: sc.get_mode_name(i),
                            mode_nr: i,
                        })
                    );
                }
            }
        }
    }
    res
}

/// Finds all the scales that are a super set of the set of notes given.
/// When `same_tonic` is true, it only gives scales that have the same note as the
/// first note in the set(ordered set shortly) as the tonic.
/// Output does not come in [Scale][Scale] form but as pairs of [PC][PC] and [ModeObj][ModeObj].
/// The relevant [Scale][Scale] can be constructed from this if needed.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::* };
/// let scale = vec![PC::C, PC::D, PC::E, PC::F, PC::G];
/// let res = find_scale_superset(&scale, false);
/// assert_eq!(res.len(), 35);
/// let mut res = find_scale_superset(&scale, true)
///     .into_iter().map(|(pc, mo)| (pc, mo.fam_name, mo.mode_nr));
/// assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 0)));
/// assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 4)));
/// assert_eq!(res.next(), Some((PC::C, "Harmonic Major".to_string(), 0)));
/// ```
pub fn find_scale_superset(scale: &[PC], same_tonic: bool) -> Vec<(PC, ModeObj)>{
    let target_tonic = scale[0].to_note().0;
    let scales = get_all_scale_objs();
    let mut res = Vec::new();
    for sc in scales{
        for (i, mode) in sc.steps.clone().mode_iter().enumerate(){
            for tonic in 0..12{
                if same_tonic && tonic != target_tonic { continue; }
                let notes = mode.clone().to_scale_try(Note(tonic)).unwrap().to_pcs();
                let mut has = true;
                'outer: for a in scale{
                    for b in &notes{
                        if a == b { continue 'outer; }
                    }
                    has = false;
                }
                if has {
                    res.push(
                        (notes[0], ModeObj{
                            steps: mode.clone(),
                            fam_name: sc.family_name(),
                            mode_name: sc.get_mode_name(i),
                            mode_nr: i,
                        })
                    );
                }
            }
        }
    }
    res
}

/// Finds all the scales where the input is the I chord.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::* };
/// let mut res = find_chordscales(&[PC::F, PC::A, PC::C, PC::E])
///     .into_iter().map(|mo| (mo.fam_name, mo.mode_nr));
/// assert_eq!(res.next(), Some(("Ionian".to_string(), 0)));
/// assert_eq!(res.next(), Some(("Ionian".to_string(), 3)));
/// assert_eq!(res.next(), Some(("Harmonic Minor".to_string(), 5)));
/// ```
pub fn find_chordscales(pcs: &[PC]) -> Vec<ModeObj>{
    let mut res = Vec::new();
    if pcs.is_empty() { return res; }
    let tonic = pcs[0].to_note();
    let scales = get_all_scale_objs();
    for sc in scales{
        'outer: for (i, mode) in sc.steps.clone().mode_iter().enumerate(){
            let modescale = mode.as_scale_try(tonic).unwrap().to_pcs();
            for j in 0..pcs.len(){
                if j * 2 > modescale.len() - 1 {
                    continue 'outer;
                }
                if pcs[j] != modescale[j * 2]{
                    continue 'outer;
                }
            }
            res.push(
                ModeObj{
                    steps: mode.clone(),
                    fam_name: sc.family_name(),
                    mode_name: sc.get_mode_name(i),
                    mode_nr: i,
                }
            );
        }
    }
    res
}

/// Finds all the scales with the given relative properties.
///
/// Example:
/// ```
/// use music_theory::{ theory::*, query::* };
/// let res = find_scale_from_ionian_relative(
///     &[Interval::NAT, Interval::NAT, Interval::NAT, Interval::NAT,
///     Interval::NAT, Interval::NAT, Interval::NAT]
/// ).unwrap();
/// assert_eq!(&res.fam_name, "Ionian");
/// assert_eq!(res.mode_nr, 0);
/// ```
pub fn find_scale_from_ionian_relative(rel: &[Interval]) -> Option<ModeObj>{
    let scales = get_all_scale_objs();
    for sc in scales{
        'outer: for (i, mode) in sc.steps.clone().mode_iter().enumerate(){
            let rl = mode.as_relative_intervals(&ionian::steps()).unwrap();
            if rel.len() != rl.len() { continue; }
            for (i, rn) in rel.iter().enumerate(){
                if rn != &rl[i] { continue 'outer; }
            }
            return Some(ModeObj{
                steps: mode,
                fam_name: sc.family_name(),
                mode_name: sc.get_mode_name(i),
                mode_nr: i,
            });
        }
    }
    None
}

#[cfg(test)]
mod tests{
    use super::*;
    use crate::theory::*;

    #[test]
    fn test_find_scale_chords(){
        let chords = find_scale_chords(&crate::libr::ionian::steps(), 3);
        assert_eq!(
            chords,
            vec![
                Chord::new(MAJOR),
                Chord::new(MINOR),
                Chord::new(MINOR),
                Chord::new(MAJOR),
                Chord::new(MAJOR),
                Chord::new(MINOR),
                Chord::new(MINOR_DIMINISHED)
            ]
        );
    }

    #[test]
    fn test_find_rooted_scale_chords(){
        let chords = find_rooted_scale_chords(&crate::libr::ionian::steps(), Note::C1, 3);
        assert_eq!(
            chords,
            vec![
                RootedChord{ root: Note::C1, chord: Chord::new(MAJOR) },
                RootedChord{ root: Note::D1, chord: Chord::new(MINOR) },
                RootedChord{ root: Note::E1, chord: Chord::new(MINOR) },
                RootedChord{ root: Note::F1, chord: Chord::new(MAJOR) },
                RootedChord{ root: Note::G1, chord: Chord::new(MAJOR) },
                RootedChord{ root: Note::A2, chord: Chord::new(MINOR) },
                RootedChord{ root: Note::B2, chord: Chord::new(MINOR_DIMINISHED) }
            ]
        );
    }

    #[test]
    fn test_find_scale(){
        let hs = Interval(1);
        let ws = Interval(2);
        let ts = Interval(3);
        assert_eq!(
            find_scale(&Scale(vec![
                Note::C1, Note::D1, Note::E1, Note::F1, Note::G1, Note::A2, Note::B2
            ])),
            Some(ModeObj {
                steps: Steps(vec![ws, ws, hs, ws, ws, ws, hs]),
                fam_name: "Ionian".to_string(),
                mode_name: "Ionian".to_string(),
                mode_nr: 0
            })
        );
        assert_eq!(
            find_scale(&Scale(vec![
                Note::A1, Note::B1, Note::C1, Note::D1, Note::E1, Note::F1, Note::G1
            ])),
            Some(ModeObj {
                steps: Steps(vec![ws, hs, ws, ws, hs, ws, ws]),
                fam_name: "Ionian".to_string(),
                mode_name: "Aeolian".to_string(),
                mode_nr: 5
            })
        );
        assert_eq!(
            find_scale(&Scale(vec![
                Note::A1, Note::B1, Note::C1, Note::D1, Note::E1, Note::F1, Note::GS1
            ])),
            Some(ModeObj {
                steps: Steps(vec![ws, hs, ws, ws, hs, ts, hs]),
                fam_name: "Harmonic Minor".to_string(),
                mode_name: "Harmonic Minor".to_string(),
                mode_nr: 0
            })
        );
        assert_eq!(
            find_scale(&Scale(vec![
                Note::A1, Note::B1, Note::C1, Note::D1, Note::E1, Note::F1
            ])),
            None
        );
    }

    #[test]
    fn test_find_scale_superstring(){
        let scale = Scale(vec![Note::C1, Note::D1, Note::E1, Note::F1, Note::G1]);
        let mut res = find_scale_superstring(&scale)
            .into_iter().map(|(pc, mo)| (pc, mo.fam_name, mo.mode_nr));
        assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 0)));
        assert_eq!(res.next(), Some((PC::A, "Ionian".to_string(), 2)));
        assert_eq!(res.next(), Some((PC::As, "Ionian".to_string(), 3)));
        assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 4)));
        assert_eq!(res.next(), Some((PC::A, "Ionian".to_string(), 5)));
        assert_eq!(res.next(), Some((PC::B, "Ionian".to_string(), 6)));
        assert_eq!(res.next(), Some((PC::C, "Harmonic Major".to_string(), 0)));
        assert_eq!(res.next(), Some((PC::Gs, "Harmonic Major".to_string(), 5)));
        assert_eq!(res.next(), Some((PC::B, "Harmonic Major".to_string(), 6)));
        assert_eq!(res.next(), Some((PC::Gs, "Melodic Minor".to_string(), 2)));
        assert_eq!(res.next(), Some((PC::As, "Melodic Minor".to_string(), 3)));
        assert_eq!(res.next(), Some((PC::C, "Melodic Minor".to_string(), 4)));
        assert_eq!(res.next(), None);
    }

    #[test]
    fn test_find_scale_superset(){
        let scale = vec![PC::C, PC::D, PC::E, PC::F, PC::G];
        let res = find_scale_superset(&scale, false);
        assert_eq!(res.len(), 35);
        let mut res = find_scale_superset(&scale, true)
            .into_iter().map(|(pc, mo)| (pc, mo.fam_name, mo.mode_nr));
        assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 0)));
        assert_eq!(res.next(), Some((PC::C, "Ionian".to_string(), 4)));
        assert_eq!(res.next(), Some((PC::C, "Harmonic Major".to_string(), 0)));
        assert_eq!(res.next(), Some((PC::C, "Melodic Minor".to_string(), 4)));
        assert_eq!(res.next(), Some((PC::C, "Enigmatic Major".to_string(), 3)));
        assert_eq!(res.next(), None);
    }

    #[test]
    fn test_find_chord_scales(){
        let mut res = find_chordscales(&[PC::F, PC::A, PC::C, PC::E])
            .into_iter().map(|mo| (mo.fam_name, mo.mode_nr));
        assert_eq!(res.next(), Some(("Ionian".to_string(), 0)));
        assert_eq!(res.next(), Some(("Ionian".to_string(), 3)));
        assert_eq!(res.next(), Some(("Harmonic Minor".to_string(), 5)));
        assert_eq!(res.next(), Some(("Harmonic Major".to_string(), 0)));
        assert_eq!(res.next(), Some(("Double Harmonic Major".to_string(), 0)));
        assert_eq!(res.next(), Some(("Double Harmonic Major".to_string(), 1)));
        assert_eq!(res.next(), Some(("Neapolitan Minor".to_string(), 1)));
        assert_eq!(res.next(), Some(("Neapolitan Minor".to_string(), 5)));
        assert_eq!(res.next(), None);
    }

    #[test]
    fn test_find_scale_from_ionian_relative(){
        let res = find_scale_from_ionian_relative(
            &[Interval::NAT, Interval::NAT, Interval::NAT, Interval::NAT,
            Interval::NAT, Interval::NAT, Interval::NAT]
        ).unwrap();
        assert_eq!(&res.fam_name, "Ionian");
        assert_eq!(res.mode_nr, 0);
        assert_eq!(
            find_scale_from_ionian_relative(&[
                Interval::NAT, Interval::FLAT, Interval::NAT, Interval::NAT,
                Interval::NAT, Interval::NAT, Interval::NAT
            ]),
            None
        );
    }
}