/
interval.py
3256 lines (2691 loc) · 106 KB
/
interval.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
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: interval.py
# Purpose: music21 classes for representing intervals
#
# Authors: Michael Scott Cuthbert
# Jackie Rogoff
# Amy Hailes
# Christopher Ariza
#
# Copyright: Copyright © 2009-2012, 2015 Michael Scott Cuthbert and the music21 Project
# License: BSD, see license.txt
# ------------------------------------------------------------------------------
'''
This module defines various types of interval objects.
Fundamental classes are :class:`~music21.interval.Interval`,
:class:`~music21.interval.GenericInterval`,
and :class:`~music21.interval.ChromaticInterval`.
'''
from fractions import Fraction
import abc
import copy
import enum
import math
import unittest
from typing import Union
from music21 import base
from music21 import common
from music21 import exceptions21
# from music21 import pitch # SHOULD NOT, b/c of enharmonics
from music21 import environment
_MOD = 'interval'
environLocal = environment.Environment(_MOD)
# ------------------------------------------------------------------------------
# constants
STEPNAMES = ('C', 'D', 'E', 'F', 'G', 'A', 'B')
class Direction(enum.IntEnum):
DESCENDING = -1
OBLIQUE = 0
ASCENDING = 1
directionTerms = {Direction.DESCENDING: 'Descending',
Direction.OBLIQUE: 'Oblique',
Direction.ASCENDING: 'Ascending'}
# specifiers are derived from these two lists;
# perhaps better represented with a dictionary
# perhaps the first entry, below, should be None, like in prefixSpecs?
niceSpecNames = ['ERROR', 'Perfect', 'Major', 'Minor', 'Augmented', 'Diminished',
'Doubly-Augmented', 'Doubly-Diminished', 'Triply-Augmented',
'Triply-Diminished', 'Quadruply-Augmented', 'Quadruply-Diminished']
prefixSpecs = [None, 'P', 'M', 'm', 'A', 'd', 'AA', 'dd', 'AAA', 'ddd', 'AAAA', 'dddd']
# constants provide the common numerical representation of an interval.
# this is not the number of half tone shift.
PERFECT = 1
MAJOR = 2
MINOR = 3
AUGMENTED = 4
DIMINISHED = 5
DBLAUG = 6
DBLDIM = 7
TRPAUG = 8
TRPDIM = 9
QUADAUG = 10
QUADDIM = 11
# ordered list of perfect specifiers
orderedPerfSpecs = ['dddd', 'ddd', 'dd', 'd', 'P', 'A', 'AA', 'AAA', 'AAAA']
perfSpecifiers = [QUADDIM, TRPDIM, DBLDIM, DIMINISHED, PERFECT,
AUGMENTED, DBLAUG, TRPAUG, QUADAUG]
perfOffset = 4 # that is, Perfect is third on the list.s
# ordered list of imperfect specifiers
orderedImperfSpecs = ['dddd', 'ddd', 'dd', 'd', 'm', 'M', 'A', 'AA', 'AAA', 'AAAA']
# why is this not called imperfSpecifiers?
specifiers = [QUADDIM, TRPDIM, DBLDIM, DIMINISHED, MINOR, MAJOR,
AUGMENTED, DBLAUG, TRPAUG, QUADAUG]
majOffset = 5 # index of Major
# the following dictionaries provide half step shifts given key values
# either as integers (generic) or as strings (adjust perfect/imperfect)
# assuming Perfect or Major
semitonesGeneric = {
1: 0,
2: 2,
3: 4,
4: 5,
5: 7,
6: 9,
7: 11
}
semitonesAdjustPerfect = {'P': 0, 'A': 1, 'AA': 2, 'AAA': 3, 'AAAA': 4,
'd': -1, 'dd': -2, 'ddd': -3, 'dddd': -4} # offset from Perfect
semitonesAdjustImperf = {'M': 0, 'm': -1, 'A': 1, 'AA': 2, 'AAA': 3, 'AAAA': 4,
'd': -2, 'dd': -3, 'ddd': -4, 'dddd': -5} # offset from Major
# ------------------------------------------------------------------------------
class IntervalException(exceptions21.Music21Exception):
pass
# ------------------------------------------------------------------------------
# some utility functions
def _extractPitch(nOrP):
'''
utility function to return either the object itself
or the `.pitch` if it's a Note.
>>> p = pitch.Pitch('D#4')
>>> interval._extractPitch(p) is p
True
>>> n = note.Note('E-4')
>>> interval._extractPitch(n) is n.pitch
True
'''
if 'Pitch' in nOrP.classes:
return nOrP
else:
return nOrP.pitch
def convertStaffDistanceToInterval(staffDist):
'''
Returns an integer of the generic interval number
(P5 = 5, M3 = 3, minor 3 = 3 also) etc. from the given staff distance.
>>> interval.convertStaffDistanceToInterval(3)
4
>>> interval.convertStaffDistanceToInterval(7)
8
>>> interval.convertStaffDistanceToInterval(0)
1
>>> interval.convertStaffDistanceToInterval(-1)
-2
'''
if staffDist == 0:
return 1
elif staffDist > 0:
return staffDist + 1
else:
return staffDist - 1
def convertDiatonicNumberToStep(dn):
'''
Convert a diatonic number to a step name (without accidental) and a octave integer.
The lowest C on a Bösendorfer Imperial Grand is assigned 1 the D above it is 2,
E is 3, etc. See pitch.diatonicNoteNum for more details
>>> interval.convertDiatonicNumberToStep(15)
('C', 2)
>>> interval.convertDiatonicNumberToStep(23)
('D', 3)
>>> interval.convertDiatonicNumberToStep(0)
('B', -1)
>>> interval.convertDiatonicNumberToStep(1)
('C', 0)
Extremely high and absurdly low numbers also produce "notes".
>>> interval.convertDiatonicNumberToStep(2100)
('B', 299)
>>> interval.convertDiatonicNumberToStep(-19)
('D', -3)
OMIT_FROM_DOCS
>>> interval.convertDiatonicNumberToStep(2)
('D', 0)
>>> interval.convertDiatonicNumberToStep(3)
('E', 0)
>>> interval.convertDiatonicNumberToStep(4)
('F', 0)
>>> interval.convertDiatonicNumberToStep(5)
('G', 0)
>>> interval.convertDiatonicNumberToStep(-1)
('A', -1)
>>> interval.convertDiatonicNumberToStep(-2)
('G', -1)
>>> interval.convertDiatonicNumberToStep(-6)
('C', -1)
>>> interval.convertDiatonicNumberToStep(-7)
('B', -2)
'''
# note -- do not replace int(dn / 7) with dn // 7 -- gives wrong numbers for negative.
if dn == 0:
return 'B', -1
elif dn > 0:
octave = int((dn - 1) / 7.0)
stepNumber = (dn - 1) - (octave * 7)
return STEPNAMES[stepNumber], octave
elif dn < 0:
octave = int(dn / 7)
stepNumber = (dn - 1) - (octave * 7)
return STEPNAMES[stepNumber], (octave - 1)
def convertSpecifier(specifier):
'''
Given an integer or a string representing a "specifier" (major, minor,
perfect, diminished, etc.), return a tuple of (1) an integer which
refers to the appropriate specifier in a list and (2) a standard form
for the specifier.
This function permits specifiers to specified in a flexible manner.
>>> interval.convertSpecifier(3)
(3, 'm')
>>> interval.convertSpecifier('p')
(1, 'P')
>>> interval.convertSpecifier('P')
(1, 'P')
>>> interval.convertSpecifier('M')
(2, 'M')
>>> interval.convertSpecifier('major')
(2, 'M')
>>> interval.convertSpecifier('m')
(3, 'm')
>>> interval.convertSpecifier('Augmented')
(4, 'A')
>>> interval.convertSpecifier('a')
(4, 'A')
>>> interval.convertSpecifier(None)
(None, None)
'''
post = None
postStr = None
if common.isNum(specifier):
post = specifier
# check string matches
if isinstance(specifier, str):
if specifier in prefixSpecs:
post = prefixSpecs.index(specifier)
# permit specifiers as prefixes without case; this will not distinguish
# between m and M, but was taken care of in the line above
elif specifier.lower() in [x.lower() for x in prefixSpecs[1:]]:
for i in range(len(prefixSpecs)):
if prefixSpecs[i] is None:
continue
if specifier.lower() == prefixSpecs[i].lower():
post = i
break
elif specifier.lower() in [x.lower() for x in niceSpecNames[1:]]:
for i in range(len(niceSpecNames)):
if niceSpecNames[i] is None:
continue
if specifier.lower() == niceSpecNames[i].lower():
post = i
break
# if no match or None, None will be returned
if post is not None:
postStr = prefixSpecs[post]
return post, postStr
def convertGeneric(value):
'''Convert an interval specified in terms of its name (second, third)
into an integer. If integers are passed, assume the are correct.
# TODO: use common.numberTools.musicOrdinals
>>> interval.convertGeneric(3)
3
>>> interval.convertGeneric('third')
3
>>> interval.convertGeneric('3rd')
3
>>> interval.convertGeneric('octave')
8
>>> interval.convertGeneric('twelfth')
12
>>> interval.convertGeneric('descending twelfth')
-12
>>> interval.convertGeneric(12)
12
>>> interval.convertGeneric(-12)
-12
>>> interval.convertGeneric(1)
1
>>> interval.convertGeneric(None)
Traceback (most recent call last):
music21.interval.IntervalException: Cannot get a direction from None.
Strings are not the same as numbers...
>>> interval.convertGeneric('1')
Traceback (most recent call last):
music21.interval.IntervalException: Cannot convert '1' to an interval.
'''
post = None
if common.isNum(value):
post = value
directionScalar = Direction.ASCENDING # may still be negative
elif isinstance(value, str):
# first, see if there is a direction term
directionScalar = Direction.ASCENDING # assume ascending
for direction in [Direction.DESCENDING, Direction.ASCENDING]:
if directionTerms[direction].lower() in value.lower():
directionScalar = direction # assign numeric value
# strip direction
value = value.lower()
value = value.replace(directionTerms[direction].lower(), '')
value = value.strip()
if value.lower() in ['unison']:
post = 1
elif value.lower() in ['2nd', 'second']:
post = 2
elif value.lower() in ['3rd', 'third']:
post = 3
elif value.lower() in ['4th', 'fourth']:
post = 4
elif value.lower() in ['5th', 'fifth']:
post = 5
elif value.lower() in ['6th', 'sixth']:
post = 6
elif value.lower() in ['7th', 'seventh']:
post = 7
elif value.lower() in ['8th', 'eighth', 'octave']:
post = 8
elif value.lower() in ['9th', 'ninth']:
post = 9
elif value.lower() in ['10th', 'tenth']:
post = 10
elif value.lower() in ['11th', 'eleventh']:
post = 11
elif value.lower() in ['12th', 'twelfth']:
post = 12
elif value.lower() in ['13th', 'thirteenth']:
post = 13
elif value.lower() in ['14th', 'fourteenth']:
post = 14
elif value.lower() in ['15th', 'fifteenth']:
post = 15
elif value.lower() in ['16th', 'sixteenth']:
post = 16
else:
raise IntervalException(f'Cannot convert {value!r} to an interval.')
else:
raise IntervalException(f'Cannot get a direction from {value}.')
post = post * directionScalar
return post
def convertSemitoneToSpecifierGenericMicrotone(count):
'''
Given a number of semitones, return a default diatonic specifier and cent offset.
DEPRECATED if it can be moved..
>>> interval.convertSemitoneToSpecifierGenericMicrotone(2.5)
('M', 2, 50.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(2.25)
('M', 2, 25.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(1.0)
('m', 2, 0.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(1.75)
('M', 2, -25.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(1.9)
('M', 2, -10.0...)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(0.25)
('P', 1, 25.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(12.25)
('P', 8, 25.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(24.25)
('P', 15, 25.0)
>>> interval.convertSemitoneToSpecifierGenericMicrotone(23.75)
('P', 15, -25.0)
'''
if count < 0:
dirScale = -1
else:
dirScale = 1
count, micro = divmod(count, 1)
# convert micro to cents
cents = micro * 100.0
if cents > 50:
cents = cents - 100
count += 1
count = int(count)
size = abs(count) % 12
octave = abs(count) // 12 # let floor to int
if size == 0:
spec = 'P'
generic = 1
elif size == 1:
spec = 'm'
generic = 2
elif size == 2:
spec = 'M'
generic = 2
elif size == 3:
spec = 'm'
generic = 3
elif size == 4:
spec = 'M'
generic = 3
elif size == 5:
spec = 'P'
generic = 4
elif size == 6:
spec = 'd'
generic = 5
elif size == 7:
spec = 'P'
generic = 5
elif size == 8:
spec = 'm'
generic = 6
elif size == 9:
spec = 'M'
generic = 6
elif size == 10:
spec = 'm'
generic = 7
elif size == 11:
spec = 'M'
generic = 7
else:
raise IntervalException('cannot match interval size: %s' % size)
return (spec, (generic + (octave * 7)) * dirScale, cents)
def convertSemitoneToSpecifierGeneric(count):
'''
Given a number of semitones, return a default diatonic specifier.
>>> interval.convertSemitoneToSpecifierGeneric(0)
('P', 1)
>>> interval.convertSemitoneToSpecifierGeneric(-2)
('M', -2)
>>> interval.convertSemitoneToSpecifierGeneric(1)
('m', 2)
>>> interval.convertSemitoneToSpecifierGeneric(7)
('P', 5)
>>> interval.convertSemitoneToSpecifierGeneric(11)
('M', 7)
>>> interval.convertSemitoneToSpecifierGeneric(12)
('P', 8)
>>> interval.convertSemitoneToSpecifierGeneric(13)
('m', 9)
>>> interval.convertSemitoneToSpecifierGeneric(-15)
('m', -10)
>>> interval.convertSemitoneToSpecifierGeneric(24)
('P', 15)
'''
# strip off microtone
return convertSemitoneToSpecifierGenericMicrotone(count)[:2]
_pythagorean_cache = {}
def intervalToPythagoreanRatio(intervalObj):
r'''
Returns the interval ratio in pythagorean tuning, always as a Fraction object.
>>> iList = [interval.Interval(name) for name in ('P4', 'P5', 'M7')]
>>> iList
[<music21.interval.Interval P4>,
<music21.interval.Interval P5>,
<music21.interval.Interval M7>]
>>> [interval.intervalToPythagoreanRatio(i) for i in iList]
[Fraction(4, 3), Fraction(3, 2), Fraction(243, 128)]
Throws an exception if no ratio can be found, such as for quarter tones.
>>> p1, p2 = pitch.Pitch('C1'), pitch.Pitch('C1')
>>> p2.accidental = 'half-sharp'
>>> fiftyCent = interval.Interval(p1, p2)
>>> fiftyCent
<music21.interval.Interval A1 (-50c)>
>>> interval.intervalToPythagoreanRatio(fiftyCent)
Traceback (most recent call last):
music21.interval.IntervalException: Could not find a pythagorean ratio for
<music21.interval.Interval A1 (-50c)>.
'''
from music21.pitch import Pitch
start_pitch = Pitch('C1')
end_pitch_wanted = start_pitch.transpose(intervalObj)
if end_pitch_wanted.name in _pythagorean_cache:
end_pitch, ratio = _pythagorean_cache[end_pitch_wanted.name]
else:
end_pitch_up = start_pitch
end_pitch_down = start_pitch
# when counter == 36, it wraps back to 'C' because of
# music21's limiting of accidentals
for counter in range(37):
if end_pitch_up.name == end_pitch_wanted.name:
ratio = Fraction(3, 2) ** counter
end_pitch = end_pitch_up
break
elif end_pitch_down.name == end_pitch_wanted.name:
ratio = Fraction(2, 3) ** counter
end_pitch = end_pitch_down
break
else:
end_pitch_up = end_pitch_up.transpose('P5')
end_pitch_down = end_pitch_down.transpose('-P5')
else:
raise IntervalException(
'Could not find a pythagorean ratio for {}.'.format(intervalObj))
_pythagorean_cache[end_pitch_wanted.name] = end_pitch, ratio
octaves = int((end_pitch_wanted.ps - end_pitch.ps) / 12)
return ratio * Fraction(2, 1) ** octaves
# ------------------------------------------------------------------------------
class IntervalBase(base.Music21Object):
'''
General base class for inheritance.
'''
def transposeNote(self, note1):
'''
Uses self.transposePitch to do the same to a note.
>>> n1 = note.Note('C#4', quarterLength=2.0)
>>> i = interval.Interval('d5')
>>> n2 = i.transposeNote(n1)
>>> n2
<music21.note.Note G>
>>> n2.pitch
<music21.pitch.Pitch G4>
>>> n2.duration.type
'half'
'''
newPitch = self.transposePitch(note1.pitch)
newNote = copy.deepcopy(note1)
newNote.pitch = newPitch
return newNote
@abc.abstractmethod
def transposePitch(self, pitch1, *, inPlace=False):
'''
IntervalBase does not know how to do this, so it must be overridden in
derived classes.
'''
raise NotImplementedError
class GenericInterval(IntervalBase):
'''
A GenericInterval is an interval such as Third, Seventh, Octave, or Tenth.
Constructor takes an integer or string specifying the interval and direction.
The interval is not specified in half-steps, but in numeric values
derived from interval names:
a Third is 3; a Seventh is 7, etc. String values for interval names ('3rd' or 'third')
are generally accepted, but discouraged since not every one will work.
staffDistance: the number of lines or spaces apart, eg:
E.g. C4 to C4 = 0; C4 to D4 = 1; C4 to B3 = -1
Two generic intervals are the equal if their size and direction are the same.
>>> gi = interval.GenericInterval(8)
>>> gi
<music21.interval.GenericInterval 8>
>>> aInterval = interval.GenericInterval(3)
>>> aInterval.directed
3
>>> aInterval.direction
<Direction.ASCENDING: 1>
>>> aInterval.perfectable
False
>>> aInterval.staffDistance
2
>>> aInterval = interval.GenericInterval('Third')
>>> aInterval.directed
3
>>> aInterval.staffDistance
2
>>> aInterval = interval.GenericInterval(-12)
>>> aInterval.niceName
'Twelfth'
>>> aInterval.perfectable
True
>>> aInterval.staffDistance
-11
>>> aInterval.mod7
4
>>> aInterval.directed
-12
>>> aInterval.undirected
12
>>> bInterval = aInterval.complement()
>>> bInterval.staffDistance
3
>>> aInterval = interval.GenericInterval('descending twelfth')
>>> aInterval.perfectable
True
>>> aInterval.staffDistance
-11
>>> aInterval = interval.GenericInterval(0)
Traceback (most recent call last):
music21.interval.IntervalException: The Zeroth is not an interval
>>> aInterval = interval.GenericInterval(24)
>>> aInterval.niceName
'24'
>>> aInterval.isDiatonicStep
False
>>> aInterval.isStep
False
>>> aInterval = interval.GenericInterval(2)
>>> aInterval.isDiatonicStep
True
>>> aInterval.isStep
True
Intervals >= 23rd use numbers instead of names
>>> aInterval = interval.GenericInterval(23)
>>> aInterval.niceName
'23'
'''
def __init__(self,
value: Union[int, str] = 'unison'):
super().__init__()
self.value = convertGeneric(value)
self.directed = self.value
self.undirected = abs(self.value)
if self.directed == 1:
self.direction = Direction.OBLIQUE
# elif self.directed == -1:
# raise IntervalException('Descending P1s not allowed; did you mean to write a ' +
# 'diminished unison instead?')
elif self.directed == 0:
raise IntervalException('The Zeroth is not an interval')
elif self.directed == self.undirected:
self.direction = Direction.ASCENDING
else:
self.direction = Direction.DESCENDING
if self.undirected > 2:
self.isSkip = True
else:
self.isSkip = False
if self.undirected == 2:
self.isDiatonicStep = True
else:
self.isDiatonicStep = False
self.isStep = self.isDiatonicStep
if self.undirected == 1:
self.isUnison = True
else:
self.isUnison = False
# unisons (even augmented) are neither steps nor skips.
steps, octaves = math.modf(self.undirected / 7)
steps = int(steps * 7 + 0.001)
octaves = int(octaves)
if steps == 0:
octaves = octaves - 1
steps = 7
self.simpleUndirected = steps
# semiSimpleUndirected, same as simple, but P8 != P1
self.semiSimpleUndirected = steps
self.undirectedOctaves = octaves
if steps == 1 and octaves >= 1:
self.semiSimpleUndirected = 8
if self.direction == Direction.DESCENDING:
self.octaves = -1 * octaves
if steps != 1:
self.simpleDirected = -1 * steps
else:
self.simpleDirected = 1 # no descending unisons...
self.semiSimpleDirected = -1 * self.semiSimpleUndirected
else:
self.octaves = octaves
self.simpleDirected = steps
self.semiSimpleDirected = self.semiSimpleUndirected
if self.simpleUndirected in (1, 4, 5):
self.perfectable = True
else:
self.perfectable = False
if self.undirected < len(common.musicOrdinals):
self.niceName = common.musicOrdinals[self.undirected]
self.simpleNiceName = common.musicOrdinals[self.simpleUndirected]
self.semiSimpleNiceName = common.musicOrdinals[self.semiSimpleUndirected]
else:
self.niceName = str(self.undirected)
self.simpleNiceName = str(self.simpleUndirected)
self.semiSimpleNiceName = str(self.semiSimpleUndirected)
if abs(self.directed) == 1:
self.staffDistance = 0
elif self.directed > 1:
self.staffDistance = self.directed - 1
elif self.directed < -1:
self.staffDistance = self.directed + 1
else:
raise IntervalException(
'Non-integer, -1, or 0 not permitted as a diatonic interval')
# 2 -> 7; 3 -> 6; 8 -> 1 etc.
self.mod7inversion = 9 - self.semiSimpleUndirected
if self.direction == Direction.DESCENDING:
self.mod7 = self.mod7inversion # see chord.semitonesFromChordStep for usage...
else:
self.mod7 = self.simpleDirected
def _reprInternal(self):
return str(self.directed)
def __eq__(self, other):
'''
True if value and direction are the same.
>>> a = interval.GenericInterval('Third')
>>> b = interval.GenericInterval(-3)
>>> c = interval.GenericInterval(3)
>>> d = interval.GenericInterval(6)
>>> a == b
False
>>> a == a == c
True
>>> b == c
False
>>> a != d
True
>>> a in [b, c, d]
True
>>> a == ''
False
>>> a is None
False
'''
if other is None:
return False
elif not hasattr(other, 'value'):
return False
elif not hasattr(other, 'directed'):
return False
elif self.value == other.value and self.directed == other.directed:
return True
else:
return False
def complement(self):
'''
Returns a new GenericInterval object where 3rds are 6ths, etc.
>>> third = interval.GenericInterval('Third')
>>> third.complement()
<music21.interval.GenericInterval 6>
Note that currently direction is lost after a complement relationship:
>>> fourth = interval.GenericInterval(-4)
>>> fourthComp = fourth.complement()
>>> fourthComp
<music21.interval.GenericInterval 5>
>>> fourthComp.directed
5
'''
return GenericInterval(self.mod7inversion)
def reverse(self):
'''
Returns a new GenericInterval object that is inverted.
>>> aInterval = interval.GenericInterval('Third')
>>> aInterval.reverse()
<music21.interval.GenericInterval -3>
>>> aInterval = interval.GenericInterval(-13)
>>> aInterval.direction
<Direction.DESCENDING: -1>
>>> aInterval.reverse()
<music21.interval.GenericInterval 13>
Unisons invert to unisons
>>> aInterval = interval.GenericInterval(1)
>>> aInterval.reverse()
<music21.interval.GenericInterval 1>
'''
if self.undirected == 1:
return GenericInterval(1)
else:
return GenericInterval(self.undirected * (-1 * self.direction))
def transposePitch(self, p, *, inPlace=False):
'''
transpose a pitch, retaining the accidental if any.
>>> aPitch = pitch.Pitch('g4')
>>> genericFifth = interval.GenericInterval(5)
>>> bPitch = genericFifth.transposePitch(aPitch)
>>> bPitch
<music21.pitch.Pitch D5>
If inPlace is True then applied to the current pitch:
>>> gPitch = pitch.Pitch('g4')
>>> genericFifth = interval.GenericInterval(5)
>>> genericFifth.transposePitch(gPitch, inPlace=True)
>>> gPitch
<music21.pitch.Pitch D5>
A generic interval transformation retains accidentals:
>>> a2 = pitch.Pitch('B-')
>>> cPitch = genericFifth.transposePitch(a2)
>>> cPitch
<music21.pitch.Pitch F->
>>> a2.octave == cPitch.octave
True
Can be done inPlace as well, in which case, nothing is returned:
>>> gSharp = pitch.Pitch('g#4')
>>> genericFifth = interval.GenericInterval(5)
>>> genericFifth.transposePitch(gSharp, inPlace=True)
>>> gSharp
<music21.pitch.Pitch D#5>
'''
if p.octave is None:
useImplicitOctave = True
else:
useImplicitOctave = False
pitchDNN = p.diatonicNoteNum
if inPlace:
newPitch = p
else:
newPitch = copy.deepcopy(p)
newPitch.diatonicNoteNum = pitchDNN + self.staffDistance
if useImplicitOctave is True:
newPitch.octave = None
if not inPlace:
return newPitch
def transposePitchKeyAware(self, p, k=None, *, inPlace=False):
'''
Transposes a pitch while remaining aware of its key context,
for modal transposition:
If k is None, works the same as `.transposePitch`:
>>> aPitch = pitch.Pitch('g4')
>>> genericFifth = interval.GenericInterval(5)
>>> bPitch = genericFifth.transposePitchKeyAware(aPitch, None)
>>> bPitch
<music21.pitch.Pitch D5>
But if a key or keySignature (such as one from .getContextByClass('KeySignature')
is given, then the fun begins...
>>> fis = pitch.Pitch('F#4')
>>> e = pitch.Pitch('E')
>>> gMaj = key.Key('G')
>>> genericStep = interval.GenericInterval('second')
>>> genericStep.transposePitchKeyAware(fis, gMaj)
<music21.pitch.Pitch G4>
>>> genericStep.transposePitchKeyAware(e, gMaj)
<music21.pitch.Pitch F#>
If a pitch already has an accidental that contradicts the current
key, the difference between that pitch and the new key is applied
to the new pitch:
>>> fNat = pitch.Pitch('F4')
>>> genericStep.transposePitchKeyAware(fNat, gMaj)
<music21.pitch.Pitch G-4>
inPlace should work:
>>> genericStep.transposePitchKeyAware(fis, gMaj, inPlace=True)
>>> fis
<music21.pitch.Pitch G4>
This is used for Stream.transpose when a GenericInterval is given:
>>> s = converter.parse('tinyNotation: 4/4 d4 e f f# g1 a-4 g b- a c1')
>>> s.measure(1).insert(0, key.Key('G'))
>>> s.measure(3).insert(0, key.Key('c'))
>>> s2 = s.transpose(interval.GenericInterval(2))
>>> s2.show('text')
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.key.Key of G major>
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note E>
{1.0} <music21.note.Note F#>
{2.0} <music21.note.Note G->
{3.0} <music21.note.Note G>
{4.0} <music21.stream.Measure 2 offset=4.0>
{0.0} <music21.note.Note A>
{8.0} <music21.stream.Measure 3 offset=8.0>
{0.0} <music21.key.Key of c minor>
{0.0} <music21.note.Note B->
{1.0} <music21.note.Note A->
{2.0} <music21.note.Note C>
{3.0} <music21.note.Note B>
{12.0} <music21.stream.Measure 4 offset=12.0>
{0.0} <music21.note.Note D>
{4.0} <music21.bar.Barline type=final>
Does not take into account harmonic or melodic minor.
'''
from music21 import pitch
if k is None:
return self.transposePitch(p, inPlace=inPlace)
accidentalByStep = k.accidentalByStep(p.step)
stepAlter = accidentalByStep.alter if accidentalByStep is not None else 0
pAlter = p.accidental.alter if p.accidental is not None else 0
offsetFromKey = pAlter - stepAlter
newPitch = self.transposePitch(p, inPlace=inPlace)
if inPlace is True:
newPitch = p
newAccidentalByStep = k.accidentalByStep(newPitch.step)
newStepAlter = newAccidentalByStep.alter if newAccidentalByStep is not None else 0
newPitchAlter = newStepAlter + offsetFromKey
if newPitchAlter != 0:
newPitch.accidental = pitch.Accidental(newPitchAlter)
elif newPitch.accidental is not None:
newPitch.accidental = None
if inPlace is False:
return newPitch
def getDiatonic(self, specifier):
'''
Given a specifier, return a :class:`~music21.interval.DiatonicInterval` object.
Specifier should be provided as a string name, such as 'dd', 'M', or 'perfect'.
>>> aInterval = interval.GenericInterval('Third')
>>> aInterval.getDiatonic('major')
<music21.interval.DiatonicInterval M3>
>>> aInterval.getDiatonic('minor')