• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python common.opFrac函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中music21.common.opFrac函数的典型用法代码示例。如果您正苦于以下问题:Python opFrac函数的具体用法?Python opFrac怎么用?Python opFrac使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了opFrac函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, 
                 offsetStart=0.0, 
                 offsetEnd=None, 
                 *,
                 includeEndBoundary=True, 
                 mustFinishInSpan=False,
                 mustBeginInSpan=True, 
                 includeElementsThatEndAtStart=True
                 ):
        super().__init__()

        self.offsetStart = opFrac(offsetStart)
        if offsetEnd is None:
            self.offsetEnd = offsetStart
            self.zeroLengthSearch = True
        else:
            self.offsetEnd = opFrac(offsetEnd)
            if offsetEnd > offsetStart:
                self.zeroLengthSearch = False
            else:
                self.zeroLengthSearch = True

        self.mustFinishInSpan = mustFinishInSpan
        self.mustBeginInSpan = mustBeginInSpan
        self.includeEndBoundary = includeEndBoundary
        self.includeElementsThatEndAtStart = includeElementsThatEndAtStart
开发者ID:cuthbertLab,项目名称:music21,代码行数:26,代码来源:filters.py


示例2: _setOffset

 def _setOffset(self, offset):
     """
     sets the offset and if necessary, translates it to a Fraction for exact representation.
     """
     if offset is None:
         self._offset = None
     elif isinstance(offset, basestring):
         self._offset = offset
     else:
         self._offset = common.opFrac(offset)
开发者ID:ifitz,项目名称:music21,代码行数:10,代码来源:sites.py


示例3: correlateHarmonies

def correlateHarmonies(currentMapping, music21Part):
    """
    Adds a new :class:`~music21.stream.Part` to an existing offset mapping.
    
    >>> from music21 import corpus
    >>> from music21.figuredBass import checker
    >>> score = corpus.parse("corelli/opus3no1/1grave").measures(1,3)   
    >>> v0 = score[0]
    >>> offsetMapping = checker.createOffsetMapping(v0)    
    >>> v1 = score[1]
    >>> newMapping = checker.correlateHarmonies(offsetMapping, v1)
    >>> for (offsets, notes) in sorted(newMapping.items()):
    ...    print("{0!s:15}[{1!s:23}{2!s:21}]".format(offsets, notes[0], notes[1]))
    (0.0, 1.5)     [<music21.note.Note C>  <music21.note.Note A>]
    (1.5, 2.0)     [<music21.note.Note C>  <music21.note.Note A>]
    (2.0, 3.0)     [<music21.note.Note B-> <music21.note.Note G>]
    (3.0, 4.0)     [<music21.note.Note A>  <music21.note.Note F>]
    (4.0, 6.0)     [<music21.note.Note G>  <music21.note.Note E>]
    (6.0, 6.5)     [<music21.note.Note A>  <music21.note.Note F>]
    (6.5, 7.0)     [<music21.note.Note B-> <music21.note.Note F>]
    (7.0, 7.5)     [<music21.note.Note C>  <music21.note.Note F>]
    (7.5, 8.0)     [<music21.note.Note C>  <music21.note.Note E>]
    (8.0, 8.5)     [<music21.note.Note C>  <music21.note.Note D>]
    (8.5, 9.0)     [<music21.note.Note F>  <music21.note.Note D>]
    (9.0, 9.5)     [<music21.note.Note B-> <music21.note.Note D>]
    (9.5, 10.0)    [<music21.note.Note B-> <music21.note.Note G>]
    (10.0, 10.5)   [<music21.note.Note B-> <music21.note.Note E>]
    (10.5, 11.0)   [<music21.note.Note B-> <music21.note.Note C>]
    (11.0, 12.0)   [<music21.note.Note A>  <music21.note.Note F>]    
    """
    newMapping = {}

    for offsets in sorted(currentMapping.keys()):
        (initOffset, endTime) = offsets
        notesInRange = music21Part.flat.getElementsByClass("GeneralNote").getElementsByOffset(
            initOffset,
            offsetEnd=endTime,
            includeEndBoundary=False,
            mustFinishInSpan=False,
            mustBeginInSpan=False,
            includeElementsThatEndAtStart=False,
        )
        allNotesSoFar = currentMapping[offsets]
        for music21GeneralNote in notesInRange:
            newInitOffset = initOffset
            newEndTime = endTime
            if not music21GeneralNote.offset < initOffset:
                newInitOffset = music21GeneralNote.offset
            if not music21GeneralNote.offset + music21GeneralNote.quarterLength > endTime:
                newEndTime = opFrac(music21GeneralNote.offset + music21GeneralNote.quarterLength)
            allNotesCopy = copy.copy(allNotesSoFar)
            allNotesCopy.append(music21GeneralNote)
            newMapping[(newInitOffset, newEndTime)] = allNotesCopy

    return newMapping
