-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchord.py
1604 lines (1323 loc) · 58.1 KB
/
chord.py
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r'''
Chord estimation algorithms produce a list of intervals and labels which denote
the chord being played over each timespan. They are evaluated by comparing the
estimated chord labels to some reference, usually using a mapping to a chord
subalphabet (e.g. minor and major chords only, all triads, etc.). There is no
single 'right' way to compare two sequences of chord labels. Embracing this
reality, every conventional comparison rule is provided. Comparisons are made
over the different components of each chord (e.g. G:maj(6)/5): the root (G),
the root-invariant active semitones as determined by the quality
shorthand (maj) and scale degrees (6), and the bass interval (5).
This submodule provides functions both for comparing a sequences of chord
labels according to some chord subalphabet mapping and for using these
comparisons to score a sequence of estimated chords against a reference.
Conventions
-----------
A sequence of chord labels is represented as a list of strings, where each
label is the chord name based on the syntax of [#harte2010towards]_. Reference
and estimated chord label sequences should be of the same length for comparison
functions. When converting the chord string into its constituent parts,
* Pitch class counting starts at C, e.g. C:0, D:2, E:4, F:5, etc.
* Scale degree is represented as a string of the diatonic interval, relative to
the root note, e.g. 'b6', '#5', or '7'
* Bass intervals are represented as strings
* Chord bitmaps are positional binary vectors indicating active pitch classes
and may be absolute or relative depending on context in the code.
If no chord is present at a given point in time, it should have the label 'N',
which is defined in the variable ``mir_eval.chord.NO_CHORD``.
Metrics
-------
* :func:`mir_eval.chord.root`: Only compares the root of the chords.
* :func:`mir_eval.chord.majmin`: Only compares major, minor, and "no chord"
labels.
* :func:`mir_eval.chord.majmin_inv`: Compares major/minor chords, with
inversions. The bass note must exist in the triad.
* :func:`mir_eval.chord.mirex`: A estimated chord is considered correct if it
shares *at least* three pitch classes in common.
* :func:`mir_eval.chord.thirds`: Chords are compared at the level of major or
minor thirds (root and third), For example, both ('A:7', 'A:maj') and
('A:min', 'A:dim') are equivalent, as the third is major and minor in
quality, respectively.
* :func:`mir_eval.chord.thirds_inv`: Same as above, with inversions (bass
relationships).
* :func:`mir_eval.chord.triads`: Chords are considered at the level of triads
(major, minor, augmented, diminished, suspended), meaning that, in addition
to the root, the quality is only considered through #5th scale degree (for
augmented chords). For example, ('A:7', 'A:maj') are equivalent, while
('A:min', 'A:dim') and ('A:aug', 'A:maj') are not.
* :func:`mir_eval.chord.triads_inv`: Same as above, with inversions (bass
relationships).
* :func:`mir_eval.chord.tetrads`: Chords are considered at the level of the
entire quality in closed voicing, i.e. spanning only a single octave;
extended chords (9's, 11's and 13's) are rolled into a single octave with any
upper voices included as extensions. For example, ('A:7', 'A:9') are
equivlent but ('A:7', 'A:maj7') are not.
* :func:`mir_eval.chord.tetrads_inv`: Same as above, with inversions (bass
relationships).
* :func:`mir_eval.chord.sevenths`: Compares according to MIREX "sevenths"
rules; that is, only major, major seventh, seventh, minor, minor seventh and
no chord labels are compared.
* :func:`mir_eval.chord.sevenths_inv`: Same as above, with inversions (bass
relationships).
* :func:`mir_eval.chord.overseg`: Computes the level of over-segmentation
between estimated and reference intervals.
* :func:`mir_eval.chord.underseg`: Computes the level of under-segmentation
between estimated and reference intervals.
* :func:`mir_eval.chord.seg`: Computes the minimum of over- and
under-segmentation between estimated and reference intervals.
References
----------
.. [#harte2010towards] C. Harte. Towards Automatic Extraction of Harmony
Information from Music Signals. PhD thesis, Queen Mary University of
London, August 2010.
'''
import numpy as np
import warnings
import collections
import re
from mir_eval import util
BITMAP_LENGTH = 12
NO_CHORD = "N"
NO_CHORD_ENCODED = -1, np.array([0]*BITMAP_LENGTH), -1
X_CHORD = "X"
X_CHORD_ENCODED = -1, np.array([-1]*BITMAP_LENGTH), -1
class InvalidChordException(Exception):
r'''Exception class for suspect / invalid chord labels'''
def __init__(self, message='', chord_label=None):
self.message = message
self.chord_label = chord_label
self.name = self.__class__.__name__
super(InvalidChordException, self).__init__(message)
# --- Chord Primitives ---
def _pitch_classes():
r'''Map from pitch class (str) to semitone (int).'''
pitch_classes = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
semitones = [0, 2, 4, 5, 7, 9, 11]
return dict([(c, s) for c, s in zip(pitch_classes, semitones)])
def _scale_degrees():
r'''Mapping from scale degrees (str) to semitones (int).'''
degrees = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', '11', '12', '13']
semitones = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21]
return dict([(d, s) for d, s in zip(degrees, semitones)])
# Maps pitch classes (strings) to semitone indexes (ints).
PITCH_CLASSES = _pitch_classes()
def pitch_class_to_semitone(pitch_class):
r'''Convert a pitch class to semitone.
Parameters
----------
pitch_class : str
Spelling of a given pitch class, e.g. 'C#', 'Gbb'
Returns
-------
semitone : int
Semitone value of the pitch class.
'''
semitone = 0
for idx, char in enumerate(pitch_class):
if char == '#' and idx > 0:
semitone += 1
elif char == 'b' and idx > 0:
semitone -= 1
elif idx == 0:
semitone = PITCH_CLASSES.get(char)
else:
raise InvalidChordException(
"Pitch class improperly formed: %s" % pitch_class)
return semitone % 12
# Maps scale degrees (strings) to semitone indexes (ints).
SCALE_DEGREES = _scale_degrees()
def scale_degree_to_semitone(scale_degree):
r"""Convert a scale degree to semitone.
Parameters
----------
scale degree : str
Spelling of a relative scale degree, e.g. 'b3', '7', '#5'
Returns
-------
semitone : int
Relative semitone of the scale degree, wrapped to a single octave
Raises
------
InvalidChordException if `scale_degree` is invalid.
"""
semitone = 0
offset = 0
if scale_degree.startswith("#"):
offset = scale_degree.count("#")
scale_degree = scale_degree.strip("#")
elif scale_degree.startswith('b'):
offset = -1 * scale_degree.count("b")
scale_degree = scale_degree.strip("b")
semitone = SCALE_DEGREES.get(scale_degree, None)
if semitone is None:
raise InvalidChordException(
"Scale degree improperly formed: {}, expected one of {}."
.format(scale_degree, list(SCALE_DEGREES.keys())))
return semitone + offset
def scale_degree_to_bitmap(scale_degree, modulo=False, length=BITMAP_LENGTH):
"""Create a bitmap representation of a scale degree.
Note that values in the bitmap may be negative, indicating that the
semitone is to be removed.
Parameters
----------
scale_degree : str
Spelling of a relative scale degree, e.g. 'b3', '7', '#5'
modulo : bool, default=True
If a scale degree exceeds the length of the bit-vector, modulo the
scale degree back into the bit-vector; otherwise it is discarded.
length : int, default=12
Length of the bit-vector to produce
Returns
-------
bitmap : np.ndarray, in [-1, 0, 1], len=`length`
Bitmap representation of this scale degree.
"""
sign = 1
if scale_degree.startswith("*"):
sign = -1
scale_degree = scale_degree.strip("*")
edit_map = [0] * length
sd_idx = scale_degree_to_semitone(scale_degree)
if sd_idx < length or modulo:
edit_map[sd_idx % length] = sign
return np.array(edit_map)
# Maps quality strings to bitmaps, corresponding to relative pitch class
# semitones, i.e. vector[0] is the tonic.
QUALITIES = {
# 1 2 3 4 5 6 7
'maj': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
'min': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0],
'aug': [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
'dim': [1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
'sus4': [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
'sus2': [1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
'7': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'maj7': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1],
'min7': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
'minmaj7': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
'maj6': [1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0],
'min6': [1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0],
'dim7': [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0],
'hdim7': [1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0],
'maj9': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1],
'min9': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
'9': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'b9': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'#9': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'min11': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
'11': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'#11': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'maj13': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1],
'min13': [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
'13': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'b13': [1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
'1': [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'5': [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
'': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
def quality_to_bitmap(quality):
"""Return the bitmap for a given quality.
Parameters
----------
quality : str
Chord quality name.
Returns
-------
bitmap : np.ndarray
Bitmap representation of this quality (12-dim).
"""
if quality not in QUALITIES:
raise InvalidChordException(
"Unsupported chord quality shorthand: '%s' "
"Did you mean to reduce extended chords?" % quality)
return np.array(QUALITIES[quality])
# Maps extended chord qualities to the subset above, translating additional
# voicings to extensions as a set of scale degrees (strings).
# TODO(ejhumphrey): Revisit how minmaj7's are mapped. This is how TMC did it,
# but MMV handles it like a separate quality (rather than an add7).
EXTENDED_QUALITY_REDUX = {
'minmaj7': ('min', set(['7'])),
'maj9': ('maj7', set(['9'])),
'min9': ('min7', set(['9'])),
'9': ('7', set(['9'])),
'b9': ('7', set(['b9'])),
'#9': ('7', set(['#9'])),
'11': ('7', set(['9', '11'])),
'#11': ('7', set(['9', '#11'])),
'13': ('7', set(['9', '11', '13'])),
'b13': ('7', set(['9', '11', 'b13'])),
'min11': ('min7', set(['9', '11'])),
'maj13': ('maj7', set(['9', '11', '13'])),
'min13': ('min7', set(['9', '11', '13']))}
def reduce_extended_quality(quality):
"""Map an extended chord quality to a simpler one, moving upper voices to
a set of scale degree extensions.
Parameters
----------
quality : str
Extended chord quality to reduce.
Returns
-------
base_quality : str
New chord quality.
extensions : set
Scale degrees extensions for the quality.
"""
return EXTENDED_QUALITY_REDUX.get(quality, (quality, set()))
# --- Chord Label Parsing ---
def validate_chord_label(chord_label):
"""Test for well-formedness of a chord label.
Parameters
----------
chord : str
Chord label to validate.
"""
# This monster regexp is pulled from the JAMS chord namespace,
# which is in turn derived from the context-free grammar of
# Harte et al., 2005.
pattern = re.compile(r'''^((N|X)|(([A-G](b*|#*))((:(maj|min|dim|aug|1|5|sus2|sus4|maj6|min6|7|maj7|min7|dim7|hdim7|minmaj7|aug7|9|maj9|min9|11|maj11|min11|13|maj13|min13)(\((\*?((b*|#*)([1-9]|1[0-3]?))(,\*?((b*|#*)([1-9]|1[0-3]?)))*)\))?)|(:\((\*?((b*|#*)([1-9]|1[0-3]?))(,\*?((b*|#*)([1-9]|1[0-3]?)))*)\)))?((/((b*|#*)([1-9]|1[0-3]?)))?)?))$''') # nopep8
if not pattern.match(chord_label):
raise InvalidChordException('Invalid chord label: '
'{}'.format(chord_label))
pass
def split(chord_label, reduce_extended_chords=False):
"""Parse a chord label into its four constituent parts:
- root
- quality shorthand
- scale degrees
- bass
Note: Chords lacking quality AND interval information are major.
- If a quality is specified, it is returned.
- If an interval is specified WITHOUT a quality, the quality field is
empty.
Some examples::
'C' -> ['C', 'maj', {}, '1']
'G#:min(*b3,*5)/5' -> ['G#', 'min', {'*b3', '*5'}, '5']
'A:(3)/6' -> ['A', '', {'3'}, '6']
Parameters
----------
chord_label : str
A chord label.
reduce_extended_chords : bool
Whether to map the upper voicings of extended chords (9's, 11's, 13's)
to semitone extensions. (Default value = False)
Returns
-------
chord_parts : list
Split version of the chord label.
"""
chord_label = str(chord_label)
validate_chord_label(chord_label)
if chord_label == NO_CHORD:
return [chord_label, '', set(), '']
bass = '1'
if "/" in chord_label:
chord_label, bass = chord_label.split("/")
scale_degrees = set()
omission = False
if "(" in chord_label:
chord_label, scale_degrees = chord_label.split("(")
omission = "*" in scale_degrees
scale_degrees = scale_degrees.strip(")")
scale_degrees = set([i.strip() for i in scale_degrees.split(",")])
# Note: Chords lacking quality AND added interval information are major.
# If a quality shorthand is specified, it is returned.
# If an interval is specified WITHOUT a quality, the quality field is
# empty.
# Intervals specifying omissions MUST have a quality.
if omission and ":" not in chord_label:
raise InvalidChordException(
"Intervals specifying omissions MUST have a quality.")
quality = '' if scale_degrees else 'maj'
if ":" in chord_label:
chord_root, quality_name = chord_label.split(":")
# Extended chords (with ":"s) may not explicitly have Major qualities,
# so only overwrite the default if the string is not empty.
if quality_name:
quality = quality_name.lower()
else:
chord_root = chord_label
if reduce_extended_chords:
quality, addl_scale_degrees = reduce_extended_quality(quality)
scale_degrees.update(addl_scale_degrees)
return [chord_root, quality, scale_degrees, bass]
def join(chord_root, quality='', extensions=None, bass=''):
r"""Join the parts of a chord into a complete chord label.
Parameters
----------
chord_root : str
Root pitch class of the chord, e.g. 'C', 'Eb'
quality : str
Quality of the chord, e.g. 'maj', 'hdim7'
(Default value = '')
extensions : list
Any added or absent scaled degrees for this chord, e.g. ['4', '\*3']
(Default value = None)
bass : str
Scale degree of the bass note, e.g. '5'.
(Default value = '')
Returns
-------
chord_label : str
A complete chord label.
"""
chord_label = chord_root
if quality or extensions:
chord_label += ":%s" % quality
if extensions:
chord_label += "(%s)" % ",".join(extensions)
if bass and bass != '1':
chord_label += "/%s" % bass
validate_chord_label(chord_label)
return chord_label
# --- Chords to Numerical Representations ---
def encode(chord_label, reduce_extended_chords=False,
strict_bass_intervals=False):
"""Translate a chord label to numerical representations for evaluation.
Parameters
----------
chord_label : str
Chord label to encode.
reduce_extended_chords : bool
Whether to map the upper voicings of extended chords (9's, 11's, 13's)
to semitone extensions.
(Default value = False)
strict_bass_intervals : bool
Whether to require that the bass scale degree is present in the chord.
(Default value = False)
Returns
-------
root_number : int
Absolute semitone of the chord's root.
semitone_bitmap : np.ndarray, dtype=int
12-dim vector of relative semitones in the chord spelling.
bass_number : int
Relative semitone of the chord's bass note, e.g. 0=root, 7=fifth, etc.
"""
if chord_label == NO_CHORD:
return NO_CHORD_ENCODED
if chord_label == X_CHORD:
return X_CHORD_ENCODED
chord_root, quality, scale_degrees, bass = split(
chord_label, reduce_extended_chords=reduce_extended_chords)
root_number = pitch_class_to_semitone(chord_root)
bass_number = scale_degree_to_semitone(bass) % 12
semitone_bitmap = quality_to_bitmap(quality)
semitone_bitmap[0] = 1
for scale_degree in scale_degrees:
semitone_bitmap += scale_degree_to_bitmap(scale_degree,
reduce_extended_chords)
semitone_bitmap = (semitone_bitmap > 0).astype(int)
if not semitone_bitmap[bass_number] and strict_bass_intervals:
raise InvalidChordException(
"Given bass scale degree is absent from this chord: "
"%s" % chord_label, chord_label)
else:
semitone_bitmap[bass_number] = 1
return root_number, semitone_bitmap, bass_number
def encode_many(chord_labels, reduce_extended_chords=False):
"""Translate a set of chord labels to numerical representations for sane
evaluation.
Parameters
----------
chord_labels : list
Set of chord labels to encode.
reduce_extended_chords : bool
Whether to map the upper voicings of extended chords (9's, 11's, 13's)
to semitone extensions.
(Default value = False)
Returns
-------
root_number : np.ndarray, dtype=int
Absolute semitone of the chord's root.
interval_bitmap : np.ndarray, dtype=int
12-dim vector of relative semitones in the given chord quality.
bass_number : np.ndarray, dtype=int
Relative semitones of the chord's bass notes.
"""
num_items = len(chord_labels)
roots, basses = np.zeros([2, num_items], dtype=int)
semitones = np.zeros([num_items, 12], dtype=int)
local_cache = dict()
for i, label in enumerate(chord_labels):
result = local_cache.get(label, None)
if result is None:
result = encode(label, reduce_extended_chords)
local_cache[label] = result
roots[i], semitones[i], basses[i] = result
return roots, semitones, basses
def rotate_bitmap_to_root(bitmap, chord_root):
"""Circularly shift a relative bitmap to its asbolute pitch classes.
For clarity, the best explanation is an example. Given 'G:Maj', the root
and quality map are as follows::
root=5
quality=[1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] # Relative chord shape
After rotating to the root, the resulting bitmap becomes::
abs_quality = [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1] # G, B, and D
Parameters
----------
bitmap : np.ndarray, shape=(12,)
Bitmap of active notes, relative to the given root.
chord_root : int
Absolute pitch class number.
Returns
-------
bitmap : np.ndarray, shape=(12,)
Absolute bitmap of active pitch classes.
"""
bitmap = np.asarray(bitmap)
assert bitmap.ndim == 1, "Currently only 1D bitmaps are supported."
idxs = list(np.nonzero(bitmap))
idxs[-1] = (idxs[-1] + chord_root) % 12
abs_bitmap = np.zeros_like(bitmap)
abs_bitmap[tuple(idxs)] = 1
return abs_bitmap
def rotate_bitmaps_to_roots(bitmaps, roots):
"""Circularly shift a relative bitmaps to asbolute pitch classes.
See :func:`rotate_bitmap_to_root` for more information.
Parameters
----------
bitmap : np.ndarray, shape=(N, 12)
Bitmap of active notes, relative to the given root.
root : np.ndarray, shape=(N,)
Absolute pitch class number.
Returns
-------
bitmap : np.ndarray, shape=(N, 12)
Absolute bitmaps of active pitch classes.
"""
abs_bitmaps = []
for bitmap, chord_root in zip(bitmaps, roots):
abs_bitmaps.append(rotate_bitmap_to_root(bitmap, chord_root))
return np.asarray(abs_bitmaps)
# --- Comparison Routines ---
def validate(reference_labels, estimated_labels):
"""Checks that the input annotations to a comparison function look like
valid chord labels.
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
"""
N = len(reference_labels)
M = len(estimated_labels)
if N != M:
raise ValueError(
"Chord comparison received different length lists: "
"len(reference)=%d\tlen(estimates)=%d" % (N, M))
for labels in [reference_labels, estimated_labels]:
for chord_label in labels:
validate_chord_label(chord_label)
# When either label list is empty, warn the user
if len(reference_labels) == 0:
warnings.warn('Reference labels are empty')
if len(estimated_labels) == 0:
warnings.warn('Estimated labels are empty')
def weighted_accuracy(comparisons, weights):
"""Compute the weighted accuracy of a list of chord comparisons.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> # Here, we're using the "thirds" function to compare labels
>>> # but any of the comparison functions would work.
>>> comparisons = mir_eval.chord.thirds(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
comparisons : np.ndarray
List of chord comparison scores, in [0, 1] or -1
weights : np.ndarray
Weights (not necessarily normalized) for each comparison.
This can be a list of interval durations
Returns
-------
score : float
Weighted accuracy
"""
N = len(comparisons)
# There should be as many weights as comparisons
if weights.shape[0] != N:
raise ValueError('weights and comparisons should be of the same'
' length. len(weights) = {} but len(comparisons)'
' = {}'.format(weights.shape[0], N))
if (weights < 0).any():
raise ValueError('Weights should all be positive.')
if np.sum(weights) == 0:
warnings.warn('No nonzero weights, returning 0')
return 0
# Find all comparison scores which are valid
valid_idx = (comparisons >= 0)
# If no comparable chords were provided, warn and return 0
if valid_idx.sum() == 0:
warnings.warn("No reference chords were comparable "
"to estimated chords, returning 0.")
return 0
# Remove any uncomparable labels
comparisons = comparisons[valid_idx]
weights = weights[valid_idx]
# Normalize the weights
total_weight = float(np.sum(weights))
normalized_weights = np.asarray(weights, dtype=float)/total_weight
# Score is the sum of all weighted comparisons
return np.sum(comparisons*normalized_weights)
def thirds(reference_labels, estimated_labels):
"""Compare chords along root & third relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.thirds(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
comparison_scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones = encode_many(reference_labels, False)[:2]
est_roots, est_semitones = encode_many(estimated_labels, False)[:2]
eq_roots = ref_roots == est_roots
eq_thirds = ref_semitones[:, 3] == est_semitones[:, 3]
comparison_scores = (eq_roots * eq_thirds).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def thirds_inv(reference_labels, estimated_labels):
"""Score chords along root, third, & bass relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.thirds_inv(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones, ref_bass = encode_many(reference_labels, False)
est_roots, est_semitones, est_bass = encode_many(estimated_labels, False)
eq_root = ref_roots == est_roots
eq_bass = ref_bass == est_bass
eq_third = ref_semitones[:, 3] == est_semitones[:, 3]
comparison_scores = (eq_root * eq_third * eq_bass).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def triads(reference_labels, estimated_labels):
"""Compare chords along triad (root & quality to #5) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.triads(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
comparison_scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones = encode_many(reference_labels, False)[:2]
est_roots, est_semitones = encode_many(estimated_labels, False)[:2]
eq_roots = ref_roots == est_roots
eq_semitones = np.all(
np.equal(ref_semitones[:, :8], est_semitones[:, :8]), axis=1)
comparison_scores = (eq_roots * eq_semitones).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def triads_inv(reference_labels, estimated_labels):
"""Score chords along triad (root, quality to #5, & bass) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.triads_inv(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones, ref_bass = encode_many(reference_labels, False)
est_roots, est_semitones, est_bass = encode_many(estimated_labels, False)
eq_roots = ref_roots == est_roots
eq_basses = ref_bass == est_bass
eq_semitones = np.all(
np.equal(ref_semitones[:, :8], est_semitones[:, :8]), axis=1)
comparison_scores = (eq_roots * eq_semitones * eq_basses).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def tetrads(reference_labels, estimated_labels):
"""Compare chords along tetrad (root & full quality) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.tetrads(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
comparison_scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones = encode_many(reference_labels, False)[:2]
est_roots, est_semitones = encode_many(estimated_labels, False)[:2]
eq_roots = ref_roots == est_roots
eq_semitones = np.all(np.equal(ref_semitones, est_semitones), axis=1)
comparison_scores = (eq_roots * eq_semitones).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def tetrads_inv(reference_labels, estimated_labels):
"""Compare chords along tetrad (root, full quality, & bass) relationships.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... est_intervals, est_labels, ref_intervals.min(),
... ref_intervals.max(), mir_eval.chord.NO_CHORD,
... mir_eval.chord.NO_CHORD)
>>> (intervals,
... ref_labels,
... est_labels) = mir_eval.util.merge_labeled_intervals(
... ref_intervals, ref_labels, est_intervals, est_labels)
>>> durations = mir_eval.util.intervals_to_durations(intervals)
>>> comparisons = mir_eval.chord.tetrads_inv(ref_labels, est_labels)
>>> score = mir_eval.chord.weighted_accuracy(comparisons, durations)
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated chord labels to score against.
Returns
-------
comparison_scores : np.ndarray, shape=(n,), dtype=float
Comparison scores, in [0.0, 1.0]
"""
validate(reference_labels, estimated_labels)
ref_roots, ref_semitones, ref_bass = encode_many(reference_labels, False)
est_roots, est_semitones, est_bass = encode_many(estimated_labels, False)
eq_roots = ref_roots == est_roots
eq_basses = ref_bass == est_bass
eq_semitones = np.all(np.equal(ref_semitones, est_semitones), axis=1)
comparison_scores = (eq_roots * eq_semitones * eq_basses).astype(float)
# Ignore 'X' chords
comparison_scores[np.any(ref_semitones < 0, axis=1)] = -1.0
return comparison_scores
def root(reference_labels, estimated_labels):
"""Compare chords according to roots.