/
meter.py
3640 lines (2953 loc) · 128 KB
/
meter.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
#-------------------------------------------------------------------------------
# Name: meter.py
# Purpose: Classes for meters
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
#
# Copyright: (c) 2009-2011 The music21 Project
# License: LGPL
#-------------------------------------------------------------------------------
'''This module defines the :class:`~music21.meter.TimeSignature` object, as well as component objects for defining nested metrical structures, :class:`~music21.meter.MeterTerminal` and :class:`~music21.meter.MeterSequence` objects.
'''
import unittest, doctest
import re, copy
#import fractions # available in 2.6 and greater
import music21
from music21 import common
from music21 import duration
from music21 import lily
from music21 import beam
from music21 import musicxml
from music21.musicxml import translate as musicxmlTranslate
from music21 import environment
_MOD = 'meter.py'
environLocal = environment.Environment(_MOD)
#-------------------------------------------------------------------------------
validDenominators = [1,2,4,8,16,32,64,128] # in order
# also [pow(2,x) for x in range(8)]
MIN_DENOMINATOR_TYPE = '128th'
# store a module-level dictionary of partitioned meter sequences used
# for setting default accent weights; store as needed
_meterSequenceAccentArchetypes = {}
# performance tests showed that caching this additional structures did not
# show immediate performance benefits
#_meterSequenceBeatArchetypes = {}
#_meterSequenceBeamArchetypes = {}
# store meter sequence division options, once created, in a module
# level dictionary
_meterSequenceDivisionOptions = {}
def slashToFraction(value):
'''
>>> from music21 import *
>>> meter.slashToFraction('3/8')
(3, 8)
>>> meter.slashToFraction('7/32')
(7, 32)
OMIT_FROM_DOCS
TODO: it seems like this should return only integers; not sure
why these originally were floats.
'''
value = value.strip() # rem whitespace
matches = re.match("(\d+)\/(\d+)", value)
if matches is not None:
n = int(matches.group(1))
d = int(matches.group(2))
return n,d
else:
environLocal.printDebug(['slashToFraction() cannot find two part fraction', value])
return None
def slashCompoundToFraction(value):
'''
>>> from music21 import *
>>> meter.slashCompoundToFraction('3/8+2/8')
[(3, 8), (2, 8)]
>>> meter.slashCompoundToFraction('5/8')
[(5, 8)]
>>> meter.slashCompoundToFraction('5/8+2/4+6/8')
[(5, 8), (2, 4), (6, 8)]
'''
post = []
value = value.strip() # rem whitespace
value = value.split('+')
for part in value:
m = slashToFraction(part)
if m == None:
pass
else:
post.append(m)
return post
def slashMixedToFraction(valueSrc):
'''Given a mixture if possible meter fraction representations, return
a list of pairs. If originally given as a summed numerator; break
into separate fractions.
>>> from music21 import *
>>> meter.slashMixedToFraction('3/8+2/8')
([(3, 8), (2, 8)], False)
>>> meter.slashMixedToFraction('3+2/8')
([(3, 8), (2, 8)], True)
>>> meter.slashMixedToFraction('3+2+5/8')
([(3, 8), (2, 8), (5, 8)], True)
>>> meter.slashMixedToFraction('3+2+5/8+3/4')
([(3, 8), (2, 8), (5, 8), (3, 4)], True)
>>> meter.slashMixedToFraction('3+2+5/8+3/4+2+1+4/16')
([(3, 8), (2, 8), (5, 8), (3, 4), (2, 16), (1, 16), (4, 16)], True)
>>> meter.slashMixedToFraction('3+2+5/8+3/4+2+1+4')
Traceback (most recent call last):
...
MeterException: cannot match denominator to numerator in: 3+2+5/8+3/4+2+1+4
'''
pre = []
post = []
summedNumerator = False
value = valueSrc.strip() # rem whitespace
value = value.split('+')
for part in value:
if '/' in part:
fraction = slashToFraction(part)
if fraction == None:
raise TimeSignatureException('cannot create time signature from:', valueSrc)
pre.append(list(fraction))
else: # its just a numerator
pre.append([int(part), None])
# when encountering a missing denominator, find the fist defined
# and apply to all previous
for i in range(len(pre)):
if pre[i][1] != None: # there is a denominator
post.append(tuple(pre[i]))
else: # search ahead for next defined denominator
summedNumerator = True
match = None
for j in range(i, len(pre)):
if pre[j][1] != None:
match = pre[j][1]
break
if match == None:
raise MeterException('cannot match denominator to numerator in: %s' % valueSrc)
else:
pre[i][1] = match
post.append(tuple(pre[i]))
return post, summedNumerator
def fractionToSlashMixed(fList):
'''Given a list of fraction values, compact numerators by sum if
denominators are the same
>>> from music21 import *
>>> meter.fractionToSlashMixed([(3, 8), (2, 8), (5, 8), (3, 4), (2, 16), (1, 16), (4, 16)])
[('3+2+5', 8), ('3', 4), ('2+1+4', 16)]
'''
pre = []
for i in range(len(fList)):
n, d = fList[i]
# look at previous fration and determin if denominator is the same
match = None
search = range(0,len(pre))
search.reverse() # go backwards
for j in search:
if pre[j][1] == d:
match = j # index to add numerator
break
else:
break # if not found in one less
if match == None:
pre.append([[n], d])
else: # appnd nuemrator
pre[match][0].append(n)
# create string representation
post = []
for part in pre:
n = [str(x) for x in part[0]]
n = '+'.join(n)
d = part[1]
post.append((n, d))
return post
def fractionSum(fList):
'''Given a list of fractions represented as a list, find the sum
>>> from music21 import *
>>> meter.fractionSum([(3,8), (5,8), (1,8)])
(9, 8)
>>> meter.fractionSum([(1,6), (2,3)])
(5, 6)
>>> meter.fractionSum([(3,4), (1,2)])
(5, 4)
>>> meter.fractionSum([(1,13), (2,17)])
(43, 221)
'''
nList = []
dList = []
nListUnique = []
dListUnique = []
for n,d in fList:
nList.append(n)
if n not in nListUnique:
nListUnique.append(n)
dList.append(d)
if d not in dListUnique:
dListUnique.append(d)
if len(dListUnique) == 1:
n = sum(nList)
d = dList[0]
return (n, d)
else: # there might be a better way to do this
d = 1
d = common.lcm(dListUnique)
# after finding d, multuple each numerator
nShift = []
for i in range(len(nList)):
nSrc = nList[i]
dSrc = dList[i]
scalar = d / dSrc
nShift.append(nSrc*scalar)
return (sum(nShift), d)
def proportionToFraction(value):
'''Given a floating point proportional value between 0 and 1, return the best-fit slash-base fraction
>>> from music21 import *
>>> meter.proportionToFraction(.5)
(1, 2)
>>> meter.proportionToFraction(.25)
(1, 4)
>>> meter.proportionToFraction(.75)
(3, 4)
>>> meter.proportionToFraction(.125)
(1, 8)
>>> meter.proportionToFraction(.375)
(3, 8)
>>> meter.proportionToFraction(.625)
(5, 8)
>>> meter.proportionToFraction(.333)
(1, 3)
>>> meter.proportionToFraction(0.83333)
(5, 6)
'''
# TODO: this is a brut-force method: is there a more elegant alternative?
for i in range(2,16+1):
xBase = 1. / i
for j in range(1,i+1): # take all multiples
x = xBase * j
if common.almostEquals(value, x, grain=1e-3):
return (j, i)
return None
#-------------------------------------------------------------------------------
class MeterException(Exception):
pass
class TimeSignatureException(MeterException):
pass
#-------------------------------------------------------------------------------
class MeterTerminal(object):
'''A MeterTerminal is a nestable primitive of rhythmic division
>>> from music21 import *
>>> a = meter.MeterTerminal('2/4')
>>> a.duration.quarterLength
2.0
>>> a = meter.MeterTerminal('3/8')
>>> a.duration.quarterLength
1.5
>>> a = meter.MeterTerminal('5/2')
>>> a.duration.quarterLength
10.0
'''
def __init__(self, slashNotation=None, weight=1):
self._numerator = 0
self._denominator = 1
self._overriddenDuration = None
if slashNotation != None:
# assign directly to values, not properties, to avoid
# calling _ratioChanged more than necessary
self._numerator, self._denominator = slashToFraction(slashNotation)
self._ratioChanged() # sets self._duration
# this will call _setWeight property for data checking
# explicitly calling base class method to avoid problems
# in the derived class MeterSequence
MeterTerminal._setWeight(self, weight)
def __deepcopy__(self, memo=None):
'''Helper method to copy.py's deepcopy function. Call it from there.
Defining a custom __deepcopy__ here is a performance boost, particularly in not copying _duration, directly assigning _weight, and other benefits.
>>> from copy import deepcopy
'''
# call class to get a new, empty instance
new = self.__class__()
#for name in dir(self):
new._numerator = self._numerator
new._denominator = self._denominator
new._ratioChanged() # faster than copying dur
#new._duration = copy.deepcopy(self._duration, memo)
new._weight = self._weight # these are numbers
return new
def __str__(self):
return str(int(self.numerator)) + "/" + str(int(self.denominator))
def __repr__(self):
return '<MeterTerminal %s>' % self.__str__()
# now using ratioEqual()
# def __eq__(self, other):
# '''Equality.
#
# >>> a = MeterTerminal('2/4')
# >>> b = MeterTerminal('3/4')
# '''
# # if not isinstnace(other, MeterTerminal):
# # return False
# if other == None: return False
# if (other.numerator == self.numerator and
# other.denominator == self.denominator):
# return True
# else:
# return False
#
# def __ne__(self, other):
# '''Inequality.
# '''
# # if not isinstnace(other, MeterTerminal):
# # return True
# if other == None: return True
# if (other.numerator == self.numerator and
# other.denominator == self.denominator):
# return False
# else:
# return True
def ratioEqual(self, other):
'''Compare the numerator and denominator of another object.
Note that these have to be exact matches; 3/4 is not the same as 6/8
>>> from music21 import meter
>>> a = meter.MeterTerminal('3/4')
>>> b = meter.MeterTerminal('6/4')
>>> c = meter.MeterTerminal('2/4')
>>> d = meter.MeterTerminal('3/4')
>>> a.ratioEqual(b)
False
>>> a.ratioEqual(c)
False
>>> a.ratioEqual(d)
True
'''
if other == None: return False
if (other.numerator == self.numerator and
other.denominator == self.denominator):
return True
else:
return False
#---------------------------------------------------------------------------
def subdivideByCount(self, countRequest=None):
'''retrun a MeterSequence
>>> from music21 import *
>>> a = meter.MeterTerminal('3/4')
>>> b = a.subdivideByCount(3)
>>> isinstance(b, meter.MeterSequence)
True
>>> len(b)
3
'''
# elevate to meter sequence
ms = MeterSequence()
# cannot set the weight of this MeterSequence w/o having offsets
# pass this MeterTerminal as an argument
# when subdividing, use autoWeight
ms.load(self, countRequest, autoWeight=True, targetWeight=self.weight)
return ms
def subdivideByList(self, numeratorList):
'''Return a MeterSequence
countRequest is within the context of the beatIndex
>>> from music21 import *
>>> a = meter.MeterTerminal('3/4')
>>> b = a.subdivideByList([1,1,1])
>>> len(b)
3
'''
# elevate to meter sequence
ms = MeterSequence()
ms.load(self) # do not need to autoWeight here
ms.partitionByList(numeratorList) # this will split weight
return ms
def subdivideByOther(self, other):
'''Return a MeterSequence
based on another MeterSequence
>>> from music21 import *
>>> a = meter.MeterSequence('1/4+1/4+1/4')
>>> a
<MeterSequence {1/4+1/4+1/4}>
>>> b = meter.MeterSequence('3/8+3/8')
>>> a.subdivideByOther(b)
<MeterSequence {{3/8+3/8}}>
'''
# elevate to meter sequence
ms = MeterSequence()
if other.duration.quarterLength != self.duration.quarterLength:
raise MeterException('cannot subdivide by other: %s' % other)
ms.load(other) # do not need to autoWeight here
#ms.partitionByOther(other) # this will split weight
return ms
def subdivide(self, value):
'''Subdivision takes a MeterTerminal and, making it into a a collection of MeterTerminals, Returns a MeterSequence.
This is different than a partitioning a MeterSequence in that this does not happen in place and instead returns a new object.
If an integer is provided, assume it is a partition count
'''
if common.isListLike(value):
return self.subdivideByList(value)
elif isinstance(value, MeterSequence):
return self.subdivideByOther(value)
elif common.isNum(value):
return self.subdivideByCount(value)
else:
raise MeterException('cannot process partition argument %s' % value)
#---------------------------------------------------------------------------
# properties
def _getWeight(self):
return self._weight
def _setWeight(self, value):
'''
>>> from music21 import *
>>> a = meter.MeterTerminal('2/4')
>>> a.weight = .5
>>> a.weight
0.5
'''
# if not common.isNum(value):
# raise MeterException('weight values must be numbers')
self._weight = value
weight = property(_getWeight, _setWeight)
def _getNumerator(self):
return self._numerator
def _setNumerator(self, value):
'''
>>> from music21 import *
>>> a = meter.MeterTerminal('2/4')
>>> a.duration.quarterLength
2.0
>>> a.numerator = 11
>>> a.duration.quarterLength
11.0
'''
self._numerator = value
self._ratioChanged()
numerator = property(_getNumerator, _setNumerator)
def _getDenominator(self):
return self._denominator
def _setDenominator(self, value):
'''
>>> from music21 import *
>>> a = meter.MeterTerminal('2/4')
>>> a.duration.quarterLength
2.0
>>> a.numerator = 11
>>> a.duration.quarterLength
11.0
'''
# use duration.typeFromNumDict?
if value not in validDenominators:
raise MeterException('bad denominator value: %s' % value)
self._denominator = value
self._ratioChanged()
denominator = property(_getDenominator, _setDenominator)
def _ratioChanged(self):
'''If ratio has been changed, call this to update duration
'''
# NOTE: this is a performance critical method and should only be
# called when necessary
if self.numerator == None or self.denominator == None:
self._duration = None
else:
self._duration = duration.Duration()
try:
self._duration.quarterLength = ((4.0 *
self.numerator)/self.denominator)
except duration.DurationException:
environLocal.printDebug(['DurationException encountered',
'numerator/denominator', self.numerator, self.denominator])
self._duration = None
def _getDuration(self):
'''
barDuration gets or sets a duration value that
is equal in length to the totalLength
>>> from music21 import *
>>> a = meter.MeterTerminal()
>>> a.numerator = 3
>>> a.denominator = 8
>>> d = a.duration
>>> d.type
'quarter'
>>> d.dots
1
>>> d.quarterLength
1.5
'''
if self._overriddenDuration:
return self._overriddenDuration
else:
return self._duration
def _setDuration(self, value):
self._overriddenDuration = value
duration = property(_getDuration, _setDuration)
def _getDepth(self):
'''Return how many levels deep this part is. Depth of a terminal is always 1
'''
return 1
depth = property(_getDepth)
# def _getBeatLengthToQuarterLengthRatio(self):
# '''
# >>> a = MeterTerminal()
# >>> a.numerator = 3
# >>> a.denominator = 2
# >>> a.beatLengthToQuarterLengthRatio
# 2.0
# '''
# return 4.0/self.denominator
#
# beatLengthToQuarterLengthRatio = property(_getBeatLengthToQuarterLengthRatio)
#
#
# def _getQuarterLengthToBeatLengthRatio(self):
# return self.denominator/4.0
#
# quarterLengthToBeatLengthRatio = property(_getQuarterLengthToBeatLengthRatio)
#
#
# def quarterPositionToBeat(self, currentQtrPosition = 0):
# return ((currentQtrPosition * self.quarterLengthToBeatLengthRatio) + 1)
#
#-------------------------------------------------------------------------------
class MeterSequence(MeterTerminal):
'''A meter sequence is a list of MeterTerminals, or other MeterSequences
'''
def __init__(self, value=None, partitionRequest=None):
MeterTerminal.__init__(self)
self._numerator = None # rationalized
self._denominator = None # lowest common multiple
self._partition = [] # a list of terminals or MeterSequences
self._overriddenDuration = None
self._levelListCache = {}
# this atribute is only used in MeterTermainals, and note
# in MeterSequences; a MeterSequences weight is based solely
# on the sum of its components
del self._weight
# store whether this meter was provided as a summed nuemerator
self.summedNumerator = False
# an optional parameter used only in displaying this meter sq
# needed in cases where a meter component is parenthetical
self.parenthesis = False
if value != None:
self.load(value, partitionRequest)
def __deepcopy__(self, memo=None):
'''Helper method to copy.py's deepcopy function. Call it from there.
Defining a custom __deepcopy__ here is a performance boost, particularly in not copying _duration and other benefits. Notably, self._levelListCache is not copied, with may not be needed in the copy and may be large.
>>> from copy import deepcopy
'''
# call class to get a new, empty instance
new = self.__class__()
#for name in dir(self):
new._numerator = self._numerator
new._denominator = self._denominator
new._partition = copy.deepcopy(self._partition, memo)
new._ratioChanged() # faster than copying dur
#new._duration = copy.deepcopy(self._duration, memo)
new._overriddenDuration = self._overriddenDuration
new.summedNumerator = self.summedNumerator
new.parenthesis = self.parenthesis
return new
def __str__(self):
msg = []
for mt in self._partition:
msg.append(str(mt))
return '{%s}' % '+'.join(msg)
def __repr__(self):
return '<MeterSequence %s>' % self.__str__()
def __len__(self):
'''Return the length of the partition list
>>> from music21 import *
>>> a = meter.MeterSequence('4/4', 4)
>>> len(a)
4
'''
return len(self._partition)
def __iter__(self):
'''Support iteration of top level partitions
'''
return common.Iterator(self._partition)
def __getitem__(self, key):
'''Get an MeterTerminal from _partition
>>> from music21 import *
>>> a = meter.MeterSequence('4/4', 4)
>>> a[3].numerator
1
'''
if abs(key) >= self.__len__():
raise IndexError
else:
return self._partition[key]
def __setitem__(self, key, value):
'''Insert items at index positions.
>>> from music21 import *
>>> a = meter.MeterSequence('4/4', 4)
>>> a[0] = a[0].subdivide(2)
>>> a
<MeterSequence {{1/8+1/8}+1/4+1/4+1/4}>
>>> a[0][0] = a[0][0].subdivide(2)
>>> a
<MeterSequence {{{1/16+1/16}+1/8}+1/4+1/4+1/4}>
>>> a[3] = a[0][0].subdivide(2)
Traceback (most recent call last):
...
MeterException: cannot insert {1/16+1/16} into space of 1/4
'''
# comparison of numerator and denominator
if not isinstance(value, MeterTerminal):
raise MeterException('values in MeterSequences must be MeterTerminals or MeterSequences, not %s' % value)
if value.ratioEqual(self[key]):
self._partition[key] = value
else:
raise MeterException('cannot insert %s into space of %s' % (value, self[key]))
# clear cache
self._levelListCache = {}
#---------------------------------------------------------------------------
# load common meter templates into this sequence
def _divisionOptionsAlgo(self, n, d):
'''
This is a primitive approach to algorithmic division production.
This can be extended.
It is assumed that these values are provided in order of priority
>>> from music21 import *
>>> a = meter.MeterSequence()
>>> a._divisionOptionsAlgo(4,4)
[['1/4', '1/4', '1/4', '1/4'], ['1/2', '1/2'], ['4/4'], ['2/4', '2/4'], ['2/2'], ['1/1'], ['8/8'], ['16/16'], ['32/32'], ['64/64'], ['128/128']]
>>> a._divisionOptionsAlgo(1,4)
[['1/4'], ['1/8', '1/8'], ['1/16', '1/16', '1/16', '1/16'], ['1/32', '1/32', '1/32', '1/32', '1/32', '1/32', '1/32', '1/32'], ['1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64', '1/64'], ['1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128', '1/128'], ['2/8'], ['4/16'], ['8/32'], ['16/64'], ['32/128']]
>>> a._divisionOptionsAlgo(2,2)
[['1/2', '1/2'], ['2/2'], ['1/1'], ['4/4'], ['8/8'], ['16/16'], ['32/32'], ['64/64'], ['128/128']]
>>> a._divisionOptionsAlgo(3,8)
[['1/8', '1/8', '1/8'], ['3/8'], ['6/16'], ['12/32'], ['24/64'], ['48/128']]
>>> a._divisionOptionsAlgo(6,8)
[['3/8', '3/8'], ['1/8', '1/8', '1/8', '1/8', '1/8', '1/8'], ['1/4', '1/4', '1/4'], ['6/8'], ['3/4'], ['12/16'], ['24/32'], ['48/64'], ['96/128']]
>>> a._divisionOptionsAlgo(12,8)
[['3/8', '3/8', '3/8', '3/8'], ['1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8', '1/8'], ['1/4', '1/4', '1/4', '1/4', '1/4', '1/4'], ['1/2', '1/2', '1/2'], ['12/8'], ['6/8', '6/8'], ['6/4'], ['3/2'], ['24/16'], ['48/32'], ['96/64'], ['192/128']]
>>> a._divisionOptionsAlgo(5,8)
[['2/8', '3/8'], ['3/8', '2/8'], ['1/8', '1/8', '1/8', '1/8', '1/8'], ['5/8'], ['10/16'], ['20/32'], ['40/64'], ['80/128']]
>>> a._divisionOptionsAlgo(18,4)
[['3/4', '3/4', '3/4', '3/4', '3/4', '3/4'], ['1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4', '1/4'], ['1/2', '1/2', '1/2', '1/2', '1/2', '1/2', '1/2', '1/2', '1/2'], ['18/4'], ['9/4', '9/4'], ['4/4', '4/4', '4/4', '4/4'], ['2/4', '2/4', '2/4', '2/4', '2/4', '2/4', '2/4', '2/4'], ['9/2'], ['36/8'], ['72/16'], ['144/32'], ['288/64'], ['576/128']]
'''
opts = []
# compound meters; 6, 9, 12, 15, 18
# 9/4, 9/2, 6/2 are all considered compound without d>4
#if n % 3 == 0 and n > 3 and d > 4:
if n % 3 == 0 and n > 3:
nMod = n / 3
seq = []
for x in range(n/3):
seq.append('%s/%s' % (3, d))
opts.append(seq)
# odd meters with common groupings
if n == 5:
for group in [[2,3], [3,2]]:
seq = []
for nMod in group:
seq.append('%s/%s' % (nMod, d))
opts.append(seq)
if n == 7:
for group in [[2,2,3], [3,2,2], [2,3,2]]:
seq = []
for nMod in group:
seq.append('%s/%s' % (nMod, d))
opts.append(seq)
# not really necessary but an example of a possibility
if n == 10:
for group in [[2,2,3,3]]:
seq = []
for nMod in group:
seq.append('%s/%s' % (nMod, d))
opts.append(seq)
# simple additive options uses the minimum numerator of 1
if n > 1 and d >= 1:
seq = []
for x in range(n):
seq.append('%s/%s' % (1, d))
opts.append(seq)
# divided additive multiples
if n % 2 == 0 and d / 2 >= 1:
nMod = n / 2
dMod = d / 2
while True:
if dMod < 1 or nMod <= 1:
break
seq = []
for x in range(nMod):
seq.append('%s/%s' % (1, dMod))
opts.append(seq)
if nMod % 2 != 0: # if no longer even must stop
break
dMod = dMod / 2
nMod = nMod / 2
# add src representation
opts.append(['%s/%s' % (n,d)])
# additive multiples with the same denominators
# numerators must be even, do not take numerator to 1
if n > 3 and n % 2 == 0:
i = 2
nMod = n / 2
while True:
if nMod <= 1:
break
seq = []
for x in range(i):
seq.append('%s/%s' % (nMod, d))
if seq not in opts: # may be cases defined elsewhere
opts.append(seq)
nMod = nMod / 2
i *= 2
# additive multiples with smaller denominators
# only doing this for numerators of 1 for now
if d < validDenominators[-1] and n == 1:
i = 2
dMod = d * 2
while True:
if dMod > validDenominators[-1]:
break
seq = []
for x in range(i):
seq.append('%s/%s' % (n, dMod))
opts.append(seq)
dMod = dMod * 2
i *= 2
# equivalent fractions downward
if d > validDenominators[0] and n % 2 == 0:
nMod = n / 2
dMod = d / 2
while True:
if dMod < validDenominators[0]:
break
opts.append(['%s/%s' % (nMod, dMod)])
if nMod % 2 != 0: # no longer even
break
dMod = dMod / 2
nMod = nMod / 2
# equivalent fractions upward
if d < validDenominators[-1]:
nMod = n * 2
dMod = d * 2
while True:
if dMod > validDenominators[-1]:
break
opts.append(['%s/%s' % (nMod, dMod)])
dMod = dMod * 2
nMod = nMod * 2
return opts
def _divisionOptionsPreset(self, n, d):
'''Provide fixed set of meter divisions that will not be easily
obtained algorithmically
'''
opts = []
return opts
#---------------------------------------------------------------------------
def _clearPartition(self):
'''This will not sync with .numerator and .denominator if called alone
'''
self._partition = []
# clear cache
self._levelListCache = {}
def _addTerminal(self, value):
'''Add a an object to the partition list. This does not update numerator and denominator.
targetWeight is the expected total Weight for this MeterSequence. This
would be self.weight, but offten partitions are cleared before _addTerminal is called.
'''
# NOTE: this is a performance critical method
if isinstance(value, MeterTerminal): # may be a MeterSequence
mt = value
else: # assume it is a string
mt = MeterTerminal(value)
# if common.isStr(value):
# mt = MeterTerminal(value)
# elif isinstance(value, MeterTerminal): # may be a MeterSequence
# mt = value
# else:
# raise MeterException('cannot add %s to this sequence' % value)
self._partition.append(mt)
# clear cache
self._levelListCache = {}
def _getOptions(self):
# all-string python dictionaries are optimized; use string key
n = int(self.numerator)
d = int(self.denominator)
tsStr = '%s/%s' % (n, d)
try:
# return a stored, cached value
return _meterSequenceDivisionOptions[tsStr]
except KeyError:
opts = []
opts += self._divisionOptionsAlgo(n, d)
opts += self._divisionOptionsPreset(n, d)
# store for access later
_meterSequenceDivisionOptions[tsStr] = opts
return opts
#---------------------------------------------------------------------------
def partitionByCount(self, countRequest, loadDefault=True):
'''This will destroy any structure in the _partition
>>> from music21 import *
>>> a = meter.MeterSequence('4/4')
>>> a.partitionByCount(2)
>>> str(a)
'{1/2+1/2}'
>>> a.partitionByCount(4)
>>> str(a)
'{1/4+1/4+1/4+1/4}'
'''
opts = self._getOptions()
optMatch = None
# get the first encountered load string with the desired
# number of beats
if countRequest != None:
for opt in opts:
if len(opt) == countRequest:
optMatch = opt
break
# if no matches this method provides a deafult
if optMatch == None and loadDefault:
optMatch = opts[0]
if optMatch != None:
targetWeight = self.weight
#environLocal.printDebug(['partitionByCount, targetWeight', targetWeight])
self._clearPartition() # weight will now be zero
for mStr in optMatch:
self._addTerminal(mStr)
self.weight = targetWeight
else:
raise MeterException('Cannot set partition by %s (%s/%s)' % (countRequest, self.numerator, self.denominator))
# clear cache
self._levelListCache = {}
def partitionByList(self, numeratorList):
'''Given a numerator list, partition MeterSequence inot a new list
of MeterTerminals
>>> from music21 import *
>>> a = meter.MeterSequence('4/4')
>>> a.partitionByList([1,1,1,1])
>>> str(a)
'{1/4+1/4+1/4+1/4}'
>>> a.partitionByList(['3/4', '1/8', '1/8'])
>>> a
<MeterSequence {3/4+1/8+1/8}>
>>> a.partitionByList(['3/4', '1/8', '5/8'])
Traceback (most recent call last):
MeterException: Cannot set partition by ['3/4', '1/8', '5/8']