开发者ID:antoniopessotti,项目名称:music21,代码行数:55,代码来源:checker.py


示例4: testTuplets

    def testTuplets(self):

        from music21 import abcFormat
        from music21.abcFormat import testFiles

        tf = testFiles.testPrimitiveTuplet
        af = abcFormat.ABCFile()
        s = abcToStreamScore(af.readstr(tf))
        match = []
        # match strings for better comparison
        for n in s.flat.notesAndRests:
            match.append(n.quarterLength)
        shouldFind = [
            1.0 / 3,
            1.0 / 3,
            1.0 / 3,
            1.0 / 5,
            1.0 / 5,
            1.0 / 5,
            1.0 / 5,
            1.0 / 5,
            1.0 / 6,
            1.0 / 6,
            1.0 / 6,
            1.0 / 6,
            1.0 / 6,
            1.0 / 6,
            1.0 / 7,
            1.0 / 7,
            1.0 / 7,
            1.0 / 7,
            1.0 / 7,
            1.0 / 7,
            1.0 / 7,
            2.0 / 3,
            2.0 / 3,
            2.0 / 3,
            2.0 / 3,
            2.0 / 3,
            2.0 / 3,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            1.0 / 12,
            2.0,
        ]
        self.assertEqual(match, [common.opFrac(x) for x in shouldFind])
开发者ID:EQ4,项目名称:music21,代码行数:55,代码来源:translate.py


示例5: newNote

        def newNote(ts, n):
            '''
            Make a copy of the note and clear some settings
            '''
            nNew = copy.deepcopy(n)
            nNew.duration = dur
            if nNew.stemDirection != 'noStem':
                nNew.stemDirection = None
            if not addTies:
                return nNew            
            
            offsetDifference = common.opFrac(self.offset - ts.offset)
            endTimeDifference = common.opFrac(ts.endTime - (self.offset + quarterLength))
            if offsetDifference == 0 and endTimeDifference <= 0:
                addTie = None
            elif offsetDifference > 0:
                if endTimeDifference > 0:
                    addTie = 'continue'
                else:
                    addTie = 'stop'
            elif endTimeDifference > 0:
                addTie = 'start'
            else:
                raise VerticalityException("What possibility was missed?", 
                                offsetDifference, endTimeDifference, ts, self)            
            
            
            if nNew.tie is not None and {nNew.tie.type, addTie} == startStopSet:
                nNew.tie.type = 'continue'  
            elif nNew.tie is not None and nNew.tie.type == 'continue':
                nNew.tie.placement = None
            elif addTie is None and nNew.tie is not None:
                nNew.tie.placement = None
            
            elif addTie:
                nNew.tie = tie.Tie(addTie)

            return nNew
开发者ID:ELVIS-Project,项目名称:music21,代码行数:38,代码来源:verticality.py


示例6: recurseGetTreeByClass

    def recurseGetTreeByClass(inputStream,
                       currentParentage,
                       initialOffset,
                       outputTree=None):
        lastParentage = currentParentage[-1]

        if outputTree is None:
            outputTree = treeClass(source=lastParentage)

        # do this to avoid munging activeSites
        inputStreamElements = inputStream._elements[:] + inputStream._endElements
        parentEndTime = initialOffset + lastParentage.duration.quarterLength


        for element in inputStreamElements:
            flatOffset = common.opFrac(lastParentage.elementOffset(element) + initialOffset)

            if element.isStream and flatten is not False: # True or "semiFlat"
                localParentage = currentParentage + (element,)
                recurseGetTreeByClass(element, # put the elements into the current tree...
                                      currentParentage=localParentage,
                                      initialOffset=flatOffset,
                                      outputTree=outputTree)
                if flatten != 'semiFlat':
                    continue  # do not insert the stream itself unless we are doing semiflat

            if classList and not element.isClassOrSubclass(classList):
                continue

            endTime = flatOffset + element.duration.quarterLength

            if useTimespans:
                pitchedTimespan = spans.PitchedTimespan(element=element,
                                                    parentage=tuple(reversed(currentParentage)),
                                                    parentOffset=initialOffset,
                                                    parentEndTime=parentEndTime,
                                                    offset=flatOffset,
                                                    endTime=endTime)
                outputTree.insert(pitchedTimespan)
            elif groupOffsets is False:
                # for sortTuples
                position = element.sortTuple(lastParentage)
                flatPosition = position.modify(offset=flatOffset)
                outputTree.insert(flatPosition, element)
            else:
                outputTree.insert(flatOffset, element)

        return outputTree
