/
base.py
4918 lines (4048 loc) · 182 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Name: base.py
# Purpose: Music21 base classes and important utilities
#
# Authors: Michael Scott Cuthbert
# Christopher Ariza
#
# Copyright: Copyright © 2006-2016 Michael Scott Cuthbert and the music21
# Project
# License: LGPL or BSD, see license.txt
#------------------------------------------------------------------------------
'''
`music21.base` is what you get in `music21` if you type ``import music21``. It
contains all the most low-level objects that also appear in the music21 module
(i.e., music21.base.Music21Object is the same as music21.Music21Object).
Music21 base classes for :class:`~music21.stream.Stream` objects and all
elements contained within them including Notes, etc.. Additional objects for
defining and manipulating elements are included.
The namespace of this file, as all base.py files, is loaded into the package
that contains this file via __init__.py. Everything in this file is thus
available after importing music21.
>>> import music21
>>> music21.Music21Object
<class 'music21.base.Music21Object'>
>>> music21.VERSION_STR
'3.0.2'
Alternatively, after doing a complete import, these classes are available
under the module "base":
>>> base.Music21Object
<class 'music21.base.Music21Object'>
'''
from __future__ import (print_function, division)
import copy
import sys
import types
import unittest
from collections import namedtuple
from music21.test.testRunner import mainTest
from music21.ext import six
## all other music21 modules below...
#------------------------------------------------------------------------------
# version string and tuple must be the same
from music21._version import __version__, __version_info__
VERSION = __version_info__
VERSION_STR = __version__
#------------------------------------------------------------------------------
__all__ = ['Music21Exception',
'SitesException',
'Music21ObjectException',
'ElementException',
'Groups',
'Music21Object',
'ElementWrapper',
'VERSION',
'VERSION_STR',
]
## N.B. for eclipse "all" import working, we need to list this
# separately in "music21/__init__.py"
## so make sure to update in both places
#-----all exceptions are in the exceptions21 package.
from music21 import exceptions21
Music21Exception = exceptions21.Music21Exception
from music21.sites import SitesException
from music21 import sites
from music21 import common
from music21 import defaults
from music21 import derivation
from music21 import duration
from music21 import environment
from music21.common import opFrac
from music21.sorting import SortTuple, ZeroSortTupleLow, ZeroSortTupleHigh
_MOD = 'music21.base.py'
environLocal = environment.Environment(_MOD)
# check external dependencies and display
_missingImport = []
import imp
for modName in ('matplotlib', 'numpy', 'scipy'):
try:
imp.find_module(modName)
except ImportError:
_missingImport.append(modName)
# used for better PNG processing in lily -- not very important
#try:
# from PIL import Image
#except ImportError:
# try:
# import Image
# except ImportError:
# _missingImport.append('PIL')
# as this is only needed for one module, and error messages print
# to standard io, this has been removed
# try:
# import pyaudio
# except (ImportError, SystemExit):
# _missingImport.append('pyaudio')
#sys.stderr.write('pyaudio is installed but PortAudio is not -- ' +
# 're-download pyaudio at http://people.csail.mit.edu/hubert/pyaudio/')
if _missingImport:
if environLocal['warnings'] in (1, '1', True):
environLocal.warn(common.getMissingImportStr(_missingImport),
header='music21:')
class Music21ObjectException(exceptions21.Music21Exception):
pass
class ElementException(exceptions21.Music21Exception):
pass
#------------------------------------------------------------------------------
# for contextSites searches...
ContextTuple = namedtuple('ContextTuple', 'site offset recurseType')
# pseudo class for returning splitAtX() type commands.
class _SplitTuple(tuple):
'''
>>> st = base._SplitTuple([1, 2])
>>> st.spannerList = [3]
>>> st
(1, 2)
>>> st.spannerList
[3]
>>> a, b = st
>>> a
1
>>> b
2
>>> st.__class__
<... 'music21.base._SplitTuple'>
'''
def __new__(cls, tupEls):
return super(_SplitTuple, cls).__new__(cls, tuple(tupEls))
def __init__(self, tupEls): # pylint: disable=super-init-not-called
self.spannerList = []
#------------------------------------------------------------------------------
# make subclass of set once that is defined properly
class Groups(list): # no need to inherit from slotted object
'''
Groups is a list (subclass) of strings used to identify
associations that an element might have.
The Groups object enforces that all elements must be strings, and that
the same element cannot be provided more than once.
NOTE: In the future, spaces will not be allowed in group names.
>>> g = Groups()
>>> g.append("hello")
>>> g[0]
'hello'
>>> g.append("hello") # not added as already present
>>> len(g)
1
>>> g
['hello']
>>> g.append(5)
Traceback (most recent call last):
GroupException: Only strings can be used as group names
'''
# could be made into a set instance, but actually
# timing: a subclassed list and a set are almost the same speed
# and set does not allow calling by number
# this speeds up creation slightly...
__slots__ = ()
def _validName(self, value):
if not isinstance(value, six.string_types):
raise exceptions21.GroupException("Only strings can be used as group names")
#if ' ' in value:
# raise exceptions21.GroupException("Spaces are not allowed as group names")
def append(self, value):
self._validName(value)
if not list.__contains__(self, value):
list.append(self, value)
def __setitem__(self, i, y):
self._validName(y)
list.__setitem__(self, i, y)
def __eq__(self, other):
'''
Test Group equality. In normal lists, order matters; here it does not. More like a set.
>>> a = base.Groups()
>>> a.append('red')
>>> a.append('green')
>>> a
['red', 'green']
>>> b = base.Groups()
>>> b.append('green')
>>> a == b
False
>>> b.append('reD') # case insensitive
>>> a == b
True
>>> a == ['red', 'green'] # need both to be groups
False
>>> c = base.Groups()
>>> c.append('black')
>>> c.append('tuba')
>>> a == c
False
'''
if not isinstance(other, Groups):
return False
if len(self) != len(other):
return False
sls = sorted(self)
slo = sorted(other)
for x in range(len(sls)):
if sls[x].lower() != slo[x].lower():
return False
return True
def __ne__(self, other):
'''
In normal lists, order matters; here it does not.
>>> a = Groups()
>>> a.append('red')
>>> a.append('green')
>>> a
['red', 'green']
>>> b = Groups()
>>> b.append('green')
>>> b.append('blue')
>>> a != b
True
'''
return not (self == other)
#------------------------------------------------------------------------------
class Music21Object(object):
'''
Base class for all music21 objects.
All music21 objects have these pieces of information:
1. id: identification string unique to the objects container (optional). Defaults to the
`id()` of the element.
2. groups: a Groups object: which is a list of strings identifying
internal subcollections (voices, parts, selections) to which this
element belongs
3. duration: Duration object representing the length of the object
4. activeSite: a reference to the currently active Stream or None
5. offset: a floating point value, generally in quarter lengths,
specifying the position of the object in a site.
6. priority: int representing the position of an object among all
objects at the same offset.
7. sites: a :class:`~music21.base.Sites` object that stores all
the Streams and Contexts that an
object is in.
8. derivation: a :class:`~music21.derivation.Derivation` object, or None, that shows
where the object came from.
Each of these may be passed in as a named keyword to any music21 object.
Some of these may be intercepted by the subclassing object (e.g., duration
within Note)
'''
classSortOrder = 20 # default classSortOrder
# these values permit fast class comparisons for performance critical cases
isStream = False
# this dictionary stores as a tuple of strings for each Class so that
# it only needs to be made once (11 microseconds per call, can be
# a big part of iteration; from cache just 1 microsecond)
_classListCacheDict = {}
_classSetCacheDict = {}
# same with fully qualified names
_classListFullyQualifiedCacheDict = {}
# define order to present names in documentation; use strings
_DOC_ORDER = [
'classes',
'classSet',
]
# documentation for all attributes (not properties or methods)
_DOC_ATTR = {
'id': '''A unique identification string; not to be confused with the
default `.id()` method. However, if not set, will return the `id()` number''',
'groups': '''An instance of a :class:`~music21.base.Group` object which describes
arbitrary `Groups` that this object belongs to.''',
'isStream': '''Boolean value for quickly identifying
:class:`~music21.stream.Stream` objects (False by default). Deprecated''',
'classSortOrder' : '''Property which returns an number (int or otherwise)
depending on the class of the Music21Object that
represents a priority for an object based on its class alone --
used as a tie for stream sorting in case two objects have the
same offset and priority. Lower numbers are sorted to the left
of higher numbers. For instance, Clef, KeySignature, TimeSignature
all come (in that order) before Note.
All undefined classes have classSortOrder of 20 -- same as note.Note
>>> m21o = base.Music21Object()
>>> m21o.classSortOrder
20
>>> tc = clef.TrebleClef()
>>> tc.classSortOrder
0
>>> ks = key.KeySignature(3)
>>> ks.classSortOrder
2
New classes can define their own default classSortOrder
>>> class ExampleClass(base.Music21Object):
... classSortOrder = 5
...
>>> ec1 = ExampleClass()
>>> ec1.classSortOrder
5
''',
'hideObjectOnPrint': '''if set to `True` will not print upon output
(only used in MusicXML output at this point and
Lilypond for notes, chords, and rests).''',
'xPosition': '''if set, defines the display x-position from
the start of the container (in musicxml "tenths" by default)''',
}
def __init__(self, *arguments, **keywords):
# None is stored as the internal location of an obj w/o any sites
self._activeSite = None
# offset when no activeSite is available
self._naiveOffset = 0.0
# offset when activeSite is already garbage collected/dead, as in short-lived sites
# like .getElementsByClass
self._activeSiteStoredOffset = None
# store a derivation object to track derivations from other Streams
# pass a reference to this object
self._derivation = None
# private duration storage; managed by property
self._duration = None
self._priority = 0 # default is zero
self.hideObjectOnPrint = False
self.xPosition = None
if "id" in keywords:
self.id = keywords["id"]
else:
self.id = id(self)
# a duration object is not created until the .duration property is
# accessed with _getDuration(); this is a performance optimization
if "duration" in keywords:
self.duration = keywords["duration"]
if "groups" in keywords and keywords["groups"] is not None:
self.groups = keywords["groups"]
else:
self.groups = Groups()
if "sites" in keywords:
self.sites = keywords["sites"]
else:
self.sites = sites.Sites()
if "activeSite" in keywords:
self.activeSite = keywords["activeSite"]
def mergeAttributes(self, other):
'''
Merge all elementary, static attributes. Namely,
`id` and `groups` attributes from another music21 object.
Can be useful for copy-like operations.
>>> m1 = base.Music21Object()
>>> m2 = base.Music21Object()
>>> m1.id = 'music21Object1'
>>> m1.groups.append("group1")
>>> m2.mergeAttributes(m1)
>>> m2.id
'music21Object1'
>>> "group1" in m2.groups
True
'''
if other.id != id(other):
self.id = other.id
self.groups = copy.deepcopy(other.groups)
def _deepcopySubclassable(self, memo=None, ignoreAttributes=None, removeFromIgnore=None):
'''
Subclassable __deepcopy__ helper so that the same attributes do not need to be called
for each Music21Object subclass.
ignoreAttributes is a set of attributes not to copy via the default deepcopy style.
More can be passed to it.
removeFromIgnore can be a set of attributes to remove from ignoreAttributes of a
superclass.
TODO: move to class attributes to cache.
'''
defaultIgnoreSet = {'_derivation', '_activeSite', 'id', 'sites', '_duration'}
if ignoreAttributes is None:
ignoreAttributes = defaultIgnoreSet
else:
ignoreAttributes = ignoreAttributes | defaultIgnoreSet
if removeFromIgnore is not None:
ignoreAttributes = ignoreAttributes - removeFromIgnore
# call class to get a new, empty instance
new = self.__class__() # TODO: this creates an extra duration object for notes... ugghhh...
#environLocal.printDebug(['Music21Object.__deepcopy__', self, id(self)])
#for name in dir(self):
if '_duration' in ignoreAttributes:
## this can be done much faster in most cases...
d = self._duration
if d is not None:
clientStore = self._duration._client
self._duration._client = None
newValue = copy.deepcopy(self._duration, memo)
self._duration._client = clientStore
newValue.client = new
setattr(new, '_duration', newValue)
if '_derivation' in ignoreAttributes:
# was: keep the old ancestor but need to update the client
# 2.1 : NO, add a derivation of __deepcopy__ to the client
newDerivation = derivation.Derivation(client=new)
newDerivation.origin = self
newDerivation.method = '__deepcopy__'
setattr(new, '_derivation', newDerivation)
if '_activeSite' in ignoreAttributes:
# TODO: Fix this so as not to allow incorrect _activeSite (???)
# keep a reference, not a deepcopy
# do not use property: .activeSite; set to same weakref obj
# restore jan 18
# setattr(new, '_activeSite', None)
setattr(new, '_activeSite', self._activeSite)
if 'id' in ignoreAttributes:
value = getattr(self, 'id')
if value != id(self) or (common.isNum(value) and
value < defaults.minIdNumberToConsiderMemoryLocation):
newValue = value
setattr(new, 'id', newValue)
if 'sites' in ignoreAttributes:
# we make a copy of the sites value even though it is obsolete because
# the spanners will need to be preserved and then set to the new value
# elsewhere. The purgeOrphans call later will remove all but
# spanners and variants.
value = getattr(self, 'sites')
# this calls __deepcopy__ in Sites
newValue = copy.deepcopy(value, memo)
setattr(new, 'sites', newValue)
for name in self.__dict__:
if name.startswith('__'):
continue
if name in ignoreAttributes:
continue
attrValue = getattr(self, name)
# attributes that do not require special handling
try:
deeplyCopiedObject = copy.deepcopy(attrValue, memo)
setattr(new, name, deeplyCopiedObject)
except TypeError:
if not isinstance(attrValue, Music21Object):
# shallow copy then...
try:
shallowlyCopiedObject = copy.copy(attrValue)
setattr(new, name, shallowlyCopiedObject)
environLocal.printDebug(
'__deepcopy__: Could not deepcopy ' +
'{0} in {1}, not a music21Object'.format(name, self) +
'so making a shallow copy')
except TypeError:
# just link...
environLocal.printDebug('__deepcopy__: Could not copy (deep or shallow) ' +
'%s in %s, not a music21Object so just making a link' % (name, self))
setattr(new, name, attrValue)
else: # raise error for our own problem.
raise Music21Exception('__deepcopy__: Cannot deepcopy Music21Object ' +
'%s probably because it requires a default value in instantiation.' % name)
return new
def __deepcopy__(self, memo=None):
'''
Helper method to copy.py's deepcopy function. Call it from there.
memo=None is the default as specified in copy.py
Problem: if an attribute is defined with an underscore (_priority) but
is also made available through a property (e.g. priority) using dir(self)
results in the copy happening twice. Thus, __dict__.keys() is used.
>>> from copy import deepcopy
>>> n = note.Note('A')
>>> n.offset = 1.0 #duration.Duration("quarter")
>>> n.groups.append("flute")
>>> n.groups
['flute']
>>> idN = n.id
>>> idN > 10000 # pointer
True
>>> b = deepcopy(n)
>>> b.offset = 2.0 #duration.Duration("half")
>>> n is b
False
>>> b.id != n.id
True
>>> n.accidental = "-"
>>> b.name
'A'
>>> n.offset
1.0
>>> b.offset
2.0
>>> n.groups[0] = "bassoon"
>>> ("flute" in n.groups, "flute" in b.groups)
(False, True)
'''
#environLocal.printDebug(['calling Music21Object.__deepcopy__', self])
new = self._deepcopySubclassable(memo)
# must do this after copying
new.purgeOrphans()
#environLocal.printDebug([self, 'end deepcopy', 'self._activeSite', self._activeSite])
return new
def __getstate__(self):
state = self.__dict__.copy()
state['_derivation'] = None
state['_activeSite'] = None
return state
def __setstate__(self, state):
# defining self.__dict__ upon initialization currently breaks everything
self.__dict__ = state #pylint: disable=attribute-defined-outside-init
def isClassOrSubclass(self, classFilterList):
'''
Given a class filter list (a list or tuple must be submitted),
which may have strings or class objects, determine
if this class is of the provided classes or a subclasses.
NOTE: this is a performance critical operation
for performance, only accept lists or tuples
>>> n = note.Note()
>>> n.isClassOrSubclass(('Note',))
True
>>> n.isClassOrSubclass(('GeneralNote',))
True
>>> n.isClassOrSubclass((note.Note,))
True
>>> n.isClassOrSubclass((note.Rest,))
False
>>> n.isClassOrSubclass((note.Note,note.Rest))
True
>>> n.isClassOrSubclass(('Rest','Note'))
True
'''
return not self.classSet.isdisjoint(classFilterList)
def _getClasses(self):
try:
return self._classListCacheDict[self.__class__]
except KeyError:
classList = tuple([x.__name__ for x in self.__class__.mro()])
self._classListCacheDict[self.__class__] = classList
return classList
classes = property(_getClasses,
doc='''Returns a tuple containing the names (strings, not objects) of classes that this
object belongs to -- starting with the object's class name and going up the mro()
for the object. Very similar to Perl's @ISA array:
>>> q = note.Note()
>>> q.classes
('Note', 'NotRest', 'GeneralNote', 'Music21Object', 'object')
Having quick access to these things as strings makes it easier to do comparisons:
Example: find GClefs that are not Treble clefs (or treble 8vb, etc.):
>>> s = stream.Stream()
>>> s.insert(10, clef.GClef())
>>> s.insert(20, clef.TrebleClef())
>>> s.insert(30, clef.FrenchViolinClef())
>>> s.insert(40, clef.Treble8vbClef())
>>> s.insert(50, clef.BassClef())
>>> s2 = stream.Stream()
>>> for t in s:
... if 'GClef' in t.classes and 'TrebleClef' not in t.classes:
... s2.insert(t)
>>> s2.show('text')
{10.0} <music21.clef.GClef>
{30.0} <music21.clef.FrenchViolinClef>
`Changed 2015 Sep`: returns a tuple, not a list.
''')
def _getClassSet(self):
try:
return self._classSetCacheDict[self.__class__]
except KeyError:
classNameList = list(self.classes)
classObjList = self.__class__.mro()
classListFQ = [x.__module__ + '.' + x.__name__ for x in self.__class__.mro()]
classList = classNameList + classObjList + classListFQ
classSet = frozenset(classList)
self._classSetCacheDict[self.__class__] = classSet
return classSet
classSet = property(_getClassSet, doc='''
Returns a set (that is, unordered, but indexed) of all of the classes that
this class belongs to, including
string names, fullyQualified string names, and objects themselves.
It's cached on a per class basis, so makes for a really fast way of checking to
see if something belongs
to a particular class when you don't know if the user has given a string,
a fully qualified string name, or an object.
Did I mention it's fast? It's a drop in substitute for the deprecated
`.isClassOrSubClass`. It's not as fast as x in n.classes or isinstance(n, x)
if you know whether it's a string or class, but this is good and safe.
>>> n = note.Note()
>>> 'Note' in n.classSet
True
>>> 'music21.note.Note' in n.classSet
True
>>> note.Note in n.classSet
True
>>> 'Rest' in n.classSet
False
>>> note.Rest in n.classSet
False
>>> object in n.classSet
True
>>> sorted([s for s in n.classSet if isinstance(s, str)])
['GeneralNote', 'Music21Object', 'NotRest', 'Note', '....object',
'music21.base.Music21Object', 'music21.note.GeneralNote', 'music21.note.NotRest',
'music21.note.Note', 'object']
>>> sorted([s for s in n.classSet if not isinstance(s, str)], key=lambda x: x.__name__)
[<class 'music21.note.GeneralNote'>,
<class 'music21.base.Music21Object'>,
<class 'music21.note.NotRest'>,
<class 'music21.note.Note'>,
<... 'object'>]
''')
#---------------------------
# convienence. used to be in note.Note, but belongs everywhere:
def _getQuarterLength(self):
return self.duration.quarterLength
def _setQuarterLength(self, value):
self.duration.quarterLength = value
quarterLength = property(_getQuarterLength, _setQuarterLength, doc='''
Set or Return the Duration as represented in Quarter Length, possibly as a fraction
>>> n = note.Note()
>>> n.quarterLength = 2.0
>>> n.quarterLength
2.0
>>> n.quarterLength = 1.0/3
>>> n.quarterLength
Fraction(1, 3)
''')
def _getDerivation(self):
'''
Return the :class:`~music21.derivation.Derivation` object for this element.
Or create one if none exists:
>>> n = note.Note()
>>> n.derivation
<Derivation of <music21.note.Note C> from None via "None">
>>> import copy
>>> n2 = copy.deepcopy(n)
>>> n2.pitch.step = 'D' # for seeing easier...
>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via "__deepcopy__">
>>> n2.derivation.origin is n
True
Note that (for now at least) derivation.origin is NOT a weakref:
>>> del n
>>> n2.derivation
<Derivation of <music21.note.Note D> from <music21.note.Note C> via "__deepcopy__">
>>> n2.derivation.origin
<music21.note.Note C>
'''
if self._derivation is None:
self._derivation = derivation.Derivation(client=self)
return self._derivation
def _setDerivation(self, newDerivation):
self._derivation = newDerivation
derivation = property(_getDerivation, _setDerivation)
def getOffsetBySite(self, site, stringReturns=False):
'''
If this class has been registered in a container such as a Stream,
that container can be provided here, and the offset in that object
can be returned.
>>> n = note.Note('A-4') # a Music21Objecct
>>> n.offset = 30
>>> n.getOffsetBySite(None)
30.0
>>> s1 = stream.Stream()
>>> s1.id = 'containingStream'
>>> s1.insert(20.0/3, n)
>>> n.getOffsetBySite(s1)
Fraction(20, 3)
>>> float(n.getOffsetBySite(s1))
6.6666...
n.getOffsetBySite(None) should still return 30.0
>>> n.getOffsetBySite(None)
30.0
If the Stream does not contain the element and the element is not derived from
an element that does, then a SitesException is raised:
>>> s2 = stream.Stream()
>>> s2.id = 'notContainingStream'
>>> n.getOffsetBySite(s2)
Traceback (most recent call last):
SitesException: an entry for this object <music21.note.Note A-> is not
stored in stream <music21.stream.Stream notContainingStream>
Consider this use of derivations:
>>> import copy
>>> nCopy = copy.deepcopy(n)
>>> nCopy.derivation
<Derivation of <music21.note.Note A-> from <music21.note.Note A-> via "__deepcopy__">
>>> nCopy.getOffsetBySite(s1)
Fraction(20, 3)
TADA! This is the primary difference between element.getOffsetBySite(stream)
and stream.elementOffset(element)
>>> s1.elementOffset(nCopy)
Traceback (most recent call last):
SitesException: an entry for this object ... is not
stored in stream <music21.stream.Stream containingStream>
If the object is stored at the end of the Stream, then the highest time
is usually returned:
>>> s3 = stream.Stream()
>>> n3 = note.Note(type='whole')
>>> s3.append(n3)
>>> rb = bar.Barline()
>>> s3.storeAtEnd(rb) # s3.rightBarline = rb would do the same...
>>> rb.getOffsetBySite(s3)
4.0
However, setting stringReturns to True will return 'highestTime'
>>> rb.getOffsetBySite(s3, stringReturns=True)
'highestTime'
Even with stringReturns normal offsets are still returned as a float or Fraction:
>>> n3.getOffsetBySite(s3, stringReturns=True)
0.0
'''
if site is None:
return self._naiveOffset
try:
a = None
tryOrigin = self
originMemo = set()
maxSearch = 100
while a is None:
try:
a = site.elementOffset(tryOrigin, stringReturns=stringReturns)
except AttributeError:
raise SitesException(
"You were using %r as a site, when it is not a Stream..." % site)
except Music21Exception as e: # currently StreamException, but will change
if tryOrigin in site._endElements:
if stringReturns is True:
return 'highestTime'
else:
return site.highestTime
tryOrigin = self.derivation.origin
if id(tryOrigin) in originMemo:
raise(e)
else:
originMemo.add(id(tryOrigin))
maxSearch -= 1 # prevent infinite recursive searches...
if tryOrigin is None or maxSearch < 0:
raise(e)
return a
except SitesException:
raise SitesException(
'an entry for this object %r is not stored in stream %r' % (self, site))
def setOffsetBySite(self, site, value):
'''
Change the offset for a site. These are equivalent:
n1.setOffsetBySite(stream1, 20)
and
stream1.setElementOffset(n1, 20)
>>> import music21
>>> aSite = stream.Stream()
>>> a = music21.Music21Object()
>>> a.sites.add(aSite)
>>> aSite.setElementOffset(a, 20)
>>> a.setOffsetBySite(aSite, 30)
>>> a.getOffsetBySite(aSite)
30.0
And if it isn't there? Nothing changes.
>>> b = note.Note()
>>> b.setOffsetBySite(aSite, 40)
>>> b.offset
0.0
'''
if site is not None:
site.setElementOffset(self, value)
if site is self.activeSite:
self._activeSiteStoredOffset = value # update...
else:
self._naiveOffset = value
def getOffsetInHierarchy(self, site):
'''
For an element which may not be in site, but might be in a Stream in site (or further
in streams), find the cumulative offset of the element in that site.
>>> s = stream.Score(id="mainScore")
>>> p = stream.Part()
>>> m = stream.Measure()
>>> n = note.Note()
>>> m.insert(5.0, n)
>>> p.insert(10.0, m)
>>> s.insert(0.0, p)
>>> n.getOffsetInHierarchy(s)
15.0
If no hierarchy beginning with site contains the element and the element is not derived from
an element that does, then a SitesException is raised:
>>> s2 = stream.Score(id="otherScore")
>>> n.getOffsetInHierarchy(s2)
Traceback (most recent call last):
SitesException: Element <music21.note.Note C>
is not in hierarchy of <music21.stream.Score otherScore>
But if the element is derived from an element in a hierarchy then it can get the offset:
>>> n2 = n.transpose('P5')
>>> n2.derivation.origin is n
True
>>> n2.derivation.method
'transpose'
>>> n2.getOffsetInHierarchy(s)
15.0
There is no corresponding `.setOffsetInHierarchy()` since it's unclear what that would mean.
*new in v.3*
OMIT_FROM_DOCS
Timing: 113microseconds for a search. vs 1 microsecond for elementOffset vs .4 for
elementOffset. Hence the short-circuit for easy looking below...
TODO: If timing permits, replace .flat and .semiFlat with this routine.
Currently not possible; b = bwv66.6
%timeit b = corpus.parse('bwv66.6') -- 24.8ms
%timeit b = corpus.parse('bwv66.6'); b.flat -- 42.9ms
%timeit b = corpus.parse('bwv66.6'); b.recurse().stream() -- 83.1ms
'''
try:
return self.getOffsetBySite(site)
except SitesException:
pass
# do not use priorityTarget, just slows things down because will need to search
# all anyhow, since site is not in self.sites.yieldSites()
for cs in self.contextSites():
if cs.site is site:
return cs.offset
raise SitesException("Element {} is not in hierarchy of {}".format(self, site))
@common.deprecated("September 2015", "January 2016", "use self.sites.getAttrByName(attr)")
def getContextAttr(self, attr):
'''
Given the name of an attribute, search the Sites object for
contexts having this attribute and return
the best match.
It is a misleading name because it does not actually search what we now call contexts,
just sites. Thus it is DEPRECATED
>>> import music21
>>> class Mock(music21.Music21Object):
... attr1 = 234
>>> aObj = stream.Stream()
>>> aObj.attr1 = 'test'
>>> a = music21.Music21Object()
>>> aObj.insert(0, a)
>>> a.sites.getAttrByName('attr1')
'test'