-
Notifications
You must be signed in to change notification settings - Fork 393
/
expressions.py
2824 lines (2354 loc) · 101 KB
/
expressions.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
863
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: expressions.py
# Purpose: Expressions such as Fermatas, etc.
#
# Authors: Michael Scott Asato Cuthbert
# Christopher Ariza
# Neena Parikh
#
# Copyright: Copyright © 2009-2023 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# ------------------------------------------------------------------------------
'''
This module provides object representations of expressions, that is
notational symbols such as Fermatas, Mordents, Trills, Turns, etc.
which are stored under a Music21Object's .expressions attribute.
A sub-category of Expressions are Ornaments.
Unlike articulations, expressions can be attached to the Stream itself.
For instance, TextExpressions.
'''
from __future__ import annotations
import copy
import string
import typing as t
from fractions import Fraction
from music21 import base
from music21 import common
from music21.common.enums import OrnamentDelay
from music21.common.numberTools import opFrac
from music21.common.types import OffsetQL
from music21 import exceptions21
from music21 import interval
from music21 import key
from music21 import pitch
from music21 import spanner
from music21 import style
if t.TYPE_CHECKING:
from music21 import note
def isUnison(intv: interval.IntervalBase) -> bool:
if isinstance(intv, interval.Interval):
return intv.name == 'P1' and intv.chromatic.semitones == 0
elif isinstance(intv, interval.DiatonicInterval):
return intv.name == 'P1'
elif isinstance(intv, interval.ChromaticInterval):
return intv.semitones == 0
return False
def realizeOrnaments(
srcObj: note.Note | note.Unpitched,
*,
keySig: key.KeySignature | None = None
):
'''
given a Note or Unpitched with Ornament expressions,
convert them into a list of objects that represents
the performed version of the object:
>>> n1 = note.Note('D5')
>>> n1.quarterLength = 1
>>> n1.expressions.append(expressions.WholeStepMordent())
>>> expList = expressions.realizeOrnaments(n1)
>>> st1 = stream.Stream()
>>> st1.append(expList)
>>> #_DOCS_SHOW st1.show()
.. image:: images/expressionsMordentRealize.*
:width: 218
'''
srcObject: note.Note | note.Unpitched | None = srcObj
if t.TYPE_CHECKING:
# it comes in as not None
assert srcObject is not None
if not hasattr(srcObject, 'expressions'):
return [srcObject]
elif not srcObject.expressions:
return [srcObject]
else:
preExpandList = []
postExpandList = []
loopBuster = 100
while loopBuster:
if t.TYPE_CHECKING:
# if it was set to None, we break out of the loop, so we won't get here
assert srcObject is not None
loopBuster -= 1
thisExpression = srcObject.expressions[0]
if hasattr(thisExpression, 'realize'):
preExpand, newSrcObject, postExpand = thisExpression.realize(
srcObject, keySig=keySig
)
for i in preExpand:
preExpandList.append(i)
for i in postExpand:
postExpandList.append(i)
if newSrcObject is None:
# some ornaments eat up the entire source object. Trills for instance
srcObject = newSrcObject
break
newSrcObject.expressions = srcObject.expressions[1:]
srcObject = newSrcObject
if t.TYPE_CHECKING:
# if newSrcObject/srcObject were None, we would have broken out of the loop
assert srcObject is not None
if not srcObject.expressions:
break
else: # cannot realize this object
srcObject.expressions = srcObject.expressions[1:]
if not srcObject.expressions:
break
retList = []
# TODO: use extend...
for i in preExpandList:
retList.append(i)
if srcObject is not None:
retList.append(srcObject)
for i in postExpandList:
retList.append(i)
return retList
# ------------------------------------------------------------------------------
class ExpressionException(exceptions21.Music21Exception):
pass
class Expression(base.Music21Object):
'''
This base class is inherited by many diverse expressions.
'''
_styleClass = style.TextStyle
def __init__(self, **keywords):
super().__init__(**keywords)
self.tieAttach = 'first' # attach to first note of a tied group.
def _reprInternal(self) -> str:
return ''
@property
def name(self) -> str:
'''
returns the name of the expression, which is generally the
class name lowercased and spaces where a new capital occurs.
Subclasses can override this as necessary.
>>> sc = expressions.Schleifer()
>>> sc.name
'schleifer'
>>> iTurn = expressions.InvertedTurn()
>>> iTurn.name
'inverted turn'
'''
className = self.__class__.__name__
return common.camelCaseToHyphen(className, replacement=' ')
# ------------------------------------------------------------------------------
class RehearsalMark(Expression):
'''
A rehearsal mark is a type of Expression that designates a rehearsal
marking, such as A., B., etc.
Takes two inputs, content ('B', 5, 'III') and an optional numbering system which
is helpful for getting the next rehearsal mark.
>>> rm = expressions.RehearsalMark('B')
>>> rm
<music21.expressions.RehearsalMark 'B'>
'''
classSortOrder = -30
_styleClass = style.TextStylePlacement
def __init__(self, content=None, *, numbering=None, **keywords):
super().__init__(**keywords)
self.content = content
if numbering not in ('alphabetical', 'roman', 'number', None):
raise ExpressionException(
'Numbering must be "alphabetical", "roman", "number", or None')
self.numbering = numbering
self.style.alignHorizontal = 'center'
self.style.alignVertical = 'middle'
def _reprInternal(self):
return repr(self.content)
@staticmethod
def _getNumberingFromContent(c) -> str | None:
'''
if numbering was not set, get it from the content
>>> ex = expressions.RehearsalMark()
>>> ex._getNumberingFromContent('C')
'alphabetical'
>>> ex._getNumberingFromContent('VII')
'roman'
>>> ex._getNumberingFromContent('X')
'roman'
>>> ex._getNumberingFromContent('CI')
'roman'
>>> ex._getNumberingFromContent('5')
'number'
>>> ex._getNumberingFromContent(5)
'number'
>>> print(ex._getNumberingFromContent('*'))
None
'''
if c is None:
return None
if isinstance(c, int):
return 'number'
if not isinstance(c, str):
return None
try:
unused = int(c)
return 'number'
except ValueError:
pass
try:
romanValue = common.numberTools.fromRoman(c)
if len(c) >= 2:
return 'roman' # two letters is enough
if romanValue < 50:
return 'roman' # I, X, V
else:
return 'alphabetical' # L, C, D, M
except ValueError:
pass
if c in string.ascii_letters:
return 'alphabetical'
else:
return None
def nextContent(self):
'''
Return the next content based on the numbering
>>> expressions.RehearsalMark('A').nextContent()
'B'
>>> expressions.RehearsalMark('II').nextContent()
'III'
>>> expressions.RehearsalMark('IV').nextContent()
'V'
>>> expressions.RehearsalMark(7).nextContent()
8
>>> expressions.RehearsalMark('Z').nextContent()
'AA'
With rehearsal mark 'I' default is to consider it
as a roman numeral:
>>> expressions.RehearsalMark('I').nextContent()
'II'
Specify `numbering` directly to avoid problems:
>>> expressions.RehearsalMark('I', numbering='alphabetical').nextContent()
'J'
'''
numbering = self.numbering
if not numbering:
numbering = self._getNumberingFromContent(self.content)
if not numbering:
if self.content is None:
return None
# duplicate current content
return self.content * 2
if numbering == 'alphabetical':
nextContent = chr(ord(self.content[-1]) 1)
if nextContent not in string.ascii_letters:
return 'A' * (len(self.content) 1)
else:
return nextContent
elif numbering == 'number':
return int(self.content) 1
elif numbering == 'roman':
return common.toRoman(common.fromRoman(self.content) 1)
def nextMark(self):
'''
Return the next rehearsal mark.
>>> rm = expressions.RehearsalMark('C')
>>> rm.nextMark()
<music21.expressions.RehearsalMark 'D'>
>>> rm = expressions.RehearsalMark('IV', numbering='roman')
>>> nm = rm.nextMark()
>>> nm.content
'V'
>>> nm.numbering
'roman'
'''
return RehearsalMark(self.nextContent(), numbering=self.numbering)
# ------------------------------------------------------------------------------
class TextExpression(Expression):
'''
A TextExpression is a word, phrase, or similar
bit of text that is positioned in a Stream or Measure.
Conventional expressive indications are text
like "agitato" or "con fuoco."
>>> te = expressions.TextExpression('Con fuoco')
>>> te.content
'Con fuoco'
Most configuration of style is done
on the `.style` :class:`~music21.style.TextStyle` object
itself.
>>> te.style.fontSize = 24.0
>>> te.style.fontSize
24
>>> te.style.fontStyle = 'italic'
>>> te.style.fontWeight = 'bold'
>>> te.style.letterSpacing = 0.5
'''
# always need to be first, before even clefs
classSortOrder = -30
_styleClass = style.TextStyle
_DOC_ATTR: dict[str, str] = {
'placement': '''
Staff placement: 'above', 'below', or None.
A setting of None implies that the placement will be determined
by notation software and no particular placement is demanded.
This is not placed in the `.style` property, since for some
expressions, the placement above or below an object has semantic
meaning and is not purely presentational.
''',
}
def __init__(self, content=None, **keywords):
super().__init__(**keywords)
# numerous properties are inherited from TextFormat
# the text string to be displayed; not that line breaks
# are given in the xml with this non-printing character: (#)
if not isinstance(content, str):
self._content = str(content)
else:
self._content = content
# this does not do anything if default y is defined
self.placement = None
def _reprInternal(self):
if len(self._content) >= 13:
shortContent = self._content[:10] '...'
return repr(shortContent)
elif self._content is not None:
return repr(self._content)
else:
return ''
@property
def enclosure(self) -> style.Enclosure | None:
'''
Returns or sets the enclosure on the Style object
stored on .style.
Exposed directly on the expression for backwards
compatibility. Does not create a .style object if
one does not exist and the value is None.
>>> te = expressions.TextExpression('Bridge')
>>> te.enclosure is None
True
>>> te.enclosure = style.Enclosure.RECTANGLE
>>> te.enclosure
<Enclosure.RECTANGLE>
Note that this is also set on `.style`.
>>> te.style.enclosure
<Enclosure.RECTANGLE>
'''
if not self.hasStyleInformation:
return None
return self.style.enclosure
@enclosure.setter
def enclosure(self, value: style.Enclosure | None):
if not self.hasStyleInformation and value is None:
return
self.style.enclosure = value
@property
def content(self):
'''
Get or set the content.
>>> te = expressions.TextExpression('dolce')
>>> te.content
'dolce'
>>> te.content = 'sweeter'
>>> te
<music21.expressions.TextExpression 'sweeter'>
'''
return self._content
@content.setter
def content(self, value):
self._content = str(value)
# --------------------------------------------------------------------------
# text expression in musicxml may be repeat expressions
# need to see if this is a repeat expression, and if so
# return the appropriate object
def getRepeatExpression(self):
'''
If this TextExpression can be a RepeatExpression,
return a new :class:`~music21.repeat.RepeatExpression`.
object, otherwise, return None.
'''
# use objects stored in
# repeat.repeatExpressionReferences for comparison to stored
# text; if compatible, create and return object
from music21 import repeat
for obj in repeat.repeatExpressionReference:
if obj.isValidText(self._content):
re = copy.deepcopy(obj)
# set the text to whatever is used here
# create a copy of these text expression and set it
# this will transfer all positional/formatting settings
re.setTextExpression(copy.deepcopy(self))
return re
# Return None if it cannot be expressed as a repeat expression
return None
def getTempoText(self):
# TODO: if this TextExpression, once imported, can be a tempo
# text object, create and return
pass
# ------------------------------------------------------------------------------
class Ornament(Expression):
'''
An Ornament is a type of Expression that, when attached to a Note
(in the future: Notes) can transform into the main note.
All ornaments have an `.autoScale` boolean which determines
whether to shrink (not currently to expand) the ornament if the
note it is attached to is too short to realize.
'''
def __init__(self, **keywords) -> None:
super().__init__(**keywords)
# should follow directly on previous; true for most "ornaments".
self.connectedToPrevious = True
self.autoScale = True
self._ornamentalPitches: tuple[pitch.Pitch, ...] = ()
def realize(
self,
srcObj: note.Note | note.Unpitched,
*,
keySig: key.KeySignature | None = None,
inPlace: bool = False
) -> tuple[list[note.Note | note.Unpitched],
note.Note | note.Unpitched | None,
list[note.Note | note.Unpitched]]:
'''
subclassable method call that takes a sourceObject and optional keySig
and returns a three-element tuple of a list of notes before the
"main note" or the result of the expression if it gobbles up the entire note,
the "main note" itself (or None) to keep processing for ornaments,
and a list of notes after the "main note".
* New in v8: inPlace boolean; note that some ornaments
might not return a Note in the second position at all (such as trills)
so inPlace does nothing.
* Changed in v9: Optional keySig can be passed in (useful in cases where there
is no keySig in srcObj's context, or where a different keySig is desired).
'''
if not inPlace:
srcObj = copy.deepcopy(srcObj)
return ([], srcObj, [])
def fillListOfRealizedNotes(
self,
srcObj: note.Note | note.Unpitched,
fillObjects: list[note.Note | note.Unpitched],
transposeInterval: interval.IntervalBase,
*,
useQL: OffsetQL | None = None
) -> None:
'''
Used by trills and mordents to fill out their realization.
'''
isTransposed: bool = not isUnison(transposeInterval)
if isTransposed and not hasattr(srcObj, 'transpose'):
raise TypeError(f'Expected note; got {type(srcObj)}')
if useQL is None:
useQL = self.quarterLength
firstNote = copy.deepcopy(srcObj)
# TODO: remove expressions
# firstNote.expressions = None
# TODO: clear lyrics.
firstNote.duration.quarterLength = useQL
secondNote = copy.deepcopy(srcObj)
secondNote.duration.quarterLength = useQL
# TODO: remove expressions
# secondNote.expressions = None
if isTransposed:
if t.TYPE_CHECKING:
assert isinstance(secondNote, note.Note)
secondNote.transpose(transposeInterval, inPlace=True)
fillObjects.append(firstNote)
fillObjects.append(secondNote)
def resolveOrnamentalPitches(
self,
srcObj: note.GeneralNote,
*,
keySig: key.KeySignature | None = None
):
'''
Only implemented in Turn, GeneralMordent, and Trill.
'''
return
@property
def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]:
'''
Only implemented in Turn, GeneralMordent, and Trill.
'''
return tuple()
def updateAccidentalDisplay(
self,
*,
pitchPast: list[pitch.Pitch] | None = None,
pitchPastMeasure: list[pitch.Pitch] | None = None,
otherSimultaneousPitches: list[pitch.Pitch] | None = None,
alteredPitches: list[pitch.Pitch] | None = None,
cautionaryPitchClass: bool = True,
cautionaryAll: bool = False,
overrideStatus: bool = False,
cautionaryNotImmediateRepeat: bool = True,
) -> None:
'''
Only implemented in Turn, GeneralMordent, and Trill.
'''
return
# ------------------------------------------------------------------------------
class GeneralMordent(Ornament):
'''
Base class for all Mordent types.
'''
_direction: str = '' # up or down
def __init__(self, *, accidental: pitch.Accidental | None = None, **keywords):
super().__init__(**keywords)
self._accidental: pitch.Accidental | None = accidental
self.quarterLength = 0.125 # 32nd note default
self.placement = 'above'
@property
def name(self) -> str:
'''
returns the name of the Mordent/InvertedMordent, which is generally
the class name lowercased, with spaces where a new capital occurs. The
name also will include any accidental, if it exists.
Subclasses can override this as necessary.
>>> mordent = expressions.Mordent()
>>> mordent.name
'mordent'
>>> sharp = pitch.Accidental('sharp')
>>> invertedMordent = expressions.InvertedMordent(accidental=sharp)
>>> invertedMordent.name
'inverted mordent (sharp)'
'''
theName: str = super().name
if self.accidental is not None:
theName = ' (' self.accidental.name ')'
return theName
@property
def accidental(self) -> pitch.Accidental | None:
'''
This is the GeneralMordent's accidental.
'''
return self._accidental
@accidental.setter
def accidental(self, newAccidental: pitch.Accidental | None):
self._accidental = newAccidental
@property
def direction(self) -> str:
'''
The direction of the mordent's ornamental pitch from the main note.
Can be 'up' or 'down'.
'''
return self._direction
def getSize(
self,
srcObj: note.GeneralNote,
*,
keySig: key.KeySignature | None = None,
) -> interval.IntervalBase:
'''
Returns the size of the mordent's interval, given a source note and
an optional key signature. If the key signature is not specified, the
source note's context is searched for the current key signature, and if
there is no such key signature, a key signature with no sharps and no flats
will be used. Any `accidental` that has been set on the mordent will also
be taken into account. If no `accidental` has been set, the appropriate
accidental from the key signature will be used.
If keySig is specified, this can be considered to be a theoretical question:
"If this particular mordent were to be attached to this note, in this key,
what would the size of the mordent interval be?"
'''
if self._direction not in ('up', 'down'):
raise ExpressionException('Cannot compute mordent size if I do not know its direction')
if not srcObj.pitches:
# perfect unison
return interval.Interval('P1')
# Use keySig if passed in, else use keySig from context, else no sharps or flats.
keySig = keySig or srcObj.getContextByClass(key.KeySignature) or key.KeySignature(0)
srcPitch: pitch.Pitch = srcObj.pitches[-1]
ornamentalPitch: pitch.Pitch = copy.deepcopy(srcPitch)
ornamentalPitch.accidental = None
if ornamentalPitch.octave is None:
ornamentalPitch.octave = ornamentalPitch.implicitOctave
if self._direction == 'up':
ornamentalPitch.transpose(interval.GenericInterval(2), inPlace=True)
else:
ornamentalPitch.transpose(interval.GenericInterval(-2), inPlace=True)
if self.accidental:
ornamentalPitch.accidental = self.accidental
else:
# use whatever accidental the key signature says
ornamentalPitch.accidental = keySig.accidentalByStep(ornamentalPitch.step)
return interval.Interval(srcPitch, ornamentalPitch)
def resolveOrnamentalPitches(
self,
srcObj: note.GeneralNote,
*,
keySig: key.KeySignature | None = None
):
'''
Computes and stores the ornamental pitch for a GeneralMordent, given the srcObj
(can be any kind of ornamented GeneralNote) and an optional keySig.
If keySig is None, srcNote's context will be searched for a key signature.
If no key signature is found, a key signature with no sharps and no flats
will be used.
A mordent on a G in a key with no sharps or flats (ornamental pitch will be F).
>>> noSharpsOrFlats = key.KeySignature(sharps=0)
>>> n1 = note.Note('G4')
>>> mordent = expressions.Mordent()
>>> mordent.resolveOrnamentalPitches(n1, keySig=noSharpsOrFlats)
>>> mordent.ornamentalPitches
(<music21.pitch.Pitch F4>,)
>>> mordent.ornamentalPitch
<music21.pitch.Pitch F4>
e.g. A mordent on a G in a key with one sharp (ornamental pitch will be F#).
>>> oneSharp = key.KeySignature(sharps=1)
>>> mordent.resolveOrnamentalPitches(n1, keySig=oneSharp)
>>> mordent.ornamentalPitches
(<music21.pitch.Pitch F#4>,)
>>> mordent.ornamentalPitch
<music21.pitch.Pitch F#4>
e.g. A mordent with a natural, on a G, in a key with one sharp
(ornamental pitch will be F).
>>> mordent.accidental = pitch.Accidental('natural')
>>> mordent.resolveOrnamentalPitches(n1, keySig=oneSharp)
>>> mordent.ornamentalPitches
(<music21.pitch.Pitch F4>,)
>>> mordent.ornamentalPitch
<music21.pitch.Pitch F4>
'''
if not srcObj.pitches:
# There are no ornamental pitches relative to this srcObj
return
srcPitch: pitch.Pitch = srcObj.pitches[-1]
transposeInterval: interval.IntervalBase = self.getSize(srcObj, keySig=keySig)
ornamentalPitch: pitch.Pitch = copy.deepcopy(srcPitch)
if ornamentalPitch.octave is None:
ornamentalPitch.octave = ornamentalPitch.implicitOctave
ornamentalPitch.transpose(transposeInterval, inPlace=True)
# if there are microtones, see if they can be converted to quarter tones.
if ornamentalPitch.microtone.cents != 0:
ornamentalPitch.convertMicrotonesToQuarterTones(inPlace=True)
if self.accidental is not None:
# Note that we don't need to look at what the accidental actually is,
# since that has already been incorporated into transposeInterval and the
# ornamentalPitch via the call to getSize()/srcPitch.transpose(). But if
# accidental is set at all, we need to copy the displayStatus.
if ornamentalPitch.accidental is None:
ornamentalPitch.accidental = pitch.Accidental(0)
ornamentalPitch.accidental.displayStatus = self.accidental.displayStatus
self._ornamentalPitches = (ornamentalPitch,)
@property
def ornamentalPitch(self) -> pitch.Pitch | None:
'''
Returns the mordent's ornamentalPitch. If resolveOrnamentalPitches
has not yet been called, None is returned.
'''
if self._ornamentalPitches:
return self._ornamentalPitches[0]
return None
@property
def ornamentalPitches(self) -> tuple[pitch.Pitch, ...]:
'''
Returns any ornamental pitch that has been resolved (see
`resolveOrnamentalPitches`, which must be called first, or an
empty tuple will be returned).
'''
return self._ornamentalPitches
def updateAccidentalDisplay(
self,
*,
pitchPast: list[pitch.Pitch] | None = None,
pitchPastMeasure: list[pitch.Pitch] | None = None,
otherSimultaneousPitches: list[pitch.Pitch] | None = None,
alteredPitches: list[pitch.Pitch] | None = None,
cautionaryPitchClass: bool = True,
cautionaryAll: bool = False,
overrideStatus: bool = False,
cautionaryNotImmediateRepeat: bool = True,
):
'''
Updates accidental display for a GeneralMordent's ornamental pitch.
Defined exactly like Pitch.updateAccidentalDisplay, with two changes:
Instead of self being the pitch to update, self is a GeneralMordent whose
ornamentalPitch is to be updated; and we pay no attention to ties,
since ornamental notes cannot be tied.
'''
p = self.ornamentalPitch
if p is None:
return
if self.accidental is not None and self.accidental.displayStatus is not None:
# copy accidental visibility from self.accidental
if p.accidental is None:
p.accidental = pitch.Accidental(0)
p.accidental.displayStatus = self.accidental.displayStatus
return
p.updateAccidentalDisplay(
pitchPast=pitchPast,
pitchPastMeasure=pitchPastMeasure,
alteredPitches=alteredPitches,
cautionaryPitchClass=cautionaryPitchClass,
cautionaryAll=cautionaryAll,
overrideStatus=overrideStatus,
cautionaryNotImmediateRepeat=cautionaryNotImmediateRepeat,
lastNoteWasTied=False)
def realize(
self,
srcObj: note.Note | note.Unpitched,
*,
keySig: key.KeySignature | None = None,
inPlace: bool = False
) -> tuple[list[note.Note | note.Unpitched],
note.Note | note.Unpitched | None,
list[note.Note | note.Unpitched]]:
'''
Realize a mordent.
returns a three-element tuple.
The first is a list of the two notes that the beginning of the note were converted to.
The second is the rest of the note.
The third is an empty list (since there are no notes at the end of a mordent).
>>> n1 = note.Note('C4')
>>> n1.quarterLength = 0.5
>>> m1 = expressions.Mordent()
>>> m1.realize(n1)
([<music21.note.Note C>, <music21.note.Note B>], <music21.note.Note C>, [])
Note: use one of the subclasses, not the GeneralMordent class
>>> n2 = note.Note('C4')
>>> n2.quarterLength = 0.125
>>> m2 = expressions.GeneralMordent()
>>> m2.realize(n2)
Traceback (most recent call last):
music21.expressions.ExpressionException: Cannot realize a mordent if I do not
know its direction
'''
if self._direction not in ('up', 'down'):
raise ExpressionException('Cannot realize a mordent if I do not know its direction')
if srcObj.duration.quarterLength == 0:
raise ExpressionException('Cannot steal time from an object with no duration')
use_ql = self.quarterLength
if srcObj.duration.quarterLength <= self.quarterLength * 2:
if not self.autoScale:
raise ExpressionException('The note is not long enough to realize a mordent')
use_ql = srcObj.duration.quarterLength / 4
currentKeySig: key.KeySignature | None = keySig
if currentKeySig is None:
currentKeySig = srcObj.getContextByClass(key.KeySignature)
if currentKeySig is None:
currentKeySig = key.KeySignature(0)
remainderQL = srcObj.duration.quarterLength - (2 * use_ql)
transposeInterval = self.getSize(srcObj, keySig=currentKeySig)
mordNotes: list[note.Note | note.Unpitched] = []
self.fillListOfRealizedNotes(srcObj, mordNotes, transposeInterval, useQL=use_ql)
isTransposed: bool = not isUnison(transposeInterval)
if isTransposed:
# second (middle) note might need an accidental from the keysig (but
# only if it doesn't already have an accidental, from self.accidental)
for noteIdx, n in enumerate(mordNotes):
if t.TYPE_CHECKING:
assert isinstance(n, note.Note)
noteNum: int = noteIdx 1
if n.pitch.accidental is None and noteNum == 2:
n.pitch.accidental = currentKeySig.accidentalByStep(n.pitch.step)
inExpressions = -1
if self in srcObj.expressions:
inExpressions = srcObj.expressions.index(self)
remainderNote = copy.deepcopy(srcObj) if not inPlace else srcObj
remainderNote.duration.quarterLength = remainderQL
if inExpressions != -1:
remainderNote.expressions.pop(inExpressions)
return (mordNotes, remainderNote, [])
# ------------------------------------------------------------------------------
class Mordent(GeneralMordent):
'''
A normal Mordent -- goes downwards and has a line through it.
Note that some computer terminology calls this one an inverted mordent, but this
is a modern term. See Apel, *Harvard Dictionary of Music*, "Mordent"::
A musical ornament consisting of the alternation of the written note
with the note immediately below it.
A mordent has the size of a second, of some form, depending on the note
that will have the mordent, the current key signature in that note's context, as
well as any accidental on the mordent itself.
e.g. Mordent without accidentals in default key (no flats or sharps)
>>> m = expressions.Mordent()
>>> m.direction
'down'
>>> m.getSize(note.Note('C4'))
<music21.interval.Interval m-2>
>>> m.getSize(note.Note('B3'))
<music21.interval.Interval M-2>
e.g. Mordent with flat, in default key (no flats or sharps)
>>> mFlat = expressions.Mordent(accidental=pitch.Accidental('flat'))
>>> mFlat.direction
'down'
>>> mFlat.getSize(note.Note('C4'))
<music21.interval.Interval M-2>
>>> mFlat.getSize(note.Note('B3'))
<music21.interval.Interval A-2>
e.g. Mordent without accidentals, in key with one flat
>>> oneFlat = key.KeySignature(-1)
>>> mNotFlat = expressions.Mordent()
>>> mNotFlat.direction
'down'
>>> mNotFlat.getSize(note.Note('C4'), keySig=oneFlat)
<music21.interval.Interval M-2>
>>> mNotFlat.getSize(note.Note('B3'), keySig=oneFlat)
<music21.interval.Interval M-2>
e.g. Mordent without accidentals, with a key from context with one flat (same results)
>>> noteC4 = note.Note('C4')
>>> noteB3 = note.Note('B3')
>>> measure = stream.Measure([oneFlat, noteC4, noteB3])
>>> mNotFlatWithKeyFromContext = expressions.Mordent()
>>> mNotFlatWithKeyFromContext.direction
'down'
>>> mNotFlatWithKeyFromContext.getSize(noteC4)
<music21.interval.Interval M-2>
>>> mNotFlatWithKeyFromContext.getSize(noteB3)
<music21.interval.Interval M-2>
* Changed in v7: Mordent sizes are GenericIntervals -- as was originally
intended but programmed incorrectly.
* Changed in v9: Support an accidental on Mordent. This also adds the concept of
an ornamental pitch that is processed by makeAccidentals.
The size property has been removed and replaced with `.getSize()` (which requires
a `srcObj` and optional `keySig` param). Added optional `keySig` param to
`.realize()` as well.
'''
_direction: str = 'down' # up or down
class HalfStepMordent(Mordent):
'''
A half step normal Mordent.
>>> m = expressions.HalfStepMordent()
>>> m.direction
'down'
>>> m.getSize(note.Note('C4'))
<music21.interval.Interval m-2>
'''
def __init__(self, **keywords) -> None:
# no accidental supported here, just "HalfStep"
if 'accidental' in keywords:
raise ExpressionException('Cannot initialize HalfStepMordent with accidental')
super().__init__(**keywords)
self._minorSecondDown: interval.IntervalBase = interval.Interval('m-2')
def getSize(
self,
srcObj: note.GeneralNote,
*,
keySig: key.KeySignature | None = None,
) -> interval.IntervalBase:
return self._minorSecondDown
@property