How to use the music21.exceptions21.Music21Exception function in music21

To help you get started, we’ve selected a few music21 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cuthbertLab / music21 / music21 / text.py View on Github external
match = leading
            break
    if match is not None:
        # recombine everything except the last comma split
        return ' '.join(src.split(' ')[1:]) + ', %s' % match
    else:  # not match
        return src


# ------------------------------------------------------------------------------
class TextException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class TextBoxException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class TextBox(base.Music21Object):
    '''
    A TextBox is arbitrary text that might be positioned anywhere on a page,
    independent of notes or staffs. A page attribute specifies what page this text is found on;
    style.absoluteY and style.absoluteX position the text from the bottom left corner in
    units of tenths.

    This object is similar to the TextExpression object, but does not have as many position
    parameters, enclosure attributes, and the ability to convert to
    RepeatExpressions and TempoTexts.

    >>> from music21 import text, stream
github cuthbertLab / music21 / music21 / alpha / webapps / server / zipfileapp.py View on Github external
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)
github cuthbertLab / music21 / music21 / search / lyrics.py View on Github external
'matchText': '''The text of the lyric that matched the search.  For a
                                 plaintext search, this will be the same as the search
                                 term, but for a regular expression
                                 search this will be the text that matched the regular
                                 expression''',
                 'els': '''A list of all lyric-containing elements that matched this text.''',
                 'indices': '''A list'''
                 }

    def __repr__(self):
        return 'SearchMatch(mStart={0}, mEnd={1}, matchText={2}, els={3}, indices=[...])'.format(
            repr(self.mStart), repr(self.mEnd), repr(self.matchText), repr(self.els)
        )


class LyricSearcherException(Music21Exception):
    pass


class LyricSearcher:
    # noinspection SpellCheckingInspection
    '''
    An object that can find lyrics that match a certain regular expression
    and return relevant information about the match.

    Construct the LyricSearcher by passing in a Stream object (it can be
    a Score or Part or other nested item), and then call ".search()" on it.

    See :ref:`User's Guide, Chapter 28, Lyric Searching ` for
    full details.

    Restriction:  Currently searches the first lyric only.
github cuthbertLab / music21 / music21 / analysis / transposition.py View on Github external
# License:      LGPL or BSD, see license.txt
#-------------------------------------------------------------------------------

import unittest

from music21 import common
from music21 import exceptions21
from music21 import pitch
from music21 import chord

from music21 import environment
_MOD = 'analysis.transposition'
environLocal = environment.Environment(_MOD)


class TranspositionException(exceptions21.Music21Exception):
    pass

class TranspositionChecker:
    '''
    Given a list of pitches, checks for the number of distinct transpositions.

    >>> pList = [pitch.Pitch('C4'), pitch.Pitch('E4'), pitch.Pitch('G#4')]
    >>> tc = analysis.transposition.TranspositionChecker(pList)
    >>> tc.numDistinctTranspositions()
    4
    >>> allNormalOrderPitchTuples = tc.getPitchesOfDistinctTranspositions()
    >>> allNormalOrderPitchTuples
    [(, ,
                                         ),
     (, ,
                                         ),
github cuthbertLab / music21 / music21 / spanner.py View on Github external
from music21 import common
from music21 import defaults
from music21 import prebase
from music21 import style

from music21 import environment
_MOD = 'spanner'
environLocal = environment.Environment(_MOD)


# ------------------------------------------------------------------------------
class SpannerException(exceptions21.Music21Exception):
    pass


class SpannerBundleException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class Spanner(base.Music21Object):
    # suppress this inspection because it fails when class is defined in
    # the __doc__
    # noinspection PyTypeChecker
    '''
    Spanner objects live on Streams in the same manner as other Music21Objects,
    but represent and store connections between one or more other Music21Objects.

    Commonly used Spanner subclasses include the :class:`~music21.spanner.Slur`,
    :class:`~music21.spanner.RepeatBracket`, :class:`~music21.spanner.Crescendo`,
    and :class:`~music21.spanner.Diminuendo`
    objects.
github cuthbertLab / music21 / music21 / analysis / windowed.py View on Github external
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:
github cuthbertLab / music21 / music21 / spanner.py View on Github external
from typing import Union, List

from music21 import exceptions21
from music21 import base
from music21 import common
from music21 import defaults
from music21 import prebase
from music21 import style