开发者ID:sbrother,项目名称:music21,代码行数:48,代码来源:fromStream.py


示例7: getSiteByOffset

    def getSiteByOffset(self, offset):
        """
        For a given offset return the site that fits it

        More than one Site may have the same offset; this at one point returned
        the last site added by sorting time, but now we use a dict, so there's
        no guarantee that the one you want will be there -- need orderedDicts!

        ::

            >>> import fractions
            >>> class Mock(base.Music21Object):
            ...     pass
            ...
            >>> aSite = Mock()
            >>> bSite = Mock()
            >>> cSite = Mock()
            >>> sitesObj = sites.Sites()
            >>> sitesObj.add(aSite, 2)
            >>> sitesObj.add(bSite, 10.0/3)
            >>> aSite is sitesObj.getSiteByOffset(2)
            True
            >>> bSite is sitesObj.getSiteByOffset(fractions.Fraction(10, 3))
            True
            >>> bSite is sitesObj.getSiteByOffset(3.33333333333)
            True

        """
        match = None
        offset = common.opFrac(offset)
        for siteId in self.siteDict:
            # might need to use almost equals here
            matched = False
            if self.siteDict[siteId].offsetRational == offset:
                matched = True
            if matched is True:
                if self.siteDict[siteId].isDead:
                    return None
                match = self.siteDict[siteId].site
                break
        return match
开发者ID:ifitz,项目名称:music21,代码行数:41,代码来源:sites.py


示例8: expand

    def expand(self, ts=None, ks=None):
        '''
        The meat of it all -- expand one rule completely and return a list of Measure objects.
        '''
        if ts is None:
            ts = meter.TimeSignature('4/4')
        if ks is None:
            ks = key.Key('C')
        measures = []

        lastRegularAtom = None
        lastChord = None
        
        for content, sep, numReps in self._measureGroups():
            lastChordIsInSameMeasure = False
            if sep == "$":
                if content not in self.parent.rules:
                    raise CTRuleException("Cannot expand rule {0} in {2}".format(content, self))
                rule = self.parent.rules[content]
                for i in range(numReps):
                    returnedMeasures = rule.expand(ts, ks)
                    self.insertKsTs(returnedMeasures[0], ts, ks)
                    for m in returnedMeasures:
                        tsEs = m.getElementsByClass('TimeSignature', returnStreamSubClass='list')
                        for returnedTs in tsEs:
                            if returnedTs is not ts:
                                ts = copy.deepcopy(ts) # the TS changed mid-rule; create a new one for return.
                    
                    measures.extend(returnedMeasures)
            elif sep == "|":
                m = stream.Measure()
                atoms = content.split()
                # key/timeSig pass...
                regularAtoms = []
                for atom in atoms:
                    if atom.startswith('['):
                        atomContent = atom[1:-1]
                        if atomContent == '0':
                            ts = meter.TimeSignature('4/4') # irregular meter.  Cannot fully represent; 
                            #TODO: replace w/ senza misura when possible. 
                                                        
                        elif '/' in atomContent: # only one key / ts per measure.
                            ts = meter.TimeSignature(atomContent)
                        else:
                            ks = key.Key(key.convertKeyStringToMusic21KeyString(atomContent))
                            
                    elif atom == '.':
                        if lastRegularAtom is None:
                            raise CTRuleException(" . w/o previous atom: %s" % self)
                        regularAtoms.append(lastRegularAtom)
                    elif atom in ("", None):
                        pass
                    else:
                        regularAtoms.append(atom)
                        lastRegularAtom = atom
                numAtoms = len(regularAtoms)
                if numAtoms == 0:
                    continue # maybe just ts and ks setting

                self.insertKsTs(m, ts, ks)
                
                atomLength = common.opFrac(ts.barDuration.quarterLength / numAtoms)            
                for atom in regularAtoms:
                    if atom == 'R':
                        rest = note.Rest(quarterLength=atomLength)
                        lastChord = None
                        lastChordIsInSameMeasure = False
                        m.append(rest)
                    else:
                        atom = self.fixupChordAtom(atom)
                        rn = roman.RomanNumeral(atom, ks)
                        if self.isSame(rn, lastChord) and lastChordIsInSameMeasure:
                            lastChord.duration.quarterLength += atomLength
                            m.elementsChanged()
                        else:
                            rn.duration.quarterLength = atomLength
                            self.addOptionalTieAndLyrics(rn, lastChord)
                            lastChord = rn
                            lastChordIsInSameMeasure = True
                            m.append(rn)
                measures.append(m)
                for i in range(1, numReps):
                    measures.append(copy.deepcopy(m))
            else:    
                environLocal.warn("Rule found without | or $, ignoring: '{0}','{1}': in {2}".format(
                                                                        content, sep, self.text))
                #pass
        if len(measures) > 0:
            for m in measures:
                noteIter = m.recurse().notes
                if noteIter and (self.parent is None or self.parent.labelSubsectionsOnScore is True) and self.LHS != 'S':
                    rn = noteIter[0]
                    lyricNum = len(rn.lyrics) + 1
                    rn.lyrics.append(note.Lyric(self.LHS, number=lyricNum))       
                    break                 
                
        return measures
