Пример #1
0
def getAccidentalCountSum(scores, includeNonAccidentals=False, excludeZeros=True):
    '''
    An extension of getAccidentalCount(). Given a list of scores, return an AccidentalSum
    containing a tally of accidentals for all scores in the list.

    >>> from pprint import pprint
    >>> s1 = stream.Stream()
    >>> s1.append(note.Note('C4'))
    >>> s2 = stream.Score()         # all types of streams are valid
    >>> s2.append(note.Note('C#4'))
    >>> getAccidentalCountSum([s1, s2])
    {'sharp': 1}
    >>> pprint(getAccidentalCountSum([s1, s2], True))
    {'natural': 1, 'sharp': 1}

    >>> s3 = corpus.parse('bach/bwv7.7')
    >>> s4 = corpus.parse('bach/bwv66.6')
    >>> pprint(getAccidentalCountSum([s3, s4], True))
    {'natural': 324, 'sharp': 195}
    '''
    tally = _initializeTally()
    for score in scores:
        if not score.isStream:
            raise exceptions21.Music21Exception("score must be a stream object")
        scoreTally = getAccidentalCount(score, includeNonAccidentals, False)
        # dict.update() won't suffice; list() for Python v3
        for k in list(scoreTally.keys()):
            tally[k] += scoreTally[k]
    return _deleteZeros(tally, excludeZeros)
Пример #2
0
 def _debug(scoreTree):
     for part, subtree in scoreTree.toPartwiseTimespanTrees().items():
         print(part)
         for timespan in subtree:
             print('\t', timespan)
         overlap = subtree.maximumOverlap()
         if overlap >= 1:
             print(part)
             raise exceptions21.Music21Exception(
                 'maximumOverlap is exceeded')
Пример #3
0
def performFunction(sc, command):
    '''
    Function that determines what command to perform on the score and returns the resulting score.
    Currently is a lookup table based on the URL, 
    but will be improved and incorporated into webapps/__init__.py
    as it changes to allow for more standard music21 functions 
    '''
    commandParts = command.split("/")
    if (len(commandParts) < 3):
        raise exceptions21.Music21Exception("Not enough parts on the command")
    
    if commandParts[1] == "transpose":
        return sc.transpose(commandParts[2])
    
    elif commandParts[1] == "allCMajor":
        key = sc.analyze('key')
        (p, unused_mode) = key.pitchAndMode
        intv = interval.Interval(note.Note(p),note.Note('C'))
        
        for ks in sc.flat.getElementsByClass('KeySignature'):
            ks.transpose(intv, inPlace = True)
        sc.transpose(intv, inPlace = True)
        return sc
    
    elif commandParts[1] == "addReduction":
        reductionStream = reduction(sc)
        sc.insert(0,reductionStream)
        return sc
    
    elif commandParts[1] == "reduction":
        reductionStream = reduction(sc)
        return reductionStream
    
    elif commandParts[1] == "scaleDegrees":
        key = sc.analyze('key')
        #rootPitch = key.pitchAndMode[0]
        #rootNote = note.Note(rootPitch)
        
        for n in sc.flat.getElementsByClass('Note'):
            sd = key.getScaleDegreeFromPitch(n)
            if sd is not None:
                n.lyric = sd
        return sc

    else:
        return sc
    def __init__(self, master):
        self.debug = True
        if 'PIL' in _missingImport:
            raise exceptions21.Music21Exception(
                "Need PIL installed to run Score Follower")
        self.master = master
        self.frame = tkinter.Frame(master)
        self.master.wm_title("Score follower - music21")

        self.scoreNameSong = 'scores/d luca gloria_Page_'  #'/Users/cuthbert/Desktop/scores/Saint-Saens-Clarinet-Sonata/Saint-Saens-Clarinet-Sonata_Page_'#C:\Users\Jordi\Desktop\m21\Saint-Saens-Clarinet-Sonata\Saint-Saens-Clarinet-Sonata\Saint-Saens-Clarinet-Sonata_Page_'#'scores/d luca gloria_Page_'##'scores/d luca gloria_Page_' #  #
        self.format = 'tiff'  #'jpg'
        self.nameRecordedSong = 'luca/gloria'  #'/Users/cuthbert/Desktop/scores/Saint-Saens-Clarinet-Sonata/saint-saens.xml'#'C:\Users\Jordi\Desktop\m21\Saint-Saens-Clarinet-Sonata\Saint-Saens-Clarinet-Sonata\saint-saens.xml'### #
        self.pageMeasureNumbers = [
        ]  # get directly from score - the last one is the last note of the score
        self.totalPagesScore = 1
        self.currentLeftPage = 1
        self.pagesScore = []
        self.phimage = []
        self.canvas = []
        self.listNamePages = []
        self.hits = 0
        self.isMoving = False
        self.firstTime = True
        self.ScF = None

        self.sizeButton = 11

        try:  # for windows
            unused_user32 = ctypes.windll.user32  # test for error...
            self.screenResolution = [1024, 600]
            #self.screenResolution = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
            environLocal.printDebug(
                "screen resolution (windows) %d x %d" %
                (self.screenResolution[0], self.screenResolution[1]))
            self.resolution = True
        except:  # mac and linux
            try:
                for screen in AppKit.NSScreen.screens():  # @UndefinedVariable
                    self.screenResolution = [
                        int(screen.frame().size.width),
                        int(screen.frame().size.height)
                    ]
                environLocal.printDebug(
                    "screen resolution (MAC or linux) %d x %d" %
                    (self.screenResolution[0], self.screenResolution[1]))
                self.resolution = True
            except:
                self.screenResolution = [1024, 600]
                environLocal.printDebug('screen resolution not detected')
                self.resolution = False

        self.y = int(self.screenResolution[1] / 1.25)
        self.x = int(self.y / 1.29)  # 1.29 = side relation of letter paper
        if self.x > self.screenResolution[
                0] / 2.6:  # 2.6 is a factor to scale canvas
            self.x = int(self.screenResolution[0] / 2.6)
            self.y = int(self.x * 1.29)
            environLocal.printDebug("resized! too big")
        environLocal.printDebug("one page score size %d x %d" %
                                (self.x, self.y))
        self.filenameRequest()
