-
Notifications
You must be signed in to change notification settings - Fork 402
/
makeNotation.py
2374 lines (2054 loc) · 88.7 KB
/
makeNotation.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: makeNotation.py
# Purpose: functionality for manipulating streams
#
# Authors: Michael Scott Asato Cuthbert
# Christopher Ariza
# Jacob Walls
# Evan Lynch
#
# Copyright: Copyright © 2008-2023 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# -----------------------------------------------------------------------------
from __future__ import annotations
from collections.abc import Iterable, Generator
import contextlib
import copy
import typing as t
import unittest
from music21 import beam
from music21 import clef
from music21 import common
from music21 import chord
from music21 import defaults
from music21 import duration
from music21 import environment
from music21 import expressions
from music21 import key
from music21 import meter
from music21 import note
from music21 import pitch
from music21.common.numberTools import opFrac
from music21.common.types import StreamType, OffsetQL
from music21.exceptions21 import StreamException
if t.TYPE_CHECKING:
from fractions import Fraction
from music21 import stream
from music21.stream.iterator import StreamIterator
environLocal = environment.Environment(__file__)
# -----------------------------------------------------------------------------
def makeBeams(
s: StreamType,
*,
inPlace=False,
setStemDirections=True,
failOnNoTimeSignature=False,
) -> StreamType | None:
# noinspection PyShadowingNames
'''
Return a new Measure, or Stream of Measures, with beams applied to all
notes. Measures with Voices will process voices independently.
Note that `makeBeams()` is automatically called in show('musicxml') and
other formats if there is no beaming information in the piece (see
`haveBeamsBeenMade`).
If `inPlace` is True, this is done in-place; if `inPlace` is False,
this returns a modified deep copy.
.. note: Before Version 1.6, `inPlace` default was `True`; now `False`
like most `inPlace` options in music21. Also, in 1.8, no tuplets are made
automatically. Use makeTupletBrackets()
See :meth:`~music21.meter.TimeSignature.getBeams` for the algorithm used.
>>> aMeasure = stream.Measure()
>>> aMeasure.timeSignature = meter.TimeSignature('4/4')
>>> aNote = note.Note()
>>> aNote.quarterLength = 0.25
>>> aMeasure.repeatAppend(aNote, 16)
>>> bMeasure = aMeasure.makeBeams(inPlace=False)
>>> for i in range(4):
... print(f'{i} {bMeasure.notes[i].beams!r}')
0 <music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>
1 <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/stop>>
2 <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/start>>
3 <music21.beam.Beams <music21.beam.Beam 1/stop>/<music21.beam.Beam 2/stop>>
This was formerly a bug -- we could not have a partial-left beam at the start of a
beam group. Now merges across the archetypeSpan
>>> aMeasure = stream.Measure()
>>> aMeasure.timeSignature = meter.TimeSignature('4/4')
>>> for i in range(4):
... aMeasure.append(note.Rest(quarterLength=0.25))
... aMeasure.repeatAppend(note.Note('C4', quarterLength=0.25), 3)
>>> bMeasure = aMeasure.makeBeams(inPlace=False).notes
>>> for i in range(6):
... print(f'{i} {bMeasure[i].beams!r}')
0 <music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>
1 <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>
2 <music21.beam.Beams <music21.beam.Beam 1/stop>/<music21.beam.Beam 2/stop>>
3 <music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>
4 <music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/continue>>
5 <music21.beam.Beams <music21.beam.Beam 1/stop>/<music21.beam.Beam 2/stop>>
Grace notes no longer interfere with beaming:
>>> m = stream.Measure()
>>> m.timeSignature = meter.TimeSignature('3/4')
>>> m.repeatAppend(note.Note(quarterLength=0.25), 4)
>>> m.repeatAppend(note.Rest(), 2)
>>> gn = note.Note(duration=duration.GraceDuration())
>>> m.insert(0.25, gn)
>>> m.makeBeams(inPlace=True)
>>> [n.beams for n in m.notes]
[<music21.beam.Beams <music21.beam.Beam 1/start>/<music21.beam.Beam 2/start>>,
<music21.beam.Beams>,
<music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/stop>>,
<music21.beam.Beams <music21.beam.Beam 1/continue>/<music21.beam.Beam 2/start>>,
<music21.beam.Beams <music21.beam.Beam 1/stop>/<music21.beam.Beam 2/stop>>]
OMIT_FROM_DOCS
TODO: inPlace=False does not work in many cases ?? still an issue? 2017
'''
from music21 import stream
# environLocal.printDebug(['calling Stream.makeBeams()'])
if not inPlace: # make a copy
returnObj = s.coreCopyAsDerivation('makeBeams')
else:
returnObj = s
# if s.isClass(Measure):
mColl: list[stream.Measure]
if isinstance(returnObj, stream.Measure):
mColl = [returnObj] # store a list of measures for processing
else:
mColl = list(returnObj.getElementsByClass(stream.Measure)) # a list of measures
if not mColl:
raise stream.StreamException(
'cannot process a stream that is neither a Measure nor has no Measures')
lastTimeSignature = None
m: stream.Measure
for m in mColl:
# this means that the first of a stream of time signatures will
# be used
lastTimeSignature = m.timeSignature or m.getContextByClass(meter.TimeSignature)
if lastTimeSignature is None:
if failOnNoTimeSignature:
raise stream.StreamException(
'cannot process beams in a Measure without a time signature')
continue
noteGroups = []
if m.hasVoices():
for v in m.voices:
noteGroups.append(v.notesAndRests.stream())
else:
noteGroups.append(m.notesAndRests.stream())
# environLocal.printDebug([
# 'noteGroups', noteGroups, 'len(noteGroups[0])',
# len(noteGroups[0])])
for noteStream in noteGroups:
if len(noteStream) <= 1:
continue # nothing to beam
durList = []
for n in noteStream:
if n.duration.isGrace:
noteStream.remove(n)
continue
durList.append(n.duration)
# environLocal.printDebug([
# 'beaming with ts', lastTimeSignature, 'measure', m, durList,
# noteStream[0], noteStream[1]])
# error check; call before sending to time signature, as, if this
# fails, it represents a problem that happens before time signature
# processing
summed = sum([d.quarterLength for d in durList])
# note, this ^^ is faster than a generator expression
# the double call below corrects for tiny errors in adding
# floats and Fractions in the sum() call -- the first opFrac makes it
# impossible to have 4.00000000001, but returns Fraction(4, 1). The
# second call converts Fraction(4, 1) to 4.0
durSum = opFrac(opFrac(summed))
barQL = lastTimeSignature.barDuration.quarterLength
if durSum > barQL:
# environLocal.printDebug([
# 'attempting makeBeams with a bar that contains durations
# that sum greater than bar duration (%s > %s)' %
# (durSum, barQL)])
continue
# getBeams
offset: float | Fraction = 0.0
if m.paddingLeft != 0.0:
offset = opFrac(m.paddingLeft)
elif m.paddingRight != 0.0:
pass
# Incomplete measure without any padding set: assume paddingLeft
elif noteStream.highestTime < barQL:
offset = barQL - noteStream.highestTime
beamsList = lastTimeSignature.getBeams(noteStream, measureStartOffset=offset)
for i, n in enumerate(noteStream):
thisBeams = beamsList[i]
if thisBeams is not None:
n.beams = thisBeams
else:
n.beams = beam.Beams()
del mColl # remove Stream no longer needed
if setStemDirections:
setStemDirectionForBeamGroups(returnObj)
returnObj.streamStatus.beams = True
if inPlace is not True:
return returnObj
def makeMeasures(
s: StreamType,
*,
meterStream=None,
refStreamOrTimeRange=None,
searchContext=False,
innerBarline=None,
finalBarline='final',
bestClef=False,
inPlace=False,
) -> StreamType | None:
'''
Takes a stream and places all of its elements into
measures (:class:`~music21.stream.Measure` objects)
based on the :class:`~music21.meter.TimeSignature` objects
placed within
the stream. If no TimeSignatures are found in the
stream, a default of 4/4 is used.
If `inPlace` is True, the original Stream is modified and lost
if `inPlace` is False, this returns a modified deep copy.
Many advanced features are available:
(1) If a `meterStream` is given, the TimeSignatures in this
stream are used instead of any found in the Stream.
Alternatively, a single TimeSignature object
can be provided in lieu of the stream. This feature lets you
test out how a group of notes might be interpreted as measures
in a number of different metrical schemes.
(2) If `refStreamOrTimeRange` is provided, this Stream or List
is used to give the span that you want to make measures as
necessary to fill empty rests at the ends or beginnings of
Streams, etc. Say for instance you'd like to make a complete
score from a short ossia section, then you might use another
Part from the Score as a `refStreamOrTimeRange` to make sure
that the appropriate measures of rests are added at either side.
(3) If `innerBarline` is not None, the specified Barline object
or string-specification of Barline style will be used to create
Barline objects between every created Measure. The default is None.
(4) If `finalBarline` is not None, the specified Barline object or
string-specification of Barline style will be used to create a Barline
objects at the end of the last Measure. The default is 'final'.
The `searchContext` parameter determines whether context
searches are used to find Clef and other notation objects.
Here is a simple example of makeMeasures:
A single measure of 4/4 is created from a Stream
containing only three quarter notes:
>>> sSrc = stream.Stream()
>>> sSrc.append(note.Note('C4', type='quarter'))
>>> sSrc.append(note.Note('D4', type='quarter'))
>>> sSrc.append(note.Note('E4', type='quarter'))
>>> sMeasures = sSrc.makeMeasures()
>>> sMeasures.show('text')
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.note.Note E>
{3.0} <music21.bar.Barline type=final>
Notice that the last measure is incomplete -- makeMeasures
does not fill up incomplete measures.
We can also check that the measure created has
the correct TimeSignature:
>>> sMeasures[0].timeSignature
<music21.meter.TimeSignature 4/4>
Now let's redo this work in 2/4 by putting a TimeSignature
of 2/4 at the beginning of the stream and rerunning
makeMeasures. Now we will have two measures, each with
correct measure numbers:
>>> sSrc.insert(0.0, meter.TimeSignature('2/4'))
>>> sMeasuresTwoFour = sSrc.makeMeasures()
>>> sMeasuresTwoFour.show('text')
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.meter.TimeSignature 2/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.stream.Measure 2 offset=2.0>
{0.0} <music21.note.Note E>
{1.0} <music21.bar.Barline type=final>
Let us put 10 quarter notes in a Part.
>>> sSrc = stream.Part()
>>> n = note.Note('E-4')
>>> n.quarterLength = 1
>>> sSrc.repeatAppend(n, 10)
After we run makeMeasures, we will have
3 measures of 4/4 in a new Part object. This experiment
demonstrates that running makeMeasures does not
change the type of Stream you are using:
>>> sMeasures = sSrc.makeMeasures()
>>> len(sMeasures.getElementsByClass(stream.Measure))
3
>>> sMeasures.__class__.__name__
'Part'
Demonstrate what `makeMeasures` will do with `inPlace` = True:
>>> sScr = stream.Score()
>>> sPart = stream.Part()
>>> sPart.insert(0, clef.TrebleClef())
>>> sPart.insert(0, meter.TimeSignature('3/4'))
>>> sPart.append(note.Note('C4', quarterLength = 3.0))
>>> sPart.append(note.Note('D4', quarterLength = 3.0))
>>> sScr.insert(0, sPart)
>>> sScr.makeMeasures(inPlace=True)
>>> sScr.show('text')
{0.0} <music21.stream.Part 0x...>
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.meter.TimeSignature 3/4>
{0.0} <music21.note.Note C>
{3.0} <music21.stream.Measure 2 offset=3.0>
{0.0} <music21.note.Note D>
{3.0} <music21.bar.Barline type=final>
If after running makeMeasures you run makeTies, it will also split
long notes into smaller notes with ties. Lyrics and articulations
are attached to the first note. Expressions (fermatas,
etc.) will soon be attached to the last note but this is not yet done:
>>> p1 = stream.Part()
>>> p1.append(meter.TimeSignature('3/4'))
>>> longNote = note.Note('D#4')
>>> longNote.quarterLength = 7.5
>>> longNote.articulations = [articulations.Staccato()]
>>> longNote.lyric = 'hi'
>>> p1.append(longNote)
>>> partWithMeasures = p1.makeMeasures()
>>> partWithMeasures is not p1
True
>>> dummy = partWithMeasures.makeTies(inPlace=True)
>>> partWithMeasures.show('text')
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.meter.TimeSignature 3/4>
{0.0} <music21.note.Note D#>
{3.0} <music21.stream.Measure 2 offset=3.0>
{0.0} <music21.note.Note D#>
{6.0} <music21.stream.Measure 3 offset=6.0>
{0.0} <music21.note.Note D#>
{1.5} <music21.bar.Barline type=final>
>>> allNotes = partWithMeasures.flatten().notes
>>> allNotes[0].articulations
[]
>>> allNotes[1].articulations
[]
>>> allNotes[2].articulations
[<music21.articulations.Staccato>]
>>> [allNotes[0].lyric, allNotes[1].lyric, allNotes[2].lyric]
['hi', None, None]
* Changed in v6: all but first attribute are keyword only
* Changed in v7: now safe to call `makeMeasures` directly on a score containing parts
'''
from music21 import spanner
from music21 import stream
mStart = None
# environLocal.printDebug(['calling Stream.makeMeasures()'])
# must take a flat representation, as we need to be able to
# position components, and sub-streams might hide elements that
# should be contained
if s.hasPartLikeStreams():
# can't flatten, because it would destroy parts
if inPlace:
returnObj = s
else:
returnObj = copy.deepcopy(s)
for substream in returnObj.getElementsByClass('Stream'):
substream.makeMeasures(meterStream=meterStream,
refStreamOrTimeRange=refStreamOrTimeRange,
searchContext=searchContext,
innerBarline=innerBarline,
finalBarline=finalBarline,
bestClef=bestClef,
inPlace=True, # copy already made
)
if inPlace:
return None
else:
return returnObj
else:
if s.hasVoices():
# cannot make flat if there are voices, as would destroy stream partitions
# parts containing voices are less likely to occur since MIDI parsing changes in v7
srcObj = s
else:
srcObj = s.flatten()
if not srcObj.isSorted:
srcObj = srcObj.sorted()
if not inPlace:
srcObj = copy.deepcopy(srcObj)
voiceCount = len(srcObj.voices)
# environLocal.printDebug([
# 'Stream.makeMeasures(): passed in meterStream', meterStream,
# meterStream[0]])
# may need to look in activeSite if no time signatures are found
if meterStream is None:
# get from this Stream, or search the contexts
meterStream = srcObj.getTimeSignatures(
returnDefault=True,
searchContext=False,
sortByCreationTime=False
)
# environLocal.printDebug([
# 'Stream.makeMeasures(): found meterStream', meterStream[0]])
elif isinstance(meterStream, meter.TimeSignature):
# if meterStream is a TimeSignature, use it
ts = meterStream
meterStream = stream.Stream()
meterStream.insert(0, ts)
else: # check that the meterStream is a Stream!
if not isinstance(meterStream, stream.Stream):
raise stream.StreamException(
'meterStream is neither a Stream nor a TimeSignature!')
# environLocal.printDebug([
# 'makeMeasures(): meterStream', 'meterStream[0]', meterStream[0],
# 'meterStream[0].offset', meterStream[0].offset,
# 'meterStream.elements[0].activeSite',
# meterStream.elements[0].activeSite])
# need a SpannerBundle to store any found spanners and place
# at the part level
spannerBundleAccum = spanner.SpannerBundle()
# MSC: Q 2020 -- why is making a clef something to do in this routine?
#
# get a clef for the entire stream; this will use bestClef
# presently, this only gets the first clef
# may need to store a clefStream and access changes in clefs
# as is done with meterStream
# clefList = srcObj.getClefs(searchActiveSite=True,
# searchContext=searchContext,
# returnDefault=True)
# clefObj = clefList[0]
# del clefList
clefObj = srcObj.clef or srcObj.getContextByClass(clef.Clef)
if clefObj is None:
clefObj = srcObj.getElementsByClass(clef.Clef).getElementsByOffset(0).first()
# only return clefs that have offset = 0.0
if not clefObj:
clefObj = clef.bestClef(srcObj, recurse=True)
# environLocal.printDebug([
# 'makeMeasures(): first clef found after copying and flattening',
# clefObj])
# for each element in stream, need to find max and min offset
# assume that flat/sorted options will be set before processing
# list of start, start dur, element
offsetMapList = srcObj.offsetMap()
# environLocal.printDebug(['makeMeasures(): offset map', offsetMap])
# offsetMapList.sort() not necessary; just get min and max
if offsetMapList:
oMax = max([x.endTime for x in offsetMapList])
else:
oMax = 0
# if a ref stream is provided, get the highest time from there
# only if it is greater than the highest time yet encountered
if refStreamOrTimeRange is not None:
if isinstance(refStreamOrTimeRange, stream.Stream):
refStreamHighestTime = refStreamOrTimeRange.highestTime
else: # assume it's a list
refStreamHighestTime = max(refStreamOrTimeRange)
if refStreamHighestTime > oMax:
oMax = refStreamHighestTime
# create a stream of measures to contain the offsets range defined
# create as many measures as needed to fit in oMax
post = s.__class__()
post.derivation.origin = s
post.derivation.method = 'makeMeasures'
o = 0.0 # initial position of first measure is assumed to be zero
measureCount = 0
lastTimeSignature = None
while True:
# TODO: avoid while True
m = stream.Measure()
m.number = measureCount 1
# environLocal.printDebug([
# 'handling measure', m, m.number, 'current offset value', o,
# meterStream._reprTextLine()])
# get active time signature at this offset
# make a copy and it to the meter
thisTimeSignature = meterStream.getElementAtOrBefore(o)
# environLocal.printDebug([
# 'm.number', m.number, 'meterStream.getElementAtOrBefore(o)',
# meterStream.getElementAtOrBefore(o), 'lastTimeSignature',
# lastTimeSignature, 'thisTimeSignature', thisTimeSignature ])
if thisTimeSignature is None and lastTimeSignature is None:
raise stream.StreamException(
'failed to find TimeSignature in meterStream; '
'cannot process Measures')
if (thisTimeSignature is not lastTimeSignature
and thisTimeSignature is not None):
lastTimeSignature = thisTimeSignature
# this seems redundant
# lastTimeSignature = meterStream.getElementAtOrBefore(o)
m.timeSignature = copy.deepcopy(thisTimeSignature)
# environLocal.printDebug(['assigned time sig', m.timeSignature])
# only add a clef for the first measure when automatically
# creating Measures; this clef is from getClefs, called above
if measureCount == 0:
m.clef = clefObj
if voiceCount > 0 and s.keySignature is not None:
m.insert(0, copy.deepcopy(s.keySignature))
# environLocal.printDebug(
# ['assigned clef to measure', measureCount, m.clef])
# add voices if necessary (voiceCount > 0)
for voiceIndex in range(voiceCount):
v = stream.Voice()
v.id = voiceIndex # id is voice index, starting at 0
m.coreInsert(0, v)
if voiceCount:
m.coreElementsChanged()
# avoid an infinite loop
if thisTimeSignature.barDuration.quarterLength == 0:
raise stream.StreamException(
f'time signature {thisTimeSignature!r} has no duration')
post.coreInsert(o, m) # insert measure
# increment by meter length
o = thisTimeSignature.barDuration.quarterLength
if o >= oMax: # may be zero
break # if length of this measure exceeds last offset
else:
measureCount = 1
post.coreElementsChanged()
# cache information about each measure (we used to do this once per element)
postLen = len(post)
postMeasureList = []
lastTimeSignature = meter.TimeSignature('4/4') # default.
for i in range(postLen):
m = post[i]
if m.timeSignature is not None:
lastTimeSignature = m.timeSignature
# get start and end offsets for each measure
# seems like should be able to use m.duration.quarterLengths
mStart = post.elementOffset(m)
mEnd = mStart lastTimeSignature.barDuration.quarterLength
# if elements start fits within this measure, break and use
# offset cannot start on end
postMeasureList.append({'measure': m,
'mStart': mStart,
'mEnd': mEnd})
# populate measures with elements
for oneOffsetMap in offsetMapList:
e, start, end, voiceIndex = oneOffsetMap
# environLocal.printDebug(['makeMeasures()', start, end, e, voiceIndex])
# iterate through all measures, finding a measure that
# can contain this element
# collect all spanners and move to outer Stream
if isinstance(e, spanner.Spanner):
spannerBundleAccum.append(e)
continue
match = False
for i in range(postLen):
postMeasureInfo = postMeasureList[i]
mStart = postMeasureInfo['mStart']
mEnd = postMeasureInfo['mEnd']
m = postMeasureInfo['measure']
if mStart <= start < mEnd:
match = True
# environLocal.printDebug([
# 'found measure match', i, mStart, mEnd, start, end, e])
break
if not match:
if start == end == oMax:
post.storeAtEnd(e)
continue
else:
raise stream.StreamException(
f'cannot place element {e} with start/end {start}/{end} within any measures')
# find offset in the temporal context of this measure
# i is the index of the measure that this element starts at
# mStart, mEnd are correct
oNew = start - mStart # remove measure offset from element offset
# insert element at this offset in the measure
# not copying elements here!
# in the case of a Clef, and possibly other measure attributes,
# the element may have already been placed in this measure
# we need to only exclude elements that are placed in the special
# first position
if m.clef is e:
continue
# do not accept another time signature at the zero position: this
# is handled above
if oNew == 0 and isinstance(e, meter.TimeSignature):
continue
# environLocal.printDebug(['makeMeasures()', 'inserting', oNew, e])
# NOTE: cannot use coreInsert here for some reason
if voiceIndex is None:
m.insert(oNew, e)
else: # insert into voice specified by the voice index
m.voices[voiceIndex].insert(oNew, e)
# add found spanners to higher-level; could insert at zero
for sp in spannerBundleAccum:
post.append(sp)
# clean up temporary streams to avoid extra site accumulation
del srcObj
# set barlines if necessary
lastIndex = len(post.getElementsByClass(stream.Measure)) - 1
for i, m in enumerate(post.getElementsByClass(stream.Measure)):
if i != lastIndex:
if innerBarline not in ['regular', None]:
m.rightBarline = innerBarline
else:
if finalBarline not in ['regular', None]:
m.rightBarline = finalBarline
if bestClef:
m.clef = clef.bestClef(m, recurse=True)
if not inPlace:
post.setDerivationMethod('makeMeasures', recurse=True)
return post # returns a new stream populated w/ new measure streams
else: # clear the stored elements list of this Stream and repopulate
# with Measures created above
s._elements = []
s._endElements = []
s.coreElementsChanged()
if post.isSorted:
postSorted = post
else:
postSorted = post.sorted()
for e in postSorted:
# may need to handle spanners; already have s as site
s.insert(post.elementOffset(e), e)
def makeRests(
s: StreamType,
*,
refStreamOrTimeRange=None,
fillGaps=False,
timeRangeFromBarDuration=False,
inPlace=False,
hideRests=False,
) -> StreamType | None:
'''
Given a Stream with an offset not equal to zero,
fill with one Rest preceding this offset.
This can be called on any Stream,
a Measure alone, or a Measure that contains
Voices. This method recurses into Parts, Measures, and Voices,
since users are unlikely to want "loose" rests outside sub-containers.
If `refStreamOrTimeRange` is provided as a Stream, this
Stream is used to get min and max offsets. If a list is provided,
the list assumed to provide minimum and maximum offsets. Rests will
be added to fill all time defined within refStream.
If `fillGaps` is True, this will create rests in any
time regions that have no active elements.
If `timeRangeFromBarDuration` is True, and the calling Stream
is a Measure with a TimeSignature (or a Part containing them),
the time range will be determined
by taking the :meth:`~music21.stream.Measure.barDuration` and subtracting
:attr:`~music21.stream.Measure.paddingLeft` and
:attr:`~music21.stream.Measure.paddingRight`.
This keyword takes priority over `refStreamOrTimeRange`.
If both are provided, `timeRangeFromBarDuration`
prevails, unless no TimeSignature can be found, in which case, the function
falls back to `refStreamOrTimeRange`.
If `inPlace` is True, this is done in-place; if `inPlace` is False,
this returns a modified deepcopy.
>>> a = stream.Stream()
>>> a.insert(20, note.Note())
>>> len(a)
1
>>> a.lowestOffset
20.0
>>> a.show('text')
{20.0} <music21.note.Note C>
Now make some rests...
>>> b = a.makeRests(inPlace=False)
>>> len(b)
2
>>> b.lowestOffset
0.0
>>> b.show('text')
{0.0} <music21.note.Rest 20ql>
{20.0} <music21.note.Note C>
>>> b[0].duration.quarterLength
20.0
Same thing, but this time, with gaps, and hidden rests...
>>> a = stream.Stream()
>>> a.insert(20, note.Note('C4'))
>>> a.insert(30, note.Note('D4'))
>>> len(a)
2
>>> a.lowestOffset
20.0
>>> a.show('text')
{20.0} <music21.note.Note C>
{30.0} <music21.note.Note D>
>>> b = a.makeRests(fillGaps=True, inPlace=False, hideRests=True)
>>> len(b)
4
>>> b.lowestOffset
0.0
>>> b.show('text')
{0.0} <music21.note.Rest 20ql>
{20.0} <music21.note.Note C>
{21.0} <music21.note.Rest 9ql>
{30.0} <music21.note.Note D>
>>> b[0].style.hideObjectOnPrint
True
Now with measures:
>>> a = stream.Part()
>>> a.insert(4, note.Note('C4'))
>>> a.insert(8, note.Note('D4'))
>>> len(a)
2
>>> a.lowestOffset
4.0
>>> a.insert(0, meter.TimeSignature('4/4'))
>>> a.makeMeasures(inPlace=True)
>>> a.show('text', addEndTimes=True)
{0.0 - 0.0} <music21.stream.Measure 1 offset=0.0>
{0.0 - 0.0} <music21.clef.TrebleClef>
{0.0 - 0.0} <music21.meter.TimeSignature 4/4>
{4.0 - 5.0} <music21.stream.Measure 2 offset=4.0>
{0.0 - 1.0} <music21.note.Note C>
{8.0 - 9.0} <music21.stream.Measure 3 offset=8.0>
{0.0 - 1.0} <music21.note.Note D>
{1.0 - 1.0} <music21.bar.Barline type=final>
>>> a.makeRests(fillGaps=True, inPlace=True)
>>> a.show('text', addEndTimes=True)
{0.0 - 4.0} <music21.stream.Measure 1 offset=0.0>
{0.0 - 0.0} <music21.clef.TrebleClef>
{0.0 - 0.0} <music21.meter.TimeSignature 4/4>
{0.0 - 4.0} <music21.note.Rest whole>
{4.0 - 8.0} <music21.stream.Measure 2 offset=4.0>
{0.0 - 1.0} <music21.note.Note C>
{1.0 - 4.0} <music21.note.Rest dotted-half>
{8.0 - 12.0} <music21.stream.Measure 3 offset=8.0>
{0.0 - 1.0} <music21.note.Note D>
{1.0 - 4.0} <music21.note.Rest dotted-half>
{4.0 - 4.0} <music21.bar.Barline type=final>
* Changed in v6: all but first attribute are keyword only
* Changed in v7:
- `inPlace` defaults False
- Recurses into parts, measures, voices
- Gave priority to `timeRangeFromBarDuration` over `refStreamOrTimeRange`
* Changed in v8: scores (or other streams having parts) edited `inPlace` return `None`.
'''
from music21 import stream
if not inPlace: # make a copy
returnObj = s.coreCopyAsDerivation('makeRests')
else:
returnObj = s
# Invalidate tuplet status
returnObj.streamStatus.tuplets = None
if returnObj.iter().parts:
for inner_part in returnObj.iter().parts:
inner_part.makeRests(
inPlace=True,
fillGaps=fillGaps,
hideRests=hideRests,
refStreamOrTimeRange=refStreamOrTimeRange,
timeRangeFromBarDuration=timeRangeFromBarDuration,
)
if inPlace:
return None
else:
return returnObj
def oHighTargetForMeasure(
m: stream.Measure | None = None,
ts: meter.TimeSignature | None = None
) -> OffsetQL:
'''
Needed for timeRangeFromBarDuration.
Returns 0.0 if no meter can be found.
'''
post: OffsetQL = 0.0
if ts is not None:
post = ts.barDuration.quarterLength
elif m is not None:
# More expensive context search
post = m.barDuration.quarterLength
if m is not None:
post -= m.paddingLeft
post -= m.paddingRight
return max(post, 0.0)
oLowTarget: OffsetQL = 0.0
oHighTarget: OffsetQL = 0.0
if timeRangeFromBarDuration:
if isinstance(returnObj, stream.Measure):
oHighTarget = oHighTargetForMeasure(m=returnObj)
elif isinstance(returnObj, stream.Voice):
if isinstance(refStreamOrTimeRange, stream.Measure):
oHighTarget = oHighTargetForMeasure(m=refStreamOrTimeRange)
elif isinstance(refStreamOrTimeRange, meter.TimeSignature):
maybe_measure: stream.Measure | None = None
if isinstance(returnObj.activeSite, stream.Measure):
maybe_measure = returnObj.activeSite
oHighTarget = oHighTargetForMeasure(m=maybe_measure, ts=refStreamOrTimeRange)
elif returnObj.hasMeasures():
# This could be optimized to save some context searches,
# but at the cost of readability.
oHighTarget = sum(
m.barDuration.quarterLength for m in returnObj.getElementsByClass(stream.Measure)
)
# If the above search didn't run or still yielded 0.0, use refStreamOrTimeRange
if oHighTarget == 0.0:
if refStreamOrTimeRange is None: # use local
oHighTarget = returnObj.highestTime
elif isinstance(refStreamOrTimeRange, stream.Stream):
oLowTarget = refStreamOrTimeRange.lowestOffset
oHighTarget = refStreamOrTimeRange.highestTime
# treat as a list
elif common.isIterable(refStreamOrTimeRange):
oLowTarget = min(refStreamOrTimeRange)
oHighTarget = max(refStreamOrTimeRange)
bundle: list[StreamType]
if returnObj.hasVoices():
bundle = list(returnObj.voices)
elif returnObj.hasMeasures():
bundle = list(returnObj.getElementsByClass('Measure'))
else:
bundle = [returnObj]
lastTimeSignature: meter.TimeSignature | None = None
# bundle components may be voices, measures, or a flat Stream
for component in bundle:
oLow = component.lowestOffset
oHigh = component.highestTime
lastTimeSignature = component.timeSignature or lastTimeSignature
if isinstance(component, stream.Measure):
ts_or_measure = lastTimeSignature or component
if timeRangeFromBarDuration:
oHighTarget = oHighTargetForMeasure(component, lastTimeSignature)
# process voices
for inner_voice in component.voices:
inner_voice.makeRests(inPlace=True,
fillGaps=fillGaps,
hideRests=hideRests,
refStreamOrTimeRange=ts_or_measure,
timeRangeFromBarDuration=timeRangeFromBarDuration,
)
# Refresh these variables given that inner voices were altered
oLow = component.lowestOffset
oHigh = component.highestTime
# adjust oHigh to not exceed measure
oHighTarget = min(ts_or_measure.barDuration.quarterLength, oHighTarget)
# create rest from start to end
qLen = oLow - oLowTarget
if qLen > 0:
r = note.Rest()
r.duration.quarterLength = qLen
r.style.hideObjectOnPrint = hideRests
# environLocal.printDebug(['makeRests(): add rests', r, r.duration])
# place at oLowTarget to reach to oLow
component.insert(oLowTarget, r)
# create rest from end to highest
qLen = oHighTarget - oHigh
if qLen > 0:
r = note.Rest()
r.duration.quarterLength = qLen
r.style.hideObjectOnPrint = hideRests
# place at oHigh to reach to oHighTarget
component.insert(oHigh, r)
if fillGaps:
gapStream = component.findGaps()
if gapStream is not None:
for e in gapStream:
r = note.Rest()
r.duration.quarterLength = e.duration.quarterLength
r.style.hideObjectOnPrint = hideRests
component.insert(e.offset, r)
if returnObj.hasMeasures():
# split rests at measure boundaries
returnObj.makeTies(classFilterList=(note.Rest,), inPlace=True)
# reposition measures
accumulatedTime = 0.0
for m in returnObj.getElementsByClass(stream.Measure):
returnObj.setElementOffset(m, accumulatedTime)
accumulatedTime = m.highestTime
if inPlace is not True:
return returnObj
def makeTies(
s: StreamType,
*,
meterStream=None,
inPlace=False,
displayTiedAccidentals=False,
classFilterList=(note.GeneralNote,),
) -> StreamType | None:
# noinspection PyShadowingNames
'''
Given a stream containing measures, examine each element in the
Stream. If the element's duration extends beyond the measure's boundary,
create a tied entity, placing the split Note in the next Measure.