开发者ID:matyastr,项目名称:msps,代码行数:97,代码来源:clercqTemperley.py


示例9: reBar

def reBar(music21Part, inPlace=True):
    """
    Re-bar overflow measures using the last known time signature.

    >>> from music21 import corpus
    >>> irl2 = corpus.parse("irl", number=2)
    >>> irl2.metadata.title
    'Aililiu na Gamhna, S.35'
    >>> music21Part = irl2[1]


    The whole part is in 2/4 time, but there are some measures expressed in 4/4 time
    without an explicit time signature change, an error in abc parsing due to the
    omission of barlines. The method will split those measures such that they conform
    to the last time signature, in this case 2/4. The default is to reBar in place.
    The measure numbers are updated accordingly. 
    
    (NOTE: reBar is called automatically in abcToStreamPart, hence not demonstrated below...)

    The key signature and clef are assumed to be the same in the second measure after the
    split, so both are omitted. If the time signature is not the same in the second measure,
    the new time signature is indicated, and the measure following returns to the last time
    signature, except in the case that a new time signature is indicated.

    >>> music21Part.measure(15).show("text")
    {0.0} <music21.note.Note A>
    {1.0} <music21.note.Note A>
    >>> music21Part.measure(16).show("text")
    {0.0} <music21.note.Note A>
    {0.5} <music21.note.Note B->
    {1.0} <music21.note.Note A>
    {1.5} <music21.note.Note G>

    An example where the time signature wouldn't be the same. This score is
    mistakenly marked as 4/4, but has some measures that are longer.

    >>> irl15 = corpus.parse("irl", number=15)
    >>> irl15.metadata.title
    'Esternowe, S. 60'
    >>> music21Part2 = irl15.parts[0] # 4/4 time signature
    >>> music21Part2.measure(1).show("text")
    {0.0} <music21.note.Note C>
    {1.0} <music21.note.Note A>
    {1.5} <music21.note.Note G>
    {2.0} <music21.note.Note E>
    {2.5} <music21.note.Note G>
    >>> music21Part2.measure(1)[-1].duration.quarterLength
    1.5

    >>> music21Part2.measure(2).show("text")
    {0.0} <music21.meter.TimeSignature 1/8>
    {0.0} <music21.note.Note E>
    """
    if not inPlace:
        music21Part = copy.deepcopy(music21Part)
    lastTimeSignature = None
    measureNumberOffset = 0 # amount to shift current measure numbers
    allMeasures = music21Part.getElementsByClass(stream.Measure)
    for measureIndex in range(len(allMeasures)):
        music21Measure = allMeasures[measureIndex]
        if music21Measure.timeSignature is not None:
            lastTimeSignature = music21Measure.timeSignature

        if lastTimeSignature is None:
            raise ABCTranslateException("No time signature found in this Part")

        tsEnd = lastTimeSignature.barDuration.quarterLength
        mEnd = common.opFrac(music21Measure.highestTime)
        music21Measure.number += measureNumberOffset
        if mEnd > tsEnd:
            m1, m2 = music21Measure.splitAtQuarterLength(tsEnd)
            m2.timeSignature = None
            if lastTimeSignature.barDuration.quarterLength != m2.highestTime:
                try:
                    m2.timeSignature = m2.bestTimeSignature()
                except exceptions21.StreamException as e:
                    raise ABCTranslateException("Problem with measure %d (%r): %s" % (music21Measure.number, music21Measure, e))
                if measureIndex != len(allMeasures) - 1:
                    if allMeasures[measureIndex+1].timeSignature is None:
                        allMeasures[measureIndex+1].timeSignature = lastTimeSignature
            m2.keySignature = None # suppress the key signature
            m2.clef = None # suppress the clef
            m2.number = m1.number + 1
            measureNumberOffset += 1
            music21Part.insert(common.opFrac(m1.offsetRational + m1.highestTime), m2)
        
        #elif (mEnd + music21Measure.paddingLeft) < tsEnd and measureIndex != len(allMeasures) - 1:
        #    The first and last measures are allowed to be incomplete
        #    music21Measure.timeSignature = music21Measure.bestTimeSignature()
        #    if allMeasures[measureIndex+1].timeSignature is None:
        #        allMeasures[measureIndex+1].timeSignature = lastTimeSignature
        #

    if not inPlace:
        return music21Part