from music21 import environment
_MOD = 'spanner'
environLocal = environment.Environment(_MOD)


# ------------------------------------------------------------------------------
class SpannerException(exceptions21.Music21Exception):
    pass


class SpannerBundleException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class Spanner(base.Music21Object):
    # suppress this inspection because it fails when class is defined in
    # the __doc__
    # noinspection PyTypeChecker
    '''
    Spanner objects live on Streams in the same manner as other Music21Objects,
    but represent and store connections between one or more other Music21Objects.
github cuthbertLab / music21 / music21 / mei / base.py View on Github external
# Exceptions
#------------------------------------------------------------------------------
class MeiValidityError(exceptions21.Music21Exception):
    "When there is an otherwise-unspecified validity error that prevents parsing."
    pass

class MeiValueError(exceptions21.Music21Exception):
    "When an attribute has an invalid value."
    pass

class MeiAttributeError(exceptions21.Music21Exception):
    "When an element has an invalid attribute."
    pass

class MeiElementError(exceptions21.Music21Exception):
    "When an element itself is invalid."
    pass


# Text Strings for Error Conditions
#------------------------------------------------------------------------------
_INVALID_XML_DOC = 'MEI document is not valid XML.'
_WRONG_ROOT_ELEMENT = 'Root element should be , not <{}>.'
_UNKNOWN_TAG = 'Found unexpected tag while parsing MEI: <{}>.'
_UNEXPECTED_ATTR_VALUE = 'Unexpected value for "{}" attribute: {}'
_SEEMINGLY_NO_PARTS = 'There appear to be no  tags in this score.'
_MISSING_VOICE_ID = 'Found a  without @n attribute and no override.'
_CANNOT_FIND_XMLID = 'Could not find the @{} so we could not create the {}.'
_MISSING_TUPLET_DATA = 'Both @num and @numbase attributes are required on  tags.'
_UNIMPLEMENTED_IMPORT = 'Importing {} without {} is not yet supported.'
_UNPROCESSED_SUBELEMENT = 'Found an unprocessed <{}> element in a <{}>.'
github cuthbertLab / music21 / music21 / alpha / counterpoint / species.py View on Github external
from music21 import interval
from music21 import meter
from music21 import scale

from music21 import stream
#from music21.stream import Stream
from music21 import voiceLeading

from music21 import environment
_MOD = "counterpoint/species.py"
environLocal = environment.Environment(_MOD)


# pylint: disable=duplicate-code

class ModalCounterpointException(exceptions21.Music21Exception):
    pass

class ModalCounterpoint:
    def __init__(self, stream1=None, stream2=None):
        self.stream1 = stream1
        self.stream2 = stream2
        self.legalHarmonicIntervals = ['P1', 'P5', 'P8', 'm3', 'M3', 'm6', 'M6']
        self.legalMelodicIntervals = ['P4', 'P5', 'P8', 'm2', 'M2', 'm3', 'M3', 'm6']
        self.legalMiddleHarmonicIntervals = ['P1', 'P4', 'P5', 'P8', 'm3', 'M3', 'm6', 'M6']

    # pylint: disable=duplicate-code
    def findParallelFifths(self, srcStream, cmpStream):
        '''Given two streams, returns the number of parallel fifths and also
        assigns a flag under note.editorial["parallelFifth"] for
        any note that has harmonic interval of a fifth and is preceded by a
        harmonic interval of a fifth.
github cuthbertLab / music21 / music21 / musicxml / m21ToXML.py View on Github external
from music21 import bar
from music21 import key
from music21 import metadata
from music21 import note
from music21 import meter
from music21 import spanner
from music21 import stream

from music21.musicxml import xmlObjects

from music21 import environment
_MOD = "musicxml.m21ToXML"
environLocal = environment.Environment(_MOD)

#-------------------------------------------------------------------------------
class ToMxObjectsException(exceptions21.Music21Exception):
    pass
class NoteheadException(ToMxObjectsException):
    pass

def dump(xmlEl):
    r'''
    wrapper around xml.etree.ElementTree as ET that returns a string
    in every case, whether Py2 or Py3...

    >>> from music21.musicxml.m21ToXML import Element
    >>> e = Element('accidental')
    >>> musicxml.m21ToXML.dump(e)
    
    
    >>> e.text = u'∆'
    >>> e.text == u'∆'