Пример #5
0
# -*- coding: utf-8 -*-
from music21 import exceptions21
from music21 import corpus

if __name__ == '__main__':
    try:
        import guppy
    except ImportError:
        raise exceptions21.Music21Exception('memoryUsage.py requires guppy')

    hp = guppy.hpy()
    hp.setrelheap()
    x = corpus.parse('bwv66.6')
    h = hp.heap()
    print(h)
Пример #6
0
    def analyze(self, windowSize, windowType='overlap'):
        '''
        Calls, for a given window size, an analysis method across all windows in the source Stream.

        If windowType is "overlap", windows above size 1 are always overlapped, so if a window
        of size 2 is used, windows 1-2, then 2-3, then 3-4 are compared. If a window of size 3
        is used, windows 1-3, then 2-4, then 3-5 are compared.

        Windows are assumed to be partitioned by :class:`music21.stream.Measure` objects.

        Returns two lists for results, each equal in size to the length of minimum windows
        minus the window size plus one. If we have 20 1/4 windows, then the results lists
        will be of length 20 for window size 1, 19 for window size 2, 18 for window size 3, etc.


        >>> s = corpus.parse('bach/bwv66.6')
        >>> p = analysis.discrete.Ambitus()
        >>> wa = analysis.windowed.WindowedAnalysis(s, p)
        >>> len(wa._windowedStream)
        36
        >>> a, b = wa.analyze(1)
        >>> len(a), len(b)
        (36, 36)

        >>> a, b = wa.analyze(4)
        >>> len(a), len(b)
        (33, 33)

        >>> a, b = wa.analyze(1, windowType='noOverlap')
        >>> len(a), len(b)
        (37, 37)

        >>> a, b = wa.analyze(4, windowType='noOverlap')
        >>> len(a), len(b)
        (10, 10)

        >>> a, b = wa.analyze(1, windowType='adjacentAverage')
        >>> len(a), len(b)
        (36, 36)

        '''
        maxWindowCount = len(self._windowedStream)
        # assuming that this is sorted

        if windowType == 'overlap':
            windowCount = maxWindowCount - windowSize + 1
        elif windowType == 'noOverlap':
            windowCountFloat = maxWindowCount / windowSize + 1
            windowCount = int(windowCountFloat)
            if windowCountFloat != windowCount:
                warnings.warn(
                    'maxWindowCount is not divisible by windowSize, possibly undefined behavior'
                )
        elif windowType == 'adjacentAverage':
            windowCount = maxWindowCount
        else:
            raise exceptions21.Music21Exception(f'Unknown windowType: {windowType}')

        data = [0] * windowCount
        color = [0] * windowCount
        # how many windows in this row
        windowCountIndices = range(windowCount)

        if windowType == 'overlap':
            for i in windowCountIndices:
                current = stream.Stream()
                for j in range(i, i + windowSize):
                    # environLocal.printDebug(['self._windowedStream[j]', self._windowedStream[j]])
                    current.append(self._windowedStream[j])

                try:
                    data[i], color[i] = self.processor.process(current)
                except DiscreteAnalysisException:
                    # current might have no notes...all rests?
                    data[i], color[i] = (None, None, 0), '#ffffff'

        elif windowType == 'noOverlap':
            start = 0
            end = start + windowSize
            i = 0
            while True:
                if end >= len(self._windowedStream):
                    end = len(self._windowedStream)

                current = stream.Stream()
                for j in range(start, end):
                    current.append(self._windowedStream[j])

                try:
                    data[i], color[i] = self.processor.process(current)
                except DiscreteAnalysisException:
                    # current might have no notes...all rests?
                    data[i], color[i] = (None, None, 0), '#ffffff'

                start = end
                end = start + windowSize
                i += 1
                if i >= windowCount:
                    break

        elif windowType == 'adjacentAverage':
            # first get overlapping windows
            overlapped = []
            for i in range(maxWindowCount - windowSize + 1):
                current = stream.Stream()
                # store indices of min windows that participate
                participants = []
                for j in range(i, i + windowSize):
                    current.append(self._windowedStream[j])
                    participants.append(j)
                overlapped.append([current, participants])

            # then distribute to each of maxWindowCount
            for i in range(maxWindowCount):
                # get all participants, combine into a single
                current = stream.Stream()
                for dataStream, participants in overlapped:
                    if i in participants:
                        for m in dataStream:
                            current.append(m)
                try:
                    data[i], color[i] = self.processor.process(current)
                except DiscreteAnalysisException:
                    # current might have no notes...all rests?
                    data[i], color[i] = (None, None, 0), '#ffffff'

        return data, color