开发者ID:antoniopessotti,项目名称:music21,代码行数:95,代码来源:translate.py


示例10: makeBeams

def makeBeams(s, inPlace=False):
    '''
    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.

    >>> from music21 import meter
    >>> from music21 import stream

    >>> aMeasure = stream.Measure()
    >>> aMeasure.timeSignature = meter.TimeSignature('4/4')
    >>> aNote = note.Note()
    >>> aNote.quarterLength = .25
    >>> aMeasure.repeatAppend(aNote,16)
    >>> bMeasure = aMeasure.makeBeams(inPlace=False)

    >>> for i in range(0, 4):
    ...   print("%d %r" % (i, bMeasure.notes[i].beams))
    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>>

    OMIT_FROM_DOCS
    TODO: inPlace=False does not work in many cases
    '''
    from music21 import stream

    #environLocal.printDebug(['calling Stream.makeBeams()'])
    if not inPlace:  # make a copy
        returnObj = copy.deepcopy(s)
    else:
        returnObj = s

    #if s.isClass(Measure):
    if 'Measure' in s.classes:
    #if s.isClassOrSubclass('Measure'):
        mColl = []  # store a list of measures for processing
        mColl.append(returnObj)
    elif s.iter.getElementsByClass('Measure'):
        mColl = list(returnObj.iter.getElementsByClass('Measure'))  # a list of measures
    else:
        raise stream.StreamException(
            'cannot process a stream that neither is a Measure nor has '
            'Measures')

    lastTimeSignature = None

    for m in mColl:
        # this means that the first of a stream of time signatures will
        # be used
        if m.timeSignature is not None:
            lastTimeSignature = m.timeSignature
        if lastTimeSignature is None:
            #environLocal.printDebug([
            #    'makeBeams(): lastTimeSignature is None: cannot process'])
            # TODO: Reduce to warning...
            raise stream.StreamException(
                'cannot process beams in a Measure without a time signature')
        noteGroups = []
        if m.hasVoices():
            for v in m.voices:
                noteGroups.append(v.iter.notesAndRests.stream())
        else:
            noteGroups.append(m.iter.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:
                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
            durSum = opFrac(sum([d.quarterLength for d in durList]))
            barQL = lastTimeSignature.barDuration.quarterLength

            if durSum > barQL:
                #environLocal.printDebug([
#.........这里部分代码省略.........
开发者ID:EQ4,项目名称:music21,代码行数:101,代码来源:makeNotation.py


示例11: makeTupletBrackets

def makeTupletBrackets(s, inPlace=False):
    '''
    Given a Stream of mixed durations, designates the first and last tuplet of any group
    of tuplets as the start or end of the tuplet, respectively.

    Changed in 1.8::
    
        * `inPlace` is False by default
        * to incorporate duration.updateTupletType, can take a list of durations
                    
    TODO: does not handle nested tuplets

    >>> n = note.Note()
    >>> n.duration.quarterLength = 1.0/3
    >>> s = stream.Stream()
    >>> s.insert(0, meter.TimeSignature('2/4'))
    >>> s.repeatAppend(n, 6)
    >>> tupletTypes = [x.duration.tuplets[0].type for x in s.notes]
    >>> tupletTypes
    [None, None, None, None, None, None]
    >>> stream.makeNotation.makeTupletBrackets(s, inPlace=True)
    >>> tupletTypes = [x.duration.tuplets[0].type for x in s.notes]
    >>> tupletTypes
    ['start', None, 'stop', 'start', None, 'stop']
    '''
    durationList = []
    
    # legacy -- works on lists not just streams...
    if isinstance(s, list) or isinstance(s, tuple):
        durationList = s
    else:
        # Stream, as it should be...
        if not inPlace:  # make a copy
            returnObj = copy.deepcopy(s)
        else:
            returnObj = s
    
        # only want to look at notes
        notes = returnObj.notesAndRests
        for n in notes:
            durationList.append(n.duration)

    tupletMap = [] # a list of (tuplet obj / Duration) pairs
    for dur in durationList: # all Duration objects
        tupletList = dur.tuplets
        if tupletList in [(), None]: # no tuplets, length is zero
            tupletMap.append([None, dur])
        elif len(tupletList) > 1:
            #for i in range(len(tuplets)):
            #    tupletMap.append([tuplets[i],dur])
            environLocal.warn('got multi-tuplet duration; cannot yet handle this. %s' % repr(tupletList))
        elif len(tupletList) == 1:
            tupletMap.append([tupletList[0], dur])
            if tupletList[0] != dur.tuplets[0]:
                raise Exception('cannot access Tuplets object from within DurationTuple.')
        else:
            raise Exception('cannot handle these tuplets: %s' % tupletList)


    # have a list of tuplet, Duration pairs
    completionCount = 0 # qLen currently filled
    completionTarget = None # qLen necessary to fill tuplet
    for i in range(len(tupletMap)):
        tupletObj, dur = tupletMap[i]

        if i > 0:
            tupletPrevious = tupletMap[i - 1][0]
        else:
            tupletPrevious = None

        if i < len(tupletMap) - 1:
            tupletNext = tupletMap[i + 1][0]
#            if tupletNext != None:
#                nextNormalType = tupletNext.durationNormal.type
#            else:
#                nextNormalType = None
        else:
            tupletNext = None
#            nextNormalType = None

#         environLocal.printDebug(['updateTupletType previous, this, next:',
#                                  tupletPrevious, tuplet, tupletNext])

        if tupletObj is not None:
#            thisNormalType = tuplet.durationNormal.type
            completionCount = opFrac(completionCount + dur.quarterLength)
            # if previous tuplet is None, always start
            # always reset completion target
            if tupletPrevious is None or completionTarget is None:
                if tupletNext is None: # single tuplet w/o tuplets either side
                    tupletObj.type = 'startStop'
                    tupletObj.bracket = False
                    completionCount = 0 # reset
                else:
                    tupletObj.type = 'start'
                    # get total quarter length of this tuplet
                    completionTarget = tupletObj.totalTupletLength()
                    #environLocal.printDebug(['starting tuplet type, value:',
                    #                         tuplet, tuplet.type])
                    #environLocal.printDebug(['completion count, target:',
#.........这里部分代码省略.........
开发者ID:EQ4,项目名称:music21,代码行数:101,代码来源:makeNotation.py


示例12: makeTies


#.........这里部分代码省略.........
            # increment measure number
            mNext.number = m.number + 1
            mNextAdd = True  # new measure, needs to be appended

        if mNext.hasVoices():
            mNextHasVoices = True
        else:
            mNextHasVoices = False

        #environLocal.printDebug([
        #    'makeTies() dealing with measure', m, 'mNextAdd', mNextAdd])
        # for each measure, go through each element and see if its
        # duraton fits in the bar that contains it

        # if there are voices, we must look at voice id values to only
        # connect ties to components in the same voice, assuming there
        # are voices in the next measure
        try:
            mEnd = lastTimeSignature.barDuration.quarterLength
        except AttributeError:
            ts = m.getContextByClass('TimeSignature')
            if ts is not None:
                lastTimeSignature = ts
                mEnd = lastTimeSignature.barDuration.quarterLength
            else:
                mEnd = 4.0  # Default
        if m.hasVoices():
            bundle = m.voices
            mHasVoices = True
        else:
            bundle = [m]
            mHasVoices = False
        # bundle components may be voices, or just a measure
        for v in bundle:
            for e in v:
                #environLocal.printDebug([
                #    'Stream.makeTies() iterating over elements in measure',
                #    m, e])
                #if hasattr(e, 'duration') and e.duration is not None:
                if e.duration is not None:
                    # check to see if duration is within Measure
                    eOffset = v.elementOffset(e)
                    eEnd = opFrac(eOffset + e.duration.quarterLength)
                    # assume end can be at boundary of end of measure
                    overshot = eEnd - mEnd

                    if overshot > 0:
                        if eOffset >= mEnd:
                            continue # skip elements that extend past measure boundary.
#                             raise stream.StreamException(
#                                 'element (%s) has offset %s within a measure '
#                                 'that ends at offset %s' % (e, eOffset, mEnd))

                        qLenBegin = mEnd - eOffset
                        e, eRemain = e.splitAtQuarterLength(qLenBegin,
                            retainOrigin=True,
                            displayTiedAccidentals=displayTiedAccidentals)

                        # manage bridging voices
                        if mNextHasVoices:
                            if mHasVoices:  # try to match voice id
                                dst = mNext.voices[v.id]
                            # src does not have voice, but dst does
                            else:  # place in top-most voice
                                dst = mNext.voices[0]
                        else:
                            # mNext has no voices but this one does
                            if mHasVoices:
                                # internalize all components in a voice
                                mNext.internalize(container=stream.Voice)
                                # place in first voice
                                dst = mNext.voices[0]
                            else:  # no voices in either
                                dst = mNext

                        #eRemain.activeSite = mNext
                        # manually set activeSite
                        # cannot use _insertCore here
                        dst.insert(0, eRemain)

                        # we are not sure that this element fits
                        # completely in the next measure, thus, need to
                        # continue processing each measure
                        if mNextAdd:
                            #environLocal.printDebug([
                            #    'makeTies() inserting mNext into returnObj',
                            #    mNext])
                            returnObj.insert(mNext.offset, mNext)
                    elif overshot > 0:
                        environLocal.printDebug([
                            'makeTies() found and skipping extremely small '
                            'overshot into next measure', overshot])
        mCount += 1
    del measureStream  # clean up unused streams
    # changes elements
    returnObj.elementsChanged()
    if not inPlace:
        return returnObj
    else:
        return None
开发者ID:keszybz,项目名称:music21,代码行数:101,代码来源:makeNotation.py


示例13: isElementOffsetInRange

    def isElementOffsetInRange(self, e, offset, *, stopAfterEnd=False):
        '''
        Given an element, offset, and stream, return
        True, False, or raise StopIteration if the
        element is in the range, not in the range, or (if stopAfterEnd is True) is not
        and no future elements will be in the range.

        Factored out from __call__ to be used by OffsetHierarchyFilter and it's just
        a beast.  :-)
        '''
        if offset > self.offsetEnd:  # anything that begins after the span is definitely out
            if stopAfterEnd:
                # if sorted, optimize by breaking after exceeding offsetEnd
                # eventually we could do a binary search to speed up...
                raise StopIteration
            else:
                return False

        dur = e.duration

        elementEnd = opFrac(offset + dur.quarterLength)
        if elementEnd < self.offsetStart:
            # anything that finishes before the span ends is definitely out
            return False

        # some part of the element is at least touching some part of span.
        # all the simple cases done! Now need to filter out those that
        # are border cases depending on settings

        if dur.quarterLength == 0:
            elementIsZeroLength = True
        else:
            elementIsZeroLength = False

        if self.zeroLengthSearch is True and elementIsZeroLength is True:
            # zero Length Searches -- include all zeroLengthElements
            return True


        if self.mustFinishInSpan is True:
            if elementEnd > self.offsetEnd:
                # environLocal.warn([elementEnd, offsetEnd, e])
                return False
            if self.includeEndBoundary is False:
                # we include the end boundary if the search is zeroLength --
                # otherwise nothing can be retrieved
                if elementEnd == self.offsetEnd:
                    return False

        if self.mustBeginInSpan is True:
            if offset < self.offsetStart:
                return False
            if self.includeEndBoundary is False and offset == self.offsetEnd:
                return False
        elif (elementIsZeroLength is False
                and elementEnd == self.offsetEnd 
                and self.zeroLengthSearch is True):
            return False
                
        if self.includeEndBoundary is False and offset == self.offsetEnd:
            return False

        if self.includeElementsThatEndAtStart is False and elementEnd == self.offsetStart:
            return False

        return True
开发者ID:cuthbertLab,项目名称:music21,代码行数:66,代码来源:filters.py


示例14: __call__

    def __call__(self, e, iterator):
        dur = e.duration
        s = iterator.srcStream
        if s is e:
            return False
        offset = s.elementOffset(e)

        #offset = common.cleanupFloat(offset)

        if offset > self.offsetEnd:  # anything that ends after the span is definitely out
            if s.isSorted:
                # if sorted, optimize by breaking after exceeding offsetEnd
                # eventually we could do a binary search to speed up...
                raise StopIteration
            else:
                return False

        elementEnd = opFrac(offset + dur.quarterLength)
        if elementEnd < self.offsetStart:
            # anything that finishes before the span ends is definitely out
            return False

        if dur.quarterLength == 0:
            elementIsZeroLength = True
        else:
            elementIsZeroLength = False


        # all the simple cases done! Now need to filter out those that
        # are border cases depending on settings

        if self.zeroLengthSearch is True and elementIsZeroLength is True:
            # zero Length Searches -- include all zeroLengthElements
            return True


        if self.mustFinishInSpan is True:
            if elementEnd > self.offsetEnd:
                #environLocal.warn([elementEnd, offsetEnd, e])
                return False
            if self.includeEndBoundary is False:
                # we include the end boundary if the search is zeroLength --
                # otherwise nothing can be retrieved
                if elementEnd == self.offsetEnd:
                    return False

        if self.mustBeginInSpan is True:
            if offset < self.offsetStart:
                return False
            if self.includeEndBoundary is False:
                if offset >= self.offsetEnd:
                    # >= is unnecessary, should just be ==, but better safe than sorry
                    return False

        if self.mustBeginInSpan is False:
            if elementIsZeroLength is False:
                if elementEnd == self.offsetEnd and self.zeroLengthSearch is True:
                    return False
        if self.includeEndBoundary is False:
            if offset >= self.offsetEnd:
                return False

        if self.includeElementsThatEndAtStart is False and elementEnd == self.offsetStart:
            return False

        return True
开发者ID:sbrother,项目名称:music21,代码行数:66,代码来源:filters.py


示例15: partScoreFromSystemScore

    def partScoreFromSystemScore(self, systemScore):
        '''
        Take a :class:`~music21.stream.Score` object which is organized
        by Systems and return a new `Score` object which is organized by
        Parts.
        '''
        # this line is redundant currently, since all we have in systemScore
        # are Systems, but later there will be other things.
        systemStream = systemScore.getElementsByClass('System') 
        partDictById = {}
        for thisSystem in systemStream:
            # this line is redundant currently, since all we have in
            # thisSystem are Parts, but later there will be other things.
            systemOffset = thisSystem.getOffsetBySite(systemScore)
            partStream = thisSystem.getElementsByClass('Part')
            for j, thisPart in enumerate(partStream):
                if thisPart.id not in partDictById:
                    newPart = stream.Part()
                    newPart.id = thisPart.id
                    partDictById[thisPart.id] = {'part': newPart, 'number': j}
                else:
                    newPart = partDictById[thisPart.id]['part']
                for el in thisPart: # no need for recurse...
                    newPart._insertCore(common.opFrac(el.offset + systemOffset), el)
                newPart._elementsChanged()
        newScore = stream.Score()
        ## ORDERED DICT
        parts = [None for i in range(len(partDictById))]
        for partId in partDictById:
            partDict = partDictById[partId]
            parts[partDict['number']] = partDict['part']
        for p in parts:
            # remove redundant Clef and KeySignatures
            clefs = p.getElementsByClass('Clef')
            keySignatures = p.getElementsByClass('KeySignature')
            lastClef = None
            lastKeySignature = None
            for c in clefs:
                if c == lastClef:
                    p.remove(c)
                else:
                    lastClef = c
            for ks in keySignatures:
                if ks == lastKeySignature:
                    p.remove(ks)
                else:
                    lastKeySignature = ks
            p.makeMeasures(inPlace=True)
#            for m in p.getElementsByClass('Measure'):
#                barLines = m.getElementsByClass('Barline')
#                for bl in barLines:
#                    blOffset = bl.offset
#                    if blOffset == 0.0:
#                        m.remove(bl)
#                        m.leftBarline = bl
#                    elif blOffset == m.highestTime:
#                        m.remove(bl)
#                        m.rightBarline = bl # will not yet work for double repeats!
                        
            newScore._insertCore(0, p)
        newScore._elementsChanged()
        return newScore
开发者ID:Wajih-O,项目名称:music21,代码行数:62,代码来源:fromCapellaXML.py


示例16: getBeatFloatOrFrac

    def getBeatFloatOrFrac(self):
        '''
        Gets the beat number as a float or fraction. Time signature independent
        
        >>> RTB = romanText.rtObjects.RTBeat
        
        Simple ones:
        
        >>> RTB('b1').getBeatFloatOrFrac()
        1.0
        >>> RTB('b2').getBeatFloatOrFrac()
        2.0
        
        etc.
        
        with easy float:
        
        >>> RTB('b1.5').getBeatFloatOrFrac()
        1.5
        >>> RTB('b1.25').getBeatFloatOrFrac()
        1.25
        
        with harder:
        
        >>> RTB('b1.33').getBeatFloatOrFrac()
        Fraction(4, 3)
        
        >>> RTB('b2.66').getBeatFloatOrFrac()
        Fraction(8, 3)
                
        >>> RTB('b1.2').getBeatFloatOrFrac()
        Fraction(6, 5)


        A third digit of .5 adds 1/2 of 1/DENOM of before.  Here DENOM is 3 (in 5/3) so
        we add 1/6 to 5/3 to get 11/6:
 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python common.relativepath函数代码示例发布时间:2022-05-27
下一篇:
Python common.isStr函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap