Skip to content

main_objs

Import functions come first, since they're the usual starting point, followed by ImportedPiece and its supporting functions; CorpusBase follows since it builds on ImportedPiece.

ImportedPiece

ImportedPiece(score, path, mei_doc=None, date=None)
Source code in crim_intervals/main_objs.py
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
def __init__(self, score, path, mei_doc=None, date=None):
    self.score = score
    self.path = path
    self.file_name = path.rsplit('.', 1)[0].rsplit('/')[-1]
    self.mei_doc = mei_doc
    self.analyses = {'note_list': None}
    title, composer = path, 'Not found'
    if mei_doc is not None:
        title = mei_doc.find('mei:meiHead//mei:titleStmt/mei:title', namespaces={"mei": MEINSURI})
        if title is not None and hasattr(title, 'text'):
            title = re.sub(r'\n', '', title.text).strip()
        composer = mei_doc.find('mei:meiHead//mei:titleStmt//mei:persName[@role="composer"]', namespaces={"mei": MEINSURI})
        if composer is None:  # for mei 3 files
            composer = mei_doc.find('mei:meiHead//mei:titleStmt/mei:composer', namespaces={"mei": MEINSURI})
        if composer is not None and hasattr(composer, 'text'):
            composer = re.sub(r'\n', '', composer.text).strip()
    else:
        if self.score.metadata.title is not None:
            title = self.score.metadata.title
        if self.score.metadata.composer is not None:
            composer = self.score.metadata.composer
    self.metadata = {'title': title, 'composer': composer, 'date': date}
    if not self.metadata['date']:
        if hasattr(self.score.metadata, 'date') and self.score.metadata.date is not None and self.score.metadata.date != 'None':
            self.metadata['date'] = int(self.score.metadata.date[:4])
        elif hasattr(self.score.metadata, 'dateCreated') and self.score.metadata.date is not None and self.score.metadata.dateCreated != 'None':
        # music21 v8 replaced date with dateCreated and date will be removed in v10
            self.metadata['date'] = int(self.score.metadata.dateCreated[:4])

    self._intervalMethods = {
        # (quality, directed, compound):   function returning the specified type of interval
        # diatonic with quality
        ('q', True, True): ImportedPiece._qualityDirectedCompound,
        ('q', True, False): ImportedPiece._qualityDirectedSimple,
        ('q', False, True): lambda cell: cell.name if hasattr(cell, 'name') else cell,
        ('q', False, False): lambda cell: cell.semiSimpleName if hasattr(cell, 'semiSimpleName') else cell,
        # diatonic interals without quality
        ('d', True, True): lambda cell: cell.directedName[1:] if hasattr(cell, 'directedName') else cell,
        ('d', True, False): ImportedPiece._noQualityDirectedSemiSimple,
        ('d', True, 'simple'): ImportedPiece._noQualityDirectedSimple,
        ('d', False, True): lambda cell: cell.name[1:] if hasattr(cell, 'name') else cell,
        ('d', False, False): lambda cell: cell.semiSimpleName[1:] if hasattr(cell, 'semiSimpleName') else cell,
        # chromatic intervals
        ('c', True, True): lambda cell: str(cell.semitones) if hasattr(cell, 'semitones') else cell,
        ('c', True, False): lambda cell: str(cell.semitones % 12) if hasattr(cell, 'semitones') else cell,
        ('c', False, True): lambda cell: str(abs(cell.semitones)) if hasattr(cell, 'semitones') else cell,
        ('c', False, False): lambda cell: str(abs(cell.semitones) % 12) if hasattr(cell, 'semitones') else cell
    }

barlines

barlines()

This method retrieves some of the barlines. It's not clear how music21 picks them, but this seems to get all the double barlines which helps detect section divisions.

Source code in crim_intervals/main_objs.py
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def barlines(self):
    """
    This method retrieves some of the barlines. It's not clear how music21
    picks them, but this seems to get all the double barlines which helps
    detect section divisions.
    """
    if "Barline" not in self.analyses:
        parts = self._getFlatParts()
        partBarlines = []
        for part in parts:
            partBarlines.append(pd.Series({b.offset: b.type \
                for b in part.getElementsByClass(['Barline'])}))
        df = pd.concat(partBarlines, axis=1, sort=True)
        df.columns = self._getPartNames()
        self.analyses["Barline"] = df
    return self.analyses["Barline"]

beatIndex

beatIndex()

Return a series of the first valid value in each row of .beats().

This is useful for getting the beat position of a given timepoint (i.e. index value) in the piece. You would use this method to lookup the beat position of a given offset (timepoint) in a piece. Provided there is a note or rest in any voice at that offset, the beatIndex results will have a value at that index.

Results from this method should not be sent to the regularize method.

Source code in crim_intervals/main_objs.py
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def beatIndex(self):
    '''
    Return a series of the first valid value in each row of .beats().

    This is useful for getting the beat position of a given timepoint (i.e.
    index value) in the piece. You would use this method to lookup the beat
    position of a given offset (timepoint) in a piece. Provided there is a
    note or rest in any voice at that offset, the `beatIndex` results will
    have a value at that index.

    Results from this method should not be sent to
    the `regularize` method. 
    '''
    if 'BeatIndex' not in self.analyses:
        ser = self.beats().dropna(how='all').apply(lambda row: row.dropna().iat[0], axis=1)
        self.analyses['BeatIndex'] = ser
    return self.analyses['BeatIndex']

beatStrengths

beatStrengths()

Returns a table of the beat strengths of all the notes and rests in the piece. This follows the music21 conventions where the downbeat is equal to 1, and all other metric positions in a measure are given smaller numbers approaching zero as their metric weight decreases.

Results from this method should not be sent to the regularize method.

Source code in crim_intervals/main_objs.py
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def beatStrengths(self):
    '''
    Returns a table of the beat strengths of all the notes and rests in
    the piece. This follows the music21 conventions where the downbeat is
    equal to 1, and all other metric positions in a measure are given
    smaller numbers approaching zero as their metric weight decreases.

    Results from this method should not be sent to the `regularize` method.
    '''
    if 'BeatStrength' not in self.analyses:
        df = self._getM21ObjsNoTies().map(self._beatStrengthHelper)
        self.analyses['BeatStrength'] = df
    return self.analyses['BeatStrength']

beats

beats()

Return a table of the beat positions of all the notes and rests.

Beats are expressed as floats. The downbeat of each measure is 1.0, and all other metric positions in a measure are given smaller numbers approaching zero as their metric weight decreases. Results from this method should not be sent to the regularize method.

The weights are determined by music21's beatStrength method, which is based on the prevailing time signature at each moment in the piece.

Source code in crim_intervals/main_objs.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
def beats(self):
    '''
    Return a table of the beat positions of all the notes and rests.

    Beats are expressed as floats. The downbeat of each measure is 1.0, and
    all other metric positions in a measure are given smaller numbers
    approaching zero as their metric weight decreases. Results from this
    method should not be sent to the regularize method.

    The weights are determined by music21's `beatStrength` method, which is based on the prevailing time signature at each moment in the piece.    
    '''
    if 'Beats' not in self.analyses:
        nr = self.notes()
        nrOffs = nr.apply(lambda row: row.index)
        ms = self.measures().apply(lambda row: row.index)
        temp = pd.concat([ms, nr], axis=1, sort=True)
        ms = temp.iloc[:, :len(ms.columns)].ffill()
        ms = ms[nr.notnull()]
        offFromMeas = nrOffs - ms
        beatDur = self._getBeatUnit()
        temp = pd.concat([beatDur, nr], axis=1, sort=True)
        beatDur = temp.iloc[:, :len(beatDur.columns)].ffill()
        beatDur = beatDur[nr.notnull()]
        self.analyses['Beats'] = (offFromMeas / beatDur) + 1
    return self.analyses['Beats']

cadenceProgressPlot

cadenceProgressPlot(includeType=False, cadTone=None, cadType=None, customOrder=None, includeLegend=True, renderer='')

Parameters Overview:

  • includeType: if set to True, the Cadence markers would be set based on both their Type. If set to False, a universal (round) marker will be used
  • cadTone: specify the Tone of cadences to explore. Takes an String input. Set to None by default
  • cadType: specify the Type of cadences to explore. Takes an String input. Set to None by default
  • customOrder: specify a custom order to be used for the plot (a dictionary: e.g. {"A":0, "B":1 ...}
  • includeLegend: flag to display legend; Default set to True

Examples:

cadenceProgressPlot(includeType=True)
Source code in crim_intervals/main_objs.py
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
def cadenceProgressPlot(self, includeType=False, cadTone=None, cadType=None, customOrder=None, includeLegend=True, renderer=""):

    '''
    Parameters Overview:

    * includeType: if set to True, the Cadence markers would be set based on both their Type. If set to False, a universal (round) marker will be used
    * cadTone: specify the Tone of cadences to explore. Takes an String input. Set to None by default
    * cadType: specify the Type of cadences to explore. Takes an String input. Set to None by default
    * customOrder: specify a custom order to be used for the plot (a dictionary: e.g. {"A":0, "B":1 ...}
    * includeLegend: flag to display legend; Default set to True

    Examples
    --------
    ```python
    cadenceProgressPlot(includeType=True)
    ```
    '''
    # runs sns plot layout
    self._plot_default()

    # defining markers for Cadence Types

    cadence_type_dict = {"Clausula Vera": "o", "Abandoned Clausula Vera": "v", "Evaded Clausula Vera": "^",
                 "Authentic" : "<", "Evaded Authentic": ">", "Abandoned Authentic": "8", "Double Leading Tone" : "s",
                 "Evaded Double Leading Tone": "p", "Abandoned Double Leading Tone": "P", "Phrygian Clausula Vera": "d",
                 "Altizans Only": "h", "Evaded Altizans Only": "H", "Leaping Contratenor": "X", "Reinterpreted": "D", 
                 "Phrygian": "d", "None": "*", "Quince": "."}

    # defining the default order list (or accepting the custom one)
    if customOrder == None:
        order_dict = {"Eb":0, "Bb":1, "F":2, "C":3, "G":4, "D":5, "A":6, "E":7, "B":8, "F#":9, "Db":10, "Ab":11}
    else:
        order_dict = customOrder

    # get cadences
    local_cadences = self.cadences()

    # check for a lookup type
    if cadType != None:
        local_cadences = local_cadences[local_cadences["CadType"] == cadType]

    # check for a lookup tone
    if cadTone != None:
        local_cadences = local_cadences[local_cadences["Tone"] == cadTone]

    # check if empty
    if len(local_cadences) < 1:
        print("No cadences found!")
        return None

    # convert Tone to a Numerical
    local_cadences["Numerical"] = local_cadences["Tone"].apply(lambda x: order_dict.get(x))

    # filtering for Types
    if includeType:
        local_cadences["CadType"] = local_cadences["CadType"].fillna("None")
        sns.scatterplot(x=local_cadences['Progress'], y=local_cadences['Numerical'], style=local_cadences["CadType"], markers=cadence_type_dict, s=140)
    else:
        sns.scatterplot(x=local_cadences['Progress'], y=local_cadences['Numerical'], s=140)

    # arranging Ticks and Tick labels
    plt.yticks(ticks=list(order_dict.values()), labels=list(order_dict.keys()))

    # producing the Type legend
    if includeType:
        type_patch_array = []
        for type_item in local_cadences["CadType"].unique().tolist():
            type_patch_array.append(mlines.Line2D([0], [0], marker=cadence_type_dict[type_item], color='black', label=type_item, markerfacecolor='black', markersize=10, linewidth=0))
            plt.legend(handles=type_patch_array)

    # Producing the chart legend
    if includeLegend:
        plt.title("Cadence Progress Graph: " + self.metadata["title"])
    plt.ylabel("Cadence Tone")
    if renderer == "streamlit":
        return plt
    else:
        plt.show()

cadenceRadarPlot

cadenceRadarPlot(combinedType=False, sounding=None, displayAll=True, customOrder=None, renderer='iframe')

Parameters Overview:

  • combinedType: if set to True, the Cadences would be classified based on both their Type and Tone. If set to False, only Tone will be used. False by default
  • sounding: specify how many voices are sounding (optional). Takes an integer input. Set to None by default
  • displayAll: if set to True, the chart will display all pitches in the Default (Fifth) or Custom order
  • customOrder: the custom order parameter. Takes in a List of Strings
  • renderer: specify what renderer to be used for the plot (options include but are not limited to "svg", "iframe", "png", "notebook" etc

Examples:

cadenceRadarPlot(combinedType=False, displayAll=True, renderer="iframe")
Source code in crim_intervals/main_objs.py
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
def cadenceRadarPlot(self, combinedType=False, sounding=None, displayAll=True, customOrder=None, renderer="iframe"):

    '''
    Parameters Overview:

    * combinedType: if set to True, the Cadences would be classified based on both their Type and Tone. If set to False, only Tone will be used. False by default
    * sounding: specify how many voices are sounding (optional). Takes an integer input. Set to None by default
    * displayAll: if set to True, the chart will display all pitches in the Default (Fifth) or Custom order
    * customOrder: the custom order parameter. Takes in a List of Strings
    * renderer: specify what renderer to be used for the plot (options include but are not limited to "svg", "iframe", "png", "notebook" etc

    Examples
    --------
    ```python
    cadenceRadarPlot(combinedType=False, displayAll=True, renderer="iframe")
    ```
    '''
# defining the Default display order
    order_array = ["D", "A", "E", "B", "F#", "Db", "Ab", "Eb", "Bb", "F", "C", "G"]

    # accepting a custom order
    if customOrder != None:
        order_array = customOrder

    # getting cadences
    local_cadences = self.cadences()

    # checking if empty
    if len(local_cadences) == 0:
        print("No cadences found in the piece")
        return None

    # filtering for sounding
    if sounding != None:
        local_cadences = local_cadences[local_cadences["Sounding"] == sounding]
        if len(local_cadences) == 0:
            print("No cadences with given number of voices Sounding found in the piece")
            return None

    # generating Combined Type (if combinedType)
    if combinedType:
        local_cadences["Combined_Type"] = local_cadences["Tone"] + "_" + local_cadences["CadType"]
        selected_type = "Combined_Type"
    else:
        selected_type = "Tone"

    # groupby: Selected Type
    grouped_combined = pd.DataFrame(local_cadences.groupby([selected_type]).size().reset_index(name='Count'))

    # displaying all values (if displayAll)
    if displayAll:
        if selected_type == "Tone":
            grouped_combined['Tone'] = pd.Categorical(grouped_combined.Tone, categories=order_array, ordered=True)
            grouped_combined = grouped_combined.sort_values(by='Tone')
        fig = px.line_polar(grouped_combined, r="Count", theta=selected_type, category_orders={"Tone": order_array}, line_close=True)
    else:
        fig = px.line_polar(grouped_combined, r="Count", theta=selected_type, line_close=True)

    # including the Title
    fig.update_layout(title_text=(self.metadata['composer'] + ": " + self.metadata['title']))
    if renderer == 'streamlit':
        return fig
    else:
        fig.show(renderer=renderer)

cadences

cadences(keep_keys=False, voice_detail=False, key_sig=False, include_final=False)

Analyzes the realized, evaded, and abandoned cadences in the score and returns a DataFrame with the results.

This method identifies the cadences in the score based on the contrapuntal voice functions (CVFs) and melodic intervals. It also includes additional contextual information about the cadences to facilitate filtering and further analysis. The information in each column is as follows (in order of their appearance):

  • Pattern: Only visible if keep_keys is set to True. This column shows the combination of cadential voice functions and chromatic intervals (of the Cantizans, Tenorizans, and Altizans cvfs) that triggered this cadence observation.

  • Key: Only visible if keep_keys is set to True. This column shows the regex string used to match the Patterns found with those in the cadenceLabels.csv file.

  • CadType: This column shows the type of cadence that was observed. These can be these can be realized, evaded, or abandoned. If fully realized, the cadence will have no additional descriptor, but "Evaded" and "Abandoned" are labelled as such. The cadence types recognized are "Authentic", "Phrygian", "Leaping Contratenor", "Clausula Vera", "Phrygian Clausula Vera", "Altizans Only", "Phrygian Altizans", "Double Leading Tone", "Quince", and "Reinterpreted". The "Quince" cadence is rare and typically only happens in thicker textures with a "Quinta pars". It is like a Clausula Vera with the Tenorizans voice typically above the Cantizans voice, but the Tenorizans moves up by a fourth or down by a fifth at the perfection such that the Cantizans and Tenorizans arrive a perfect fifth. The very rare "Reinterpreted" cadence initially sounds like it will be an authentic type because one pair of voices can be understood as a Cantizans-Bassizans pair. But then Tenorizans below what sounded like a Bassizans causes the Cantizans to be reinterpreted as an Altizans, and the Bassizans to be reinterpreted as a Quintizans CVF, hence the name "Reinterpreted".

  • LeadingTones: The number of leading tones (i.e. semitones) as notated in the score. These can be from the Cantizans, Tenorizans, or Altizans. If the CVF that would normally have the leading tone (usually the Cantizans) is evaded or abandoned, the basic melodic movement is no longer fulfilled so this measurement doesn't apply and a -1 is given. 0 shows that no leading tone is notated in the score, so these places are likely candidates for adding editorial ficta.

  • CVFs: The cadential voice functions condensed into one string, following the order in which they appear in the voice parts, starting with the uppermost voice. Thus CB means the cantizans is above the bassizans, and TC means the tenorizans is above the cantizans (in terms of staff positions). For an explanation of the symbols see cvfs documentation. Uppercase CVFs are realized, lowercase are evaded or abandoned. However, the presence of evaded or abandoned CVFs does not necessarily mean the cadence is evaded or abandoned.

  • PartMap: Only visible if voice_detail is set to True. A dict mapping each CVF letter in the "CVFs" column to the staff position(s) (1 = highest voice, per numberParts) of the voice(s) that performed it, e.g. {'T': ['1'], 'C': ['2'], 'B': ['4']}. Values are lists because two voices can occasionally share a role letter in one cadence. Staff positions are used rather than voice names so the result stays comparable across pieces with different voice naming conventions.

  • Low: The pitch of the lowest sounding note at the perfection.

  • RelLow: The lowest pitch of each cadence shown as an interval measured against the final. Speaking of which, you can get the final of a piece with the .final() method. Looking at lowest sounding pitch of cadences relative to the final makes it easier to compare the modal procedure of pieces that are in different modes and/or transposed.

  • Tone: Similar to the "Low" column, the "Tone" is the goal tone of the cantizans (or altizans if there is no cantizans) respectively. This is usually the same pitch class as the "Low" column, but not always. This is NaN if the cadence has an evaded or abandoned Cantizans CVF.

  • RelTone: The cadential tone from the "Tone" column shown as an interval measured against the final. This is similar to the "RelLow" column, but for the cadential tone instead of the lowest sounding pitch. Looking at cadential tones relative to the final makes it easier to compare the modal procedure of pieces that are in different modes and/or transposed.

  • TSig: The prevailing time signature (as encoded in the score) at the perfection. This can be useful to look at cadences in different mensurations/meters, particularly comparing binary vs. ternary situations.

  • Measure: The measure number at the perfection.

  • Beat: The beat number at the perfection.

  • Sounding: How many voices are sounding at the perfection. Note that this count includes voices that did not have a CVF role in the cadence, and ones that only started or entered at the perfection.

  • Progress: The progress toward the end of the piece measured 0-1 where 0 is the very beginning of the piece and 1 is the time point of the last attack in the piece. This is particularly useful if you want to compare cadences in different pieces, especially if they are of different lengths. For example, a "Progress" value of 0.5 will always be at the halfway point of a piece, no matter how long or short the piece is.

  • SinceLast: The time in quarter notes since the last cadence. The first cadence's SinceLast time is the time since the beginning of the piece. An unusually high value here could suggest that the prior cadence was particularly conclusive, and that a less broken-up stretch of counterpoint follwed it. Alternatively a high value could mean that a cadence is being missed within the "SinceLast" number of quarter notes just prior to the cadence in question.

  • ToNext: The time in quarter notes to the next cadence. The last cadence's ToNext time is the time to the end of the piece. An unusually high value here could suggest that this cadence is particularly conclusive, and that a less broken-up stretch of counterpoint follows it. Alternatively a high value could mean that a cadence is being missed within the "ToNext" number of quarter notes just after the cadence in question.

  • KeySig: Only visible if key_sig is set to True. The prevailing system key signature at the perfection (music21 .sharps convention: positive = number of sharps, negative = number of flats, 0 = none). See ImportedPiece.keySignatures.

  • Final: Only visible if include_final is set to True. The piece's final tone (from ImportedPiece.final()), repeated on every row. Useful for corpus studies that group or filter cadences by mode/final.

Parameters:

Name Type Description Default
keep_keys bool

If True, the returned DataFrame includes the 'Pattern' and 'Key' columns. Note that this 'Key' is not a musical key/key-signature -- it's the regex string used internally to match cadence Patterns against cadenceLabels.csv, i.e. a lookup key for cadence-type classification. If False (default), these columns are dropped from the DataFrame.

False
voice_detail bool

If True, the returned DataFrame includes the 'PartMap' column. If False (default), this column is dropped from the DataFrame.

False
key_sig bool, optional (default False)

If True, add a 'KeySig' column with the prevailing system key signature (music21 .sharps convention) at each cadence's perfection. Defaults to False to keep existing output unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column with the piece's final tone, repeated on every row. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame

A DataFrame where each row represents a cadence. The first three columns are Composer, Title and Date (from the source file). The others provide details about the cadence, including the CVFs, melodic intervals, measure, beat, time signature, sounding pitch, progress, lowest pitch, and relative pitches (plus key signature and/or final, if requested).

Notes

This method caches the result in the analyses attribute of the Score object to avoid recomputing the cadences if the method is called again with the same parameters.

Source code in crim_intervals/main_objs.py
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
@_records_settings('cadences', ('keep_keys', 'voice_detail', 'key_sig', 'include_final'), inherit=())
def cadences(self, keep_keys=False, voice_detail=False, key_sig=False, include_final=False):
    """
    Analyzes the realized, evaded, and abandoned cadences in the score and returns
    a DataFrame with the results.

    This method identifies the cadences in the score based on the contrapuntal voice
    functions (CVFs) and melodic intervals. It also includes additional contextual
    information about the cadences to facilitate filtering and further analysis.
    The information in each column is as follows (in order of their appearance):

    * Pattern: Only visible if `keep_keys` is set to `True`. This column shows the
    combination of cadential voice functions and chromatic intervals (of the
    Cantizans, Tenorizans, and Altizans cvfs) that triggered this cadence
    observation.

    * Key: Only visible if `keep_keys` is set to `True`. This column shows the
    regex string used to match the Patterns found with those in the cadenceLabels.csv
    file.

    * CadType: This column shows the type of cadence that was observed. These can
    be these can be realized, evaded, or abandoned. If fully realized, the cadence
    will have no additional descriptor, but "Evaded" and "Abandoned" are labelled
    as such. The cadence types recognized are "Authentic", "Phrygian", "Leaping
    Contratenor", "Clausula Vera", "Phrygian Clausula Vera", "Altizans Only",
    "Phrygian Altizans", "Double Leading Tone", "Quince", and "Reinterpreted".
    The "Quince" cadence is rare and typically only happens in thicker textures
    with a "Quinta pars". It is like a Clausula Vera with the Tenorizans voice
    typically above the Cantizans voice, but the Tenorizans moves up by a fourth
    or down by a fifth at the perfection such that the Cantizans and Tenorizans
    arrive a perfect fifth. The very rare "Reinterpreted" cadence initially sounds
    like it will be an authentic type because one pair of voices can be understood
    as a Cantizans-Bassizans pair. But then Tenorizans below what sounded like a
    Bassizans causes the Cantizans to be reinterpreted as an Altizans, and the
    Bassizans to be reinterpreted as a Quintizans CVF, hence the name "Reinterpreted".

    * LeadingTones: The number of leading tones (i.e. semitones) as notated in the
    score. These can be from the Cantizans, Tenorizans, or Altizans. If the CVF
    that would normally have the leading tone (usually the Cantizans) is evaded or
    abandoned, the basic melodic movement is no longer fulfilled so this measurement
    doesn't apply and a -1 is given. 0 shows that no leading tone is notated in the
    score, so these places are likely candidates for adding editorial ficta.

    * CVFs: The cadential voice functions condensed into one string, following the
    order in which they appear in the voice parts, starting with the uppermost voice.
    Thus CB means the cantizans is above the bassizans, and TC means the tenorizans
    is above the cantizans (in terms of staff positions). For an explanation of the
    symbols see cvfs documentation. Uppercase CVFs are realized, lowercase are evaded
    or abandoned. However, the presence of evaded or abandoned CVFs does not
    necessarily mean the cadence is evaded or abandoned.

    * PartMap: Only visible if `voice_detail` is set to True. A dict mapping each CVF
    letter in the "CVFs" column to the staff position(s) (1 = highest voice, per
    `numberParts`) of the voice(s) that performed it, e.g. {'T': ['1'], 'C': ['2'],
    'B': ['4']}. Values are lists because two voices can occasionally share a role
    letter in one cadence. Staff positions are used rather than voice names so the
    result stays comparable across pieces with different voice naming conventions.

    * Low: The pitch of the lowest sounding note at the perfection.

    * RelLow: The lowest pitch of each cadence shown as an interval measured against
    the final. Speaking of which, you can get the final of a piece with the .final()
    method. Looking at lowest sounding pitch of cadences relative to the final
    makes it easier to compare the modal procedure of pieces that are in different
    modes and/or transposed.

    * Tone: Similar to the "Low" column, the "Tone" is the goal tone of the cantizans
    (or altizans if there is no cantizans) respectively. This is usually the same
    pitch class as the "Low" column, but not always. This is NaN if the cadence has
    an evaded or abandoned Cantizans CVF.

    * RelTone: The cadential tone from the "Tone" column shown as an interval
    measured against the final. This is similar to the "RelLow" column, but for the
    cadential tone instead of the lowest sounding pitch. Looking at cadential tones
    relative to the final makes it easier to compare the modal procedure of pieces
    that are in different modes and/or transposed.

    * TSig: The prevailing time signature (as encoded in the score) at the
    perfection. This can be useful to look at cadences in different
    mensurations/meters, particularly comparing binary vs. ternary situations.

    * Measure: The measure number at the perfection.

    * Beat: The beat number at the perfection.

    * Sounding: How many voices are sounding at the perfection. Note that this
    count includes voices that did not have a CVF role in the cadence, and ones
    that only started or entered at the perfection.

    * Progress: The progress toward the end of the piece measured 0-1 where 0 is
    the very beginning of the piece and 1 is the time point of the last attack in
    the piece. This is particularly useful if you want to compare cadences in
    different pieces, especially if they are of different lengths. For example,
    a "Progress" value of 0.5 will always be at the halfway point of a piece, no
    matter how long or short the piece is.

    * SinceLast: The time in quarter notes since the last cadence. The first
    cadence's SinceLast time is the time since the beginning of the piece. An
    unusually high value here could suggest that the prior cadence was particularly
    conclusive, and that a less broken-up stretch of counterpoint follwed it.
    Alternatively a high value could mean that a cadence is being missed within
    the "SinceLast" number of quarter notes just prior to the cadence in question.

    * ToNext: The time in quarter notes to the next cadence. The last cadence's
    ToNext time is the time to the end of the piece. An unusually high value here
    could suggest that this cadence is particularly conclusive, and that a less
    broken-up stretch of counterpoint follows it. Alternatively a high value
    could mean that a cadence is being missed within the "ToNext" number of
    quarter notes just after the cadence in question.

    * KeySig: Only visible if `key_sig` is set to True. The prevailing system key
    signature at the perfection (music21 .sharps convention: positive = number of
    sharps, negative = number of flats, 0 = none). See ImportedPiece.keySignatures.

    * Final: Only visible if `include_final` is set to True. The piece's final tone
    (from ImportedPiece.final()), repeated on every row. Useful for corpus studies
    that group or filter cadences by mode/final.

    Parameters
    ----------
    keep_keys : bool, optional
        If True, the returned DataFrame includes the 'Pattern' and 'Key' columns.
        Note that this 'Key' is not a musical key/key-signature -- it's the regex
        string used internally to match cadence Patterns against cadenceLabels.csv,
        i.e. a lookup key for cadence-type classification. If False (default),
        these columns are dropped from the DataFrame.
    voice_detail : bool, optional
        If True, the returned DataFrame includes the 'PartMap' column. If False
        (default), this column is dropped from the DataFrame.
    key_sig : bool, optional (default False)
        If True, add a 'KeySig' column with the prevailing system key signature
        (music21 .sharps convention) at each cadence's perfection. Defaults to
        False to keep existing output unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column with the piece's final tone, repeated on
        every row. Defaults to False to keep existing output unchanged.

    Returns
    -------
    pandas.DataFrame
        A DataFrame where each row represents a cadence. The first three columns
        are Composer, Title and Date (from the source file). The others provide details
        about the cadence, including the CVFs, melodic intervals, measure, beat,
        time signature, sounding pitch, progress, lowest pitch, and relative pitches
        (plus key signature and/or final, if requested).

    Notes
    -----
    This method caches the result in the `analyses` attribute of the `Score` object
    to avoid recomputing the cadences if the method is called again with the same parameters.
    """
    # key_sig/include_final change which columns get computed, so (unlike
    # keep_keys/voice_detail, which just drop columns post-hoc) they must be
    # part of the cache key -- otherwise a cached call without them would be
    # silently reused for a later call requesting them, and vice versa.
    memo_key = ('Cadences', key_sig, include_final)

    def _finish(labels):
        # works on a copy so the cached result is never altered
        labels = labels.copy()
        if not keep_keys:
            labels = labels.drop(['Pattern', 'Key'], axis=1)
        if not voice_detail:
            labels = labels.drop(['PartMap'], axis=1)
        # add piece metadata, as voice_ranges and melodic_species do, so the
        # result can go straight to visualizations.cadence_radar etc.
        labels.insert(0, 'Composer', self.metadata['composer'])
        labels.insert(1, 'Title', self.metadata['title'])
        labels.insert(2, 'Date', self.metadata['date'])
        return labels

    if memo_key in self.analyses:
        return _finish(self.analyses[memo_key])

    cvfs = self.cvfs(offsets='last')
    mel = self.melodic('c', True, True)
    mel = mel[cvfs.notnull()].dropna(how='all')
    if len(cvfs.index):
        _cvfs = cvfs.apply(self._cvf_simplifier, axis=1)
        _cvfs.replace(['Q', 's', 'S'], np.nan, inplace=True)
    else:
        _cvfs = cvfs.copy()
    mel = mel[_cvfs.isin(list('ACTctu'))].reindex_like(_cvfs).fillna('')
    cadKeys = _cvfs + mel
    keys = cadKeys.apply(lambda row: ''.join(row.dropna().sort_values().unique()), axis=1)
    keys.name = 'Pattern'
    keys = pd.DataFrame(keys)
    cadDict = _getCadenceTable()
    keys['Key'] = keys.Pattern.replace(cadDict.index, cadDict.index, regex=True)
    labels = keys.join(cadDict, on='Key')
    labels['CVFs'] = cvfs.apply(lambda row: ''.join(row.dropna()), axis=1)

    # map each CVF letter (as it appears in "CVFs") to the staff position(s) of the
    # voice(s) that performed it, e.g. {'T': ['1'], 'C': ['2'], 'B': ['4']}
    cvfs_numbered = self.numberParts(cvfs)
    def _cvf_role_map(row):
        roles = {}
        for part, cell in row.dropna().items():
            roles.setdefault(cell[0], []).append(part)
        return roles
    labels['PartMap'] = cvfs_numbered.apply(_cvf_role_map, axis=1)

    detailed = self.detailIndex(labels, measure=True, beat=True, offset=True, t_sig=True, key_sig=key_sig,
        sounding=True, progress=True, lowest=True)
    # NEW: check for Rest and remove that row in detailed and labels
    # temp reset of index for value check
    det_reset = detailed.reset_index()
    # index of "Rest" rows
    index_rest = det_reset.loc[det_reset['Lowest'] == 'Rest'].index.tolist()
    # Filter out rows where the fifth level (now a column after reset) contains 'Rest'
    det_filtered = det_reset[~det_reset['Lowest'].str.contains('Rest')]
    # set index back to what it was
    detailed = det_filtered.set_index(detailed.index.names)

    # filter out corresponding row from Labels df
    # temp reset of index
    labels_reset = labels.reset_index()
    # remove corresponding rows that have rests in the detailed DF, based on stored index_rest
    labels_filtered = labels_reset.drop(index_rest, axis=0)
    # put labels back to previous index
    labels = labels_filtered.set_index(labels.index.names)

    # Named (rather than positional) level lookups, since the `key_sig` column
    # inserts an extra index level between TSig and Sounding when requested.
    labels['Low'] = detailed.index.get_level_values('Lowest').values
    final = note.Note(self.final())
    labels['RelLow'] = labels.Low.apply(lambda x: ImportedPiece._qualityDirectedCompound(interval.Interval(final, note.Note(x))))
    nr = self.notes()
    if len(labels.index):
        labels['Tone'] = cvfs.apply(self._cadential_pitch, args=(nr,), axis=1)
    else:
        labels['Tone'] = []
    # Tone (and thus RelTone) is NaN when the Cantizans CVF is evaded/abandoned
    # (see docstring); guard note.Note(x) against that, since some music21
    # versions raise instead of tolerating a NaN pitch name.
    labels['RelTone'] = labels.Tone.apply(
        lambda x: ImportedPiece._qualityDirectedSimple(interval.Interval(final, note.Note(x))) if pd.notna(x) else np.nan
    )
    labels.RelTone = labels.RelTone[labels.Tone.notnull()]
    labels.Tone = labels.Tone.fillna(np.nan)
    labels['TSig'] = detailed.index.get_level_values('TSig').values
    if key_sig:
        labels['KeySig'] = detailed.index.get_level_values('KeySig').values
    labels['Measure'] = detailed.index.get_level_values('Measure').values
    labels['Beat'] = detailed.index.get_level_values('Beat').values
    labels['Offset'] = detailed.index.get_level_values('Offset').values
    labels['Sounding'] = detailed.index.get_level_values('Sounding').values
    labels['Progress'] = detailed.index.get_level_values('Progress').values
    if include_final:
        labels['Final'] = self.final()
    ndx = labels.index.to_series()
    labels['SinceLast'] = ndx - ndx.shift(1)
    if len(labels.index):
        labels.iat[0, -1] = labels.index[0]
    labels['ToNext'] = labels['SinceLast'].shift(-1)
    if len(labels.index):
        labels.iat[-1, -1] = self.score.highestTime - labels.index[-1]
    self.analyses[memo_key] = labels
    return _finish(labels)

combineEmaAddresses

combineEmaAddresses(emas)

EMA stands for Enhancing Music Addressability specification, a system we use with the OMAS API to cite and render any combination of musical events at a given set of Beats, Measures and Staves. Given a list of EMA addresses, emas, return a single ema address that combines them into one.
Learn more about EMA and OMAS at https://music-encoding.org/projects/ema.html.

Source code in crim_intervals/main_objs.py
 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
1001
1002
1003
1004
1005
def combineEmaAddresses(self, emas):
    '''
    EMA stands for Enhancing Music Addressability specification, a system we use with the OMAS API
    to cite and render any combination of musical events at a given set of Beats, Measures and Staves.
    Given a list of EMA addresses, `emas`, return a single ema address that combines them into one.  
    Learn more about EMA and OMAS at https://music-encoding.org/projects/ema.html.
    '''
    if isinstance(emas, str):
        return emas
    if len(emas) == 1:
        return emas[0]
    chunks = []
    num_parts = len(self._getPartNames())
    last_m = self.measures().iat[-1, 0]
    for ema in emas:
        ema = ema.replace('start', '1')
        _measures, _parts, _beats = ema.split('/')
        _beats = _beats.replace('1.0-', '1-')
        _beats = _beats.replace('1.0@', '1@')
        measures, parts, beats = _measures.split(','), _parts.split(','), _beats.split(',') 
        for i, meas in enumerate(measures):
            # handle measures
            if meas == 'all':
                meas == '1-{}'.format(last_m)  # measures 1 through the final measure
            meas = meas.replace('end', str(last_m))
            if '-' in meas:   # this is a measure range, e.g. 9-12
                start, end = meas.split('-')
                ms = [str(m) for m in range(int(start), int(end) + 1)]
                meas = ms[0]
                measures[i+1:i+1] = ms[1:]
            # handle beats
            if beats[i] == '@all' or beats[i] == '@1-end':
                bs = '@all'
            else:
                bs = beats[i].split('+')
            # handle parts
            if parts[i] == 'all':
                ps = [str(x) for x in range(1, num_parts + 1)]
            else:
                ps = parts[i].replace('end', str(num_parts))
                ps = ps.split('+')
                for _j, _p in enumerate(ps):
                    if '-' in _p:
                        start, end = _p.split('-')
                        if end == 'end':
                            end = num_parts
                        parts_in_range = [str(part) for part in range(int(start), int(end) + 1)]
                        for part in parts_in_range:
                            if isinstance(bs, str):
                                chunks.append((meas, part, bs))
                            else:
                                chunks.append((meas, part, bs[_j]))
                    if isinstance(bs, str):
                        chunks.append((meas, _p, bs))
                    else:
                        chunks.append((meas, _p, bs[_j]))

    # collect the beats for the addresses at the same measure and part
    mp2bs = {}
    for chunk in chunks:
        key = (chunk[0], chunk[1])
        if key not in mp2bs:
            mp2bs[key] = [chunk[2]]
        else:
            mp2bs[key].append(chunk[2])

    # combine the beats into one for each measure-part combo
    slices = [(*mp, '@all') if '@all' in bs else (*mp, ''.join(set(bs))) for mp, bs in mp2bs.items()]
    # sort by part number, then by measure so the slices are ordered by measure then part number
    df = pd.DataFrame(slices, columns=['Measure', 'Part', 'Beat']).sort_values(['Measure', 'Part'])
    mpost = df.Measure.unique()
    ppost = ','.join(['+'.join(df.loc[df.Measure == _m, 'Part']) for _m in mpost])
    bpost = ','.join(['+'.join(df.loc[df.Measure == _m, 'Beat']) for _m in mpost])
    mpost = ','.join(mpost)
    return '/'.join((mpost, ppost, bpost))

condenseMultiIndex

condenseMultiIndex(df, to_drop=0)

Take a df with a 'First' and 'Last' multi-index and return a copy condensed such that the to_drop index is dropped.

Source code in crim_intervals/main_objs.py
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
def condenseMultiIndex(self, df, to_drop=0):
    '''
    Take a df with a 'First' and 'Last' multi-index and return a copy condensed such that 
    the `to_drop` index is dropped.
    '''
    if isinstance(df, pd.core.series.Series):
        df = pd.DataFrame(df)
    if df.index.nlevels < 2:
        ret = df.copy()
    else:
        ret = df.droplevel(to_drop)
    dup_mask = ret.index.duplicated()
    dups = ret.index[dup_mask]
    ret = ret[~dup_mask]
    for dup in dups:
        filled = df.loc[(slice(None), dup), :].infer_objects(copy=False).ffill()
        ret.loc[dup, :] = filled.iloc[-1, :].values
    return ret

cvfs

cvfs(keep_keys=False, offsets='last')

Return a dataframe of cadential voice functions in the piece. If keep_keys is set to True, the ngrams that triggered each CVF pair will be shown in additional columns in the table. If offsets='last' (default) the last offset of the cvfs will be shown. If offsets is set to anything else the table will be returned with a multi-index for First and Last offsets for the module patterns.

Each CVF is represented with a single-character label as follows:

Realized Cadential Voice Functions:

  • "C": cantizans motion up a step (can also be ornamented e.g. Landini)
  • "T": tenorizans motion down a step (can be ornamented with anticipations)
  • "B": bassizans motion up a fourth or down a fifth
  • "A": altizans motion, similar to cantizans, but cadences to a fifth above a tenorizans instead of an octave
  • "L": leaping contratenor motion up an octave at the perfection
  • "P": plagal bassizans motion up a fifth or down a fourth
  • "Q": quintizans, like a tenorizans, but resolves down by fifth or up by fourth to a fourth below the goal tone of a cantizans or an octave below the goal tone of an altizans
  • "S": sestizans, occurring in some thicker 16th century textures, this is where the agent against the cantizans is already the cantizans' note of resolution (often results in a simultaneous false relation); the melodic motion is down by third at the moment of perfection

Evaded Cadential Voice Functions:

  • "c": evaded cantizans when it moves to an unexpected note at the perfection
  • "t": evaded tenorizans when it goes up by step at the perfection
  • "b": evaded bassizans when it goes up by step at the perfection
  • "u": evaded bassizans when it goes down by third at the perfection (there are no evaded labels for the altizans, plagal bassizans leaping contratenor CVFs)
  • "s": evaded sestizans when it resolves down by second

Abandoned Cadential Voice Functions:

  • "x": evaded bassizans motion where the voice drops out at the perfection
  • "y": evaded cantizans motion where the voice drops out at the perfection
  • "z": evaded tenorizans motion where the voice drops out at the perfection

The way these CVFs combine determines which cadence labels are assigned in the .cadences() method.

Source code in crim_intervals/main_objs.py
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
def cvfs(self, keep_keys=False, offsets='last'):
    '''
    Return a dataframe of cadential voice functions in the piece. If
    `keep_keys` is set to True, the ngrams that triggered each CVF pair
    will be shown in additional columns in the table. If `offsets='last'`
    (default) the last offset of the cvfs will be shown. If offsets is
    set to anything else the table will be returned with a multi-index
    for First and Last offsets for the module patterns.

    Each CVF is represented with a single-character label as follows:

    Realized Cadential Voice Functions:

    * "C": cantizans motion up a step (can also be ornamented e.g. Landini)
    * "T": tenorizans motion down a step (can be ornamented with anticipations)
    * "B": bassizans motion up a fourth or down a fifth
    * "A": altizans motion, similar to cantizans, but cadences to a fifth
        above a tenorizans instead of an octave
    * "L": leaping contratenor motion up an octave at the perfection
    * "P": plagal bassizans motion up a fifth or down a fourth
    * "Q": quintizans, like a tenorizans, but resolves down by fifth or up by
        fourth to a fourth below the goal tone of a cantizans or an octave
        below the goal tone of an altizans
    * "S": sestizans, occurring in some thicker 16th century textures, this is
        where the agent against the cantizans is already the cantizans' note
        of resolution (often results in a simultaneous false relation); the
        melodic motion is down by third at the moment of perfection

    Evaded Cadential Voice Functions:

    * "c": evaded cantizans when it moves to an unexpected note at the perfection
    * "t": evaded tenorizans when it goes up by step at the perfection
    * "b": evaded bassizans when it goes up by step at the perfection
    * "u": evaded bassizans when it goes down by third at the perfection
    (there are no evaded labels for the altizans, plagal bassizans leaping
    contratenor CVFs)
    * "s": evaded sestizans when it resolves down by second

    Abandoned Cadential Voice Functions:

    * "x": evaded bassizans motion where the voice drops out at the perfection
    * "y": evaded cantizans motion where the voice drops out at the perfection
    * "z": evaded tenorizans motion where the voice drops out at the perfection

    The way these CVFs combine determines which cadence labels are assigned
    in the `.cadences()` method.
    '''
    if len(self._getPartNames()) < 2:
        return pd.DataFrame()
    key = ('CVF', keep_keys, offsets)
    if key in self.analyses:
        return self.analyses[key].copy()
    cadences = _getCVFTable()
    cadences['N'] = cadences.index.map(lambda i: i.count(', ') + 1)
    harmonic = self.markFourths()
    melodic = self.melodic('d', True, False)
    ngrams = {n: self.ngrams(how='modules', df=harmonic, other=melodic, n=n, offsets='both',
              held='1', exclude=[], show_both=True).stack() for n in cadences.N.unique()}
    hits = [ser[ser.str.contains('|'.join(cadences[cadences.N == n].index), regex=True)]
            for n, ser in ngrams.items() if not ser.empty]
    if not hits:
        # no cadential n-gram patterns of any length were even possible
        # for this piece (e.g. too short), so there's nothing to concat
        return pd.DataFrame()
    hits = pd.concat(hits)
    hits.sort_index(level=1, inplace=True)
    hits = hits[~hits.index.duplicated('last')]
    if keep_keys:
        ngramKeys = hits.unstack(level=-1)
    hits.name = 'Ngram'
    df = pd.DataFrame(hits)
    df['Pattern'] = df.Ngram.replace(cadences.index, cadences.index, regex=True)
    df = df.join(cadences, on='Pattern')
    voices = [pair.split('_') for pair in df.index.get_level_values(2)]
    # When there are no cadential-pattern hits at all, `voices` is `[]`,
    # whose shape (0,) doesn't broadcast into the 2 target columns the
    # way a list of 2-element lists does; building a DataFrame first
    # keeps both the empty and non-empty cases working the same way.
    df[['LowerVoice', 'UpperVoice']] = pd.DataFrame(voices, index=df.index, columns=['LowerVoice', 'UpperVoice'])
    df.index = df.index.droplevel(2)
    cvfs = pd.DataFrame(columns=self._getPartNames(), index=pd.MultiIndex.from_arrays([[], []], names=df.index.names))
    if len(df):
        # `DataFrame.apply(axis=1)` on a 0-row df still calls the function
        # once with a dummy all-NaN row to infer the result dtype. Since
        # `_cvf_helper` mutates `cvfs` in place via `row.LowerVoice`/
        # `row.UpperVoice` (both NaN on the dummy row), that phantom call
        # would otherwise inject two spurious NaN-named columns into
        # `cvfs`, which later breaks `numberParts` (columns must be str).
        df.apply(func=self._cvf_helper, axis=1, args=(cvfs,))
    cvfs = cvfs.apply(self._cvf_disambiguate_h, axis=1).dropna(how='all')
    cvfs = cvfs.astype('object', copy=False)
    mel = self.melodic('c', True, True)
    for _index in cvfs.index:
        for _voice in cvfs.columns:
            if cvfs.at[_index, _voice] == 'x' and mel.at[_index[1], _voice] in ('5', '-7'):
                cvfs.at[_index, _voice] = 'B'
                continue
            if cvfs.at[_index, _voice] == 'y' and mel.at[_index[1], _voice] in ('1', '2'):
                cvfs.at[_index, _voice] = 'C'
                continue
            if cvfs.at[_index, _voice] == 'z' and mel.at[_index[1], _voice] in ('-1', '-2'):
                cvfs.at[_index, _voice] = 'T'
    if keep_keys:
        cvfs = pd.concat([cvfs, ngramKeys], axis=1, sort=True)
    if offsets == 'last' and len(cvfs.index.levels) > 1:
        cvfs = self.condenseMultiIndex(cvfs)
    self.analyses[key] = cvfs
    return cvfs.copy()

detailIndex

detailIndex(df, measure=True, beat=True, offset=False, t_sig=False, key_sig=False, sounding=False, progress=False, lowest=False, highest=False, _all=False)

Return the passed dataframe with a multi-index of any combination of the measure, beat, offset, prevailing time signature, and progress towards the end of the piece (0-1) in the index labels. At least one must be chosen, and the default is to have measure and beat information, but no other information. Here are all the Boolean parameters that default to False, but that you can set to True if you also want to see them:

  • offset: row's offset (distance in quarter notes from beginning, 1.0 = one quarter note)
  • t_sig: the prevailing time signature
  • key_sig: the prevailing system key signature, as music21's .sharps value (positive = number of sharps, negative = number of flats, 0 = none)
  • sounding: how many voices are sounding (i.e. not resting) at this point
  • progress: 0-1 how far along in the piece this moment is, 0 = beginning, 1 = last attack onset
  • lowest: the lowest sounding note at this moment
  • highest: the highest sounding note at this moment

You can also pass _all=True to include all these types of index information.

Source code in crim_intervals/main_objs.py
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
@_records_settings()
def detailIndex(self, df, measure=True, beat=True, offset=False, t_sig=False,
    key_sig=False, sounding=False, progress=False, lowest=False, highest=False, _all=False):
    '''
    Return the passed dataframe with a multi-index of any combination of the
    measure, beat, offset, prevailing time signature, and progress towards
    the end of the piece (0-1) in the index labels. At least one must be
    chosen, and the default is to have measure and beat information, but no
    other information. Here are all the Boolean parameters that default to `False`,
    but that you can set to `True` if you also want to see them:

    * offset: row's offset (distance in quarter notes from beginning, 1.0 = one quarter note)
    * t_sig: the prevailing time signature
    * key_sig: the prevailing system key signature, as music21's .sharps value
      (positive = number of sharps, negative = number of flats, 0 = none)
    * sounding: how many voices are sounding (i.e. not resting) at this point
    * progress: 0-1 how far along in the piece this moment is, 0 = beginning, 1 = last attack onset
    * lowest: the lowest sounding note at this moment
    * highest: the highest sounding note at this moment

    You can also pass `_all=True` to include all these types of index information.
    '''
    cols = [df]
    names = []
    if _all:
        measure, beat, offset, t_sig, key_sig, sounding, progress, lowest, highest = [True] * 9
    if measure:
        cols.append(self.measures().iloc[:, 0])
        names.append('Measure')
    if beat:
        cols.append(self.beatIndex())
        names.append('Beat')
    if offset:
        cols.append(df.index.to_series())
        names.append('Offset')
    if t_sig:
        cols.append(self.timeSignatures().iloc[:, 0])
        names.append('TSig')
    if key_sig:
        cols.append(self.keySignatures().iloc[:, 0])
        names.append('KeySig')
    if sounding:
        cols.append(self.soundingCount())
        names.append('Sounding')
    if progress:
        prog = (df.index / self.notes().index[-1]).to_series()
        prog.index = df.index
        cols.append(prog)
        names.append('Progress')
    if lowest:
        cols.append(self.lowLine())
        names.append('Lowest')
    if highest:
        cols.append(self.highLine())
        names.append('Highest')
    temp = pd.concat(cols, axis=1, sort=True)
    temp2 = temp.iloc[:, len(df.columns):].ffill()
    if measure:
        temp2.iloc[:, 0] = temp2.iloc[:, 0].astype(int)
    mi = pd.MultiIndex.from_frame(temp2, names=names)
    ret = temp.iloc[:, :len(df.columns)].copy()
    ret.index = mi
    ret.dropna(inplace=True, how='all')
    ret.sort_index(inplace=True)
    return ret

di

di(df, measure=True, beat=True, offset=False, t_sig=False, key_sig=False, sounding=False, progress=False, lowest=False, highest=False, _all=False)

Convenience shortcut for .detailIndex. See that method's documentation for instructions.

Source code in crim_intervals/main_objs.py
1404
1405
1406
1407
1408
1409
1410
def di(self, df, measure=True, beat=True, offset=False, t_sig=False, key_sig=False,
    sounding=False, progress=False, lowest=False, highest=False, _all=False):
    """
    Convenience shortcut for .detailIndex. See that method's documentation for instructions.
    """
    return self.detailIndex(df=df, measure=measure, beat=beat, offset=offset, t_sig=t_sig,
        key_sig=key_sig, sounding=sounding, progress=progress, lowest=lowest, highest=highest, _all=_all)

distance

distance(df=None, n=3)

Return the distances between all the values in df which should be a dataframe of strings of integer ngrams. Specifically, this is meant for 0-indexed, directed, and compound melodic ngrams. If nothing is passed for df, melodic ngrams of this type will be provided at the value of n passed. An alternative that would make sense would be to use chromatic melodic intervals instead.

Parameters:

Name Type Description Default
df DataFrame

A dataframe of strings of integer ngrams. If not passed, melodic ngrams of this type will be calculated at the value of n.

None
n int, optional (default 3)

The ngram length to use when df is not passed. Ignored if df is passed.

3

Returns:

Type Description
DataFrame

A square distance matrix indexed and columned by the unique ngram values found in df.

Examples:

Call like this:

importedPiece.distance()

If you don't pass a value for df, you can specify a different value for n to change from the default of 3:

importedPiece.distance(n=5)

If you already have the melodic ngrams calculated for a different aspect of your query, you can pass that as df to save a little runtime on a large query. Note that if you pass something for df, the n parameter will be ignored:

mel = importedPiece.melodic('z', True, True)
ngrams = importedPiece.ngrams(df=mel, n=4, exclude=['Rest'])
importedPiece.distance(df=ngrams)

To search the table for the distances from a given pattern, just get the column of that name. This example looks for distances involving a melodic pattern that goes up a step, down a third, up a step, down a third:

dist = importedPiece.distance(n=4)
target = '1, -2, 1, -2'
col = dist[target]

If you then want to filter that column, say to distances less than or equal to 2, do this:

col[col <= 2]
Source code in crim_intervals/main_objs.py
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
def distance(self, df=None, n=3):
    '''
    Return the distances between all the values in df which should be a
    dataframe of strings of integer ngrams. Specifically, this is meant for
    0-indexed, directed, and compound melodic ngrams. If nothing is passed
    for df, melodic ngrams of this type will be provided at the value of n
    passed. An alternative that would make sense would be to use chromatic
    melodic intervals instead.

    Parameters
    ----------
    df : pandas.DataFrame, optional
        A dataframe of strings of integer ngrams. If not passed, melodic
        ngrams of this type will be calculated at the value of `n`.
    n : int, optional (default 3)
        The ngram length to use when `df` is not passed. Ignored if `df`
        is passed.

    Returns
    -------
    pandas.DataFrame
        A square distance matrix indexed and columned by the unique ngram
        values found in `df`.

    Examples
    --------
    Call like this:

    ```python
    importedPiece.distance()
    ```

    If you don't pass a value for df, you can specify a different value
    for n to change from the default of 3:

    ```python
    importedPiece.distance(n=5)
    ```

    If you already have the melodic ngrams calculated for a different
    aspect of your query, you can pass that as df to save a little
    runtime on a large query. Note that if you pass something for df,
    the n parameter will be ignored:

    ```python
    mel = importedPiece.melodic('z', True, True)
    ngrams = importedPiece.ngrams(df=mel, n=4, exclude=['Rest'])
    importedPiece.distance(df=ngrams)
    ```

    To search the table for the distances from a given pattern, just get
    the column of that name. This example looks for distances involving a
    melodic pattern that goes up a step, down a third, up a step, down a
    third:

    ```python
    dist = importedPiece.distance(n=4)
    target = '1, -2, 1, -2'
    col = dist[target]
    ```

    If you then want to filter that column, say to distances less than or
    equal to 2, do this:

    ```python
    col[col <= 2]
    ```
    '''
    if df is None:
        df = self.melodic('z', True, True)
        df = self.ngrams(df=df, n=n, exclude=['Rest'])
    uni = df.stack().unique()
    ser = pd.Series(uni)
    df = pd.DataFrame.from_records(ser.apply(lambda cell: tuple(tuple_to_list(cell, cast=int))))
    cols = [(df - df.loc[i]).abs().apply(sum, axis=1) for i in df.index]
    dist = pd.concat(cols, axis=1, sort=True)
    dist.columns = uni
    dist.index = uni
    return dist

durationalRatios

durationalRatios(df=None, end=True)

Return durational ratios of each item in each column compared to the previous item in the same column. If a df is passed, it should be of float or integer values. If no df is passed, the default results from .durations will be used as input (durations of notes and rests).

The end parameter works the same as for .melodic(). It associates the durational ratios with the start of the first event rather than with the start of the second event.

Source code in crim_intervals/main_objs.py
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
def durationalRatios(self, df=None, end=True):
    '''
    Return durational ratios of each item in each column compared to the
    previous item in the same column. If a df is passed, it should be of
    float or integer values. If no df is passed, the default results from
    `.durations` will be used as input (durations of notes and rests).

    The `end` parameter works the same as for `.melodic()`. It associates the
    durational ratios with the start of the first event rather than with the
    start of the second event.
    '''
    cachable = False
    key = ('DurationalRatios', end)
    if df is None:
        cachable = True
        if key in self.analyses:
            return self.analyses['DurationalRatios']
        df = self.durations()
    res = df.apply(self._durationalRatioHelper, args=(end,)).dropna(how='all')
    if cachable:
        self.analyses['DurationalRatios'] = res
    return res

durations

durations(df=None, n=1, mask_df=None)

If no arguments are passed, return a pandas.DataFrame of floats giving the duration of notes and rests in each part:

  • 1 = quarternote,
  • 1.5 = a dotted quarter,
  • 4 = a whole note, etc.

If a df is passed, then return a df of the same shape giving the duration of each of the cells of this df.

This is useful if you want to know what the durations of something other than single notes and rests, such as the durations of intervals. E.g.:

har = importedPiece.harmonic()
harDur = importedPiece.durations(df=har)

The n parameter should be an integer greater than zero, or -1. When n is a positive integer, it groups together a sliding window of n consecutive non-NaN cells in each column.

If you pass a df, it will sum the durations 'Rest' and non-Rest cell, provided they are in the same n-sized window. For example, set n=3 if you wanted to get the durations of all 3-event-long pair-wise harmonic events:

har = importedPiece.harmonic()
dur_3 = importedPiece.durations(df=har, n=3)

Setting n to -1 sums the durations of all adjacent non-rest events, excluding NaNs. You could use this to find the durations of all melodies in a piece. Note that the results of piece.notes() will be used for thedf` parameter if none is provided:

dur = importedPiece.durations(n=-1)

You can also pass a mask_df, which will serve as a Boolean filter, only keeping values at the same indices (i.e. index and columns) as `mask_df. This is needed to get the durations of ngrams.

To get the durations of ngrams, pass the same value of n and the same dataframe you passed to piece.ngrams() as the n and df parameters, then pass your dataframe of ngrams as the mask_df. For example:

har = importedPiece.harmonic()
mel = importedPiece.melodic()
_n = 5
ngrams = importedPiece.ngrams(df=har, other=mel, n=_n)
ngramDurations = importedPiece.durations(df=har, n=_n, mask_df=ngrams)
Source code in crim_intervals/main_objs.py
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
def durations(self, df=None, n=1, mask_df=None):
    '''
    If no arguments are passed, return a `pandas.DataFrame` of floats giving
    the duration of notes and rests in each part:

     * 1 = quarternote,
     * 1.5 = a dotted quarter,
     * 4 = a whole note, etc.

    If a df is passed, then return a df of the same shape giving the duration 
    of each of the cells of this df.

    This is useful if you want to know what the durations of
    something other than single notes and rests, such as the durations of
    intervals. E.g.:

    ```python
    har = importedPiece.harmonic()
    harDur = importedPiece.durations(df=har)
    ```

    The `n` parameter should be an integer greater than zero, or -1. When
    n is a positive integer, it groups together a sliding window of n
    consecutive non-NaN cells in each column.

    If you pass a df, it will sum
    the durations 'Rest' and non-Rest cell, provided they are in the same
    n-sized window. For example, set `n=3` if you wanted to get the durations
    of all 3-event-long pair-wise harmonic events:

    ```python
    har = importedPiece.harmonic()
    dur_3 = importedPiece.durations(df=har, n=3)
    ```

    Setting n to -1 sums the durations of all adjacent non-rest events,
    excluding NaNs. You could use this to find the durations of all melodies
    in a piece. Note that the results of `piece.notes() will be used for the
    `df` parameter if none is provided:

    ```python
    dur = importedPiece.durations(n=-1)
    ```

    You can also pass a `mask_df`, which will serve as a Boolean filter, only
    keeping values at the same indices (i.e. index and columns) as `mask_df.
    This is needed to get the durations of ngrams.

    To get the durations of ngrams, pass the same value of n and the same
    dataframe you passed to `piece.ngrams()` as the `n` and `df` parameters,
    then pass your dataframe of ngrams as the `mask_df`. For example:

    ```python
    har = importedPiece.harmonic()
    mel = importedPiece.melodic()
    _n = 5
    ngrams = importedPiece.ngrams(df=har, other=mel, n=_n)
    ngramDurations = importedPiece.durations(df=har, n=_n, mask_df=ngrams)
    ```
    '''
    if 'Duration' in self.analyses and df is None and n == 1 and mask_df is None:
        return self.analyses['Duration']
    _df = self.notes().copy() if df is None else df.copy()
    highestTime = self.score.highestTime
    _df.loc[highestTime, :] = 'Rest'  # this is just a placeholder
    if n > 0:
        result = _df.apply(self._durationHelper, args=(n,))
        if df is None and n == 1 and mask_df is None:
            self.analyses['Duration'] = result
    else:  # n == -1
        result = _df.apply(self._maxnDurationHelper)
    result = result.astype('float64')
    result.index = result.index.astype('float64')
    if mask_df is not None:
        mask = mask_df.map(lambda cell: True, na_action='ignore')
        result = result[mask]
    return result.dropna(how='all')

emaAddresses

emaAddresses(df=None, mode='', combine_unisons=None)

Return a df that is the same shape as the passed df. Currently only works for 1D ngrams, like melodic ngrams. The mode parameter is detected automatically if it isn't passed.

The mode parameter can be set to 'melodic', 'cadences', 'cvfs', or 'homorhythm' to specify the type of EMA addresses to return. If mode is not specified, it will be inferred based on the structure of the input dataframe.

Example usage:
mel = piece.melodic()
ng = piece.ngrams(df=mel, n=4, offsets='both')
ema = piece.emaAddresses(df=ng, mode='melodic')
Source code in crim_intervals/main_objs.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def emaAddresses(self, df=None, mode='', combine_unisons=None):
    '''
    Return a df that is the same shape as the passed df. Currently only works for 1D ngrams,
    like melodic ngrams. The `mode` parameter is detected automatically if it isn't passed.

    The `mode` parameter can be set to 'melodic', 'cadences', 'cvfs', or 'homorhythm' to specify the type of EMA addresses to return. If `mode` is not specified, it will be inferred based on the structure of the input dataframe.

    Example usage:
    --------
    ```python
    mel = piece.melodic()
    ng = piece.ngrams(df=mel, n=4, offsets='both')
    ema = piece.emaAddresses(df=ng, mode='melodic')
    ```
    '''
    if isinstance(df, pd.DataFrame):
        ret = df.copy()
    if mode == 'melodic':
        newCols = []
        for i in range(len(ret.columns)):
            part = ret.iloc[:, i].dropna()
            notes = self.notes().loc[:, part.name].dropna()
            new_index = []
            for (_first, _last) in part.index:
                new_index.append((notes.loc[:_first].index[-2], _last))
            part.index = pd.MultiIndex.from_tuples(new_index, names=part.index.names)
            newCols.append(part)
        ret = pd.concat(newCols, axis=1, sort=True)
    elif mode.startswith('c'):  # cadences/cvfs mode
        ret = self.cvfs(keep_keys=True, offsets='both').copy()
        ngrams = ret.iloc[:, len(self._getPartNames()):]
        addresses = self.emaAddresses(df=ngrams, mode='')
        if isinstance(df, pd.DataFrame) and ('First' in df.index.names and 'Last' in df.index.names):
            return addresses
        else:
            uni = addresses.index.levels[-1].unique()
            ret = pd.Series(index=uni, name='EMA').astype(str)
            for un in uni:
                val = self.combineEmaAddresses(addresses.loc[(slice(None), un)].to_list())
                ret.at[un] = val
            return ret
    # hr mode--works with HR dataframe, adding ema address to each hr passage (= row).  
    # pass in output of hr = piece.homorhythm() as the df and set mode = 'hr'
    elif mode == 'homorhythm': # hr mode
        if isinstance(df, pd.DataFrame):
            hr = df.copy()
            ngram_length = int(hr.iloc[0]['ngram_length'])
            nr = self.notes()
            dur = self.durations(df = nr)
            ngrams = self.ngrams(df = dur, n = ngram_length, offsets = 'both', exclude=[])
            hr = hr.reset_index()
            hr['ema'] = hr.apply(lambda row: self._hr_helper(row, ngrams), axis=1)
            hr.set_index(['Measure', 'Beat', 'Offset'], inplace=True)
            return hr  
    # for ptypes output
    # pass in output of p_types = piece.presentationTypes() as the df and set mode = 'p_types'
    elif mode == 'p_types': # p_type mode
        if isinstance(df, pd.DataFrame):
            # print(df.columns)
            # p_types = df.copy()
            # ngram_length = 4
            ngram_length = len(df.iloc[0]['Soggetti'][0])
            nr = self.notes(combineUnisons = combine_unisons)
            mel = self.melodic(df = nr, end=False)
            ngrams = self.ngrams(df=mel, n=ngram_length)

            # now get the ema addresses for each row of p_types
            # note that we need to pass the mel, ngrams, durs and ngram length to the helper function
            # so that it can calculate the ema addresses for each row
            df['ema'] = df.apply(lambda row: self._ptype_ema_helper(row, mel, ngrams, ngram_length), axis=1)
            return df

    if isinstance(df, pd.DataFrame):
        if len(df) >= 1:
            idf = ret.index.to_frame()
            _measures = self.measures().iloc[:, 0]
            measures = idf.map(lambda i: _measures.loc[:i].iat[-1])
            _beats = self.beatIndex()
            beats = idf.map(lambda i: _beats[i])
            res = pd.concat([measures['First'], beats['First'], measures['Last'], beats['Last']], axis=1, sort=True)
            res.columns = ['First Measure', 'First Beat', 'Last Measure', 'Last Beat']
            ret = self.numberParts(ret)
            res = pd.concat([res, ret], axis=1, sort=True)
            res = res.apply(self._emaRowHelper, axis=1)
            res.name = 'EMA'
            return res

entries

entries(df=None, n=None, thematic=False, anywhere=False, fermatas=True, exclude=['Rest'])

Return a filtered copy of the passed df that only keeps the events in that df if they either start a piece or come after a silence. If the df parameter is left as None, it will be replaced with melodic interval results calculated after combining unisons and using diatonic intervals without interval quality, and with end=False since this is needed specifically for this use case.

When melodic intervals are calculated with end=False the offset of each melodic entry is the starting offset of the first note in the melody. If you want melodies 4 notes long, for example, note that this would be n=3, because four consecutive notes are constitute 3 melodic intervals. If the n parameter is not None, then the default melodic interval results or passed df argument will be replaced with n-long ngrams of those events. Note that this does not currently work for dataframes where the columns are combinations of voices, e.g. harmonic intervals.

If thematic is set to True, this method returns all instances of entries that happen at least twice anywhere in the piece. This means that a melody must happen at least once coming from a rest, and at least one more time, though the additional time doesn't have to be after a rest. If anywhere is set to True, the final results returned include all instances of entry melodies, whether they come from rests or not. If fermatas is set to True (default), any melody starting immediately after a fermata will also be counted as an entry. exclude is passed to ngrams() when n is given. It defaults to ['Rest'] (the same as ngrams()), so entry n-grams never contain a rest. Pass exclude=[] to keep n-grams that contain rests. It has no effect when n is None.

Source code in crim_intervals/main_objs.py
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
@_records_settings('entries', ('n', 'thematic', 'anywhere'))
def entries(self, df=None, n=None, thematic=False, anywhere=False, fermatas=True, exclude=['Rest']):
    """
    Return a filtered copy of the passed df that only keeps the events in
    that df if they either start a piece or come after a silence. If the df
    parameter is left as None, it will be replaced with melodic interval results
    calculated after combining unisons and using diatonic intervals without
    interval quality, and with end=False since this is needed specifically
    for this use case.

    When melodic intervals are calculated with `end=False` the offset of each
    melodic entry is the starting offset of the first note in the melody. If you
    want melodies 4 notes long, for example, note that this would be n=3,
    because four consecutive notes are constitute 3 melodic intervals.
    If the n parameter is not None, then the default melodic interval results
    or passed df argument will be replaced with n-long ngrams of those events.
    Note that this does not currently work for dataframes where the columns
    are combinations of voices, e.g. harmonic intervals.

    If `thematic` is set to `True`, this method returns all instances of entries
    that happen at least twice anywhere in the piece. This means
    that a melody must happen at least once coming from a rest, and at least
    one more time, though the additional time doesn't have to be after a rest.
    If `anywhere` is set to `True`, the final results returned include all
    instances of entry melodies, whether they come from rests or not.
    If `fermatas` is set to `True` (default), any melody starting immediately
    after a fermata will also be counted as an entry.
    `exclude` is passed to `ngrams()` when `n` is given. It defaults to
    `['Rest']` (the same as `ngrams()`), so entry n-grams never contain a
    rest. Pass `exclude=[]` to keep n-grams that contain rests. It has no
    effect when `n` is None.
    """
    if df is None:
        nr = self.notes(combineUnisons=True)
        df = self.melodic(df=nr, kind='d', end=False)
    if n is not None:
        df = self.ngrams(df, n, exclude=exclude)
    mask = self.entryMask(fermatas)
    num_parts = len(mask.columns)
    mask.columns = df.columns[:num_parts]
    entries = df.copy()
    entries.iloc[:, :num_parts] = entries.iloc[:, :num_parts][mask]
    source = entries.copy()
    if anywhere:
        ret = df[df.isin(entries.stack().values)].copy()
    else:
        ret = entries.copy()
    if thematic:
        stack = ret.iloc[:, :num_parts].stack()
        counts = stack.value_counts()
        recurring = counts[counts > 1].index
        # recurring_entries = recurring[recurring.isin(ret.stack())]
        ret = ret[ret.isin(recurring)]
    ret.dropna(how='all', subset=ret.columns[:num_parts], inplace=True)
    return ret

entryMask

entryMask(fermatas=True)

Return a dataframe of True, False, or NaN values which can be used as a mask (filter). When applied to another dataframe, only the True cells in the mask will be kept.

Examples:

piece = importScore('path_to_piece')
mask = piece.entryMask()
df = piece.notes()
df[mask].dropna(how='all')

If fermatas is set to True (default), anything coming immediately after a fermata will also be counted as an entry.

Source code in crim_intervals/main_objs.py
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
def entryMask(self, fermatas=True):
    """
    Return a dataframe of `True`, `False`, or NaN values which can be used as
    a mask (filter). When applied to another dataframe, only the True cells
    in the mask will be kept.

    Examples
    --------
    ```python
    piece = importScore('path_to_piece')
    mask = piece.entryMask()
    df = piece.notes()
    df[mask].dropna(how='all')
    ```

    If fermatas is set to True (default), anything coming immediately after
    a fermata will also be counted as an entry.
    """
    key = ('EntryMask', fermatas)
    if key not in self.analyses:
        nr = self.notes()
        self.analyses[key] = nr.apply(self._entryHelper, args=(fermatas,))
    return self.analyses[key]

fermatas

fermatas()

Get all the fermatas in a piece. A fermata is designated by a True value.

Source code in crim_intervals/main_objs.py
567
568
569
570
571
572
573
574
575
def fermatas(self):
    '''
    Get all the fermatas in a piece. A fermata is designated by a `True` value.
    '''
    if 'Fermatas' not in self.analyses:
        df = self._m21Expressions().map(
            lambda exps: any(isinstance(exp, expressions.Fermata) for exp in exps), na_action='ignore')
        self.analyses['Fermatas'] = df
    return self.analyses['Fermatas']

final

final()

Return the final of the piece, defined as the lowest sounding note at the end of the piece.

Source code in crim_intervals/main_objs.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def final(self):
    '''
    Return the final of the piece, defined as the lowest sounding note at
    the end of the piece.'''
    if 'Final' not in self.analyses:
        lowLine = self.lowLine()
        if len(lowLine.index):
            final = lowLine.iat[-1]
        else:
            final = None
        if final == 'Rest' and len(lowLine.index) > 1:
            final = lowLine.iat[-2]
        self.analyses['Final'] = final
    return self.analyses['Final']

flexed_distance

flexed_distance(head_flex, df=None, n=3)

Return the distances between all the values in df which should be a dataframe of strings of integer ngrams. Specifically, this is meant for 0-indexed, directed, and compound melodic ngrams. If nothing is passed for df, melodic ngrams of this type will be provided at the value of n passed. An alternative that would make sense would be to use chromatic melodic intervals instead.

This function differs from "distance" in that it treats the first item in each ngram differently from the others. That is, the first item can "flex" differently from the remainder. Thus users can choose an overall body_flex of "0" while still allowing flexing only at the head of the ngram.

The default flex is up to "1" unit of difference, but passing the "head_flex" argument allows users to set their own threshold.

This function is meant mainly for melodic ngrams, but it can also be used for durational ngrams.

Parameters:

Name Type Description Default
head_flex int

The threshold of difference allowed for the first item in each ngram.

required
df DataFrame

A dataframe of strings of integer ngrams. If not passed, melodic ngrams of this type will be calculated at the value of n.

None
n int, optional (default 3)

The ngram length to use when df is not passed. Ignored if df is passed.

3

Returns:

Type Description
DataFrame

A square distance matrix indexed and columned by the unique ngram values found in df, using the flexed head comparison.

Examples:

Call like this:

importedPiece.flexed_distance()

If you don't pass a value for df, you can specify a different value for n to change from the default of 3:

importedPiece.flexed_distance(n=5)

If you already have the melodic ngrams calculated for a different aspect of your query, you can pass that as df to save a little runtime on a large query. Note that if you pass something for df, the n parameter will be ignored:

mel = importedPiece.melodic('z', True, True)
ngrams = importedPiece.ngrams(df=mel, n=4, exclude=['Rest'])
importedPiece.flexed_distance(df=ngrams)

To search the table for the distances from a given pattern, just get the column of that name. This example looks for distances involving a melodic pattern that goes up a step, down a third, up a step, down a third:

dist = importedPiece.flexed_distance(n=4)
target = '1, -2, 1, -2'
col = dist[target]

If you then want to filter that column, say to flexed distances less than or equal to 2, do this:

col[col <= 2]
Source code in crim_intervals/main_objs.py
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
def flexed_distance(self, head_flex, df=None, n=3):
      '''
      Return the distances between all the values in df which should be a
      dataframe of strings of integer ngrams. Specifically, this is meant for
      0-indexed, directed, and compound melodic ngrams. If nothing is passed
      for df, melodic ngrams of this type will be provided at the value of n
      passed. An alternative that would make sense would be to use chromatic
      melodic intervals instead.

      This function differs from "distance" in that it treats the first item in
      each ngram differently from the others. That is, the first item can "flex"
      differently from the remainder. Thus users can choose an overall body_flex
      of "0" while still allowing flexing only at the head of the ngram.

      The default flex is up to "1" unit of difference, but passing the "head_flex"
      argument allows users to set their own threshold.

      This function is meant mainly for melodic ngrams, but it can also be used
      for durational ngrams.

      Parameters
      ----------
      head_flex : int
          The threshold of difference allowed for the first item in each
          ngram.
      df : pandas.DataFrame, optional
          A dataframe of strings of integer ngrams. If not passed, melodic
          ngrams of this type will be calculated at the value of `n`.
      n : int, optional (default 3)
          The ngram length to use when `df` is not passed. Ignored if `df`
          is passed.

      Returns
      -------
      pandas.DataFrame
          A square distance matrix indexed and columned by the unique ngram
          values found in `df`, using the flexed head comparison.

      Examples
      --------
      Call like this:

      ```python
      importedPiece.flexed_distance()
      ```

      If you don't pass a value for df, you can specify a different value
      for n to change from the default of 3:

      ```python
      importedPiece.flexed_distance(n=5)
      ```

      If you already have the melodic ngrams calculated for a different
      aspect of your query, you can pass that as df to save a little
      runtime on a large query. Note that if you pass something for df,
      the n parameter will be ignored:

      ```python
      mel = importedPiece.melodic('z', True, True)
      ngrams = importedPiece.ngrams(df=mel, n=4, exclude=['Rest'])
      importedPiece.flexed_distance(df=ngrams)
      ```

      To search the table for the distances from a given pattern, just get
      the column of that name. This example looks for distances involving a
      melodic pattern that goes up a step, down a third, up a step, down a
      third:

      ```python
      dist = importedPiece.flexed_distance(n=4)
      target = '1, -2, 1, -2'
      col = dist[target]
      ```

      If you then want to filter that column, say to flexed distances less
      than or equal to 2, do this:

      ```python
      col[col <= 2]
      ```
      '''
      if df is None:
          df = self.melodic('z', True, True)
          df = self.ngrams(df=df, n=n, exclude=['Rest'])
      uni = df.stack().unique()
      ser = pd.Series(uni)
      df = pd.DataFrame.from_records(ser.apply(lambda cell: tuple(tuple_to_list(cell, cast=int))))
      cols = [(df - df.loc[i]).abs().apply(self._flexed_sum, axis=1, args=(head_flex,)) for i in df.index]
      dist = pd.concat(cols, axis=1, sort=True)
      dist.columns = uni
      dist.index = uni
      return dist

graphIntervalFamilies

graphIntervalFamilies(length=4, combineUnisons=True, kind='d', end=False, variableLength=False, suggestedPattern=None, useEntries=True, arriveAt=None, includeLegend=False)

It is possible to select:

length=4
combineUnisons=True
kind="d"
end=False
variableLength=False
suggestedPattern=None
useEntries=True

Examples:

Graphing the Interval Families with length=4 and useEntries=True by default:

graphIntervalFamilies()

Another useful option is variableLength=True, therefore including all unique patterns up to the specified length:

graphIntervalFamilies(length=4, variableLength=True)

We can narrow down patterns of interested by specifying suggestedPattern=Tuple(Str*), for example looking for all patterns that start with -2, -2:

graphIntervalFamilies(length=4, variableLength=True, suggestedPattern=("4", "2"))
Source code in crim_intervals/main_objs.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def graphIntervalFamilies(self, length=4, combineUnisons=True, kind="d", end=False, variableLength=False, suggestedPattern=None, useEntries=True, arriveAt=None, includeLegend=False):

    '''
    It is possible to select:

    ```python
    length=4
    combineUnisons=True
    kind="d"
    end=False
    variableLength=False
    suggestedPattern=None
    useEntries=True
    ```

    Examples
    --------
    Graphing the Interval Families with `length=4` and `useEntries=True` by default:

    ```python
    graphIntervalFamilies()
    ```

    Another useful option is `variableLength=True`, therefore including **all unique patterns up to the specified length**:

    ```python
    graphIntervalFamilies(length=4, variableLength=True)
    ```

    We can narrow down patterns of interested by specifying `suggestedPattern=Tuple(Str*)`, for example looking for **all patterns that start with `-2, -2`**:

    ```python
    graphIntervalFamilies(length=4, variableLength=True, suggestedPattern=("4", "2"))
    ```
    '''
    # runs sns plot layout
    self._plot_default()

    local_ngrams = pd.DataFrame(columns=self.notes().columns)

    if length < 1:
        print("Please use length >= 1")
        return None

    if kind not in ["d", "z", "c"]:
        print("\n Warning: you might encounter an error due to using an uncommon interval kind. \n Currently, we have been working with \"z\", \"d\", and \"c\"")

    if variableLength:
        loop_start = 1
    else:
        loop_start = length

    for i in range(loop_start, length + 1):
        loop_notes = self.notes(combineUnisons=True)
        loop_melodic = self.melodic(df=loop_notes, kind=kind, end=end)
        if useEntries:
            loop_ngrams = self.entries(df=loop_melodic, n=int(i), exclude=["Rest"]).fillna('')
        else:
            loop_ngrams = self.ngrams(df=loop_melodic, exclude=["Rest"], n=int(i)).fillna('')
        local_ngrams = pd.concat([local_ngrams, loop_ngrams], sort=True)

    total_unique_ngrams_list = list(filter(lambda x: x != "", list(set(local_ngrams.values.flatten().tolist()))))

    if suggestedPattern:
        matching_unique_ngrams_list = list(map(lambda x: x if ",".join(x).startswith(",".join(suggestedPattern)) else "", total_unique_ngrams_list))
        total_unique_ngrams_list = list(filter(lambda x: x != "", matching_unique_ngrams_list))
        if len(total_unique_ngrams_list) < 1:
            print("No patterns matching the suggestedPattern found")
            return None

    graph_pattern_list = self._createGraphList(total_unique_ngrams_list)

    if arriveAt != None:
        graph_pattern_list = list(filter(lambda x: x[-1] == arriveAt, graph_pattern_list))
        if len(graph_pattern_list) < 1:
            print("No patterns arriving at arriveAt found")
            return None

    for pattern in graph_pattern_list:
        plt.plot(pattern, alpha=0.35, lw=6)
    plt.yticks(np.arange(min(list(map(lambda x: sorted(x)[0], graph_pattern_list))) - 1, max(list(map(lambda x: sorted(x)[-1], graph_pattern_list))) + 1, 1.0))
    plt.xticks(np.arange(0, max(list(map(lambda x: len(x), graph_pattern_list))), 1.0))
    if includeLegend:
        plt.title("Total Number of Patterns: " + str(len(graph_pattern_list)) + "\n Piece Name: " + self.metadata["title"])
    plt.show()

harmonic

harmonic(kind='q', directed=True, compound=True, againstLow=False, df=None)

Return harmonic intervals for all voice pairs.

The voice pairs are named 'from the bottom up':
the first voice in the pair is lower in the score than the second voice in the pair. The two voices separated with an underscore, e.g. "Bassus_Tenor". If againstLow is True, intervals will be measured against the lowest sounding note in the entire score (and not simply relative to the lower voice of the given pair).

Parameters:

Name Type Description Default
kind str, optional (default 'q')

Use "q" (default) for diatonic intervals with quality, "d" for diatonic intervals without quality, "z" for zero-indexed diatonic intervals without quality (i.e. unison = 0, second = 1, etc.), or "c" for chromatic intervals. Only the first character is used, and it's case insensitive.

'q'
directed bool, optional (default True)

Defaults to True which shows that the voice that is lower on the staff is a higher pitch than the voice that is higher on the staff. This is designated with a "-" prefix.

True
compound bool, optional (default True)

Whether to use compound (True, default) or simple (False) intervals. In the case of simple diatonic intervals, it simplifies to within the octave, so octaves don't get simplified to unisons. But for semitonal intervals, an interval of an octave (12 semitones) does get simplified to a unison (0 semitones).

True
againstLow bool, optional (default False)

If False (default) harmonic intervals between all pairs of voices will be returned. If True harmonic intervals of each voice against the lowest sounding note at each moment is returned.

False
df DataFrame

None (default) is the standard behavior. Pass a df of note and rest strings or music21 objects to calculate the harmonic intervals in any dataframe.

None

Returns:

Type Description
DataFrame

Harmonic intervals in each pair in the format specified by the kind, directed, and compound parameters.

Source code in crim_intervals/main_objs.py
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
@_records_settings('harmonic', ('kind', 'directed', 'compound', 'againstLow'))
def harmonic(self, kind='q', directed=True, compound=True, againstLow=False, df=None):
    '''
    Return harmonic intervals for all voice pairs.

    The voice pairs are named 'from the bottom up':  
    the first voice in the pair is lower in the score than the second voice in the pair.
    The two voices separated with an underscore, e.g. "Bassus_Tenor". If `againstLow`
    is `True`, intervals will be measured against the lowest sounding note in the entire score 
    (and not simply relative to the lower voice of the given pair).

    Parameters
    ----------
    kind : str, optional (default 'q')
        Use "q" (default) for diatonic intervals with quality, "d" for
        diatonic intervals without quality, "z" for zero-indexed diatonic
        intervals without quality (i.e. unison = 0, second = 1, etc.), or
        "c" for chromatic intervals. Only the first character is used,
        and it's case insensitive.
    directed : bool, optional (default True)
        Defaults to True which shows that the voice that is lower on the
        staff is a higher pitch than the voice that is higher on the
        staff. This is designated with a "-" prefix.
    compound : bool, optional (default True)
        Whether to use compound (True, default) or simple (False)
        intervals. In the case of simple diatonic intervals, it
        simplifies to within the octave, so octaves don't get simplified
        to unisons. But for semitonal intervals, an interval of an octave
        (12 semitones) does get simplified to a unison (0 semitones).
    againstLow : bool, optional (default False)
        If False (default) harmonic intervals between all pairs of
        voices will be returned. If True harmonic intervals of each
        voice against the lowest sounding note at each moment is
        returned.
    df : pandas.DataFrame, optional
        None (default) is the standard behavior. Pass a df of note and
        rest strings or music21 objects to calculate the harmonic
        intervals in any dataframe.

    Returns
    -------
    pandas.DataFrame
        Harmonic intervals in each pair in the format specified by the
        `kind`, `directed`, and `compound` parameters.
    '''
    kind = kind[0].lower()
    kind = {'s': 'c'}.get(kind, kind)
    _kind = {'z': 'd'}.get(kind, kind)
    settings = (_kind, directed, compound)
    key = ('HarmonicIntervals', kind, directed, compound, againstLow)

    # Fixed logic: when df is provided OR key not in cache, compute intervals
    if df is not None or key not in self.analyses:
        _df = self._getM21HarmonicIntervals(againstLow, df)
        _df = _df.map(self._intervalMethods[settings], na_action='ignore')
        if kind == 'z':
            _df = _df.map(ImportedPiece._zeroIndexIntervals, na_action='ignore')
        _df = _df.sort_index()

        # Fixed caching logic: only cache when df is None (standard behavior)
        if df is not None:
            return _df  # Return computed result for custom df without caching
        else:
            self.analyses[key] = _df  # Cache result for standard behavior

    return self.analyses[key]

highLine

highLine()

Return a series that corresponds to the highest sounding note of the piece at any given moment. Attack information cannot be reliably preserved so consecutive repeated notes and rests are combined. If all parts have a rest, then "Rest" is shown for that stretch of the piece.

Source code in crim_intervals/main_objs.py
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def highLine(self):
    '''
    Return a series that corresponds to the highest sounding note of the piece at
    any given moment. Attack information cannot be reliably preserved so
    consecutive repeated notes and rests are combined. If all parts have a rest,
    then "Rest" is shown for that stretch of the piece.'''
    if 'HighLine' not in self.analyses:
        # use m21 objects so that you can do comparison with min
        notes = self._getM21ObjsNoTies()
        # you can't compare notes and rests, so replace rests with a really high note
        lowNote = note.Note('C', octave=-9)
        notes = notes.map(lambda n: lowNote if n.isRest else n, na_action='ignore')
        notes.ffill(inplace=True)
        highLine = notes.apply(max, axis=1)
        highLine = highLine.apply(lambda n: n.nameWithOctave)
        highLine.replace('C-9', 'Rest', inplace=True)
        highLine.name = 'High Line'
        self.analyses['HighLine'] = highLine[highLine != highLine.shift()]
    return self.analyses['HighLine']

homorhythm

homorhythm(ngram_length=4, full_hr=True)

This function predicts homorhythmic passages in a given piece. The method follows various stages:

Gets durational ngrams, and finds passages in which these are the same in two or more voices at a given offsets; Gets syllables at every offset, and identifies passages where two or more voices are singing the same lyrics_hr; Checks the number of active voices (thus eliminating places where some voices have rests).

Users can supply either of two arguments:

'ngram_length' (which is 4 by default, and determines the number of durations and syllables that must be in common among the voices in order to be marked as HR);

'full_hr' (which is True default). When full_hr=True the method will find any passage where all active voices share the same durational ngram and syllables; if full_hr=False the method will find any passage where even two voices share the same durational ngram and the same syllables.

Examples:

piece.homorhythm()
piece.homorhythm(ngram_length=4, full_hr=True)

Also see verovioHomorhythm() for a function that prints results.

Source code in crim_intervals/main_objs.py
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
def homorhythm(self, ngram_length=4, full_hr=True):
    """
    This function predicts homorhythmic passages in a given piece.
    The method follows various stages:

    Gets durational ngrams, and finds passages in which these are the same in two or more voices at a given offsets;
    Gets syllables at every offset, and identifies passages where two or more voices are singing the same lyrics_hr;
    Checks the number of active voices (thus eliminating places where some voices have rests).

    Users can supply either of two arguments:

    'ngram_length' (which is 4 by default, and determines the number of durations and syllables that must be in common among the voices in order to be marked as HR);

    'full_hr' (which is True default).  When `full_hr=True` the method will find any passage where _all active voices_ share the same durational ngram and syllables; if `full_hr=False` the method will find any passage where even _two voices_ share the same durational ngram and the same syllables.

    Examples
    --------
    ```python
    piece.homorhythm()
    piece.homorhythm(ngram_length=4, full_hr=True)
    ```

    Also see verovioHomorhythm() for a function that prints results.


    """
    # active version with lyric ngs
    nr = self.notes()
    dur = self.durations(df=nr)

    # add ng = exclude=[] to arguments in ngrams
    # specify ngram length with arguments
    ng = self.ngrams(df=dur, n=ngram_length, exclude=[])
    dur_ngrams = []
    for index, rows in ng.iterrows():
        dur_ngrams_no_nan = [x for x in rows if pd.isnull(x) == False]
        dur_ngrams.append(dur_ngrams_no_nan)
    ng['dur_ngrams'] = dur_ngrams
    ng['active_voices'] = ng['dur_ngrams'].apply(len)
    ng['number_dur_ngrams'] = ng['dur_ngrams'].apply(lambda lyst: len(set(lyst)))

    # from JS to check full_hr or partial
    if full_hr == True:
        ng = ng[(ng['number_dur_ngrams'] < 2) & (ng['active_voices'] > 1)]
    else:
        ng = ng[ng['number_dur_ngrams'] < ng['active_voices']]

    #find involved voices

    hr_voices = []
    for index, rows in ng. iterrows():
        seen = set()
        hr_ngrams = []
        for x in rows['dur_ngrams']:
            if x in seen and not x in hr_ngrams:
                hr_ngrams.append(x)
            else:
                seen.add(x)
        hr_v = []
        for index, value in rows.items():
            if value in hr_ngrams:
                hr_v.append(index)
        hr_voices.append(hr_v)

    ng['hr_voices'] = hr_voices

    # get the lyrics as ngrams to match the durations
    lyrics = self.lyrics()
    lyrics = lyrics.map(self._alpha_only)

    # specify ngram length with arguments
    lyrics_ng = self.ngrams(df=lyrics, n=ngram_length)

    # filter lyric ng's according to what we already know about durations:
    ng_list = ng.index.to_list()
    filtered_lyric_ngs = lyrics_ng.filter(items = ng_list, axis=0)

    # count the lyric_ngrams at each position
    syll_set = []
    for index, rows in filtered_lyric_ngs.iterrows():
        syll_no_nan = [z for z in rows if pd.isnull(z) == False]
        syll_set.append(syll_no_nan)
    filtered_lyric_ngs['syllable_set'] = syll_set
    filtered_lyric_ngs["count_lyr_ngrams"] = filtered_lyric_ngs["syllable_set"].apply(lambda lyst: len(set(lyst)))

    # and the number of active voices
    filtered_lyric_ngs['active_syll_voices'] = filtered_lyric_ngs['syllable_set'].apply(len)
    if full_hr == True:
        hr_sylls_mask = filtered_lyric_ngs[(filtered_lyric_ngs['active_syll_voices'] > 1) & (filtered_lyric_ngs['count_lyr_ngrams'] < 2)]
    else:
        hr_sylls_mask = filtered_lyric_ngs[filtered_lyric_ngs['active_syll_voices'] > filtered_lyric_ngs['count_lyr_ngrams']]

    # combine of both dur_ng and lyric_ng to show passages where more than 2 voices have the same syllables and durations
    ng = ng[['active_voices', 'number_dur_ngrams', 'hr_voices']]
    hr = pd.merge(ng, hr_sylls_mask, left_index=True, right_index=True)
    # the intersection of coordinated durations and coordinate lyrics
    hr['voice_match'] = hr['active_voices'] == hr['active_syll_voices']
    # retain ngram length for use with ema
    hr['ngram_length'] = int(ngram_length)
    result = self.detailIndex(hr, offset=True)
    result["Progress"] = (result.index.get_level_values(2) / self.notes().index[-1])

    if len(result) == 0:
        print ("No HR passages found in " + self.metadata['composer'] + ":" + self.metadata['title'])
    else:



        return result

ic

ic(module, generic=False, df=None)

Invertible Counterpoint and Double Counterpoint Finder.

This method takes a string of a module and finds all the instances of that module at any level of inversion. The module is an interval succession in the format of what you get from the .ngrams()method. Specifically, you would need to show melodic motion of both voices, which you can do by running the .ngrams()method with these parameters: exclude=[], show_both=True, held=1, interval_settings('d', True, True)

In this method, Invertible Counterpoint is where we have a repetition of the given module but where the upper and lower melodies have been exchanged. Double Counterpoint is when the module repeats and the melody of each part is the same as before, but the harmonic intervals are all off by a given amount. This is like Invertible Counterpoint, but the parts have not actually crossed.

Examples:

piece.ic('7_1:-2, 6_-2:2, 8')

Notice that the intervals used must be diatonic and without quality.

The generic setting changes the output from the different interval successions observed that are at some level of invertible counterpoint from the passed module, to a generic form where the level of invertible counterpoint is given. This is particularly useful if you want to compare how invertible counterpoint is used as a technique among different pieces.

Source code in crim_intervals/main_objs.py
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
def ic(self, module, generic=False, df=None):
    '''
    Invertible Counterpoint and Double Counterpoint Finder. 

    This method takes a string of a module and finds all the instances of
    that module at any level of inversion. The module is an interval
    succession in the format of what you get from the `.ngrams()`method.
    Specifically, you would need to show melodic motion of both voices,
    which you can do by running the `.ngrams()`method with these
    parameters: `exclude=[], show_both=True, held=1, interval_settings('d', True, True)`

    In this method, Invertible Counterpoint is where we have a repetition of
    the given module but where the upper and lower melodies have been exchanged.
    Double Counterpoint is when the module repeats and the melody of each
    part is the same as before, but the harmonic intervals are all off by a
    given amount. This is like Invertible Counterpoint, but the parts have
    not actually crossed.

    Examples
    --------
    ```python
    piece.ic('7_1:-2, 6_-2:2, 8')
    ```

    Notice that the intervals used must be diatonic and without quality.

    The `generic` setting changes the output from the different interval
    successions observed that are at some level of invertible counterpoint
    from the passed module, to a generic form where the level of invertible
    counterpoint is given. This is particularly useful if you want to
    compare how invertible counterpoint is used as a technique among
    different pieces.
    '''
    har_regex = '[^_]*'
    target1, target2 = [], []
    chunks = module.split(', ')
    for chunk in chunks:
        if '_' not in chunk:
            target1.append(har_regex)
            target2.append(har_regex)
            break
        temp = re.split('_|:', chunk)
        mel1 = temp[1]
        mel2 = temp[2]
        target1.append('{}_{}:{}'.format(har_regex, mel1, mel2))
        target2.append('{}_{}:{}'.format(har_regex, mel2, mel1))
    target1 = ', '.join(target1)
    target2 = ', '.join(target2)
    _n = 1 + module.count(',')
    if df is None:
        ngrams = self.ngrams(n=_n, held='1', exclude=[], show_both=True)
    else:
        ngrams = df.copy()
    mask1 = ngrams.apply(lambda row: row.str.contains(target1, regex=True))
    mask2 = ngrams.apply(lambda row: row.str.contains(target2, regex=True))
    if not generic:
        return ngrams[(mask1 | mask2)].dropna(how='all')
    else:
        reference_int = int(module.rsplit(' ', 1)[-1])
        prefix = 'DBL'
        def _icHelper(repetition):
            '''
            Helper function to calculate the level of invertible counterpoint at which
            a repetition is found. This only gets used when the `generic` setting of
            .ic() is set to True.
            '''
            last_har_int = int(repetition.rsplit(' ', 1)[-1])
            if (module == repetition) or (reference_int % 7 == last_har_int % 7 and reference_int > 0 and last_har_int > 0):
                return 'Repeat'
            if prefix == 'DBL':
                val = last_har_int - reference_int
                if val > 0:
                    val += 1
                else:
                    val -= 1
            elif ((last_har_int > 0 and reference_int > 0) or (last_har_int + reference_int < 0)):
                val = last_har_int + reference_int - 1
            else:
                val = last_har_int + reference_int + 1
            return '{}@{}'.format(prefix, val)
        res1 = ngrams[mask1].dropna(how='all').map(_icHelper, na_action='ignore')
        prefix = 'IC'
        res2 = ngrams[mask2].dropna(how='all').map(_icHelper, na_action='ignore')
        res1.update(res2)
        return res1

keySignatures

keySignatures()

Return a data frame containing the key signatures and their offsets.

This is useful for getting the prevailing system key signature (i.e. the sharps/flats printed at the start of each staff) at any given moment in the piece. Following music21's .sharps convention, the value is a positive integer for the number of sharps, a negative integer for the number of flats, and 0 for no accidentals in the key signature.

Source code in crim_intervals/main_objs.py
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
def keySignatures(self):
    """
    Return a data frame containing the key signatures and their offsets.

    This is useful for getting the prevailing system key signature (i.e.
    the sharps/flats printed at the start of each staff) at any given
    moment in the piece. Following music21's `.sharps` convention, the value
    is a positive integer for the number of sharps, a negative integer for
    the number of flats, and 0 for no accidentals in the key signature.
    """
    if 'KeySignature' not in self.analyses:
        df = self._getM21KeySigObjs()
        df = df.map(lambda ks: ks.sharps, na_action='ignore')
        df.columns = self._getPartNames()
        self.analyses['KeySignature'] = df
    return self.analyses['KeySignature']

linkExamples

linkExamples(df, piece_url='', mode='', combine_unisons=None)

Given a dataframe of EMA addresses, return a dataframe of clickable links to the EMA React app. The piece_url parameter is the URL of the piece on the EMA React app. If you don't pass a piece_url, the method will try to construct one based on the piece's metadata. The resulting dataframe will have the same data results, but instead of plain text they will be links to highlighted examples of each result.

Learn more about the EMA React Application at https://github.com/RichardFreedman/ema_react_app.

The mode parameter can be set to 'melodic', 'cadences', 'p_types', or 'homorhythm' to specify the type of EMA addresses to return. If mode is not specified, it will be inferred based on the structure of the input dataframe.

Source code in crim_intervals/main_objs.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
def linkExamples(self, df, piece_url='', mode='', combine_unisons=None):
    '''
    Given a dataframe of EMA addresses, return a dataframe of clickable
    links to the EMA React app. The `piece_url` parameter is the URL of the
    piece on the EMA React app. If you don't pass a `piece_url`, the method
    will try to construct one based on the piece's metadata. The resulting
    dataframe will have the same data results, but instead of plain text
    they will be links to highlighted examples of each result.

    Learn more about the EMA React Application at https://github.com/RichardFreedman/ema_react_app.

    The `mode` parameter can be set to 'melodic', 'cadences', 'p_types', or 'homorhythm' to specify the type of EMA addresses to return. If `mode` is not specified, it will be inferred based on the structure of the input dataframe.
    '''
    if piece_url == '':
        if self.path.startswith('https://'):
            piece_url = self.path
        else:
            print('No piece URL was passed and the piece was not downloaded from a public respository. Please provide a piece_url.')
            return

    # Initialize variables
    data_col_name = None
    ema = None

    # Detect mode if not passed, or validate if passed
    if mode != '':
        mode = mode.lower()
    else:   # detect mode if it is not passed
        if 'hr_voices' in df.columns:
            mode = 'homorhythm'
        elif 'Presentation_Type' in df.columns:
            mode = 'p_types'
        elif 'CVFs' in df.columns:
            mode = 'cadences'
        elif all(self._getPartNames() == df.columns):
            if any(char in df.values for char in 'CAyca'):
                print('Running on cadences which have the same ema addresses as cvfs...')
                return self.linkExamples(self.cadences(), piece_url)
            else:
                mode = 'melodic'
        else:
            raise ValueError(f"Cannot detect mode from DataFrame columns: {df.columns.tolist()}")

    # Set data column name and generate EMA addresses based on mode
    if mode == 'p_types':
        data_col_name = 'Presentation_Type'
        ema = pd.DataFrame(self.emaAddresses(df, mode=mode, combine_unisons=combine_unisons)['ema'])

    elif mode == 'homorhythm':
        data_col_name = 'hr_voices'
        ema = pd.DataFrame(self.emaAddresses(df, mode=mode)['ema'])
    elif mode == 'cadences':
        data_col_name = 'CadType'
        ema = pd.DataFrame(self.emaAddresses(df, mode=mode))
    elif mode == 'melodic':
        # Melodic mode is handled separately below - no need to initialize ema
        pass
    else:
        # Handle unknown modes
        raise ValueError(f"Unsupported mode: {mode}")

    # Format string for creating HTML links
    fmt = '<a href="{}&{}" rel="noopener noreferrer" target="_blank">{}</a>'

    if mode == 'melodic':
        res = []
        # this loop is needed because the "last" offset of df is the beginning
        # of its last event, whereas in temp it's the beginning of the next event
        for col in range(len(df.columns)):
            col_urls = pd.DataFrame(self.emaAddresses(df.take([col], axis=1), mode=mode).dropna())
            col_urls = col_urls.map(ImportedPiece._constructColumnwiseUrl, na_action='ignore', piece_url=piece_url)
            col_data = df.iloc[:, col].dropna()
            links = [] if col_data.empty else [fmt.format(url,
                urllib.parse.urlencode({'observation': f' {col_data.iat[ii]}'}),
                col_data.iat[ii])
                for ii, url in enumerate(col_urls['EMA'])]
            col_links = pd.Series(links, name=col_data.name, index=col_data.index)   # use df's index vals
            res.append(col_links)
        res = pd.concat(res, axis=1, sort=True)
    else:
        col_urls = ema.map(lambda cell: ImportedPiece._constructColumnwiseUrl(cell, piece_url), na_action='ignore')
        col_data = df.loc[:, data_col_name]
        links = [fmt.format(col_urls.iat[col_urls.index.get_loc(ndx), 0],
            urllib.parse.urlencode({'observation': f' {col_data.at[ndx]}'}),
            col_data.at[ndx])
            if isinstance(col_data.at[ndx], (str, list)) else np.nan for ndx in col_data.index]
        res = df.copy()
        res[data_col_name] = links
        if 'ema' in res.columns:
            res.drop(columns='ema', inplace=True)

    display(HTML(res.to_html(render_links=True, escape=False)))

lowLine

lowLine()

Return a series that corresponds to the lowest sounding note of the piece at any given moment. Attack information cannot be reliably preserved so consecutive repeated notes and rests are combined. If all parts have a rest, then "Rest" is shown for that stretch of the piece.

Source code in crim_intervals/main_objs.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def lowLine(self):
    '''
    Return a series that corresponds to the lowest sounding note of the piece at
    any given moment. Attack information cannot be reliably preserved so
    consecutive repeated notes and rests are combined. If all parts have a rest,
    then "Rest" is shown for that stretch of the piece.'''
    if 'LowLine' not in self.analyses:
        # use m21 objects so that you can do comparison with min
        notes = self._getM21ObjsNoTies()
        # you can't compare notes and rests, so replace rests with a really high note
        highNote = note.Note('C9')
        notes = notes.map(lambda n: highNote if n.isRest else n, na_action='ignore')
        notes.ffill(inplace=True)
        lowLine = notes.apply(min, axis=1)
        lowLine = lowLine.apply(lambda n: n.nameWithOctave)
        lowLine.replace('C9', 'Rest', inplace=True)
        lowLine.name = 'Low Line'
        self.analyses['LowLine'] = lowLine[lowLine != lowLine.shift()]
    return self.analyses['LowLine']

lyrics

lyrics(strip=True)

Return a dataframe of the lyrics associated with each note in the piece. If strip is True (default), then the lyrics will be stripped of leading and trailing whitespace and dashes. If strip is False, then the lyrics will be returned as they are in the score. Notes without lyrics are shown as NaN.

Source code in crim_intervals/main_objs.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def lyrics(self, strip=True):
    '''
    Return a dataframe of the lyrics associated with each note in the piece.
    If `strip` is `True` (default), then the lyrics will be stripped of leading
    and trailing whitespace and dashes. If `strip` is `False`, then the lyrics will
    be returned as they are in the score. Notes without lyrics are shown as NaN.
    '''
    key = ('Lyrics', strip)
    if key not in self.analyses:
        m21Objs = self._getM21ObjsNoTies()
        if strip:
            df = m21Objs.map(na_action='ignore',
                func=lambda cell: cell.lyric.strip('\n \t-') if (cell.isNote and cell.lyric) else np.nan )
        else: 
            df = m21Objs.map(na_action='ignore',
                func=lambda cell: cell.lyric if cell.isNote else np.nan)
        self.analyses[key] = df
    return self.analyses[key]

markFourths

markFourths()

Distinguish between consonant and dissonant fourths. Returns a df of the diatonic, directed, and simple intervals of the piece with a "D" appended to dissonant fourths. Consonant fourths and all other intervals remain unchanged. A fourth is considered dissonant if it is against the same pitch class as the lowest sounding note.

Source code in crim_intervals/main_objs.py
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
def markFourths(self):
    '''
    Distinguish between consonant and dissonant fourths. Returns a df of the diatonic,
    directed, and simple intervals of the piece with a "D" appended to dissonant fourths.
    Consonant fourths and all other intervals remain unchanged. A fourth is considered
    dissonant if it is against the same pitch class as the lowest sounding note.'''
    if 'AnalyzeFourths' in self.analyses:
        return self.analyses['AnalyzeFourths']
    if len(self._getPartNames()) == 1:
        self.analyses['AnalyzeFourths'] = pd.DataFrame()
        return self.analyses['AnalyzeFourths']
    har = self.harmonic('d', True, False).copy()
    nr = self.notes().ffill()
    lowLine = self.lowLine()
    label = 'D'  # the label to use for fourths against the lowest note
    for col in har.columns:
        for i in har.index:
            if har.at[i, col] == '4':
                lowerVoice = col.split('_')[0]
                lowerNote = nr.at[i, lowerVoice]
                lowest = lowLine.asof(i)
                if lowerNote[0] == lowest[0]:
                    har.at[i, col] += label
            elif har.at[i, col] == '-4':
                upperVoice = col.split('_')[1]
                upperNote = nr.at[i, upperVoice]
                lowest = lowLine.asof(i)
                if upperNote[0] == lowest[0]:
                    har.at[i, col] += label
    self.analyses['AnalyzeFourths'] = har
    return self.analyses['AnalyzeFourths']

measures

measures()

This method retrieves the offsets of each measure in each voice.

Measures are expressed as integers.

Source code in crim_intervals/main_objs.py
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
def measures(self):
    """
    This method retrieves the offsets of each measure in each voice.

    Measures are expressed as integers.
    """
    if "Measure" not in self.analyses:
        parts = self._getFlatParts()
        partMeasures = []
        for part in parts:
            partMeasures.append(pd.Series({m.offset: m.measureNumber \
                for m in part.makeMeasures().getElementsByClass(['Measure'])}))
        df = pd.concat(partMeasures, axis=1, sort=True)
        df.columns = self._getPartNames()
        self.analyses["Measure"] = df
    return self.analyses["Measure"]

melodic

melodic(kind='q', directed=True, compound=True, unit=0, end=True, df=None)

Return melodic intervals for all voice pairs. Each melodic interval is associated with the starting offset of the second note in the interval.

  • To associate intervals with the offset of the first notes, pass end=False.

  • If you want melodic intervals measured at a regular duration, do NOT pipe this method's result to the regularize method. Instead, pass the desired regular durational interval as an integer or float as the unit parameter.

For example, to get melodic intervals measured at every quarter note:

mel_at_quarter = importedPiece.melodic(unit=1.0)

Parameters:

Name Type Description Default
kind str, optional (default 'q')

Use "q" (default) for diatonic intervals with quality, "d" for diatonic intervals without quality, "z" for zero-indexed diatonic intervals without quality (i.e. unison = 0, second = 1, etc.), or "c" for chromatic intervals. Only the first character is used, and it's case insensitive.

'q'
directed bool, optional (default True)

Defaults to True which shows that the voice that is lower on the staff is a higher pitch than the voice that is higher on the staff. This is designated with a "-" prefix.

True
compound bool, optional (default True)

Whether to use compound (True, default) or simple (False) intervals. In the case of simple diatonic intervals, it simplifies to within the octave, so octaves don't get simplified to unisons. But for semitonal intervals, an interval of an octave (12 semitones) does get simplified to a unison (0).

True
unit int or float, optional (default 0)

Regular durational interval at which to measure melodic intervals. See the documentation of the regularize method for more about this.

0
end bool, optional (default True)

True (default) associates each melodic interval with the offset of the second note in the interval. Pass False to change this to the first note in each interval.

True
df DataFrame

None (default) is the standard behavior. Pass a df of note and rest strings to calculate the melodic intervals in any dataframe. For example, if you want to find the melodic intervals between notes, but don't want to count repetitions of the same note as an interval, first run .notes(combineUnisons=True) then pass that result as the df parameter for .melodic. Results are not cached in this case.

None

Returns:

Type Description
DataFrame

Melodic intervals in each part.

Source code in crim_intervals/main_objs.py
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
@_records_settings('melodic', ('kind', 'directed', 'compound', 'unit', 'end'))
def melodic(self, kind='q', directed=True, compound=True, unit=0, end=True, df=None):
    '''
    Return melodic intervals for all voice pairs. Each melodic interval
    is associated with the starting offset of the second note in the
    interval.

    * To associate intervals with the offset of the first notes,
    pass `end=False`.

    * If you want melodic intervals measured at a regular
    duration, do NOT pipe this method's result to the `regularize` method.
    Instead, pass the desired regular durational interval as an integer or
    float as the `unit` parameter.

    For example, to get melodic intervals measured at every quarter note:

    ```python
    mel_at_quarter = importedPiece.melodic(unit=1.0)
    ```

    Parameters
    ----------
    kind : str, optional (default 'q')
        Use "q" (default) for diatonic intervals with quality, "d" for
        diatonic intervals without quality, "z" for zero-indexed diatonic
        intervals without quality (i.e. unison = 0, second = 1, etc.), or
        "c" for chromatic intervals. Only the first character is used,
        and it's case insensitive.
    directed : bool, optional (default True)
        Defaults to True which shows that the voice that is lower on the
        staff is a higher pitch than the voice that is higher on the
        staff. This is designated with a "-" prefix.
    compound : bool, optional (default True)
        Whether to use compound (True, default) or simple (False)
        intervals. In the case of simple diatonic intervals, it
        simplifies to within the octave, so octaves don't get simplified
        to unisons. But for semitonal intervals, an interval of an octave
        (12 semitones) does get simplified to a unison (0).
    unit : int or float, optional (default 0)
        Regular durational interval at which to measure melodic
        intervals. See the documentation of the `regularize` method for
        more about this.
    end : bool, optional (default True)
        True (default) associates each melodic interval with the offset
        of the second note in the interval. Pass False to change this to
        the first note in each interval.
    df : pandas.DataFrame, optional
        None (default) is the standard behavior. Pass a df of note and
        rest strings to calculate the melodic intervals in any dataframe.
        For example, if you want to find the melodic intervals between
        notes, but don't want to count repetitions of the same note as an
        interval, first run .notes(combineUnisons=True) then pass that
        result as the df parameter for .melodic. Results are not cached
        in this case.

    Returns
    -------
    pandas.DataFrame
        Melodic intervals in each part.
    '''
    kind = kind[0].lower()
    kind = {'s': 'c'}.get(kind, kind)
    _kind = {'z': 'd'}.get(kind, kind)
    settings = (_kind, directed, compound)
    key = ('MelodicIntervals', kind, directed, compound, end)
    if key not in self.analyses or unit or df is not None:
        _df = self._getRegularM21MelodicIntervals(unit) if unit else self._getM21MelodicIntervals(end, df)
        _df = _df.map(self._intervalMethods[settings], na_action='ignore')
        if kind == 'z':
            _df = _df.map(ImportedPiece._zeroIndexIntervals, na_action='ignore')
        if unit or df is not None:
            return _df
        else:
            self.analyses[key] = _df
    return self.analyses[key]

melodic_species

melodic_species(limit_to_entries=True, species_intervals=['5', '-5', '4', '-4'], four_five_dict={'C_5': 'C/G', 'C_-5': 'C/F', 'C_4': 'C/F', 'C_-4': 'C/G', 'D_5': 'D/A', 'D_-5': 'D/G', 'D_4': 'D/G', 'D_-4': 'D/A', 'E_5': 'E/B', 'E_-5': 'E/A', 'E_4': 'E/A', 'E_-4': 'E/B', 'F_5': 'F/C', 'F_-5': 'F/B-', 'F_4': 'F/B-', 'F_-4': 'F/C', 'G_5': 'G/D', 'G_-5': 'G/C', 'G_4': 'G/C', 'G_-4': 'G/D', 'A_5': 'A/E', 'A_-5': 'A/D', 'A_4': 'A/D', 'A_-4': 'A/E', 'B_5': 'B/F#', 'B_-5': 'B/E', 'B_4': 'B/E', 'B_-4': 'B/F#', 'B-_5': 'B-/F', 'B-_-5': 'B-/E-', 'B-_4': 'B-/E-', 'B-_-4': 'B-/F'}, octave_dict={'C/G': 'CGC', 'C/F': 'FCF', 'D/A': 'DAD', 'D/G': 'GDG', 'E/B': 'EBE', 'E/A': 'AEA', 'F/C': 'FCF', 'F/B-': 'BbFBb', 'G/D': 'GDG', 'G/C': 'CGC', 'A/E': 'AEA', 'A/D': 'DAD', 'B/F#': 'BF#B', 'B/E': 'EBE', 'B-/F': 'BbFBb', 'B-/E-': 'EbBbEb'})

This function finds and classifies melodic leaps according to the octave they serve to articulate. It first finds directed diatonic melodic intervals, recording both the starting note and the interval that leads away from it (for example C_5). These intervals are in turn mapped onto the octave species they help to articulate (for example C_5 and G_4 would help to articulate the CGC octave type.)

Parameters:

Name Type Description Default
limit_to_entries bool

If True, only intervals that begin a melodic entry are kept: those at the start of the piece, after a rest, or after a fermata (via self.entries()). This focuses the results on the opening gestures of phrases, where modal and tonal identity is most clearly stated. If False, every qualifying interval in every voice is kept.

True
species_intervals list of str

The directed diatonic melodic intervals to keep, written as returned by piece.melodic(kind='d') (for example '5', '-5', '4', '-4', '8', '-8'). Ascending intervals are positive and descending intervals are negative. All other intervals are discarded.

species_intervals_list
four_five_dict dict

Maps each combined note-and-interval label (for example 'C_5' or 'G_-4') to the fourth or fifth species it outlines. Fills the 'Species' column. This dict is defined in the sorting_lists.py file but a custom dict could be passed here.

species_four_five_dict
octave_dict dict

Maps each fourth or fifth species (the values of four_five_dict) to the octave species it helps articulate (for example 'CGC'). Fills the 'Octave' column. This dict is defined in the sorting_lists.py file but a custom dict could be passed here.

species_octave_dict

Returns:

Type Description
DataFrame

A long-format table with one row per qualifying interval and these columns: 'Composer', 'Title' : piece metadata 'Measure' : measure number 'Beat' : beat within the measure 'Progress' : position in the piece, from 0 to 1 'System' : the key signature at the start of the first staff, using music21's .sharps convention (0 = none, -1 = one flat, 1 = one sharp, etc.) 'Final' : the pitch class of the lowest sounding note at the end of the piece (music21 spelling, e.g. 'G' or 'B-') 'Voice' : voice number as a string (1 = highest staff) 'Interval' : the combined starting note and interval (for example 'C_5' or 'B-_4'), with pitches in music21 spelling 'Species' : the fourth or fifth species from four_five_dict (NaN if the label is not in the dict) 'Octave' : the octave species from octave_dict (NaN if the species is not in the dict)

Examples:

>>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
>>> species_df = piece.melodic_species() # this accepts defaults
>>> species_df['Octave'].value_counts()
>>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
>>> species_df = piece.melodic_species(limit_to_entries=True, 
            species_intervals=species_intervals_list, 
            four_five_dict = species_four_five_dict, 
            octave_dict = species_octave_dict) # these are defaults, but could be customized
>>> species_df['Octave'].value_counts()
Notes

Pitch names are stripped of octave numbers (via extract_letter) before being combined with the interval. So C4 and C5 both appear as 'C', which means the classification depends on pitch class, not register. Accidentals are kept, so B-4 appears as 'B-' and is classified separately from B.

Pitches in the 'Final' and 'Interval' columns use music21 spelling ('B-', 'E-', 'F#'), while the 'Octave' labels from the default octave_dict use 'b' for flats (for example 'BbFBb', 'EbBbEb').

Source code in crim_intervals/main_objs.py
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
@_records_settings('melodic_species', ('limit_to_entries',), inherit=())
def melodic_species(self, limit_to_entries=True,
                species_intervals=species_intervals_list, 
                four_five_dict = species_four_five_dict, 
                octave_dict = species_octave_dict):

    '''This function finds and classifies melodic leaps according to the octave
    they serve to articulate.  It first finds directed diatonic melodic intervals, 
    recording both the starting note and the interval that leads away from it (for example C_5). 
    These intervals are in turn mapped onto the octave species they help to articulate 
    (for example C_5 and G_4 would help to articulate the CGC octave type.)

    Parameters
    ----------
    limit_to_entries : bool, default True
        If True, only intervals that begin a melodic entry are kept: those at
        the start of the piece, after a rest, or after a fermata (via
        `self.entries()`).  This focuses the results on the opening gestures
        of phrases, where modal and tonal identity is most clearly stated.
        If False, every qualifying interval in every voice is kept.

    species_intervals : list of str, default species_intervals_list
        The directed diatonic melodic intervals to keep, written as returned by
        `piece.melodic(kind='d')` (for example '5', '-5', '4', '-4', '8', '-8').
        Ascending intervals are positive and descending intervals are negative.
        All other intervals are discarded.

    four_five_dict : dict, default species_four_five_dict
        Maps each combined note-and-interval label (for example 'C_5' or 'G_-4')
        to the fourth or fifth species it outlines.  Fills the 'Species' column.
        This dict is defined in the sorting_lists.py file but a custom dict could be passed here.

    octave_dict : dict, default species_octave_dict
        Maps each fourth or fifth species (the values of `four_five_dict`) to
        the octave species it helps articulate (for example 'CGC').  Fills the
        'Octave' column.  This dict is defined in the sorting_lists.py file
        but a custom dict could be passed here.

    Returns
    -------
    pandas.DataFrame
        A long-format table with one row per qualifying interval and these columns:
        'Composer', 'Title' : piece metadata
        'Measure'           : measure number
        'Beat'              : beat within the measure
        'Progress'          : position in the piece, from 0 to 1
        'System'            : the key signature at the start of the first staff,
                            using music21's `.sharps` convention (0 = none,
                            -1 = one flat, 1 = one sharp, etc.)
        'Final'             : the pitch class of the lowest sounding note at the
                            end of the piece (music21 spelling, e.g. 'G' or 'B-')
        'Voice'             : voice number as a string (1 = highest staff)
        'Interval'          : the combined starting note and interval (for example 'C_5'
                            or 'B-_4'), with pitches in music21 spelling
        'Species'           : the fourth or fifth species from `four_five_dict`
                            (NaN if the label is not in the dict)
        'Octave'            : the octave species from `octave_dict`
                            (NaN if the species is not in the dict)


    Examples
    --------
    >>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
    >>> species_df = piece.melodic_species() # this accepts defaults
    >>> species_df['Octave'].value_counts()

    >>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
    >>> species_df = piece.melodic_species(limit_to_entries=True, 
                species_intervals=species_intervals_list, 
                four_five_dict = species_four_five_dict, 
                octave_dict = species_octave_dict) # these are defaults, but could be customized
    >>> species_df['Octave'].value_counts()

    Notes
    -----
    Pitch names are stripped of octave numbers (via `extract_letter`)
    before being combined with the interval.  So C4 and C5 both appear as 'C',
    which means the classification depends on pitch class, not register.
    Accidentals are kept, so B-4 appears as 'B-' and is classified separately
    from B.

    Pitches in the 'Final' and 'Interval' columns use music21 spelling
    ('B-', 'E-', 'F#'), while the 'Octave' labels from the default
    `octave_dict` use 'b' for flats (for example 'BbFBb', 'EbBbEb').
    '''

    # get notes and melodic intervals
    notes = self.notes()

    # strip octave digits but keep accidentals (B-4 -> B-); helper is in sorting_lists.py
    notes = notes.map(extract_letter)
    notes_numb = self.numberParts(df=notes)
    mel = self.melodic(kind='d', end=False)
    mel_numb = self.numberParts(df=mel)

    # entry limit logic
    if limit_to_entries:
        mel_numb = self.entries(mel_numb)

    # keep only the intervals in species_intervals; everything else becomes NaN.
    # (Masking in place keeps the full shape, so the NaNs can mask the notes below.)
    filtered_mel = mel_numb.where(mel_numb.isin(species_intervals))

    # keep only the notes that start a qualifying interval
    # (reindex in case the notes and intervals have different offsets)
    filtered_nr = notes_numb.reindex(filtered_mel.index).where(filtered_mel.notna())

    # force column names to string
    filtered_nr.columns = filtered_nr.columns.astype(str)
    filtered_mel.columns = filtered_mel.columns.astype(str)

    # combine note and interval into labels like 'C_5'; non-qualifying cells stay NaN
    result_df = filtered_nr + '_' + filtered_mel

    # add detail index and metadata.  Also add final and system
    result_df_numbered = self.detailIndex(result_df, measure=True, beat=True, offset=False, progress=True)
    result_df_numbered['Composer'] = self.metadata['composer']
    result_df_numbered['Title'] = self.metadata['title']
    result_df_numbered['Final'] = extract_letter(self.final())
    result_df_numbered['System'] = self.keySignatures().iloc[0,0]
    result_df_numbered = result_df_numbered.reset_index()

    # melt the columns so we have 'voice and interval' as main data
    id_cols = ['Composer', 'Title', 'Measure', 'Beat', 'Progress', 'System', 'Final']
    species_df = pd.melt(
        result_df_numbered,
        id_vars=id_cols,
        var_name='Voice',
        value_name='Interval',
        value_vars=[col for col in result_df_numbered.columns if col not in id_cols]
    )

    # drop time points where nothing qualified
    species_df = species_df.dropna(subset=['Interval'])

    species_df['Species'] = species_df['Interval'].map(four_five_dict)
    species_df['Octave'] = species_df['Species'].map(octave_dict)
    return species_df.reset_index(drop=True)

morleyCadences

morleyCadences()

Return a dataframe of the places where there appear to be patient-type melodies. These moments are labeled with "Morley Cadence" as they match Morley's definition of a cadence which is a one-voice melodic pattern.

Source code in crim_intervals/main_objs.py
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
def morleyCadences(self):
    '''
    Return a dataframe of the places where there appear to be patient-type melodies. These
    moments are labeled with "Morley Cadence" as they match Morley's definition of a cadence
    which is a one-voice melodic pattern.
    '''
    nr = self.notes(combineUnisons=True)
    mel = self.melodic(kind='d', end=True, df=nr)
    mel_ng = self.ngrams(n=2, df=mel, offsets='last')
    mel2_matches = mel_ng.map(lambda cell: cell == ('-2', '2'), na_action='ignore').replace(False, np.nan).dropna(how='all')
    bs = self.beatStrengths().reindex_like(nr)
    bs_ng = self.ngrams(n=3, df=bs, exclude=[], offsets='last')
    bs_ng = bs_ng.reindex_like(mel_ng)
    bs2_matches = bs_ng.map(lambda cell: cell[0] < cell[2] > cell[1], na_action='ignore').replace(False, np.nan).dropna(how='all')
    # C-B-A-B-C
    mel4_ng = self.ngrams(n=4, df=mel, offsets='last')
    mel4_matches = mel4_ng.map(lambda cell: cell == ('-2', '-2', '2', '2'), na_action='ignore').replace(False, np.nan).dropna(how='all')
    bs4_ng = self.ngrams(n=5, df=bs, exclude=[], offsets='last')
    bs4_ng = bs4_ng.reindex_like(mel4_ng)
    bs4_matches = bs_ng.map(lambda cell: all([cell[-1] > val for val in cell[:-1]]), na_action='ignore').replace(False, np.nan).dropna(how='all')

    res = pd.DataFrame().reindex_like(bs_ng).astype(object)
    res[bs2_matches & mel2_matches] = 'Morley Cadence'
    res4 = pd.DataFrame().reindex_like(bs4_ng).astype(object)
    res4[bs4_matches & mel4_matches] = 'Morley Cadence'
    res.update(res4)        
    return res.dropna(how='all')

morleyCloses

morleyCloses()

Return "closes" according to Morley, which are normally called cadences. This method uses a harmonically based definition of a cadence. A close is observed if the harmony goes from a root position triad to another root position triad a fifth lower at the same time as a morleyCadence event is observed.

Source code in crim_intervals/main_objs.py
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
def morleyCloses(self):
    """
    Return "closes" according to Morley, which are normally called cadences. This
    method uses a harmonically based definition of a cadence. A close is observed
    if the harmony goes from a root position triad to another root position triad
    a fifth lower at the same time as a `morleyCadence` event is observed."""
    mcads = self.morleyCadences()
    mcad = pd.Series(True, index=mcads.index, name='MCad')
    sons = self.sonorities()
    low = pd.DataFrame(self.lowLine())
    lowMel = self.melodic(end=True, kind='d', df=low)
    progressions = self.ngrams(df=sons, other=lowMel, n=2, offsets='last', held='1')
    data = pd.concat([progressions, mcad], axis=1, sort=True).dropna(subset=('MCad',))
    res = data.Sonority.str.match('(7/5/3|7/3|5/3|3)_(-5|4), (3|)')
    res = res[res].astype(object)
    res.name = 'Close'
    res.iloc[:] = 'Close'
    return pd.DataFrame(res)

ngrams

ngrams(df=None, n=3, how='columnwise', other=None, held='Held', exclude=['Rest'], interval_settings=('d', True, True), unit=0, offsets='first', show_both=False)

Generate n-grams from the given dataframe (df) or from the harmonic and melodic intervals of the piece.

Group sequences of observations in a sliding window "n" events long (default n=3). Whether df and/or other parameters are passed determines how the ngrams are assembled.

When a df is passed but no other is passed, the columns of the df are the data source. When both df and other parameters are passed, contrapuntal-module ngrams are generated.

Similarly, if neither df nor other dataframes are provided, they will be supplied according to the interval_settings parameter. These contrapuntal-module ngrams are useful to assign specific labels to all 2-voice combinations n events long. For our ngrams, an "event" is a note or rest in either voice. This method accepts the following parameters.

Parameters: df : pandas.DataFrame A DataFrame of note and rest strings. If df is None, harmonic intervals will be supplied by the .harmonic method according to the interval_settings parameter. n : int The size of the ngrams. If n is set to -1, the longest ngrams at all time points excluding subset ngrams will be returned. how : str This parameter is deprecated. The mode is now determined by what is or is not passed as the df and other parameters. other : pandas.DataFrame A DataFrame of melodic motions. If provided, the method will return contrapuntal-module ngrams. This will also happen if neither df nor other are provided. held : str The label for when one voice sustains a note while the other voice moves. This defaults to "Held" to distinguish between held notes and reiterated ones but you may want to pass the way a unison gets labeled in your other DataFrame (e.g. "P1" or "1"). exclude : list A list of strings that will be used to filter out ngrams that contain any of the strings in the list. The default is to exclude rests and most likely you will want to leave this setting as is. interval_settings : tuple A tuple of settings that will be passed to the .harmonic and .melodic methods if df and other are not provided. The first item in the tuple is the kind of interval to use. The second item is whether to use directed intervals. The third item is whether to use compound intervals. unit : int or float If you want to measure the intervals at a regular durational interval, pass the desired regular durational interval as an integer or float. offsets : str If "first" is selected (default option), the returned ngrams will be grouped according to their first notes' offsets, while if "last" is selected, the returned ngrams will be grouped according to the last notes' offsets. You can also set offsets to "both" in which case a dataframe with a multi-index of both the starting and ending offsets will be returned. show_both : bool If True, the melodic motion of both voices in contrapuntal modules are shown. If False, only the melodic motion of the lower voice is shown. This added information is needed to disambiguate some complex contrapuntal modules.

When a dataframe is passed as df and nothing is given for other, this is the simple case where the events in each column of the df DataFrame are grouped at the offset of the first event in the window. For example, to get 4-grams of melodic intervals:

ip = ImportedPiece('path_to_piece')
ngrams = ip.ngrams(df=ip.melodic(), n=4)

For the "module" mode (interval successions) you must either pass dataframes to both df and other, or leave both as None (default). In this case, if the df or other parameters are left as None, they will be replaced with the current piece's harmonic and melodic intervals respectively. These intervals will be formed according to the interval_settings argument, which gets passed to the melodic and harmonic methods (see those methods for an explanation of those settings). This makes it easy to make contrapuntal-module ngrams, e.g.:

ip = ImportedPiece('path_to_piece')
ngrams = ip.ngrams()

There is a special case for "open-ended" module ngrams. Set n=1 and the module ngrams will show the vertical interval between two voices, followed by the connecting melodic interal in the lower voice, but not the next harmonic interval. Open-ended module ngrams can be useful if you want to see how long the imitation in two voice parts goes on for.

Another special case is when n is set to -1. This finds the longest ngrams at all time points excluding subset ngrams. The returned dataframe will have ngrams of length varying between 1 and the longest ngram in the piece.

If you want want "module" ngrams taken at a regular durational interval, you can omit passing df and other dataframes and instead pass the desired interval_settings and an integer or float for the unit parameter. See the .regularize documentation for how to use this parameter. Here's an example that will generate contrapuntal-module ngrams at regular minim (half-note) intervals.

ip = ImportedPiece('path_to_piece')
ngrams = ip.ngrams(unit=2)

Otherwise, you can give specific df and/or other DataFrames in which case the interval_settings parameter will be ignored. Also, you can use the held parameter to be used for when the lower voice sustains a note while the upper voice moves. This defaults to "Held" to distinguish between held notes and reiterated notes in the lower voice, but if this distinction is not wanted for your query, you may want to pass the way a unison gets labeled in your other DataFrame (e.g. "P1" or "1").

The show_both parameter controls whether the melodic motion of both voices in contrapuntal modules are shown. If True, the melodic motions of the two voices appear with a colon between them in the format lower:upper e.g. "3_-2:1, 4_1:-2, 3_-5:2, 8". This is needed for the detection of cadential voice function evasion by dropout and also to be able to detect which voice attacks at a dissonance.

Source code in crim_intervals/main_objs.py
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
@_records_settings('ngrams', ('n', 'exclude', 'interval_settings', 'offsets'), inherit=('df', 'other'))
def ngrams(self, df=None, n=3, how='columnwise', other=None, held='Held',
              exclude=['Rest'], interval_settings=('d', True, True), unit=0,
              offsets='first', show_both=False):
    '''
    Generate n-grams from the given dataframe (df) or from the harmonic and
    melodic intervals of the piece.

    Group sequences of observations in a sliding window "n" events long
    (default n=3). Whether `df` and/or `other` parameters are passed determines
    how the ngrams are assembled. 

    When a `df` is passed but no `other` is passed,
    the columns of the `df` are the data source. When both `df` and `other`
    parameters are passed, contrapuntal-module ngrams are generated. 

    Similarly,
    if neither `df` nor `other` dataframes are provided, they will be supplied
    according to the interval_settings parameter. These contrapuntal-module
    ngrams are useful to assign specific labels to all 2-voice combinations `n`
    events long. For our ngrams, an "event" is a note or rest in either voice. This
    method accepts the following parameters.

    Parameters:
    df : pandas.DataFrame
        A DataFrame of note and rest strings. If `df` is None, harmonic intervals
        will be supplied by the .harmonic method according to the `interval_settings`
        parameter.
    n : int
        The size of the ngrams. If `n` is set to -1, the longest ngrams at
        all time points excluding subset ngrams will be returned.
    how : str
        This parameter is deprecated. The mode is now determined by what is
        or is not passed as the `df` and `other` parameters.
    other : pandas.DataFrame
        A DataFrame of melodic motions. If provided, the method will return
        contrapuntal-module ngrams. This will also happen if neither `df` nor
        `other` are provided.
    held : str
        The label for when one voice sustains a note while the other voice moves.
        This defaults to "Held" to distinguish between held notes and reiterated ones
        but you may want to pass the way a unison gets labeled in your `other`
        DataFrame (e.g. "P1" or "1").
    exclude : list
        A list of strings that will be used to filter out ngrams that contain any
        of the strings in the list. The default is to exclude rests and most likely
        you will want to leave this setting as is.
    interval_settings : tuple
        A tuple of settings that will be passed to the .harmonic and .melodic
        methods if `df` and `other` are not provided. The first item in the tuple
        is the kind of interval to use. The second item is whether to use directed
        intervals. The third item is whether to use compound intervals.
    unit : int or float
        If you want to measure the intervals at a regular durational interval,
        pass the desired regular durational interval as an integer or float.
    offsets : str
        If "first" is selected (default option), the returned ngrams will be
        grouped according to their first notes' offsets, while if "last" is
        selected, the returned ngrams will be grouped according to the last
        notes' offsets. You can also set offsets to "both" in which case a
        dataframe with a multi-index of both the starting and ending offsets
        will be returned.
    show_both : bool
        If True, the melodic motion of both voices in contrapuntal modules are
        shown. If False, only the melodic motion of the lower voice is shown.
        This added information is needed to disambiguate some complex contrapuntal
        modules.

    When a dataframe is passed as `df` and nothing is given for `other`, this
    is the simple case where the events in each column of the `df` DataFrame
    are grouped at the offset of the first event in the window. For example,
    to get 4-grams of melodic intervals:

    ```python
    ip = ImportedPiece('path_to_piece')
    ngrams = ip.ngrams(df=ip.melodic(), n=4)
    ```

    For the "module" mode (interval successions) you must either pass dataframes
    to both `df` and `other`, or leave both as None (default). In
    this case, if the `df` or `other` parameters are left as None, they will
    be replaced with the current piece's harmonic and melodic intervals
    respectively. These intervals will be formed according to the
    `interval_settings` argument, which gets passed to the melodic and
    harmonic methods (see those methods for an explanation of those
    settings). This makes it easy to make contrapuntal-module ngrams, e.g.:

    ```python
    ip = ImportedPiece('path_to_piece')
    ngrams = ip.ngrams()
    ```

    There is a special case for "open-ended" module ngrams. Set `n=1` and the
    module ngrams will show the vertical interval between two voices,
    followed by the connecting melodic interal in the lower voice, but not
    the next harmonic interval. Open-ended module ngrams can be useful if
    you want to see how long the imitation in two voice parts goes on for.

    Another special case is when `n` is set to -1. This finds the longest
    ngrams at all time points excluding subset ngrams. The returned
    dataframe will have ngrams of length varying between 1 and the longest
    ngram in the piece.

    If you want want "module" ngrams taken at a regular durational interval,
    you can omit passing `df` and `other` dataframes and instead pass the
    desired `interval_settings` and an integer or float for the `unit`
    parameter. See the `.regularize` documentation for how to use this
    parameter. Here's an example that will generate contrapuntal-module
    ngrams at regular minim (half-note) intervals.

    ```python
    ip = ImportedPiece('path_to_piece')
    ngrams = ip.ngrams(unit=2)
    ```

    Otherwise, you can give specific `df` and/or `other` DataFrames in which
    case the `interval_settings` parameter will be ignored. Also, you can
    use the `held` parameter to be used for when the lower voice sustains a
    note while the upper voice moves. This defaults to "Held" to distinguish
    between held notes and reiterated notes in the lower voice, but if this
    distinction is not wanted for your query, you may want to pass the way a
    unison gets labeled in your `other` DataFrame (e.g. "P1" or "1").

    The `show_both` parameter controls whether the melodic motion of both
    voices in contrapuntal modules are shown. If `True`, the melodic motions of
    the two voices appear with a colon between them in the format lower:upper
    e.g. "3_-2:1, 4_1:-2, 3_-5:2, 8". This is needed for the detection of
    cadential voice function evasion by dropout and also to be able to detect
    which voice attacks at a dissonance.
    '''
    if df is not None and other is None:
        how = 'columnwise'
    elif (df is not None and other is not None) or (df is None and other is None):
        how = 'modules'
    if how == 'columnwise':
        return df.apply(ImportedPiece._ngramHelper, args=(n, exclude, offsets))
    if df is None:
        df = self.harmonic(*interval_settings)
        if unit:
            df = self.regularize(df, unit)
    if other is None:
        other = self.melodic(*interval_settings, unit=unit)
    cols = []
    other = other.fillna(held)
    if '_' not in df.columns[0] and 'Sonority' != df.columns[0]:  # df is not a pair of voices, but rather info about 1 voice at a time
        _df = df.map(str, na_action='ignore')
        _other = other.map(str, na_action='ignore')
        ret = _df + '_' + _other
        return self.ngrams(df=ret, n=n, exclude=exclude, offsets=offsets)
    for pair in df.columns:
        if pair == 'Sonority':
            lowerVoice = other.columns[0]
            lowerMel = other.iloc[:, 0].copy()
        else:
            lowerVoice, upperVoice = pair.split('_')
            lowerMel = other[lowerVoice].copy()
        if show_both and 'Rest' not in exclude:
            lowerMel += ':' + other[upperVoice]
        # can't use pd.concat here because of an issue with pandas, maybe a bug
        combo = pd.DataFrame(lowerMel).join(df[pair], how='outer')
        combo.dropna(subset=(pair,), inplace=True)
        filler = held + ':' + held if show_both else held
        combo[lowerVoice] = combo[lowerVoice].fillna(filler)
        combo.insert(loc=1, column='Joiner', value=', ')
        combo['_'] = '_'
        if n == -1:
            har = df[pair].dropna()
            prev, nxt = har.shift(1), har.shift(-1)
            starts = har[(har != 'Rest') & ((prev == 'Rest') | prev.isna())]
            ends   = har[(har != 'Rest') & ((nxt == 'Rest') | nxt.isna())]
            starts.dropna(inplace=True)
            ends.dropna(inplace=True)
            si = tuple(har.index.get_loc(i) for i in starts.index)
            ei = tuple(har.index.get_loc(i) + 1 for i in ends.index)
            col = [''.join([cell for row in combo.iloc[si[i]: ei[i]].values  # second loop
                                     for cell in row][2:-1])  # innermost loop
                   for i in range(len(si))]  # outermost loop
            col = pd.Series(col)
            if offsets == 'last':
                col.index = ends.index
            elif offsets == 'both':
                col.index = pd.MultiIndex.from_arrays([starts.index, ends.index], names=['First', 'Last'])
            else: # offsets == 'first'
                col.index = starts.index
        else:  # n >= 1
            lastIndex = -1
            if n == 1:
                lastIndex = -3
                n = 2
            combo = ImportedPiece._ngrams_offsets_helper(combo, n, offsets)
            col = combo.iloc[:, 2:lastIndex].dropna().apply(lambda row: ''.join(row), axis=1)
            if exclude:
                mask = col.apply(lambda cell: all([excl not in cell for excl in exclude]))
                col = col[mask]
        col.name = pair
        cols.append(col)
    # in case piece has no harmony and cols stays empty
    if cols:
        ret = pd.concat(cols, axis=1, sort=True)
        # modules: pass on the harmonic and melodic settings used (the
        # decorator adds this method's own)
        ret.attrs = {SETTINGS_KEY: {**get_settings(other), **get_settings(df)}}
        return ret
    else:
        return pd.DataFrame()

note_weights

note_weights(include_rests=True, key_sig=False, include_final=False)

Weight each pitch class by its total duration in the piece: how much of the piece's time (summed across all voices) is spent on C, D, E-, ...

Parameters:

Name Type Description Default
include_rests bool, optional (default True)

Whether to count rests as a pitch class (labeled 'Rest'), or drop them and scale proportions over sounding notes only.

True
key_sig bool, optional (default False)

If True, add a 'key_sig' column with the piece's prevailing key signature (music21 .sharps convention: 0 = none, -1 = one flat).

False
include_final bool, optional (default False)

If True, add a 'final' column with the piece's final (pitch class).

False

Returns:

Type Description
DataFrame

One row per pitch class, in pitch-class order, with columns 'pitch_class' (music21 spelling, e.g. 'B-'), 'count' (summed duration in quarter notes), 'scaled' (proportion of the total, 0 to 1), 'composer', 'title' (and 'final'/'key_sig' if requested). Pass this to visualizations.radar_note_plot.

Examples:

>>> weights = piece.note_weights(include_rests=False)
>>> radar_note_plot(weights)
Source code in crim_intervals/main_objs.py
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
@_records_settings('note_weights', ('include_rests',), inherit=())
def note_weights(self, include_rests=True, key_sig=False, include_final=False):
    """
    Weight each pitch class by its total duration in the piece: how much of
    the piece's time (summed across all voices) is spent on C, D, E-, ...

    Parameters
    ----------
    include_rests : bool, optional (default True)
        Whether to count rests as a pitch class (labeled 'Rest'), or drop
        them and scale proportions over sounding notes only.
    key_sig : bool, optional (default False)
        If True, add a 'key_sig' column with the piece's prevailing key
        signature (music21 .sharps convention: 0 = none, -1 = one flat).
    include_final : bool, optional (default False)
        If True, add a 'final' column with the piece's final (pitch class).

    Returns
    -------
    pandas.DataFrame
        One row per pitch class, in pitch-class order, with columns
        'pitch_class' (music21 spelling, e.g. 'B-'), 'count' (summed
        duration in quarter notes), 'scaled' (proportion of the total,
        0 to 1), 'composer', 'title' (and 'final'/'key_sig' if requested).
        Pass this to `visualizations.radar_note_plot`.

    Examples
    --------
    >>> weights = piece.note_weights(include_rests=False)
    >>> radar_note_plot(weights)
    """
    memo_key = ('NoteWeights', include_rests, key_sig, include_final)
    if memo_key in self.analyses:
        return self.analyses[memo_key].copy()
    pc_order = pitch_class_order_with_rests if include_rests else pitch_class_order_no_rests
    nr = self.notes()
    # align each note with its own duration by (offset, voice)
    pairs = pd.concat([nr.stack(), self.durations(df=nr).stack()], axis=1,
                      keys=['note', 'dur']).dropna()
    pairs['pitch_class'] = pairs['note'].map(lambda v: extract_letter(v, include_rests=include_rests))
    pairs = pairs.dropna(subset=['pitch_class'])
    weights = (pairs.groupby('pitch_class')['dur'].sum().astype(float)
                    .reset_index().rename(columns={'dur': 'count'}))
    total = weights['count'].sum()
    weights['scaled'] = (weights['count'] / total).round(4) if total else 0.0
    # pitch-class order, with any unexpected spellings kept at the end
    rank = {pc: i for i, pc in enumerate(pc_order)}
    weights = (weights.assign(_r=weights['pitch_class'].map(lambda p: rank.get(p, len(rank))))
                      .sort_values(['_r', 'pitch_class']).drop(columns='_r')
                      .reset_index(drop=True))
    weights['composer'] = self.metadata['composer']
    weights['title'] = self.metadata['title']
    if include_final:
        weights['final'] = extract_letter(self.final())
    if key_sig:
        ks = self.keySignatures().iloc[:, 0].dropna()
        weights['key_sig'] = ks.iloc[0] if len(ks) else None
    self.analyses[memo_key] = weights
    return weights.copy()

notes

notes(combineRests=True, combineUnisons=False)

Return a table of the notes and rests in the piece. Rests are designated with the string "Rest". Notes are shown such that middle C is "C4". If combineRests is True (default), non-first consecutive rests will be removed, effectively combining consecutive rests in each voice. combineUnisons works the same way for consecutive attacks on the same pitch in a given voice, however, combineUnisons defaults to False.

Source code in crim_intervals/main_objs.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
@_records_settings('notes', ('combineRests', 'combineUnisons'), inherit=())
def notes(self, combineRests=True, combineUnisons=False):
    '''
    Return a table of the notes and rests in the piece. Rests are
    designated with the string "Rest". Notes are shown such that middle C
    is "C4".
    If `combineRests` is `True` (default), non-first consecutive rests will be
    removed, effectively combining consecutive rests in each voice.
    `combineUnisons` works the same way for consecutive attacks on the same
    pitch in a given voice, however, `combineUnisons` defaults to `False`.
    '''
    if 'Notes' not in self.analyses:
        df = self._getM21ObjsNoTies().map(self._noteRestHelper, na_action='ignore')
        self.analyses['Notes'] = df
    ret = self.analyses['Notes'].copy()
    if combineRests:
        ret = ret.apply(self._combineRests)
    if combineUnisons:
        ret = ret.apply(self._combineUnisons)
    return ret

numberParts

numberParts(df)

Return the passed df with the part names in the columns replaced with numbers where 1 is the highest staff. Works with single parts and multi-part column names. Returns a renamed copy; the original df is left unchanged, so use the return value.

Source code in crim_intervals/main_objs.py
339
340
341
342
343
344
345
346
347
348
def numberParts(self, df):
    '''
    Return the passed df with the part names in the columns replaced with numbers
    where 1 is the highest staff. Works with single parts and multi-part column names.
    Returns a renamed copy; the original df is left unchanged, so use the return value.'''
    _dict = self._getPartNumberDict()
    cols = ['_'.join(_dict.get(part, part) for part in col.split('_')) for col in df.columns]
    res = df.copy()
    res.columns = cols
    return res

pitch_class_order

pitch_class_order(include_rests=True)

Return the shared pitch-class ordering list.

Source code in crim_intervals/main_objs.py
291
292
293
def pitch_class_order(self, include_rests=True):
    """Return the shared pitch-class ordering list."""
    return pitch_class_order_with_rests if include_rests else pitch_class_order_no_rests

pitch_order

pitch_order(values, order=None, include_rests=True)

Return a list of pitch values sorted by the shared ordering helpers.

Source code in crim_intervals/main_objs.py
279
280
281
def pitch_order(self, values, order=None, include_rests=True):
    """Return a list of pitch values sorted by the shared ordering helpers."""
    return sort_pitch_values(values, order=order, include_rests=include_rests)

presentationTypes

presentationTypes(kind='d', end=False, melodic_ngram_length=4, limit_to_entries=True, body_flex=0, head_flex=1, include_hidden_types=False, combine_unisons=False)

This function uses several other functions to classify the entries in a given piece. The output is a list, in order of offset, of each presentation type, including information about

  • measures/beats (of each entry)
  • starting offset (of each entry)
  • soggetti involved (depending on 'flex' settings, there could be more tha one)
  • melodic intervals of entry (the melodic distance between the first tones of successive entries)
  • time intervals of entry (the duration in offets from one entry to the next)
  • presense of flexed entries (either head or body of soggetto, depending on the settings)
  • presense of parallel entries (the parallel entry is reported separately, and is not included in the metadata about Time or Melodic intervals of imitation; the preferred intervals are ["P1", "P4", "P-4", "P5", "P-5", "P8", "P-8", "P12", "P-12"] and can be adjusted via the code for _temp_dict_of_details
  • how many of the entries fail to overlap with another one

It is also possible to find PEns and IDs that are 'hidden' within longer Fugas. Note that this method finds both PEns and IDs that can be found among all combinations of voices in a longer fuga (thus between entries 1, 2, 4; 2, 4, 5, etc) as well as thosefound between successive entries.

Arguments include:

  • set ngram length with 'melodic_ngram_length' (=4 by default)
  • limit_to_entries (True by default) finds only soggetti that start after a rest or after a section break.
  • setting this to "False" will produce a 'moving window' of all sub-strings (and Presentation Types) created by the soggetto, starting on notes 1, 2, 3, 4, etc.
  • set 'combineUnisons' as True or False (False by default)set the length of the soggetti with melodic_ngram_length
  • set the maximum difference between the first interval in similar soggetto with 'head_flex' (=1 by default)
  • set the maximum difference between similar soggetti with body_flex (=0 by default)
  • for chromatic vs diatonic, compound, and directed data in soggetti, see interval_settings
  • to include all the hidden PENs and IDS (those found within longer Fugas), use include_hidden_types == True (set to False by default)
  • for faster (and simpler) listing of points of imitation without hidden forms, use include_hidden_types == False (= default)

Examples:

piece = importScore('url')
piece.presentationTypes(head_flex=1)

Note that the output of this function can be used with verovioPtypes to show each cadence in staff notation.

Source code in crim_intervals/main_objs.py
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
@_records_settings('presentationTypes',
                   ('kind', 'end', 'melodic_ngram_length', 'limit_to_entries', 'body_flex',
                    'head_flex', 'include_hidden_types', 'combine_unisons'), inherit=())
def presentationTypes(self, kind='d', end=False, melodic_ngram_length=4, limit_to_entries=True,
                      body_flex=0, head_flex=1, include_hidden_types=False,
                      combine_unisons=False):
    """
    This function uses several other functions to classify the entries in a given piece.
    The output is a list, in order of offset, of each presentation type, including information about

    * measures/beats (of each entry)
    * starting offset (of each entry)
    * soggetti involved (depending on 'flex' settings, there could be more tha one)
    * melodic intervals of entry (the melodic distance between the first tones of successive entries)
    * time intervals of entry (the duration in offets from one entry to the next)
    * presense of flexed entries (either head or body of soggetto, depending on the settings)
    * presense of parallel entries (the parallel entry is reported separately, and is not included in the
    metadata about Time or Melodic intervals of imitation; the preferred intervals are
    ["P1", "P4", "P-4", "P5", "P-5", "P8", "P-8", "P12", "P-12"] and can be adjusted via the code
    for _temp_dict_of_details
    * how many of the entries fail to overlap with another one

    It is also possible to find PEns and IDs that are 'hidden' within
    longer Fugas. Note that this method finds both PEns and IDs that can be
    found among all combinations of voices in a longer fuga (thus between
    entries 1, 2, 4; 2, 4, 5, etc) as well as thosefound between successive entries.

    Arguments include:

    * set ngram length with 'melodic_ngram_length' (=4 by default)
    * limit_to_entries (True by default) finds only soggetti that start after a rest or after a section break.
    * setting this to "False" will produce a 'moving window' of all sub-strings (and Presentation Types) created by the
    soggetto, starting on notes 1, 2, 3, 4, etc.
    * set 'combineUnisons' as True or False (False by default)set the length of the soggetti with `melodic_ngram_length`
    * set the maximum difference between the first interval in similar soggetto with 'head_flex' (=1 by default)
    * set the maximum difference between similar soggetti with `body_flex` (=0 by default)
    * for chromatic vs diatonic, compound, and directed data in soggetti, see `interval_settings`
    * to include all the hidden PENs and IDS (those found within longer Fugas),
    use `include_hidden_types == True` (set to False by default)
    * for faster (and simpler) listing of points of imitation without hidden forms, use `include_hidden_types == False` (= default)


    Examples
    --------
    ```python
    piece = importScore('url')
    piece.presentationTypes(head_flex=1)
    ```

    Note that the output of this function can be used with verovioPtypes to show
    each cadence in staff notation.
    """
    memo_key = ('PresentationTypes', kind, end, melodic_ngram_length, limit_to_entries,
        body_flex, head_flex, include_hidden_types, combine_unisons)
    if memo_key in self.analyses:
        return self.analyses[memo_key]
    nr = self.notes(combineUnisons=combine_unisons)
    mel = self.melodic(df=nr, kind=kind, end=end)
    mel_ng = self.ngrams(df=mel, exclude=['Rest'], n=melodic_ngram_length)
    if limit_to_entries:
        entries = self.entries(mel_ng)
    else:
        entries = self.ngrams(df=mel, exclude=['Rest'], n=melodic_ngram_length)
    # remove entries that start at fractional offsets
    integer_mask = entries.index % 1 == 0
    entries = entries[integer_mask]
    # get ngram durs to use for overlap check as part of _temp files
    ng_durs = self.durations(df=entries)
    points = pd.DataFrame(columns=['Composer',
                'Title',
                'Presentation_Type',
                'First_Offset',
                'Measures_Beats',
                'Melodic_Entry_Intervals',
                'Offsets',
                'Soggetti',
                'Time_Entry_Intervals',
                'Voices'])
    points2 = pd.DataFrame()
    # defines column order in final df
    # others are at the end for the overlapping entries
    col_order = list(points.columns) + ['Number_Entries',
                                        'Flexed_Entries',
                                        'Parallel_Entries',
                                        'Parallel_Voice',
                                        'Count_Offsets',
                                        'Offsets_Key']

    det = self.detailIndex(nr, offset=True, progress=True)
    # ngrams of melodic entries
    mels_stacked = entries.stack().to_frame()
    mels_stacked.rename(columns =  {0:"pattern"}, inplace = True)
    # edit distance, based on side-by-side comparison of melodic ngrams
    # gets flexed and other similar soggetti
    dist = self.flexed_distance(head_flex, entries)
    dist_stack = dist.stack().to_frame()
    # # filter distances to threshold.  <2 is good
    distance_factor = body_flex + 1
    filtered_dist_stack = dist_stack[dist_stack[0] < distance_factor]
    filtered_dist = filtered_dist_stack.reset_index()
    filtered_dist.rename(columns =  {'level_0':"source", 'level_1':'match'}, inplace = True)
    # # Group the filtered distanced patterns
    full_list_of_matches = filtered_dist.groupby('source')['match'].apply(list).reset_index()

    list_temps = []
    # # classification without hidden types
    if include_hidden_types == False:
        for matches in full_list_of_matches["match"]:
            related_entry_list = mels_stacked[mels_stacked['pattern'].isin(matches)]
            entry_array = related_entry_list.reset_index(level=1).rename(columns = {'level_1': "voice", 0: "pattern"})
            dfs = self._split_dataframe(entry_array, "index", 70)
            # classification of the full set
            for df in dfs:
                temp = self._temp_dict_of_details(df, det, matches)
                # print(temp)
                if temp in list_temps:
                    pass
                else:
                    list_temps.append(temp)
        points = pd.DataFrame(list_temps)
        if not points.empty:
            points["Count_Offsets"] = points["Offsets"].apply(lambda lyst: len(set(lyst)))
            points = points[points["Count_Offsets"] > 1]
            points["Count_Voices"] = points["Voices"].apply(lambda lyst: len(set(lyst)))
            points = points[points["Count_Voices"] > 1]
            points['Presentation_Type'] = points['Time_Entry_Intervals'].apply(ImportedPiece._classify_by_offset)
            points["Offsets_Key"] = points["Offsets"].apply(self._offset_joiner)
            points['Flexed_Entries'] = points["Soggetti"].apply(len) > 1
            points["Number_Entries"] = points["Offsets"].apply(len)
            if len(points) == 0:
                print("No Presentation Types Found in " + self.metadata['composer'] + ":" + self.metadata['title'])
            else:
                points = points.reindex(columns=col_order).sort_values("First_Offset")
                # applying various private functions for overlapping entry tests.
                # note that ng_durs must be passed to the first of these, via args
                points["Entry_Durs"] = points[["Offsets", "Voices"]].apply(ImportedPiece._dur_ngram_helper, args=(ng_durs,), axis=1)
                points["Overlaps"] = points[["Entry_Durs", "Offsets"]].apply(ImportedPiece._entry_overlap_helper, axis=1)
                points["Count_Non_Overlaps"] = points["Overlaps"].apply(ImportedPiece._non_overlap_count)
                points.drop(['Count_Offsets', 'Offsets_Key', 'Entry_Durs', 'Overlaps'], axis=1, inplace=True)
                points["Progress"] = (points["First_Offset"] / self.notes().index[-1])        
                points = points.sort_values("Progress")
                points = points.reset_index(drop=True)
                self.analyses[memo_key] = points
                return points

    # classification with hidden types
    elif include_hidden_types == True:
        # hidden_types_list = ["PEN", "ID"]
        for matches in full_list_of_matches["match"]:
            related_entry_list = mels_stacked[mels_stacked['pattern'].isin(matches)]
            entry_array = related_entry_list.reset_index(level=1).rename(columns = {'level_1': "voice", 0: "pattern"})

            split_list = list(ImportedPiece._split_by_threshold(entry_array.index))
            for item in split_list:
                # the initial classification of the full set
                df = entry_array.loc[item].reset_index()
                if len(df) > 1:
                # df = df.reset_index()
                    temp = self._temp_dict_of_details(df, det, matches)
                    list_temps.append(temp)

                if len(item) > 2 :
                    # make range from 2 to allow for fugas needed in NIMs
                    for r in range(3, 6):
                        list_combinations = list(combinations(item, r))
                        for slist in list_combinations:
                            df = entry_array.loc(axis=0)[slist].reset_index()
                            temp = self._temp_dict_of_details(df, det, matches)
                            list_temps.append(temp)
        # 8/24 patch for empty lists
        if len(list_temps) == 0:
            print("No Hidden Types Found in " + self.metadata['composer'] + ":" + self.metadata['title'])
        else:
            points = pd.DataFrame(list_temps)
            if not points.empty:
                points["Count_Offsets"] = points["Offsets"].apply(lambda lyst: len(set(lyst)))
                points = points[points["Count_Offsets"] > 1]
                points = points[points["Voices"].apply(lambda lyst: len(set(lyst))) > 1]
                points['Presentation_Type'] = points['Time_Entry_Intervals'].apply(ImportedPiece._classify_by_offset)
                points["Offsets_Key"] = points["Offsets"].apply(self._offset_joiner)
                points['Flexed_Entries'] = points["Soggetti"].apply(len) > 1
                points["Number_Entries"] = points["Offsets"].apply(len)
                # return points
                if len(points) == 0:
                    print("No Presentation Types Found in " + self.metadata['composer'] + ":" + self.metadata['title'])
                else:
                    points = points.reindex(columns=col_order).sort_values("First_Offset")
                    points.drop_duplicates(subset=["Offsets_Key"], keep='first', inplace=True)
                    # applying various private functions for overlapping entry tests.
                    # note that ng_durs must be passed to the first of these, via args
                    points["Entry_Durs"] = points[["Offsets", "Voices"]].apply(ImportedPiece._dur_ngram_helper, args=(ng_durs,), axis=1)
                    points["Overlaps"] = points[["Entry_Durs", "Offsets"]].apply(ImportedPiece._entry_overlap_helper, axis=1)
                    # points["Count_Non_Overlaps"] = points["Overlaps"].apply(ImportedPiece._non_overlap_count)
                    points.drop(['Count_Offsets', 'Offsets_Key', 'Entry_Durs', 'Overlaps'], axis=1, inplace=True)
                    points["Progress"] = (points["First_Offset"] / self.notes().index[-1])
                    # return points
                    points = points.sort_values("Progress")
                    points = points.reset_index(drop=True)
                    self.analyses[memo_key] = points
                    return points

regularize

regularize(df, unit=2)

Return the passed pandas.DataFrame (df) with its observations regularized rhythmically. Pass a duration as the unit parameter to control at what regular distance observations will be made. Durations are measured according to the music21 convention where:

  • eighth note = .5
  • quarter note = 1
  • half note = 2
  • whole note = 4

For example, if you pass a dataframe of the notes and rests of a piece, and set unit to 4, a new df that records whatever is "sounding" (whether a note or a rest) at every regular whole note will be kept, and any intervening notes or rests will be removed. A breve would be renotated as two whole notes.

Typical use:

nr = importedPiece.notes()
nr_reg = importedPiece.regularize(nr, unit=4)

Regularization also works with non-integer values. So if you wanted to regularize at the swung eighth note, for example, you could set:

unit=1/3

Source code in crim_intervals/main_objs.py
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
def regularize(self, df, unit=2):
    '''
    Return the passed `pandas.DataFrame` (df) with its observations
    regularized rhythmically. Pass a duration as the `unit` parameter to
    control at what regular distance observations will be made. Durations
    are measured according to the music21 convention where:

    * eighth note = .5
    * quarter note = 1
    * half note = 2
    * whole note = 4

    For example, if you pass a dataframe of the notes and rests of a piece,
    and set `unit` to 4, a new df that records whatever is "sounding" (whether a note or a
    rest) at every regular whole note will be kept, and any intervening
    notes or rests will be removed. A breve would be renotated as two
    whole notes.

    Typical use:

    ```python
    nr = importedPiece.notes()
    nr_reg = importedPiece.regularize(nr, unit=4)
    ```

    Regularization also works with non-integer values. So if you wanted to
    regularize at the swung eighth note, for example, you could set:

    `unit=1/3`
    '''
    spot = df.index[0] * 1000
    end = self.score.highestTime * 1000
    vals = []
    step = unit * 1000
    while spot < end:
        vals.append(spot)
        spot += step
    new_index = pd.Index(vals).map(lambda i: round(i) / 1000)
    res = df.ffill().reindex(new_index, method='pad')
    return res

sonorities

sonorities(kind='d', directed=True, compound='simple', sort=True)

Return a dataframe of sonorities that are similar to a continuo part but not reduced.

There is a sonority observed every time any part in the piece has an attack. The kind, directed, and compound parameters are passed unchanged to .harmonic and will control the type of intervals used. In all cases Rests are ignored.

sort will sort the values before returning them, and remove duplicates as well as any unisons against the lowest line.

Source code in crim_intervals/main_objs.py
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
@_records_settings('sonorities', ('kind', 'directed', 'compound', 'sort'), inherit=())
def sonorities(self, kind='d', directed=True, compound='simple', sort=True):
    """
    Return a dataframe of sonorities that are similar to a continuo part but not reduced.

    There is a sonority observed every time any part in the piece has an attack. The
    `kind`, `directed`, and `compound` parameters are passed unchanged to .harmonic and
    will control the type of intervals used. In all cases Rests are ignored. 

    `sort` will sort the values before returning them, and remove duplicates as well as any unisons
    against the lowest line.
    """
    har = self.harmonic(kind=kind, directed=directed, compound=compound, againstLow=True).ffill()

    if sort:
        son = har.apply(self._sort_and_join_intervals, axis=1)
    else:
        son = har.apply(lambda row: '/'.join([note for note in row.unique() if note != 'Rest']), axis=1)

    son.name = 'Sonority'
    return pd.DataFrame(son)

sonority_ngrams

sonority_ngrams(ngram_length=4, metadata_choice=True, include_offset=False, include_progress=True, compound=True, sort=False, minimum_beat_strength=0.0, key_sig=False, include_final=False)

Generate sonority n-grams (plus bassline) in this piece. These are complex n-grams that combine the sonority (chord) formed by all tones sounding at each moment with the melodic interval formed by the low line (bass) of each sonority, joined as 'Low_Sonority'.

Sonorities on weak beats (beat strength at or below minimum_beat_strength) can be filtered out.

CorpusBase.sonority_ngrams runs this on every piece in a corpus.

Parameters:

Name Type Description Default
ngram_length int (default 4)

Number of Low_Sonority events in each n-gram.

4
metadata_choice bool (default True)

Whether to add Composer/Title/Date columns.

True
include_offset bool

Whether detailIndex should also include each row's raw offset.

False
include_progress bool (default True)

Whether detailIndex should include the 0-1 progress-through-piece column.

True
compound

Passed through to ImportedPiece.sonorities.

True
sort

Passed through to ImportedPiece.sonorities.

True
minimum_beat_strength float (default 0.0)

Keep only sonorities on beats stronger than this.

0.0
key_sig bool, optional (default False)

If True, add the prevailing system key signature to the row index via detailIndex, alongside Measure/Beat.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving the piece's final tone.

False

Returns:

Type Description
DataFrame

One row per n-gram, with Measure, Beat (and Offset, Progress) as columns. The settings used are stored in df.attrs['sonority_ngram_settings'].

Examples:

>>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
>>> son = piece.sonority_ngrams(ngram_length=4)
Source code in crim_intervals/main_objs.py
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
@_records_settings('sonority_ngrams', ('ngram_length', 'minimum_beat_strength', 'compound', 'sort'),
                   inherit=())
def sonority_ngrams(self,
                    ngram_length=4,
                    metadata_choice=True,
                    include_offset=False,
                    include_progress=True,
                    compound=True,
                    sort=False,
                    minimum_beat_strength=0.0,
                    key_sig=False,
                    include_final=False):
    """
    Generate sonority n-grams (plus bassline) in this piece.
    These are complex n-grams that combine the sonority (chord) formed by
    all tones sounding at each moment with the melodic interval formed by
    the low line (bass) of each sonority, joined as 'Low_Sonority'.

    Sonorities on weak beats (beat strength at or below
    `minimum_beat_strength`) can be filtered out.

    CorpusBase.sonority_ngrams runs this on every piece in a corpus.

    Parameters
    ----------
    ngram_length : int (default 4)
        Number of Low_Sonority events in each n-gram.
    metadata_choice : bool (default True)
        Whether to add Composer/Title/Date columns.
    include_offset : bool
        Whether detailIndex should also include each row's raw offset.
    include_progress : bool (default True)
        Whether detailIndex should include the 0-1 progress-through-piece column.
    compound, sort
        Passed through to ImportedPiece.sonorities.
    minimum_beat_strength : float (default 0.0)
        Keep only sonorities on beats stronger than this.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature to the row index
        via detailIndex, alongside Measure/Beat.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving the piece's final tone.

    Returns
    -------
    pd.DataFrame
        One row per n-gram, with Measure, Beat (and Offset, Progress) as
        columns. The settings used are stored in
        `df.attrs['sonority_ngram_settings']`.

    Examples
    --------
    >>> piece = importScore('https://crimproject.org/mei/CRIM_Model_0008.mei')
    >>> son = piece.sonority_ngrams(ngram_length=4)
    """
    bs = self.beatStrengths()
    strong_beat_positions = bs[(bs > minimum_beat_strength).any(axis=1)].index

    son = self.sonorities(sort=sort, compound=compound)
    son = son[son['Sonority'] != '']
    son = son[son.index.isin(strong_beat_positions)]

    low = self.lowLine()
    low = pd.DataFrame(low[low.index.isin(strong_beat_positions)])
    low_mel = self.melodic(end=False, df=low)

    combined = pd.merge(son, low_mel, left_index=True, right_index=True, how='left')
    combined['Low Line'] = combined['Low Line'].fillna('Held')
    combined['Low_Sonority'] = combined['Low Line'] + "_" + combined['Sonority']

    res = self.ngrams(df=combined, n=ngram_length)
    res = self.detailIndex(res, offset=include_offset, progress=include_progress, key_sig=key_sig)
    res = self.numberParts(res)
    if len(res) > 0:
        res['Low_Sonority'] = res['Low_Sonority'].apply(
            lambda x: tuple_to_string(x, separator='_') if isinstance(x, tuple) else x)
    if include_final:
        res['Final'] = self.final()
    if metadata_choice:
        res[['Composer', 'Title', 'Date']] = (self.metadata['composer'], self.metadata['title'],
                                              self.metadata['date'])
        cols_to_move = ['Composer', 'Title', 'Date']
        res = res[cols_to_move + [c for c in res.columns if c not in cols_to_move]]
    res = res.reset_index()
    # the sonorities/ngrams settings picked up along the way are covered
    # by this method's own settings (recorded by the decorator)
    res.attrs = {}
    return res

soundingCount

soundingCount()

Return a series with the number of parts that currently sounding.

This information is included the .cadences method so you can filter cadence results based on how many voices are sounding at the time of the cadence. It is also available in the .detailIndex method to add this information to almost any dataframe CRIM-Intervals provides.

Source code in crim_intervals/main_objs.py
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
def soundingCount(self):
    """
    Return a series with the number of parts that currently sounding.

    This information is included the .cadences method so you can filter cadence
    results based on how many voices are sounding at the time of the cadence.
    It is also available in the `.detailIndex` method to add this information to
    almost any dataframe CRIM-Intervals provides.
    """
    if not 'SoundingCount' in self.analyses:
        nr = self.notes().ffill()
        df = nr[nr != 'Rest']
        ser = df.count(axis=1)
        ser.name = 'Sounding'
        self.analyses['SoundingCount'] = ser
    return self.analyses['SoundingCount']

supplementum

supplementum()

Return the portion of the piece that corresponds to the supplementum, or what is often called a Plagal Coda. This is defined as part after the last [Authentic] cadence in the piece.

Source code in crim_intervals/main_objs.py
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
def supplementum(self):
    '''
    Return the portion of the piece that corresponds to the supplementum, or what is often called a Plagal Coda. 
    This is defined as part after the last [Authentic] cadence in the piece.'''
    if 'Supplementum' not in self.analyses:
        cads = self.cadences()
        if cads['Progress'].iat[-1] == 1:
            supp = None
        else:
            lastCad = cads.index[-1]
            supp = self.notes().loc[lastCad:]
        self.analyses['Supplementum'] = supp
    return self.analyses['Supplementum']

timeSignatures

timeSignatures()

Return a data frame containing the time signatures and their offsets.

This is useful for getting the prevailing time signature at any given moment in the piece. The time signature is expressed as a string taken from music21's .ratioString attribute. For example, 4/4 time is expressed as "4/4", 3/4 time is expressed as "3/4", etc.

Source code in crim_intervals/main_objs.py
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
def timeSignatures(self):
    """
    Return a data frame containing the time signatures and their offsets.

    This is useful for getting the prevailing time signature at any given
    moment in the piece. The time signature is expressed as a string taken
    from music21's `.ratioString` attribute. For example, 4/4 time is
    expressed as "4/4", 3/4 time is expressed as "3/4", etc.
    """
    if 'TimeSignature' not in self.analyses:
        df = self._getM21TSigObjs()
        df = df.map(lambda ts: ts.ratioString, na_action='ignore')
        df.columns = self._getPartNames()
        self.analyses['TimeSignature'] = df
    return self.analyses['TimeSignature']

tuple_to_list

tuple_to_list(value, separator=None, cast=None)

Convert tuple-like values to a list using the shared helper.

Source code in crim_intervals/main_objs.py
283
284
285
def tuple_to_list(self, value, separator=None, cast=None):
    """Convert tuple-like values to a list using the shared helper."""
    return tuple_to_list(value, separator=separator, cast=cast)

tuple_to_string

tuple_to_string(value, separator=', ')

Convert tuple-like values to a string using the shared helper.

Source code in crim_intervals/main_objs.py
287
288
289
def tuple_to_string(self, value, separator=', '):
    """Convert tuple-like values to a string using the shared helper."""
    return tuple_to_string(value, separator=separator)

verovioCadences

verovioCadences(df=None, highlights=False, highlight_color='#d62728')

This function is used to display the results of the Cadence classifier in the Notebook with Verovio (learn more at: https://www.verovio.org/index.xhtml). Each excerpt is three measures long: the measure of the final tone of the cadence and the measures before and after it (only two for a cadence in the final bar).

The function also displays metadata about each excerpt, drawn from the cadence results dataframe: piece ID, composer, title, measures, type of cadence, beat of the bar in which the final tone is heard, and evaded status.

Parameters:

Name Type Description Default
df DataFrame

The (optionally filtered) result of piece.cadences(). None (default) runs piece.cadences().

None
highlights bool, optional (default False)

If True, colour the arrival notes of each cadence: the notes sounding at the cadence's Offset in the voices that take part in it (its cadential voice functions). Requires an MEI source.

False
highlight_color str

CSS colour for the highlighted notes (default red, '#d62728').

'#d62728'

Examples:

You will need to run cadences = piece.cadences() in order to build the initial set of results, then pass these results to the Verovio print function:

cadences = piece.cadences()
piece.verovioCadences(cadences)

It is also possible to pass a filtered list of cadences to this function by specifying a df into verovioCadences()` as shown below:

cadences = piece.cadences()
cadences_filtered = cadences[cadences['Tone'] == 'G']
piece.verovioCadences(cadences_filtered)

To show the arrival notes of each cadence in red:

piece.verovioCadences(cadences_filtered, highlights=True)
Source code in crim_intervals/main_objs.py
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
def verovioCadences(self, df=None, highlights=False, highlight_color=HIGHLIGHT_COLOR):
    """
    This function is used to display the results of the Cadence
    classifier in the Notebook with Verovio (learn more at:  https://www.verovio.org/index.xhtml).  Each excerpt is
    three measures long:  the measure of the final tone of the cadence
    and the measures before and after it (only two for a cadence in the
    final bar).

    The function also displays metadata about each excerpt, drawn from the
    cadence results dataframe:  piece ID, composer, title, measures, type of
    cadence, beat of the bar in which the final tone is heard, and evaded
    status.

    Parameters
    ----------
    df : pandas.DataFrame, optional
        The (optionally filtered) result of `piece.cadences()`. None
        (default) runs `piece.cadences()`.
    highlights : bool, optional (default False)
        If True, colour the arrival notes of each cadence: the notes
        sounding at the cadence's Offset in the voices that take part in it
        (its cadential voice functions). Requires an MEI source.
    highlight_color : str, optional
        CSS colour for the highlighted notes (default red, '#d62728').

    Examples
    --------
    You will need to run cadences = piece.cadences() in order to build the
    initial set of results, then pass these results to the Verovio print function:

    ```python
    cadences = piece.cadences()
    piece.verovioCadences(cadences)
    ```

    It is also possible to pass a filtered list of cadences to this function
    by specifying a df into `verovioCadences`()` as shown below:

    ```python
    cadences = piece.cadences()
    cadences_filtered = cadences[cadences['Tone'] == 'G']
    piece.verovioCadences(cadences_filtered)
    ```

    To show the arrival notes of each cadence in red:

    ```python
    piece.verovioCadences(cadences_filtered, highlights=True)
    ```
    """
    tk = self._verovioToolkit(page_width=1500)
    # adding option to import filtered df of cadences
    if df is None:
        cadences = self.cadences()
    else:
        cadences = df
    part_maps = {}
    if highlights and 'PartMap' not in cadences.columns:
        # voice_detail adds the PartMap (CVF -> staff numbers); cadences() is memoized
        full = self.cadences(voice_detail=True)
        part_maps = dict(zip(full['Offset'], full['PartMap']))
    found_any = 0
    for cad, row in cadences.iterrows():
        c_meas = row["Measure"]
        c_tone = row["Tone"]
        c_type = row["CadType"]
        c_beat = row["Beat"]
        cvfs = row['CVFs']
        low = int(c_meas-1)
        high = int(c_meas+1)   # clamped to the final bar in _verovioPages
        ids = []
        if highlights:
            offset = row['Offset'] if 'Offset' in row.index else self._offsetAt(c_meas, c_beat)
            part_map = row['PartMap'] if 'PartMap' in row.index else part_maps.get(offset)
            if offset is not None:
                voices = [num for nums in part_map.values() for num in nums] if part_map else None
                ids = self._noteIdsAtOffset(offset, voices)

        # select verovio measures, redo layout and render
        pages, found = self._verovioPages(tk, low, high, ids, highlight_color)
        found_any += found

        # get the number of pages and display the music
        print("Results:")
        for music in pages:
            print("File Name: ", self.file_name)
            print(self.metadata['composer'])
            print(self.metadata['title'])
            print("Cadence End Measure:", c_meas)
            print("Beat: ", c_beat)
            print("Cadence Tone: ", c_tone)
            print("Cadence Type: ", c_type)
            print("Cadential Voice Functions: ", cvfs)
            display(HTML(music))
    self._reportHighlights(highlights and len(cadences), found_any)

verovioHomorhythm

verovioHomorhythm(df=None, ngram_length=4, full_hr=True, highlights=False, highlight_color='#d62728')

Prints HR passages for a given piece with Verovio (learn more at: https://www.verovio.org/index.xhtml), based on imported piece and other parameters.

Parameters:

Name Type Description Default
df DataFrame

None (default) runs piece.homorhythm() internally using ngram_length and full_hr. Alternatively, pass the (optionally filtered) result of piece.homorhythm() to render just those passages.

None
ngram_length int, optional (default 4)

Determines the number of durations and syllables that must be in common among the voices in order to be marked as HR.

4
full_hr bool, optional (default True)

When True the method will find any passage where all active voices share the same durational ngram and syllables; if False the method will find any passage where even two voices share the same durational ngram and the same syllables.

True
highlights bool, optional (default False)

If True, colour the notes of the homorhythmic voices in each passage: for every row, ngram_length notes from the row's offset in each of its hr_voices. Requires an MEI source.

False
highlight_color str

CSS colour for the highlighted notes (default red, '#d62728').

'#d62728'

Examples:

piece.verovioHomorhythm()

Or with custom parameters:

piece.verovioHomorhythm(ngram_length=5, full_hr=False)

To show the homorhythmic voices in red:

piece.verovioHomorhythm(highlights=True)

It is also possible to run piece.homorhythm(), then filter the results in some way and pass those results to the print function:

# run hr function and convert hr['syllable_set'] to string
hr = piece.homorhythm(ngram_length=6, full_hr=True).fillna('')
hr["hr_voices"] = hr["hr_voices"].apply(lambda x: ', '.join(map(str, x))).copy()

# supply names of voices. They must match the voice names in `piece.notes.columns()`
chosen_voices = ["Tenor", "Bassus"]
# filter the results for hr passages involving chosen voices:
hr_with_chosen_voices = hr[hr.apply(lambda x: hr['hr_voices'].str.contains('|'.join(chosen_voices)))].dropna()

# render just the hr_with_chosen_voices using `piece.verovioHomorhythm()`:
piece.verovioHomorhythm(hr_with_chosen_voices)
Source code in crim_intervals/main_objs.py
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
def verovioHomorhythm(self, df=None, ngram_length=4, full_hr=True,
                      highlights=False, highlight_color=HIGHLIGHT_COLOR):
    '''
    Prints HR passages for a given piece with Verovio (learn more at:  https://www.verovio.org/index.xhtml), based on imported piece and
    other parameters.

    Parameters
    ----------
    df : pandas.DataFrame, optional
        None (default) runs `piece.homorhythm()` internally using
        `ngram_length` and `full_hr`. Alternatively, pass the (optionally
        filtered) result of `piece.homorhythm()` to render just those
        passages.
    ngram_length : int, optional (default 4)
        Determines the number of durations and syllables that must be in
        common among the voices in order to be marked as HR.
    full_hr : bool, optional (default True)
        When True the method will find any passage where _all active
        voices_ share the same durational ngram and syllables; if False
        the method will find any passage where even _two voices_ share
        the same durational ngram and the same syllables.
    highlights : bool, optional (default False)
        If True, colour the notes of the homorhythmic voices in each
        passage: for every row, `ngram_length` notes from the row's offset
        in each of its `hr_voices`. Requires an MEI source.
    highlight_color : str, optional
        CSS colour for the highlighted notes (default red, '#d62728').

    Examples
    --------
    ```python
    piece.verovioHomorhythm()
    ```

    Or with custom parameters:

    ```python
    piece.verovioHomorhythm(ngram_length=5, full_hr=False)
    ```

    To show the homorhythmic voices in red:

    ```python
    piece.verovioHomorhythm(highlights=True)
    ```

    It is also possible to run `piece.homorhythm()`, then filter the
    results in some way and pass those results to the print function:

    ```python
    # run hr function and convert hr['syllable_set'] to string
    hr = piece.homorhythm(ngram_length=6, full_hr=True).fillna('')
    hr["hr_voices"] = hr["hr_voices"].apply(lambda x: ', '.join(map(str, x))).copy()

    # supply names of voices. They must match the voice names in `piece.notes.columns()`
    chosen_voices = ["Tenor", "Bassus"]
    # filter the results for hr passages involving chosen voices:
    hr_with_chosen_voices = hr[hr.apply(lambda x: hr['hr_voices'].str.contains('|'.join(chosen_voices)))].dropna()

    # render just the hr_with_chosen_voices using `piece.verovioHomorhythm()`:
    piece.verovioHomorhythm(hr_with_chosen_voices)
    ```
    '''
    tk = self._verovioToolkit(page_width=3000)

    # Now get meas ranges and number of active voices
    if df is None:
        homorhythm = self.homorhythm(ngram_length=ngram_length, full_hr=full_hr)
    else:
        homorhythm = df
    hr_list = list(homorhythm.index.get_level_values('Measure').tolist())
    #Get the groupings of consecutive items
    short_list =sorted(list(set(hr_list)))
    li = [list(item) for item in consecutive_groups(short_list)]
    row_offsets = self._rowOffsets(homorhythm) if highlights else []
    found_any = 0

    # adjusts number of measures to display based on length of each span
    # of adjacent bars.
    # This matters for long 'n'
    for span in li:
        if ngram_length > 4:
            if len(span) == 1:
                low, high = int(span[0]), int(span[0] + 3)
            else:
                low, high = int(span[0]), int(span[-1] + 1)
        else:
            low, high = int(span[0]), int(span[-1] + 1)
        min_hr_count = 20
        max_hr_count = 0

        # for n in range(span[0], span[-1]+1):
        for n in range(int(span[0]), int(span[-1]) +  1):
            ma = 0
            mi = 20
            for item in homorhythm.loc[n]['hr_voices'].to_list():
                if len(item) > ma:
                    ma = len(item)
                if len(item) < mi:
                    mi = len(item)
                if ma > max_hr_count:
                    max_hr_count = ma
                if mi < min_hr_count:
                    min_hr_count = mi

        ids = []
        if highlights:
            in_span = homorhythm.index.get_level_values('Measure').isin(span)
            spans = []
            for (_, row), offset, keep in zip(homorhythm.iterrows(), row_offsets, in_span):
                if not keep or offset is None:
                    continue
                voices = row['hr_voices']
                if isinstance(voices, str):   # e.g. joined with ', ' for filtering
                    voices = [v.strip() for v in voices.split(',') if v.strip()]
                n_notes = int(row['ngram_length']) if 'ngram_length' in row.index else ngram_length
                spans += [self._noteIdsInSpan(v, offset, n_notes) for v in voices]
            ids, span_range = self._mergeSpans(spans)
            if span_range:   # show the last passage in full
                high = max(high, int(span_range[1]))

        # select verovio measures and redo layout for each passage
        pages, found = self._verovioPages(tk, low, high, ids, highlight_color)
        found_any += found
        # get the number of pages and display the music for each passage
        print("Results:")
        print("File Name: ", self.file_name)
        print(self.metadata['composer'])
        print(self.metadata['title'])
        print("HR Start Measure: ", span[0])
        print("HR Stop Measure: ", span[-1])
        print("Minimum Number of HR Voices: ", min_hr_count)
        print("Maximum Number of HR Voices: ", max_hr_count)

        for music in pages:
            display(SVG(music))
    self._reportHighlights(highlights and len(li), found_any)

verovioNgrams

verovioNgrams(df, highlights=False, highlight_color='#d62728', combine_unisons=None, end=None)

Display the passages behind a table of n-grams with Verovio (learn more at: https://www.verovio.org/index.xhtml): one excerpt per row of df, covering the measures of every n-gram in that row, with a caption listing each voice's n-gram.

Works with the results of piece.ngrams() on melodic intervals or notes, and of piece.entries(), with columns for single voices (part names, or staff numbers from numberParts). The index may be plain offsets, the 'First'/'Last' index of ngrams(offsets='both'), or a detailIndex with an Offset level or Measure and Beat levels.

Filter the table first: a full n-gram table has a row for nearly every offset in the piece.

Parameters:

Name Type Description Default
df DataFrame

The (filtered) n-grams to show.

required
highlights bool, optional (default False)

If True, colour the notes of each n-gram. Requires an MEI source.

False
highlight_color str

CSS colour for the highlighted notes (default red, '#d62728').

'#d62728'
combine_unisons bool

How the notes were counted. By default these are read from the settings that crim_intervals records on the result (the notes() combineUnisons and melodic() end settings); pass them only if those settings were lost, e.g. after reading the table from a CSV.

None
end bool

How the notes were counted. By default these are read from the settings that crim_intervals records on the result (the notes() combineUnisons and melodic() end settings); pass them only if those settings were lost, e.g. after reading the table from a CSV.

None

Examples:

Show where one soggetto occurs, with its notes in red:

mel = piece.melodic(kind='d', end=False)
ngrams = piece.ngrams(df=mel, n=4)
soggetto = ('2', '2', '-3', '2')
matches = ngrams[ngrams.isin([soggetto])].dropna(how='all')
piece.verovioNgrams(matches, highlights=True)

Or show each entry (n-grams that follow a rest):

entries = piece.entries(n=4)
piece.verovioNgrams(entries.head(10), highlights=True)
Source code in crim_intervals/main_objs.py
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
def verovioNgrams(self, df, highlights=False, highlight_color=HIGHLIGHT_COLOR,
                  combine_unisons=None, end=None):
    '''
    Display the passages behind a table of n-grams with Verovio (learn more
    at:  https://www.verovio.org/index.xhtml): one excerpt per row of `df`,
    covering the measures of every n-gram in that row, with a caption
    listing each voice's n-gram.

    Works with the results of `piece.ngrams()` on melodic intervals or
    notes, and of `piece.entries()`, with columns for single voices (part
    names, or staff numbers from `numberParts`). The index may be plain
    offsets, the 'First'/'Last' index of `ngrams(offsets='both')`, or a
    `detailIndex` with an Offset level or Measure and Beat levels.

    Filter the table first: a full n-gram table has a row for nearly every
    offset in the piece.

    Parameters
    ----------
    df : pandas.DataFrame
        The (filtered) n-grams to show.
    highlights : bool, optional (default False)
        If True, colour the notes of each n-gram. Requires an MEI source.
    highlight_color : str, optional
        CSS colour for the highlighted notes (default red, '#d62728').
    combine_unisons, end : bool, optional
        How the notes were counted. By default these are read from the
        settings that crim_intervals records on the result (the `notes()`
        combineUnisons and `melodic()` end settings); pass them only if
        those settings were lost, e.g. after reading the table from a CSV.

    Examples
    --------
    Show where one soggetto occurs, with its notes in red:

    ```python
    mel = piece.melodic(kind='d', end=False)
    ngrams = piece.ngrams(df=mel, n=4)
    soggetto = ('2', '2', '-3', '2')
    matches = ngrams[ngrams.isin([soggetto])].dropna(how='all')
    piece.verovioNgrams(matches, highlights=True)
    ```

    Or show each entry (n-grams that follow a rest):

    ```python
    entries = piece.entries(n=4)
    piece.verovioNgrams(entries.head(10), highlights=True)
    ```
    '''
    settings = get_settings(df)
    ng = settings.get('ngrams') or settings.get('entries') or {}
    melodic_settings = settings.get('melodic')
    if combine_unisons is None:
        combine_unisons = settings.get('notes', {}).get('combineUnisons', False)
    # n-grams of intervals span one more note than they have items; n-grams of
    # notes span exactly as many. Without settings, assume melodic intervals.
    is_melodic = melodic_settings is not None or 'notes' not in settings
    if end is None:
        end = melodic_settings.get('end', True) if melodic_settings else True
    mode = 'first' if 'First' in df.index.names else settings.get('ngrams', {}).get('offsets', 'first')
    n_setting = ng.get('n')

    def _span_args(cell):
        """(n_notes, before) for one n-gram cell."""
        if isinstance(cell, (tuple, list)):
            n = len(cell)
        elif isinstance(n_setting, int) and n_setting > 0:
            n = n_setting
        else:
            n = len(str(cell).split('_'))
        if not is_melodic:
            return n, (n - 1 if mode == 'last' else 0)
        n_notes = n + 1
        if mode == 'last':   # offset of the last interval: its second note, or its first
            return n_notes, (n_notes - 1 if end else n_notes - 2)
        return n_notes, (1 if end else 0)

    if len(df) > 100:
        print(f"Showing {len(df)} excerpts; filter the n-grams first to show fewer.")
    tk = self._verovioToolkit(page_width=3000)
    print("Results:")
    found_any = 0
    for offset, (_, row) in zip(self._rowOffsets(df), df.iterrows()):
        cells = row.dropna()
        cells = cells[[self._voiceName(c) is not None for c in cells.index]]
        if offset is None or cells.empty:
            continue
        spans = []
        for voice, cell in cells.items():
            n_notes, before = _span_args(cell)
            spans.append(self._noteIdsInSpan(voice, offset, n_notes, combine_unisons, before))
        ids, span_range = self._mergeSpans(spans)
        if span_range:
            low, high = int(span_range[0]), int(span_range[1])
        else:
            low = self._measureAtOffset(offset) or 1
            high = low + 1
        pages, found = self._verovioPages(tk, low, high, ids if highlights else (), highlight_color)
        found_any += found

        print("File Name: ", self.file_name)
        print(self.metadata['composer'])
        print(self.metadata['title'])
        print("Measures:", f"{low}-{high}")
        print("Offset:", offset)
        for voice, cell in cells.items():
            shown = ', '.join(map(str, cell)) if isinstance(cell, (tuple, list)) else cell
            print(f"{voice}: {shown}")
        for music in pages:
            display(HTML(music))
    self._reportHighlights(highlights and len(df), found_any)

verovioPrintExample

verovioPrintExample(start, stop, highlight_ids=None, highlight_color='#d62728')

Pass a range of measures (as integers) to print the given range (learn more at: https://www.verovio.org/index.xhtml).

For last measure you can also use '-1', thus for all measures:

piece.verovioPrintExample(1, -1)

Pass a list of MEI xml:ids as highlight_ids to colour those notes (red by default; set highlight_color to change it). Each note's xml:id is its music21 .id, so ids can be gathered from the piece's notes, e.g. every note in the Tenor in measures 1-4:

objs = piece._getM21Objs()['Tenor'].dropna()
ids = [n.id for n in objs if n.isNote and n.measureNumber <= 4]
piece.verovioPrintExample(1, 4, highlight_ids=ids)
Source code in crim_intervals/main_objs.py
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
def verovioPrintExample(self, start, stop, highlight_ids=None, highlight_color=HIGHLIGHT_COLOR):

    """
    Pass a range of measures (as integers) to print the given range (learn more at:  https://www.verovio.org/index.xhtml).

    For last measure you can also use '-1', thus for all measures:

    ```python
    piece.verovioPrintExample(1, -1)
    ```

    Pass a list of MEI xml:ids as `highlight_ids` to colour those notes
    (red by default; set `highlight_color` to change it). Each note's
    xml:id is its music21 `.id`, so ids can be gathered from the piece's
    notes, e.g. every note in the Tenor in measures 1-4:

    ```python
    objs = piece._getM21Objs()['Tenor'].dropna()
    ids = [n.id for n in objs if n.isNote and n.measureNumber <= 4]
    piece.verovioPrintExample(1, 4, highlight_ids=ids)
    ```
    """
    tk = self._verovioToolkit(page_width=3000)

    if stop == -1:
        meas = self.measures()
        stop = meas.iloc[-1].tolist()[0]

    mr = str(start) + "-" + str(stop)

    if stop < start:
        print("Check the measure range, the stop measure must be equal to or greater than the start measure")
    else:# select verovio measures and redo layout
        pages, found = self._verovioPages(tk, start, stop, highlight_ids, highlight_color)

        # get the number of pages and display the music
        print("Score:")
        for music in pages:
            print("File Name: ", self.file_name)
            print(self.metadata['composer'])
            print(self.metadata['title'])
            print("Measures: " + mr)
            display(HTML(music))
        self._reportHighlights(bool(highlight_ids), found)

verovioPtypes

verovioPtypes(p_types=None, highlights=False, highlight_color='#d62728')

This function is used to display the results of the presentationTypes function in the Notebook with Verovio (learn more at: https://www.verovio.org/index.xhtml). Each excerpt begins with the first measure of the given presentation type and continues through four measures after the last entry.

The function also displays metadata about each excerpt, drawn from the presentation type dataframe: piece ID, composer, title, measure range, presentation type, voices in order of entry, number of entries, the soggetti , melodic entry intervals, time entry intervals.

Parameters:

Name Type Description Default
p_types DataFrame

The (optionally filtered) result of piece.presentationTypes(). None (default) runs piece.presentationTypes().

None
highlights bool, optional (default False)

If True, colour the notes of every entry's soggetto. Notes are counted with the melodic_ngram_length and combine_unisons settings that presentationTypes() recorded on the result, and the excerpt is extended if needed so the last entry is shown in full. Requires an MEI source.

False
highlight_color str

CSS colour for the highlighted notes (default red, '#d62728').

'#d62728'

Examples:

You must first run p_types to build the initial list of results and define these as a new variable name "p_types":

p_types = piece.presentationTypes()

Note that there are many options in the presentationTypes methods to determine the length of soggetti, degree of head or body flex, status of unisons, whether to use main entries only (or moving window of soggetti) and status of hidden entries.)

After any additional filtering, pass the results of that work to verovioPtypes:

piece.verovioPtypes(p_types)

To show the notes of each entry in red:

piece.verovioPtypes(p_types, highlights=True)
Source code in crim_intervals/main_objs.py
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
def verovioPtypes(self, p_types=None, highlights=False, highlight_color=HIGHLIGHT_COLOR):
    """
    This function is used to display the results of the presentationTypes function
    in the Notebook with Verovio (learn more at:  https://www.verovio.org/index.xhtml).  Each excerpt begins with
    the first measure of the given presentation type and continues through four
    measures after the last entry.

    The function also displays metadata about each excerpt, drawn from the
    presentation type dataframe:  piece ID, composer, title, measure range,
    presentation type, voices in order of entry, number of entries, the soggetti
    , melodic entry intervals, time entry intervals.

    Parameters
    ----------
    p_types : pandas.DataFrame, optional
        The (optionally filtered) result of `piece.presentationTypes()`.
        None (default) runs `piece.presentationTypes()`.
    highlights : bool, optional (default False)
        If True, colour the notes of every entry's soggetto. Notes are
        counted with the `melodic_ngram_length` and `combine_unisons`
        settings that `presentationTypes()` recorded on the result, and the
        excerpt is extended if needed so the last entry is shown in full.
        Requires an MEI source.
    highlight_color : str, optional
        CSS colour for the highlighted notes (default red, '#d62728').

    Examples
    --------
    You must first run p_types to build the initial list of results and define
    these as a new variable name "p_types":

    ```python
    p_types = piece.presentationTypes()
    ```

    Note that there are many options in the presentationTypes methods to
    determine the length of soggetti, degree of head or body flex, status
    of unisons, whether to use main entries only (or moving window of soggetti)
    and status of hidden entries.)

    After any additional filtering, pass the results of that work to verovioPtypes:

    ```python
    piece.verovioPtypes(p_types)
    ```

    To show the notes of each entry in red:

    ```python
    piece.verovioPtypes(p_types, highlights=True)
    ```
    """
    tk = self._verovioToolkit(page_width=3000)
    print("Results:")
    # collect the metadata
    if p_types is None:
        p_types = self.presentationTypes()
    # how the soggetti were counted, so each entry is highlighted note for note
    pt_settings = get_settings(p_types).get('presentationTypes', {})
    combine_unisons = pt_settings.get('combine_unisons', False)
    before = 1 if pt_settings.get('end', False) else 0
    found_any = 0
    for p_type, row in p_types.iterrows():
        this_p_type = row["Presentation_Type"]
        p_voices = row["Voices"]
        n_voices = row["Number_Entries"]
        soggetti = row["Soggetti"]
        mint = row["Melodic_Entry_Intervals"]
        tint = row["Time_Entry_Intervals"]
        flexed = row["Flexed_Entries"]
        ml = row["Measures_Beats"]
        parallel = row["Parallel_Voice"]
        non_overlaps = row["Count_Non_Overlaps"]

        # build the measure range dictionary
        # Find the first and last items
        first_item = ml[0]
        last_item = ml[-1]

        # Split each item at '/' and take the first part as integer
        first_part_first_item = int(float(first_item.split('/')[0]))
        first_part_last_item = int(float(last_item.split('/')[0]))

        ids = []
        stop = first_part_last_item
        if highlights:
            n_ints = pt_settings.get('melodic_ngram_length') or len(soggetti[0])
            spans = [self._noteIdsInSpan(voice, offset, n_ints + 1, combine_unisons, before)
                     for offset, voice in zip(row["Offsets"], p_voices)]
            ids, span_range = self._mergeSpans(spans)
            if span_range:   # show the last entry's soggetto in full
                stop = max(stop, int(span_range[1]))

        mr = str(first_part_first_item) + "-" + str(stop)

        # select measures in verovio, redo the layout and render
        pages, found = self._verovioPages(tk, first_part_first_item, stop, ids, highlight_color)
        found_any += found

        # print caption
        print("File Name: ", self.file_name)
        print(self.metadata['composer'])
        print(self.metadata['title'])
        print("Measures:", mr)
        print("Presentation Type: ", this_p_type)
        print("Voices: ", p_voices)
        print("Number of Entries: ", n_voices)
        print("Soggetti: ", soggetti)
        print("Melodic Entry Intervals: ", mint)
        print("Time Entry Intervals: ", tint )
        print("Flexed: ", flexed)
        print("Parallel Entries:", parallel)
        print("Number of Non-Overlapping Voices:", non_overlaps)
        # print the music
        for music in pages:
            # display(SVG(music))
            display(HTML(music))
    self._reportHighlights(highlights and len(p_types), found_any)

voice_ranges

voice_ranges(top_n=7, number_parts=True, include_final=True)

Return the range of each voice as used to distinguish modal types: the lowest and highest of the top_n pitches that take up the most time in that voice.

Taking the extremes of the most prominent pitches (rather than the absolute lowest and highest notes) keeps brief excursions from distorting the range. Pitches are ordered by sounding pitch (music21 pitch space), so e.g. B-3 is below B3.

Composer and title information are added from the source file.

Parameters:

Name Type Description Default
top_n int, optional (default 7)

How many of each voice's most prominent pitches (by share of the voice's total duration) to consider. Rests count toward the total duration but are never chosen as range notes.

7
number_parts bool, optional (default True)

If True, voices are numbered by staff position ('1' = highest), so results can be compared across pieces. If False, part names are used.

True
include_final bool, optional (default True)

If True, add a 'Final' column with the piece's final as a pitch class (see ImportedPiece.final).

True

Returns:

Type Description
DataFrame

One row per voice: Composer, Title, Voice, Final (optional), LowestNote, HighestNote, Range (e.g. 'D3 to D4'). Pass this (or the output of CorpusBase.voice_ranges) to visualizations.voice_range_chart.

Source code in crim_intervals/main_objs.py
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
@_records_settings('voice_ranges', ('top_n',), inherit=())
def voice_ranges(self, top_n=7, number_parts=True, include_final=True):
    """
    Return the range of each voice as used to distinguish modal types:
    the lowest and highest of the `top_n` pitches that take up the most
    time in that voice.

    Taking the extremes of the most prominent pitches (rather than the
    absolute lowest and highest notes) keeps brief excursions from
    distorting the range. Pitches are ordered by sounding pitch (music21
    pitch space), so e.g. B-3 is below B3.

    Composer and title information are added from the source file.

    Parameters
    ----------
    top_n : int, optional (default 7)
        How many of each voice's most prominent pitches (by share of the
        voice's total duration) to consider. Rests count toward the total
        duration but are never chosen as range notes.
    number_parts : bool, optional (default True)
        If True, voices are numbered by staff position ('1' = highest),
        so results can be compared across pieces. If False, part names
        are used.
    include_final : bool, optional (default True)
        If True, add a 'Final' column with the piece's final as a pitch
        class (see ImportedPiece.final).

    Returns
    -------
    pandas.DataFrame
        One row per voice: Composer, Title, Voice, Final (optional),
        LowestNote, HighestNote, Range (e.g. 'D3 to D4'). Pass this (or the output of
        CorpusBase.voice_ranges) to `visualizations.voice_range_chart`.
    """
    memo_key = ('voice_ranges', top_n, number_parts, include_final)
    if memo_key in self.analyses:
        return self.analyses[memo_key].copy()

    notes = self.notes()
    durs = self.durations()
    if number_parts:
        notes = self.numberParts(notes)
        durs = self.numberParts(durs)

    long = pd.DataFrame({'Notes': notes.stack(), 'Durs': durs.stack()}).dropna()
    long['Voice'] = long.index.get_level_values(-1)
    long['Durs'] = long['Durs'].astype(float)
    # sum durations first, then divide, so no per-note rounding creeps in
    totals = long.groupby('Voice')['Durs'].sum()           # includes rests
    pitched = long[long['Notes'] != 'Rest']
    per_note = pitched.groupby(['Voice', 'Notes'])['Durs'].sum().reset_index()
    per_note['Percentage'] = per_note['Durs'] / per_note['Voice'].map(totals) * 100
    top = (per_note.sort_values('Percentage', ascending=False, kind='stable')
                   .groupby('Voice').head(top_n))
    top = top.assign(ps=top['Notes'].map(lambda n: pitch.Pitch(n).ps))

    rows = []
    for voice in notes.columns:                            # score order
        group = top[top['Voice'] == voice]
        if group.empty:
            continue
        low = group.loc[group['ps'].idxmin(), 'Notes']
        high = group.loc[group['ps'].idxmax(), 'Notes']
        rows.append({'Voice': voice, 'LowestNote': low,
                     'HighestNote': high, 'Range': f'{low} to {high}'})
    result = pd.DataFrame(rows, columns=['Voice', 'LowestNote', 'HighestNote', 'Range'])
    if include_final:
        result.insert(1, 'Final', extract_letter(self.final()))
    result.insert(0, 'Composer', self.metadata['composer'])
    result.insert(1, 'Title', self.metadata['title'])
    self.analyses[memo_key] = result
    return result.copy()

CorpusBase

CorpusBase(paths: list)

A class for importing multiple scores at once.

Attributes:

Name Type Description
paths list

list of file paths and urls of scores to be imported file paths MUST begin with a '/', otherwise they will be categoried as urls

scores list of music21.Score

list of music21.Score objects- imported from urls and paths

note_list list of NoteListElement

list of notes constructed from scores

note_list_no_unisons list of NoteListElement

list of notes constructed from scores, combining unisons

Parameters:

Name Type Description Default
paths list

list file paths/urls to mei files file paths MUST begin with a '/', otherwise they will be categoried as urls

required

Raises:

Type Description
Exception

If at least one score isn't succesfully imported, raises error

Source code in crim_intervals/main_objs.py
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
def __init__(self, paths: list):
    """
    Parameters
    ----------
    paths : list
        list file paths/urls to mei files
        file paths MUST begin with a '/', otherwise they will be categoried as urls

    Raises
    ----------
    Exception
        If at least one score isn't succesfully imported, raises error
    """
    self.paths = paths
    self.scores = []  # store lists of ImportedPieces generated from the path above
    self.analyses = {'note_list': None}
    for path in paths:
        if type(path) == str:
            _score = importScore(path)
            if _score is not None:
                self.scores.append(_score)
        else:   # path is already an ImportedPiece
            self.scores.append(path)

    if len(self.scores) == 0:
        print("Empty corpus created. Please import at least one score.")

batch

batch(func, kwargs={}, metadata=True, number_parts=True, verbose=False)

The batch method is a convenience function for running the same analysis on all pieces in a CorpusBase object. It takes an unbound method from the ImportedPiece class and applies it to each score in the corpus, returning a list of dfs with the results for each piece.
The list of dfs can be passed to a succession of methods (so that each piece in the corpus is processed separately).
In a final step the list of dfs can be concatenated to a single set of corpus results.

Run the func on each of the scores in this CorpusBase object and return a list of the results. func should be a method from the ImportedPiece class. If you need to pass arguments to that function, pass them as a dictionary of keyword arguments with the kwargs parameter. These parameters will be the same for each ImportedPiece object as it gets the func applied to its score.

When passing a parameter that is a dataframe, a different dataframe is needed for each piece in the corpus. This applies to the parameters called "df", "mask_df", and "other". In these cases you should pass a list of dataframes in batch's kwargs for that parameter. This makes it easy to chain uses of the .batch` method.

By default, .batch will replace columns that consist of part names (like .melodic() results) or combinations of part names (like .harmonic() results) with numbers starting with "1" for the highest part on the staff, "2" for the second highest, etc. This is useful when combining results from pieces with parts that have different names. You can override this and keep the original part names in the columns by setting the number_parts parameter to False.

Parameters:

Name Type Description Default
func callable

An unbound method from the ImportedPiece class, e.g. ImportedPiece.notes (note: no parentheses).

required
kwargs dict

Keyword arguments to pass to func for each piece. Only include the parameters you need to override. Dataframe-valued parameters ("df", "mask_df", "other") should be passed as a list of dataframes, one per piece in the corpus.

{}
metadata bool, optional (default True)

Whether to add Composer/Title/Date columns to each result.

True
number_parts bool, optional (default True)

Whether to replace part-name columns with numbers ("1" for the highest part on the staff, "2" for the second highest, etc.) so that results from pieces with differently named parts can be combined. Pass False to keep the original part names.

True
verbose bool, optional (default False)

If True, prints the function being called and the piece being analyzed as the batch runs. Useful for pinpointing a piece that triggers a bug.

False

Returns:

Type Description
list

One result per piece in the corpus, in the order of self.scores.

Examples:

Basic analysis with no added parameters:

corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                     'https://crimproject.org/mei/CRIM_Model_0009.mei'])
func = ImportedPiece.notes  # <- NB there are no parentheses here
list_of_dfs = corpus.batch(func)

Passing some parameters to func calls. Note that you only add the parameters to kwargs that you need to pass. This example returns a list of dataframes of the melodic intervals of each piece in the corpus, and in this case will be chromatic and undirected intervals because of parameters passed in kwargs.

corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                     'https://crimproject.org/mei/CRIM_Model_0009.mei'])
func = ImportedPiece.melodic  # <- NB there are no parentheses here
kwargs = {'kind': 'c', 'directed': False}
list_of_dfs = corpus.batch(func, kwargs)

Using batch to count the cadence types from multiple pieces:

corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                     'https://crimproject.org/mei/CRIM_Model_0009.mei'])
list_of_dfs = corpus.batch(ImportedPiece.cadences, metadata=False)
combined_df = pd.concat(list_of_dfs, ignore_index=True)
# Get the number of each type of cadence observed:
cadTypeCounts = combined_df['CadType'].value_counts()
# Get the number of cadences per Beat level:
cadTypeCounts = combined_df['Beat'].value_counts()

Using .batch to first get the melodic intervals of each piece in a corpus, and then pass that list of dataframes on to get melodic ngrams for each piece:

corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                     'https://crimproject.org/mei/CRIM_Model_0009.mei'])
func1 = ImportedPiece.melodic
# NB: you would probably want to set metadata to False for most preliminary results
list_of_dfs = corpus.batch(func=func1, kwargs={'end': False}, metadata=False)
func2 = ImportedPiece.ngrams
list_of_melodic_ngrams = corpus.batch(func=func2, kwargs={'n': 4, 'df': list_of_dfs})

Overriding number_parts:

list_of_dfs_with_numbers_for_part_names = corpus.batch(ImportedPiece.melodic)
list_of_dfs_with_original_part_names = corpus.batch(ImportedPiece.melodic, number_parts=False)
Source code in crim_intervals/main_objs.py
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
def batch(self, func, kwargs={}, metadata=True, number_parts=True, verbose=False):
    '''
    The batch method is a convenience function for running the same analysis 
    on all pieces in a `CorpusBase` object. It takes an unbound method from the 
    `ImportedPiece` class and applies it to each score in the corpus, returning a list of dfs with the results for each piece.  
    The list of dfs can be passed to a succession of methods (so that each piece in the corpus is processed separately).  
    In a final step the list of dfs can be concatenated to a single set of corpus results.

    Run the `func` on each of the scores in this `CorpusBase` object and
    return a list of the results. `func` should be a method from the
    ImportedPiece class. If you need to pass arguments to that function,
    pass them as a dictionary of keyword arguments with the kwargs
    parameter. These parameters will be the same for each ImportedPiece
    object as it gets the `func` applied to its score.

    When passing a parameter that is a dataframe, a different dataframe
    is needed for each piece in the corpus. This applies to the parameters
    called "df", "mask_df", and "other". In these cases you should pass a
    list of dataframes in batch's kwargs for that parameter. This makes it
    easy to chain uses of the `.`batch` method.

    By default, .batch will replace columns that consist of part names (like `.melodic()` results)
    or combinations of part names (like `.harmonic()` results) with numbers starting with "1" for
    the highest part on the staff, "2" for the second highest, etc. This is useful when combining
    results from pieces with parts that have different names. You can override this and keep the
    original part names in the columns by setting the `number_parts` parameter to False.

    Parameters
    ----------
    func : callable
        An unbound method from the ImportedPiece class, e.g.
        `ImportedPiece.notes` (note: no parentheses).
    kwargs : dict, optional
        Keyword arguments to pass to `func` for each piece. Only include
        the parameters you need to override. Dataframe-valued parameters
        ("df", "mask_df", "other") should be passed as a list of
        dataframes, one per piece in the corpus.
    metadata : bool, optional (default True)
        Whether to add Composer/Title/Date columns to each result.
    number_parts : bool, optional (default True)
        Whether to replace part-name columns with numbers ("1" for the
        highest part on the staff, "2" for the second highest, etc.) so
        that results from pieces with differently named parts can be
        combined. Pass False to keep the original part names.
    verbose : bool, optional (default False)
        If True, prints the function being called and the piece being
        analyzed as the batch runs. Useful for pinpointing a piece that
        triggers a bug.

    Returns
    -------
    list
        One result per piece in the corpus, in the order of `self.scores`.

    Examples
    --------
    Basic analysis with no added parameters:

    ```python
    corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                         'https://crimproject.org/mei/CRIM_Model_0009.mei'])
    func = ImportedPiece.notes  # <- NB there are no parentheses here
    list_of_dfs = corpus.batch(func)
    ```

    Passing some parameters to `func` calls. Note that you only add the
    parameters to kwargs that you need to pass. This example returns a
    list of dataframes of the melodic intervals of each piece in the
    corpus, and in this case will be chromatic and undirected intervals
    because of parameters passed in kwargs.

    ```python
    corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                         'https://crimproject.org/mei/CRIM_Model_0009.mei'])
    func = ImportedPiece.melodic  # <- NB there are no parentheses here
    kwargs = {'kind': 'c', 'directed': False}
    list_of_dfs = corpus.batch(func, kwargs)
    ```

    Using batch to count the cadence types from multiple pieces:

    ```python
    corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                         'https://crimproject.org/mei/CRIM_Model_0009.mei'])
    list_of_dfs = corpus.batch(ImportedPiece.cadences, metadata=False)
    combined_df = pd.concat(list_of_dfs, ignore_index=True)
    # Get the number of each type of cadence observed:
    cadTypeCounts = combined_df['CadType'].value_counts()
    # Get the number of cadences per Beat level:
    cadTypeCounts = combined_df['Beat'].value_counts()
    ```

    Using .batch to first get the melodic intervals of each piece in a
    corpus, and then pass that list of dataframes on to get melodic
    ngrams for each piece:

    ```python
    corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Mass_0014_3.mei',
                         'https://crimproject.org/mei/CRIM_Model_0009.mei'])
    func1 = ImportedPiece.melodic
    # NB: you would probably want to set metadata to False for most preliminary results
    list_of_dfs = corpus.batch(func=func1, kwargs={'end': False}, metadata=False)
    func2 = ImportedPiece.ngrams
    list_of_melodic_ngrams = corpus.batch(func=func2, kwargs={'n': 4, 'df': list_of_dfs})
    ```

    Overriding `number_parts`:

    ```python
    list_of_dfs_with_numbers_for_part_names = corpus.batch(ImportedPiece.melodic)
    list_of_dfs_with_original_part_names = corpus.batch(ImportedPiece.melodic, number_parts=False)
    ```
    '''
    post = []
    dfs = ('df', 'mask_df', 'other')
    _kwargs = {key: val for key, val in kwargs.items() if key not in dfs}
    list_args = {key: val for key, val in kwargs.items() if key in dfs}
    if verbose:
        print('\nRunning {} analysis on {} pieces:'.format(func.__name__, len(self.scores)))
    # these methods either have no part-name columns or number their own voices
    if number_parts and func.__name__ in ('cadences', 'presentationTypes', 'lowLine', 'highLine',
                                          'final', 'voice_ranges', 'melodic_species',
                                          'note_weights'):
        number_parts = False
    for i, score in enumerate(self.scores):
        if verbose:
            print('\t{}: {}'.format(i + 1, score.metadata['title']))
        largs = {key: val[i] for key, val in list_args.items()}
        df = func(score, **_kwargs, **largs)
        if isinstance(df, pd.DataFrame):
            # numberParts returns a renamed copy; otherwise copy explicitly, so
            # adding metadata below never alters the piece's cached results
            df = score.numberParts(df) if number_parts else df.copy()
            if metadata:
                df[['Composer', 'Title', 'Date']] = score.metadata['composer'], score.metadata['title'], score.metadata['date']
        post.append(df)
    return post

cadences

cadences(keep_keys=False, voice_detail=False, key_sig=False, include_final=False)

Return cadences for all pieces in the corpus. Accepts the same parameters as ImportedPiece.cadences; see that method for the full column documentation.

Parameters:

Name Type Description Default
keep_keys bool, optional (default False)

If True, include the 'Pattern' and 'Key' columns (the CVF/interval pattern and the cadenceLabels.csv regex that matched it). Note that this 'Key' is a lookup key for cadence-type classification, not a musical key.

False
voice_detail bool, optional (default False)

If True, include the 'PartMap' column mapping each CVF letter to the staff position(s) that performed it, e.g. {'C': ['1'], 'T': ['3']}. Staff positions (not voice names) keep this comparable across pieces.

False
key_sig bool, optional (default False)

If True, add a 'KeySig' column with the prevailing system key signature (music21 .sharps convention) at each cadence's perfection. Defaults to False to keep existing output unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column with each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame

If none of the pieces in the corpus have any cadences, an empty DataFrame (with the expected columns) is returned. Pieces with no cadences are reported by title via a printed message rather than raising an error.

Source code in crim_intervals/main_objs.py
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
def cadences(self,
             keep_keys=False,
             voice_detail=False,
             key_sig=False,
             include_final=False):
    """
    Return cadences for all pieces in the corpus. Accepts the same parameters
    as `ImportedPiece.cadences`; see that method for the full column
    documentation.

    Parameters
    ----------
    keep_keys : bool, optional (default False)
        If True, include the 'Pattern' and 'Key' columns (the CVF/interval
        pattern and the cadenceLabels.csv regex that matched it). Note that
        this 'Key' is a lookup key for cadence-type classification, not a
        musical key.
    voice_detail : bool, optional (default False)
        If True, include the 'PartMap' column mapping each CVF letter to the
        staff position(s) that performed it, e.g. {'C': ['1'], 'T': ['3']}.
        Staff positions (not voice names) keep this comparable across pieces.
    key_sig : bool, optional (default False)
        If True, add a 'KeySig' column with the prevailing system key
        signature (music21 .sharps convention) at each cadence's
        perfection. Defaults to False to keep existing output unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column with each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
        If none of the pieces in the corpus have any cadences, an empty
        DataFrame (with the expected columns) is returned. Pieces with no
        cadences are reported by title via a printed message rather than
        raising an error.
    """
    col_list = ['Composer', 'Title', 'Date', 'Measure', 'Beat', 'Offset']
    if keep_keys:
        col_list += ['Pattern', 'Key']
    col_list += ['CadType', 'Tone', 'CVFs']
    if voice_detail:
        col_list.append('PartMap')
    col_list += ['LeadingTones', 'Sounding', 'Low', 'RelLow', 'RelTone',
                 'Progress', 'SinceLast', 'ToNext']
    if key_sig:
        col_list.append('KeySig')
    if include_final:
        col_list.append('Final')

    func = ImportedPiece.cadences
    kwargs = {'keep_keys': keep_keys,
              'voice_detail': voice_detail,
              'key_sig': key_sig,
              'include_final': include_final}
    list_of_dfs = self.batch(func=func, kwargs=kwargs, metadata=True)

    # Some pieces may have no cadences at all (an empty df from
    # ImportedPiece.cadences). Report these by title instead of letting
    # them silently vanish from the corpus results.
    missing_pieces = [score.metadata['title'] for df, score in zip(list_of_dfs, self.scores) if len(df) == 0]
    if missing_pieces:
        print('No cadences found in {} piece(s): {}'.format(len(missing_pieces), ', '.join(missing_pieces)))
    list_of_dfs = [df for df in list_of_dfs if len(df) > 0]

    if not list_of_dfs:
        print('No cadences found in the corpus')
        return pd.DataFrame(columns=col_list)

    corpus_cadences = pd.concat(list_of_dfs, ignore_index=False)
    corpus_cadences = corpus_cadences[col_list]
    return corpus_cadences

compareCadenceProgressPlots

compareCadenceProgressPlots(includeType=False, cadTone=None, cadType=None, includeLegend=True, customOrder=None, renderer='')

Parameters Overview:

  • includeType: if set to True, the Cadence markers would be set based on both their Type. If set to False, a universal (round) marker will be used
  • cadTone: specify the Tone of cadences to explore. Takes an String input. Set to None by default
  • cadType: specify the Type of cadences to explore. Takes an String input. Set to None by default
  • customOrder: specify a custom order to be used for the plot (a dictionary: e.g. {"A":0, "B":1 ...}
  • includeLegend: flag to display legend; Default set to True

Examples:

compareCadenceProgressPlots(includeType=True)
Source code in crim_intervals/main_objs.py
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
def compareCadenceProgressPlots(self, 
                                includeType=False, 
                                cadTone=None, 
                                cadType=None, 
                                includeLegend=True, 
                                customOrder=None, 
                                renderer=""):

    '''
    Parameters Overview:

    * includeType: if set to True, the Cadence markers would be set based on both their Type. If set to False, a universal (round) marker will be used
    * cadTone: specify the Tone of cadences to explore. Takes an String input. Set to None by default
    * cadType: specify the Type of cadences to explore. Takes an String input. Set to None by default
    * customOrder: specify a custom order to be used for the plot (a dictionary: e.g. {"A":0, "B":1 ...}
    * includeLegend: flag to display legend; Default set to True

    Examples
    --------
    ```python
    compareCadenceProgressPlots(includeType=True)
    ```
    '''

    # runs sns plot layout
    self._plot_default()

    # defining a palette for the pieces
    colors_array = sns.color_palette(n_colors=len(self.scores), as_cmap=True)
    color_pointer = 0
    patch_set = []
    type_patch_array = []

    # creating the piece legend
    for i in range(len(self.scores)):
        patch_set.append(mpatches.Patch(color=colors_array[i], label=self.scores[i].metadata["title"]))
    piece_legend = plt.legend(handles=patch_set, loc='upper left')

    # looking for unique Types
    unique_types_array = []

    # defining markers for Cadence Types
    cadence_type_dict = {"Clausula Vera": "o", "Abandoned Clausula Vera": "v", "Evaded Clausula Vera": "^",
                "Authentic" : "<", "Evaded Authentic": ">", "Abandoned Authentic": "8", "Double Leading Tone" : "s",
                "Evaded Double Leading Tone": "p", "Abandoned Double Leading Tone": "P", "Phrygian Clausula Vera": "d",
                "Altizans Only": "h", "Evaded Altizans Only": "H", "Leaping Contratenor": "X", "Reinterpreted": "D", "Phrygian": "d", "Quince": ".", "None": "*"}

    # defining the default order or accepting the custom order
    if customOrder == None:
        order_dict = {"Eb":0, "Bb":1, "F":2, "C":3, "G":4, "D":5, "A":6, "E":7, "B":8, "F#":9, "C#":10, "Ab":11}
    else:
        order_dict = customOrder

    # piece loop
    for piece_item in self.scores:

        # get cadences
        loop_cadences = piece_item.cadences()

        # pick color
        local_color = colors_array[color_pointer]
        color_pointer += 1

        # check for a lookup type
        if cadType != None:
            loop_cadences = loop_cadences[loop_cadences["CadType"] == cadType]

        # check for a lookup tone
        if cadTone != None:
            loop_cadences = loop_cadences[loop_cadences["Tone"] == cadTone]

        # check if empty
        if len(loop_cadences) < 1:
            print("No cadences found in: " + piece_item.metadata["title"])
            continue

        # convert Tone to a Numerical
        loop_cadences["Numerical"] = loop_cadences["Tone"].apply(lambda x: order_dict.get(x))

        # include Type (if includeType)
        if includeType:
            loop_cadences["CadType"] = loop_cadences["CadType"].fillna("None")
            sns.scatterplot(x=loop_cadences['Progress'], y=loop_cadences['Numerical'], style=loop_cadences["CadType"], markers=cadence_type_dict, s=140, color=local_color)
            unique_types_array.extend(loop_cadences["CadType"].unique().tolist())
        else:
            plt.scatter(x=loop_cadences['Progress'], y=loop_cadences['Numerical'], s=140, color=local_color)

    # produce y Ticks and Labels
    plt.yticks(ticks=list(order_dict.values()), labels=list(order_dict.keys()))

    # producing the Type Legend (if includeType)
    if includeType:
        type_patches = list(set(unique_types_array))
        for type_item in type_patches:
            type_patch_array.append(mlines.Line2D([0], [0], marker=cadence_type_dict[type_item], color='black', label=type_item, markerfacecolor='black', markersize=10, linewidth=0))
            plt.legend(handles=type_patch_array)

    # producing the Legend (if includeLegend)
    if includeLegend:
        plt.title("Cadence Progress Comparison")
        plt.gca().add_artist(piece_legend)
    plt.ylabel("Cadence Tone")
    if renderer == "streamlit":
        return plt
    else:
        plt.show()

compareCadenceRadarPlots

compareCadenceRadarPlots(combinedType=False, sounding=None, displayAll=True, customOrder=None, renderer='')

Parameters Overview:

  • combinedType: if set to True, the Cadences would be classified based on both their Type and Tone. If set to False, only Tone will be used. False by default
  • sounding: specify how many voices are sounding (optional). Takes an integer input. Set to None by default
  • displayAll: if set to True, the chart will display all pitches in the Default (Fifth) or Custom order
  • customOrder: the custom order parameter. Takes in a List of Strings
  • renderer: specify what renderer to be used for the plot (options include but are not limited to "svg", "iframe", "png", "notebook" etc

Examples:

compareCadenceRadarPlots(combinedType=False, displayAll=True, renderer="iframe")
Source code in crim_intervals/main_objs.py
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
def compareCadenceRadarPlots(self, 
                             combinedType=False, 
                             sounding=None, 
                             displayAll=True, 
                             customOrder=None, 
                             renderer=""):

    '''
    Parameters Overview:

    * combinedType: if set to True, the Cadences would be classified based on both their Type and Tone. If set to False, only Tone will be used. False by default
    * sounding: specify how many voices are sounding (optional). Takes an integer input. Set to None by default
    * displayAll: if set to True, the chart will display all pitches in the Default (Fifth) or Custom order
    * customOrder: the custom order parameter. Takes in a List of Strings
    * renderer: specify what renderer to be used for the plot (options include but are not limited to "svg", "iframe", "png", "notebook" etc

    Examples
    --------
    ```python
    compareCadenceRadarPlots(combinedType=False, displayAll=True, renderer="iframe")
    ```
    '''

    # specifying the Default order:
    order_array = ["D", "A", "E", "B", "F#", "Db", "Ab", "Eb", "Bb", "F", "C", "G"]

    # accepting a custom order (if customOrder)
    if customOrder != None:
        order_array = customOrder

    # creating an empty DataFrame
    data = pd.DataFrame()

    # iterating
    for piece_item in self.scores:

        # get Piece cadences
        loop_cadences = piece_item.cadences()

        # check if empty
        if len(loop_cadences) == 0:
            print("No cadences found in the piece: " + piece_item.metadata["title"])
            continue

        # filter for sounding (if sounding)
        if sounding != None:
            loop_cadences = loop_cadences[loop_cadences["Sounding"] == sounding]
            if len(loop_cadences) == 0:
                print("No cadences with given number of voices Sounding found in the piece: " + piece_item.metadata["title"])
                continue

        # create Combined Type (if combinedType)
        if combinedType:
            loop_cadences["Combined_Type"] = loop_cadences["Tone"] + "_" + loop_cadences["CadType"]
            selected_type = "Combined_Type"
        else:
            selected_type = "Tone"

        # groupby: Selected Type
        loop_group = pd.DataFrame(loop_cadences.groupby([selected_type]).size().reset_index(name='Count'))
        # assign Piece Title
        loop_group["Piece"] = piece_item.metadata["title"]

        # making sure grapher graphs in order (before displaying in order)
        if displayAll and selected_type == "Tone":
            loop_group['Tone'] = pd.Categorical(loop_group.Tone, categories=order_array, ordered=True)
            loop_group = loop_group.sort_values(by='Tone')

        # concat
        data = pd.concat([loop_group, data], ignore_index=True)

    if len(data) == 0:
        print("No cadences found in the corpus")
        return None

    # display all categories (if displayAll)
    if displayAll and selected_type == "Tone":
        fig = px.line_polar(data, r="Count", theta=selected_type, color="Piece", category_orders={"Tone": order_array}, line_close=True)
    else:
        if combinedType:
            sort_order = sorted(data["Combined_Type"].unique())
            fig = px.line_polar(data, r="Count", theta=selected_type, color="Piece", category_orders={"Combined_Type": sort_order}, line_close=True)
        else:
            fig = px.line_polar(data, r="Count", theta=selected_type, color="Piece", line_close=True)
    # chart title
    fig.update_layout(title_text=("Cadence Distribution Comparison"))
    if renderer == "streamlit":
        return fig
    else:
        fig.show()

compareIntervalFamilies

compareIntervalFamilies(length=4, combineUnisons=True, kind='d', end=False, variableLength=False, suggestedPattern=None, useEntries=True, arriveAt=None, includeLegend=True, renderer='')

It is possible to select:

length=4
combineUnisons=True
kind="d"
end=False
variableLength=False
suggestedPattern=None
useEntries=True

Examples:

Comparing the Interval Families with length=4 and useEntries=True by default:

compareIntervalFamilies(length=4)

Another useful option is variableLength=True, therefore including all unique patterns up to the specified length:

compareIntervalFamilies(length=4, variableLength=True)

We can narrow down patterns of interested by specifying suggestedPattern=Tuple(Str*), for example looking for all patterns that start with -2, -2:

compareIntervalFamilies(length=4, variableLength=True, suggestedPattern=("4", "2"))
Source code in crim_intervals/main_objs.py
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
def compareIntervalFamilies(self, 
                            length=4, 
                            combineUnisons=True, 
                            kind="d", 
                            end=False, 
                            variableLength=False,
                            suggestedPattern=None, 
                            useEntries=True, 
                            arriveAt=None, 
                            includeLegend=True, 
                            renderer=""):

    '''
    It is possible to select:

    ```python
    length=4
    combineUnisons=True
    kind="d"
    end=False
    variableLength=False
    suggestedPattern=None
    useEntries=True
    ```

    Examples
    --------
    Comparing the Interval Families with `length=4` and `useEntries=True` by default:

    ```python
    compareIntervalFamilies(length=4)
    ```

    Another useful option is `variableLength=True`, therefore including **all unique patterns up to the specified length**:

    ```python
    compareIntervalFamilies(length=4, variableLength=True)
    ```

    We can narrow down patterns of interested by specifying `suggestedPattern=Tuple(Str*)`, for example looking for **all patterns that start with `-2, -2`**:

    ```python
    compareIntervalFamilies(length=4, variableLength=True, suggestedPattern=("4", "2"))
    ```
    '''

    # runs sns plot layout
    self._plot_default()

    if length < 1:
        print("Please use length >= 1")
        return None

    if kind not in ["d", "z", "c"]:
        print("\n Warning: you might encounter an error due to using an uncommon interval kind. \n Currently, we have been working with \"z\", \"d\", and \"c\"")

    number_of_patterns = 0
    colors_array = sns.color_palette(n_colors=length, as_cmap=True)
    color_pointer = 0
    patch_array = []
    for piece_item in self.scores:
        local_color = colors_array[color_pointer]
        color_pointer += 1
        patch_array.append(mpatches.Patch(color=local_color, label=piece_item.metadata["title"]))
        local_ngrams = pd.DataFrame(columns=piece_item.notes().columns)

        if variableLength:
            loop_start = 1
        else:
            loop_start = length

        for i in range(loop_start, length + 1):
            loop_notes = piece_item.notes(combineUnisons=combineUnisons)
            loop_melodic = piece_item.melodic(df=loop_notes, kind=kind, end=end)
            if useEntries:
                loop_ngrams = piece_item.entries(df=loop_melodic, n=int(i), exclude=["Rest"]).fillna('')
            else:
                loop_ngrams = piece_item.ngrams(df=loop_melodic, n=int(i), exclude=["Rest"]).fillna('')
            # TODO: try to move this out of the loop and just concat once if possible
            local_ngrams = pd.concat([local_ngrams, loop_ngrams])

        total_unique_ngrams_list = list(filter(lambda x: x != "", list(set(local_ngrams.values.flatten().tolist()))))

        if suggestedPattern:
            matching_unique_ngrams_list = list(map(lambda x: x if ",".join(x).startswith(",".join(suggestedPattern)) else "", total_unique_ngrams_list))
            total_unique_ngrams_list = list(filter(lambda x: x != "", matching_unique_ngrams_list))
            if len(total_unique_ngrams_list) < 1:
                print("No patterns matching the suggestedPattern found in: " + piece_item.metadata["title"])
                continue

        graph_pattern_list = self._createGraphList(total_unique_ngrams_list)

        if arriveAt != None:
            graph_pattern_list = list(filter(lambda x: x[-1] == arriveAt, graph_pattern_list))
            if len(graph_pattern_list) < 1:
                print("No patterns arriving at arriveAt found in: " + piece_item.metadata["title"])
                continue

        number_of_patterns += len(graph_pattern_list)
        for single_pattern in graph_pattern_list:
            plt.plot(single_pattern, alpha=0.35, lw=6, color=local_color)

    plt.yticks(np.arange(-15, 15, 1.0))
    plt.xticks(np.arange(0, length + 1, 1.0))
    if includeLegend:
        plt.title("Total Number of Patterns: " + str(number_of_patterns))
        plt.legend(handles=patch_array)
    if renderer == "streamlit":
        return plt
    else:
        plt.show()

contrapuntal_ngrams

contrapuntal_ngrams(ngram_length=3, key_sig=False, include_final=False)

Generate contrapuntal n-grams in a corpus.

Parameters:

Name Type Description Default
ngram_length int

Passed through to ImportedPiece.ngrams as n.

3
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
def contrapuntal_ngrams(self, 
                        ngram_length=3, 
                        key_sig=False, 
                        include_final=False):
    """
    Generate contrapuntal n-grams in a corpus.

    Parameters
    ----------
    ngram_length : int
        Passed through to ImportedPiece.ngrams as `n`.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func = ImportedPiece.ngrams  # <- NB there are no parentheses here
    list_of_dfs = self.batch(func=func,
                              kwargs={'n': ngram_length},
                              metadata=False)
    func1 = ImportedPiece.detailIndex
    list_of_detail_index_dfs = self.batch(func=func1,
                                           kwargs={'df': list_of_dfs, 'progress': True, 'key_sig': key_sig},
                                           metadata=False)
    func2 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func2,
                              kwargs={'df': list_of_detail_index_dfs},
                              metadata=True)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    ngrams = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date']
    ngrams = ngrams[cols_to_move + [col for col in ngrams.columns if col not in cols_to_move]]
    ngrams = ngrams.reset_index()
    return ngrams

derivativeAnalyzer

derivativeAnalyzer(df=None, n=10)

Find the top n masses with the highest derivation scores for each model in a table of .modelFinder results. The scores from the different movements in each mass are averaged together to get a single score for each model-mass pair. Thedfparameter should be the results from themodelFindermethod. If it is left as the default value of None, it will be replaced with the results of themodelFinder on this corpus with the default settings.

Source code in crim_intervals/main_objs.py
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
def derivativeAnalyzer(self, df=None, n=10):
    '''
    Find the top n masses with the highest derivation scores for each model in a table of `.modelFinder results.
    The scores from the different movements in each mass are averaged together to get a single score for each
    model-mass pair. The `df` parameter should be the results from the `modelFinder` method. If it is left as the
    default value of None, it will be replaced with the results of the `modelFinder on this corpus with the
    default settings.'''
    if df is None:
        _df = self.modelFinder()
    else:
        _df = df.copy()
    _df.dropna(inplace=True, how='all')
    _df.index = [i.rsplit('_', 1)[0].split('_', 1)[1] if 'Mass' in i else i.split('_', 1)[1] for i in _df.index]
    means = _df.groupby(level=0, sort=False).mean()
    if n > len(means.index):
        print('\nYou used an n of size {} but only passed a corpus with {} masses in it. Returning all results ranked.\n'.format(n, len(means.index)))
        n = len(means.index)
    cols = []
    for col in means.columns:
        topDerivatives = means[col].nlargest(n).round(4)
        cols.append([(i, topDerivatives[i]) for i in topDerivatives.index])
    res = pd.DataFrame(cols, columns=range(1, n+1), index=_df.columns).T
    res.index.set_names('Rank', inplace=True)
    return res

har

har(kind_choice='d', compound_choice=True, directed_choice=True, key_sig=False, include_final=False)

Generate harmonic intervals in a corpus.

Parameters:

Name Type Description Default
kind_choice

Passed through to ImportedPiece.harmonic as kind, compound, directed.

'd'
compound_choice

Passed through to ImportedPiece.harmonic as kind, compound, directed.

'd'
directed_choice

Passed through to ImportedPiece.harmonic as kind, compound, directed.

'd'
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
def har(self, kind_choice='d', compound_choice=True, directed_choice=True, key_sig=False, include_final=False):
    """
    Generate harmonic intervals in a corpus.

    Parameters
    ----------
    kind_choice, compound_choice, directed_choice
        Passed through to ImportedPiece.harmonic as `kind`, `compound`, `directed`.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func = ImportedPiece.harmonic  # <- NB there are no parentheses here
    list_of_dfs = self.batch(func=func,
                              kwargs={'kind': kind_choice,
                                      'compound': compound_choice,
                                      'directed': directed_choice},
                              metadata=False)
    func1 = ImportedPiece.detailIndex
    list_of_detail_index_dfs = self.batch(func=func1,
                                           kwargs={'df': list_of_dfs, 'progress': True, 'key_sig': key_sig},
                                           metadata=False)
    func2 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func2,
                              kwargs={'df': list_of_detail_index_dfs},
                              metadata=True)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    har = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date']
    har = har[cols_to_move + [col for col in har.columns if col not in cols_to_move]]
    har = har.reset_index()
    return har

harmonic_ngrams

harmonic_ngrams(ngram_length=4, kind_choice='d', compound_choice=True, directed_choice=True, metadata_choice=True, againstLow_choice=False, include_offset=False, key_sig=False, include_final=False)

Generate harmonic n-grams in a corpus.

Parameters:

Name Type Description Default
ngram_length

Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.

4
kind_choice

Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.

4
compound_choice

Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.

4
directed_choice

Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.

4
againstLow_choice

Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.

4
metadata_choice bool

Whether to attach Composer/Title/Date columns.

True
include_offset bool

Whether detailIndex should also include each row's raw offset.

False
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
def harmonic_ngrams(self,
                     ngram_length=4,
                     kind_choice='d',
                     compound_choice=True,
                     directed_choice=True,
                     metadata_choice=True,
                     againstLow_choice=False,
                     include_offset=False,
                     key_sig=False,
                     include_final=False):
    """
    Generate harmonic n-grams in a corpus.

    Parameters
    ----------
    ngram_length, kind_choice, compound_choice, directed_choice, againstLow_choice
        Passed through to ImportedPiece.harmonic/ImportedPiece.ngrams.
    metadata_choice : bool
        Whether to attach Composer/Title/Date columns.
    include_offset : bool
        Whether detailIndex should also include each row's raw offset.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func1 = ImportedPiece.harmonic
    list_of_dfs = self.batch(func=func1, kwargs={'kind': kind_choice,
                                                  'compound': compound_choice,
                                                  'directed': directed_choice,
                                                  'againstLow': againstLow_choice}, metadata=False)
    func2 = ImportedPiece.ngrams
    list_of_harmonic_ngrams = self.batch(func=func2, kwargs={'n': ngram_length, 'df': list_of_dfs}, metadata=False)
    func3 = ImportedPiece.detailIndex
    list_of_detail_index = self.batch(func=func3, kwargs={'offset': include_offset,
                                                           'df': list_of_harmonic_ngrams,
                                                           'progress': True,
                                                           'key_sig': key_sig}, metadata=False)
    func4 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func4,
                              kwargs={'df': list_of_detail_index},
                              metadata=metadata_choice)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    corpus_har_ngrams = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date']
    corpus_har_ngrams = corpus_har_ngrams[cols_to_move + [col for col in corpus_har_ngrams.columns if col not in cols_to_move]]
    corpus_har_ngrams = corpus_har_ngrams.reset_index()
    return corpus_har_ngrams

mel

mel(kind_choice='d', compound_choice=True, directed_choice=True, key_sig=False, include_final=False)

Generate melodic intervals in a corpus.

Parameters:

Name Type Description Default
kind_choice

Passed through to ImportedPiece.melodic as kind, compound, directed.

'd'
compound_choice

Passed through to ImportedPiece.melodic as kind, compound, directed.

'd'
directed_choice

Passed through to ImportedPiece.melodic as kind, compound, directed.

'd'
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
def mel(self, 
        kind_choice='d', 
        compound_choice=True, 
        directed_choice=True, 
        key_sig=False, 
        include_final=False):
    """
    Generate melodic intervals in a corpus.

    Parameters
    ----------
    kind_choice, compound_choice, directed_choice
        Passed through to ImportedPiece.melodic as `kind`, `compound`, `directed`.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func = ImportedPiece.melodic  # <- NB there are no parentheses here
    list_of_dfs = self.batch(func=func,
                              kwargs={'kind': kind_choice,
                                      'compound': compound_choice,
                                      'directed': directed_choice},
                              metadata=False)
    func1 = ImportedPiece.detailIndex
    list_of_detail_index_dfs = self.batch(func=func1,
                                           kwargs={'df': list_of_dfs, 'progress': True, 'key_sig': key_sig},
                                           metadata=False)
    func2 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func2,
                              kwargs={'df': list_of_detail_index_dfs},
                              metadata=True)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    mel = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date']
    mel = mel[cols_to_move + [col for col in mel.columns if col not in cols_to_move]]
    mel = mel.reset_index()
    return mel

melodic_durational_ratios_ngrams

melodic_durational_ratios_ngrams(ngram_length=4, end_choice=False, kind_choice='d', compound_choice=True, directed_choice=True, metadata_choice=True, include_offset=False, key_sig=False, include_final=False)

Generate melodic n-grams with durational ratios in a corpus.

Parameters:

Name Type Description Default
ngram_length

Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.

4
end_choice

Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.

4
kind_choice

Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.

4
compound_choice

Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.

4
directed_choice

Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.

4
metadata_choice bool

Whether to attach Composer/Title/Date columns.

True
include_offset bool

Whether detailIndex should also include each row's raw offset.

False
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
def melodic_durational_ratios_ngrams(self, ngram_length=4,
                                      end_choice=False,
                                      kind_choice='d',
                                      compound_choice=True,
                                      directed_choice=True,
                                      metadata_choice=True,
                                      include_offset=False,
                                      key_sig=False,
                                      include_final=False):
    """
    Generate melodic n-grams with durational ratios in a corpus.

    Parameters
    ----------
    ngram_length, end_choice, kind_choice, compound_choice, directed_choice
        Passed through to ImportedPiece.melodic/ImportedPiece.durationalRatios/ImportedPiece.ngrams.
    metadata_choice : bool
        Whether to attach Composer/Title/Date columns.
    include_offset : bool
        Whether detailIndex should also include each row's raw offset.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func1 = ImportedPiece.melodic
    list_of_mel_dfs = self.batch(func=func1, kwargs={'kind': kind_choice,
                                                      'end': end_choice,
                                                      'compound': compound_choice,
                                                      'directed': directed_choice,
                                                      }, metadata=False)

    func2 = ImportedPiece.numberParts
    list_of_mel_dfs = self.batch(func=func2,
                                  kwargs={'df': list_of_mel_dfs},
                                  metadata=metadata_choice)

    func3 = ImportedPiece.durationalRatios
    list_of_dur_rat_dfs = self.batch(func=func3, kwargs={'end': end_choice}, metadata=False)
    # number the parts using func2 above
    list_of_dur_rat_dfs = self.batch(func=func2,
                                      kwargs={'df': list_of_dur_rat_dfs},
                                      metadata=False)
    # round the values
    list_of_dur_rat_dfs_rounded = []
    for df in list_of_dur_rat_dfs:
        df_rounded = df.apply(lambda x: x.astype('float64')).round(2)
        list_of_dur_rat_dfs_rounded.append(df_rounded)

    func4 = ImportedPiece.ngrams
    list_of_mel_dur_ngrams = self.batch(func=func4, kwargs={'n': ngram_length,
                                                             'df': list_of_mel_dfs,
                                                             'other': list_of_dur_rat_dfs_rounded}, metadata=False)
    list_of_mel_dur_rounded_no_tuple = []
    for df in list_of_mel_dur_ngrams:
        df_joined = df.map(lambda x: tuple_to_string(x, separator='_') if isinstance(x, tuple) else x)
        list_of_mel_dur_rounded_no_tuple.append(df_joined)

    func5 = ImportedPiece.detailIndex
    list_of_detail_index = self.batch(func=func5, kwargs={'offset': include_offset,
                                                           'df': list_of_mel_dur_rounded_no_tuple,
                                                           'progress': True,
                                                           'key_sig': key_sig},
                                                           metadata=metadata_choice)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_detail_index = [df.assign(Final=final) for df, final in zip(list_of_detail_index, finals)]

    corpus_mel_dur_rat_ngrams = pd.concat(list_of_detail_index)

    cols_to_move = ['Composer', 'Title', 'Date']
    corpus_mel_dur_rat_ngrams = corpus_mel_dur_rat_ngrams[cols_to_move + [col for col in corpus_mel_dur_rat_ngrams.columns if col not in cols_to_move]]
    corpus_mel_dur_rat_ngrams = corpus_mel_dur_rat_ngrams.reset_index()
    return corpus_mel_dur_rat_ngrams

melodic_ngrams

melodic_ngrams(ngram_length=4, kind_choice='d', compound_choice=True, directed_choice=True, end_choice=False, metadata_choice=True, include_offset=False, key_sig=False, include_final=False)

Generate melodic n-grams in a corpus.

Parameters:

Name Type Description Default
ngram_length

Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.

4
kind_choice

Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.

4
compound_choice

Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.

4
directed_choice

Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.

4
end_choice

Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.

4
metadata_choice bool

Whether to attach Composer/Title/Date columns.

True
include_offset bool

Whether detailIndex should also include each row's raw offset.

False
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
def melodic_ngrams(self,
                    ngram_length=4,
                    kind_choice='d',
                    compound_choice=True,
                    directed_choice=True,
                    end_choice=False,
                    metadata_choice=True,
                    include_offset=False,
                    key_sig=False,
                    include_final=False):
    """
    Generate melodic n-grams in a corpus.

    Parameters
    ----------
    ngram_length, kind_choice, compound_choice, directed_choice, end_choice
        Passed through to ImportedPiece.melodic/ImportedPiece.ngrams.
    metadata_choice : bool
        Whether to attach Composer/Title/Date columns.
    include_offset : bool
        Whether detailIndex should also include each row's raw offset.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func1 = ImportedPiece.melodic
    list_of_dfs = self.batch(func=func1, kwargs={'kind': kind_choice,
                                                  'compound': compound_choice,
                                                  'directed': directed_choice,
                                                  'end': end_choice}, metadata=False)
    func2 = ImportedPiece.ngrams
    list_of_melodic_ngrams = self.batch(func=func2, kwargs={'n': ngram_length, 'df': list_of_dfs}, metadata=False)
    func3 = ImportedPiece.detailIndex
    list_of_detail_index = self.batch(func=func3, kwargs={'offset': include_offset, 'df': list_of_melodic_ngrams, 'progress': True, 'key_sig': key_sig}, metadata=False)
    func4 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func4,
                              kwargs={'df': list_of_detail_index},
                              metadata=metadata_choice)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    corpus_mel_ngrams = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date']
    corpus_mel_ngrams = corpus_mel_ngrams[cols_to_move + [col for col in corpus_mel_ngrams.columns if col not in cols_to_move]]
    corpus_mel_ngrams = corpus_mel_ngrams.reset_index()
    return corpus_mel_ngrams

melodic_species

melodic_species(limit_to_entries=True, species_intervals=['5', '-5', '4', '-4'], four_five_dict={'C_5': 'C/G', 'C_-5': 'C/F', 'C_4': 'C/F', 'C_-4': 'C/G', 'D_5': 'D/A', 'D_-5': 'D/G', 'D_4': 'D/G', 'D_-4': 'D/A', 'E_5': 'E/B', 'E_-5': 'E/A', 'E_4': 'E/A', 'E_-4': 'E/B', 'F_5': 'F/C', 'F_-5': 'F/B-', 'F_4': 'F/B-', 'F_-4': 'F/C', 'G_5': 'G/D', 'G_-5': 'G/C', 'G_4': 'G/C', 'G_-4': 'G/D', 'A_5': 'A/E', 'A_-5': 'A/D', 'A_4': 'A/D', 'A_-4': 'A/E', 'B_5': 'B/F#', 'B_-5': 'B/E', 'B_4': 'B/E', 'B_-4': 'B/F#', 'B-_5': 'B-/F', 'B-_-5': 'B-/E-', 'B-_4': 'B-/E-', 'B-_-4': 'B-/F'}, octave_dict={'C/G': 'CGC', 'C/F': 'FCF', 'D/A': 'DAD', 'D/G': 'GDG', 'E/B': 'EBE', 'E/A': 'AEA', 'F/C': 'FCF', 'F/B-': 'BbFBb', 'G/D': 'GDG', 'G/C': 'CGC', 'A/E': 'AEA', 'A/D': 'DAD', 'B/F#': 'BF#B', 'B/E': 'EBE', 'B-/F': 'BbFBb', 'B-/E-': 'EbBbEb'}, final=None, voices=None)

Return melodic species (fourth/fifth species and the octave species they articulate) for every piece in the corpus. See ImportedPiece.melodic_species for how the intervals are found and classified.

Composer, title, and date metadata are added from the source files.

Parameters:

Name Type Description Default
limit_to_entries bool, optional (default True)

If True, keep only intervals that begin a melodic entry (start of piece, after a rest, or after a fermata).

True
species_intervals list of str, optional (default species_intervals_list)

Directed diatonic melodic intervals to keep (e.g. '5', '-5', '4', '-4').

['5', '-5', '4', '-4']
four_five_dict dict, optional (default species_four_five_dict)

Maps note-and-interval labels (e.g. 'C_5') to fourth/fifth species.

{'C_5': 'C/G', 'C_-5': 'C/F', 'C_4': 'C/F', 'C_-4': 'C/G', 'D_5': 'D/A', 'D_-5': 'D/G', 'D_4': 'D/G', 'D_-4': 'D/A', 'E_5': 'E/B', 'E_-5': 'E/A', 'E_4': 'E/A', 'E_-4': 'E/B', 'F_5': 'F/C', 'F_-5': 'F/B-', 'F_4': 'F/B-', 'F_-4': 'F/C', 'G_5': 'G/D', 'G_-5': 'G/C', 'G_4': 'G/C', 'G_-4': 'G/D', 'A_5': 'A/E', 'A_-5': 'A/D', 'A_4': 'A/D', 'A_-4': 'A/E', 'B_5': 'B/F#', 'B_-5': 'B/E', 'B_4': 'B/E', 'B_-4': 'B/F#', 'B-_5': 'B-/F', 'B-_-5': 'B-/E-', 'B-_4': 'B-/E-', 'B-_-4': 'B-/F'}
octave_dict dict, optional (default species_octave_dict)

Maps fourth/fifth species to octave species (e.g. 'CGC').

{'C/G': 'CGC', 'C/F': 'FCF', 'D/A': 'DAD', 'D/G': 'GDG', 'E/B': 'EBE', 'E/A': 'AEA', 'F/C': 'FCF', 'F/B-': 'BbFBb', 'G/D': 'GDG', 'G/C': 'CGC', 'A/E': 'AEA', 'A/D': 'DAD', 'B/F#': 'BF#B', 'B/E': 'EBE', 'B-/F': 'BbFBb', 'B-/E-': 'EbBbEb'}
final str or list of str

Keep only pieces with this final (pitch class, e.g. 'G' or ['D', 'G']). Use music21 spelling for accidentals: 'B-' for B-flat, not 'Bb'. Default: all pieces.

None
voices str, int, or list

Keep only these voices by staff number (1 = highest), e.g. 2 or ['1', '2']. Default: all voices.

None

Returns:

Type Description
DataFrame

Columns: Composer, Title, Date, Measure, Beat, Progress, Voice, System, Final, Interval, Species, Octave. 'Final' and 'Interval' use music21 spelling ('B-'), while the default 'Octave' labels use 'b' for flats ('BbFBb').

Examples:

>>> corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Model_0008.mei',
...                      'https://crimproject.org/mei/CRIM_Model_0009.mei'])
>>> species_df = corpus.melodic_species()
>>> species_df.groupby('Title')['Octave'].value_counts()
Source code in crim_intervals/main_objs.py
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
def melodic_species(self, limit_to_entries=True,
                    species_intervals=species_intervals_list,
                    four_five_dict=species_four_five_dict,
                    octave_dict=species_octave_dict,
                    final=None, voices=None):
    """
    Return melodic species (fourth/fifth species and the octave species
    they articulate) for every piece in the corpus. See
    `ImportedPiece.melodic_species` for how the intervals are found and
    classified.

    Composer, title, and date metadata are added from the source files.

    Parameters
    ----------
    limit_to_entries : bool, optional (default True)
        If True, keep only intervals that begin a melodic entry (start of
        piece, after a rest, or after a fermata).
    species_intervals : list of str, optional (default species_intervals_list)
        Directed diatonic melodic intervals to keep (e.g. '5', '-5', '4', '-4').
    four_five_dict : dict, optional (default species_four_five_dict)
        Maps note-and-interval labels (e.g. 'C_5') to fourth/fifth species.
    octave_dict : dict, optional (default species_octave_dict)
        Maps fourth/fifth species to octave species (e.g. 'CGC').
    final : str or list of str, optional
        Keep only pieces with this final (pitch class, e.g. 'G' or
        ['D', 'G']). Use music21 spelling for accidentals: 'B-' for
        B-flat, not 'Bb'. Default: all pieces.
    voices : str, int, or list, optional
        Keep only these voices by staff number (1 = highest), e.g. 2 or
        ['1', '2']. Default: all voices.

    Returns
    -------
    pandas.DataFrame
        Columns: Composer, Title, Date, Measure, Beat, Progress, Voice,
        System, Final, Interval, Species, Octave. 'Final' and 'Interval'
        use music21 spelling ('B-'), while the default 'Octave' labels
        use 'b' for flats ('BbFBb').

    Examples
    --------
    >>> corpus = CorpusBase(['https://crimproject.org/mei/CRIM_Model_0008.mei',
    ...                      'https://crimproject.org/mei/CRIM_Model_0009.mei'])
    >>> species_df = corpus.melodic_species()
    >>> species_df.groupby('Title')['Octave'].value_counts()
    """
    kwargs = {'limit_to_entries': limit_to_entries,
              'species_intervals': species_intervals,
              'four_five_dict': four_five_dict,
              'octave_dict': octave_dict}
    # results are already in long format with a 'Voice' column (voices are
    # numbered inside the piece method), so skip batch's part numbering
    list_of_dfs = self.batch(ImportedPiece.melodic_species, kwargs=kwargs,
                             metadata=True, number_parts=False)
    result = pd.concat(list_of_dfs, ignore_index=True)
    if final is not None:
        finals = [final] if isinstance(final, str) else list(final)
        result = result[result['Final'].isin(finals)]
    if voices is not None:
        voices = [voices] if isinstance(voices, (str, int)) else voices
        result = result[result['Voice'].isin([str(v) for v in voices])]
    cols = ['Composer', 'Title', 'Date', 'Measure', 'Beat', 'Progress', 'Voice',
            'System', 'Final', 'Interval', 'Species', 'Octave']
    return result[cols].reset_index(drop=True)

modelFinder

modelFinder(models=None, masses=None, n=4, thematic=True, anywhere=True)

Searches for pieces that may be models of one or more masses. This method returns a "driving distance table" showing how likely each model was a source for each mass. This is represented by a score 0-1 where 0 means that this relationship was highly unlikely and 1 means that the the two are highly likely to be related in this way (or that a piece was compared to itself).

Specifically, the value is the percentage of the mass's thematic (i.e. recurring) melodies can be found as thematic melodies from the model. The specific number of times they appear in the model is not considered, provided that it is at least two.

You can optionally pass a CorpusBase object as the models and/or masses parameters. If you do, the CorpusBase object you pass will be used as that group of pieces in the analysis. If either or both of these parameters is omitted, the calling CorpusBase object's scores will be used. For clarity, the "calling"CorpusBaseobject is what goes to the left of the period in:calling_corpus.modelFinder(...)Since the callingCorpusBaseobject's scores are used if themodelsand/ormasses` parameters are omitted, this means that if you omit both, i.e.

calling_corpus.modelFinder()

... this will compare every score the corpus to every other score in the corpus. You should do this if you want to be able to consider every piece a potential model and a potential derivative mass.

Examples:

model_list = ['https://crimproject.org/mei/CRIM_Model_0010.mei',
      'https://crimproject.org/mei/CRIM_Model_0011.mei',
     'https://crimproject.org/mei/CRIM_Model_0014.mei']
mass_list = ['https://crimproject.org/mei/CRIM_Mass_0008_1.mei',
     'https://crimproject.org/mei/CRIM_Mass_0008_2.mei',
      'https://crimproject.org/mei/CRIM_Mass_0008_3.mei']

mod_corp = CorpusBase(model_list)
mass_corp = CorpusBase(mass_list)
cross_plot = mod_corp.modelFinder(masses=mass_corp, models=mod_corp)
cross_plot
Source code in crim_intervals/main_objs.py
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
def modelFinder(self, 
                models=None, 
                masses=None, 
                n=4, 
                thematic=True, 
                anywhere=True):
    """
    Searches for pieces that may be models of one or more masses. This method returns a
    "driving distance table" showing how likely each model was a source for each mass. This
    is represented by a score 0-1 where 0 means that this relationship was highly unlikely
    and 1 means that the the two are highly likely to be related in this way (or that a
    piece was compared to itself). 

    Specifically, the value is the percentage of the mass's
    thematic (i.e. recurring) melodies can be found as thematic melodies from the model. The
    specific number of times they appear in the model is not considered, provided that it is
    at least two.

    You can optionally pass a `CorpusBase` object as the `models` and/or `masses` parameters.
    If you do, the `CorpusBase object you pass will be used as that group of pieces in the
    analysis. If either or both of these parameters is omitted, the calling CorpusBase
    object's scores will be used. For clarity, the "calling" `CorpusBase` object is what goes
    to the left of the period in: `calling_corpus.modelFinder(...)`
    Since the calling `CorpusBase` object's scores are used if the `models` and/or `masses`
    parameters are omitted, this means that if you omit both, i.e.

    ```python
    calling_corpus.modelFinder()
    ```

    ... this will compare every score the corpus to every other score in the corpus. You
    should do this if you want to be able to consider every piece a potential model and
    a potential derivative mass.

    Examples
    --------
    ```python
    model_list = ['https://crimproject.org/mei/CRIM_Model_0010.mei',
          'https://crimproject.org/mei/CRIM_Model_0011.mei',
         'https://crimproject.org/mei/CRIM_Model_0014.mei']
    mass_list = ['https://crimproject.org/mei/CRIM_Mass_0008_1.mei',
         'https://crimproject.org/mei/CRIM_Mass_0008_2.mei',
          'https://crimproject.org/mei/CRIM_Mass_0008_3.mei']

    mod_corp = CorpusBase(model_list)
    mass_corp = CorpusBase(mass_list)
    cross_plot = mod_corp.modelFinder(masses=mass_corp, models=mod_corp)
    cross_plot
    ```
    """
    if models is None:
        models = self
    if masses is None:
        masses = self

    # get entries from all the models
    notes = models.batch(ImportedPiece.notes, number_parts=False, metadata=False, kwargs={'combineUnisons': True})
    mel = models.batch(ImportedPiece.melodic, number_parts=False, metadata=False, kwargs={'df': notes, 'kind': 'd', 'end': False})
    entries = models.batch(ImportedPiece.entries, number_parts=False, metadata=False,
                           kwargs={'df': mel, 'n': n, 'thematic': thematic, 'anywhere': anywhere})

    # get entries from the masses
    mass_notes = masses.batch(ImportedPiece.notes, number_parts=False, metadata=False, kwargs={'combineUnisons': True})
    mass_mel = masses.batch(ImportedPiece.melodic, number_parts=False, metadata=False, kwargs={'df': mass_notes, 'kind': 'd', 'end': False})
    mass_entries = masses.batch(ImportedPiece.entries, number_parts=False, metadata=False,
                                kwargs={'df': mass_mel, 'n': n, 'thematic': thematic, 'anywhere': anywhere})
    res = pd.DataFrame(columns=list(model.file_name for model in models.scores), index=list(mass.file_name for mass in masses.scores))
    res.columns.name = 'Model'
    res.index.name = 'Mass'
    for i, model in enumerate(models.scores):
        mod_patterns = entries[i].stack().unique()
        for j, mass in enumerate(masses.scores):
            stack = mass_entries[j].stack()
            hits = stack[stack.isin(mod_patterns)]
            if len(stack.index):
                percent = len(hits.index) / len(stack.index)
                res.at[mass.file_name, model.file_name] = percent
    return res

moduleFinder

moduleFinder(models=None, masses=None, n=4, ic=False)

Like the `modelFinder, this compares a corpus of pieces, returning a table of percentages of shared ngrams.

In this case the ngrams are contrapuntal modules.

You can optionally pass a CorpusBase object as the models and/or masses parameters. If you do, the CorpusBase object you pass will be used as that group of pieces in the analysis. If either or both of these parameters is omitted, the calling CorpusBase object's scores will be used. For clarity, the "calling" CorpusBase object is what goes to the left of the period in: calling_corpus.moduleFinder(...) Since the calling `CorpusBase object's scores are used if the models and/or masses parameters are omitted, this means that if you omit both, i.e.

calling_corpus.moduleFinder()

... this will compare every score the corpus to every other score in the corpus. You should do this if you want to be able to consider every piece a potential model and a potential derivative mass.

Examples:

model_list = ['https://crimproject.org/mei/CRIM_Model_0010.mei',
      'https://crimproject.org/mei/CRIM_Model_0011.mei',
     'https://crimproject.org/mei/CRIM_Model_0014.mei']
mass_list = ['https://crimproject.org/mei/CRIM_Mass_0008_1.mei',
     'https://crimproject.org/mei/CRIM_Mass_0008_2.mei',
      'https://crimproject.org/mei/CRIM_Mass_0008_3.mei']

mod_corp = CorpusBase(model_list)
mass_corp = CorpusBase(mass_list)
cross_plot = mod_corp.moduleFinder(masses=mass_corp, models=mod_corp)
cross_plot
Source code in crim_intervals/main_objs.py
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
def moduleFinder(self, models=None, masses=None, n=4, ic=False):
    """
    Like the `modelFinder, this compares a corpus of pieces, returning
    a table of percentages of shared ngrams.

    In this case the ngrams are contrapuntal modules.

    You can optionally pass a `CorpusBase` object as the `models` and/or `masses` parameters.
    If you do, the `CorpusBase` object you pass will be used as that group of pieces in the
    analysis. If either or both of these parameters is omitted, the calling `CorpusBase`
    object's scores will be used. For clarity, the "calling" `CorpusBase` object is what
    goes to the left of the period in: `calling_corpus.moduleFinder(...)`
    Since the calling ``CorpusBase` object's scores are used if the `models` and/or `masses`
    parameters are omitted, this means that if you omit both, i.e.

    ```python
    calling_corpus.moduleFinder()
    ```

    ... this will compare every score the corpus to every other score in the corpus. You
    should do this if you want to be able to consider every piece a potential model and a
    potential derivative mass.

    Examples
    --------
    ```python
    model_list = ['https://crimproject.org/mei/CRIM_Model_0010.mei',
          'https://crimproject.org/mei/CRIM_Model_0011.mei',
         'https://crimproject.org/mei/CRIM_Model_0014.mei']
    mass_list = ['https://crimproject.org/mei/CRIM_Mass_0008_1.mei',
         'https://crimproject.org/mei/CRIM_Mass_0008_2.mei',
          'https://crimproject.org/mei/CRIM_Mass_0008_3.mei']

    mod_corp = CorpusBase(model_list)
    mass_corp = CorpusBase(mass_list)
    cross_plot = mod_corp.moduleFinder(masses=mass_corp, models=mod_corp)
    cross_plot
    ```
    """
    if models is None:
        models = self
    if masses is None:
        masses = self
    res = pd.DataFrame(columns=list(model.file_name for model in models.scores), index=list(mass.file_name for mass in masses.scores))
    res.columns.name = 'Model'
    res.index.name = 'Mass'

    if not ic:
        # get modules at entries from all the models using helper
        model_modules = models.batch(ImportedPiece._entry_ngram_helper, kwargs={'n': n}, metadata=False)
        # get modules at entries from the masses using helper
        mass_modules = masses.batch(ImportedPiece._entry_ngram_helper, kwargs={'n': n}, metadata=False)
    else:   # ic == True
        model_modules = models.batch(ImportedPiece.ngrams, kwargs={'n': n, 'held': '1', 'exclude': [], 'show_both': True}, metadata=False)
        mass_modules = masses.batch(ImportedPiece.ngrams, kwargs={'n': n, 'held': '1', 'exclude': [], 'show_both': True}, metadata=False)

    for i, model in enumerate(models.scores):
        mod_patterns = model_modules[i].stack()
        mod_patterns = mod_patterns[~mod_patterns.str.contains('Rest')].unique()
        if ic:
            copy = pd.Series(mod_patterns)
            reduced_patterns = []
            while len(copy.index):
                reduced_patterns.append(copy.iat[0])
                variants = model.ic(module=copy.iat[0], df=model_modules[i])
                copy = copy[~copy.isin(variants.stack().unique())]
            mod_patterns = reduced_patterns
        for j, mass in enumerate(masses.scores):
            if ic and mass.file_name == model.file_name:
                res.at[mass.file_name, model.file_name] = 1
                continue
            df = mass_modules[j]
            df = df[df.map(lambda cell: 'Rest' not in cell, na_action='ignore')].dropna(how='all')
            stack = df.stack()
            if not ic:
                hits = stack[stack.isin(mod_patterns)]
            else:   # ic == True
                ic_targets = []
                for patt in mod_patterns:
                    temp = mass.ic(module=patt, df=mass_modules[j])
                    ic_targets.append(temp.stack().unique())
                unique_targets = np.unique(np.concatenate(ic_targets))
                hits = stack[stack.isin(unique_targets)]
            if len(stack.index):
                percent = len(hits.index) / len(stack.index)
                res.at[mass.file_name, model.file_name] = percent

    return res

note_durs

note_durs(pitch_class=True, aggregate=False, key_sig=False, include_final=True)

Calculate durations of notes in a corpus. Uses helper function extract_letter to extract the letter part of the note as pitch class (optional).

Parameters:

Name Type Description Default
pitch_class bool, optional (default True)

If True, the 'Notes' column holds pitch classes (via extract_letter, octave stripped) rather than full pitch-with-octave note names.

True
aggregate bool, optional (default False)

If False (default), returns one row per individual note attack, with 'Durs' being that single event's duration -- unchanged from this method's original behavior. If True, rows are grouped by (Composer, Title, Voice, Notes, and KeySig/Final if present) and 'Durs' becomes the total summed duration of that pitch/pitch-class in that voice for that piece -- i.e. one row per piece/voice/pitch, useful for corpus studies like modal range/final analysis.

False
key_sig bool, optional (default False)

If True, add a 'KeySig' column giving each piece's prevailing key signature (ImportedPiece.keySignatures(), music21 .sharps convention), repeated on every row for that piece. Defaults to False, in which case the 'KeySig' column is omitted entirely.

False
include_final bool, optional (default True)

If True (the original, default behavior), add a 'Final' column giving each piece's final tone (from ImportedPiece.final(), reduced to pitch class via extract_letter), repeated on every row for that piece. If False, the 'Final' column is omitted entirely.

True

Returns:

Type Description
DataFrame

Columns: Composer, Title, Date, Voice, Notes, Durs, plus 'Final' and/or 'KeySig' if the corresponding argument is True. Since these two columns are optional, callers that concatenate or otherwise combine results across calls with different key_sig/include_final settings should account for the resulting columns possibly being missing rather than assuming they are always present.

Source code in crim_intervals/main_objs.py
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
def note_durs(self,
              pitch_class=True,
              aggregate=False,
              key_sig=False,
              include_final=True):
    """
    Calculate durations of notes in a corpus.
    Uses helper function extract_letter to extract the letter part of the note as pitch class (optional).

    Parameters
    ----------
    pitch_class : bool, optional (default True)
        If True, the 'Notes' column holds pitch classes (via extract_letter,
        octave stripped) rather than full pitch-with-octave note names.
    aggregate : bool, optional (default False)
        If False (default), returns one row per individual note attack, with
        'Durs' being that single event's duration -- unchanged from this
        method's original behavior.
        If True, rows are grouped by (Composer, Title, Voice, Notes, and
        KeySig/Final if present) and 'Durs' becomes the *total* summed
        duration of that pitch/pitch-class in that voice for that piece --
        i.e. one row per piece/voice/pitch, useful for corpus studies like
        modal range/final analysis.
    key_sig : bool, optional (default False)
        If True, add a 'KeySig' column giving each piece's prevailing key
        signature (ImportedPiece.keySignatures(), music21 .sharps
        convention), repeated on every row for that piece. Defaults to
        False, in which case the 'KeySig' column is omitted entirely.
    include_final : bool, optional (default True)
        If True (the original, default behavior), add a 'Final' column
        giving each piece's final tone (from ImportedPiece.final(),
        reduced to pitch class via extract_letter), repeated on every row
        for that piece. If False, the 'Final' column is omitted entirely.

    Returns
    -------
    pd.DataFrame
        Columns: Composer, Title, Date, Voice, Notes, Durs, plus 'Final'
        and/or 'KeySig' if the corresponding argument is True. Since these
        two columns are optional, callers that concatenate or otherwise
        combine results across calls with different key_sig/include_final
        settings should account for the resulting columns possibly being
        missing rather than assuming they are always present.
    """
    func = ImportedPiece.notes  # <- NB there are no parentheses here
    list_of_note_dfs = self.batch(func=func, metadata=True)
    func_voices = ImportedPiece.numberParts
    list_of_note_dfs = self.batch(func=func_voices,
                                   metadata=False,
                                   kwargs={'df': list_of_note_dfs})
    func2 = ImportedPiece.durations  # <- NB there are no parentheses here
    list_of_dur_dfs = self.batch(func=func2, metadata=False)
    list_of_dur_dfs = self.batch(func=func_voices,
                                  metadata=True,
                                  kwargs={'df': list_of_dur_dfs})
    if include_final:
        func3 = ImportedPiece.final
        list_of_finals = self.batch(func=func3, metadata=True)
    else:
        list_of_finals = [None] * len(self.scores)

    if key_sig:
        list_of_key_sigs = [self._prevailing_key_sig(score) for score in self.scores]
    else:
        list_of_key_sigs = [None] * len(self.scores)

    zipped_dfs = zip(list_of_note_dfs, list_of_dur_dfs, list_of_finals, list_of_key_sigs)

    note_dur_dfs = []
    for a, b, c, ks in zipped_dfs:
        id_columns = [col for col in a.columns if col not in ['1', '2', '3', '4', '5', '6', '7', '8']]
        var_cols = [col for col in a.columns if col in ['1', '2', '3', '4', '5', '6', '7', '8']]

        # Now melt the DataFrame
        melted_notes = a.melt(
            id_vars=id_columns,
            value_vars=var_cols,
            var_name='Voice',
            value_name='Notes'
        )
        melted_durs = b.melt(
            id_vars=id_columns,
            value_vars=var_cols,
            var_name='Voice',
            value_name='Durs'
        )

        note_dur = pd.merge(melted_notes, melted_durs, left_index=True, right_index=True, suffixes=('', '_y'))
        note_dur = note_dur.dropna(subset=['Notes', 'Durs'])

        # option to extract pitch class
        if pitch_class == True:
            note_dur['Notes'] = note_dur['Notes'].apply(extract_letter)
        else:
            note_dur['Notes'] = note_dur['Notes']

        if include_final:
            # we always extract the letter from the final
            note_dur['Final'] = c
            note_dur['Final'] = note_dur['Final'].apply(extract_letter)

        if key_sig:
            note_dur['KeySig'] = ks

        note_dur_final = note_dur

        # Drop columns ending with _y
        note_dur_final = note_dur_final.drop(columns=[col for col in note_dur.columns if col.endswith('_y')])
        note_dur_final = note_dur_final.dropna(subset=['Notes', 'Durs'])
        note_dur_final['Durs'] = note_dur_final['Durs'].map(float)
        note_dur_dfs.append(note_dur_final)

    corpus_note_durs = pd.concat(note_dur_dfs)
    if aggregate:
        group_cols = [col for col in ['Composer', 'Title', 'Date', 'Voice', 'Notes', 'KeySig', 'Final']
                      if col in corpus_note_durs.columns]
        # dropna=False: 'Date' is commonly None, and groupby drops all-NaN
        # key rows by default, which would otherwise silently empty the result.
        corpus_note_durs = corpus_note_durs.groupby(group_cols, as_index=False, dropna=False)['Durs'].sum()
    return corpus_note_durs

note_scaled

note_scaled(combine_unisons_choice=True, combine_rests_choice=False, key_sig=False, include_final=False)

Count occurrences of notes and rests in a corpus, including scaled (proportional) counts.

Parameters:

Name Type Description Default
combine_unisons_choice bool

Passed to ImportedPiece.notes as combineUnisons.

True
combine_rests_choice bool

Passed to ImportedPiece.notes as combineRests.

False
key_sig bool, optional (default False)

If True, add a 'KeySig' column giving each piece's prevailing key signature (ImportedPiece.keySignatures(), music21 .sharps convention), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame

One row per (pitch/rest token, piece), with 'count' and 'scaled_count' columns plus Composer/Title (and Final/KeySig if requested).

Source code in crim_intervals/main_objs.py
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
def note_scaled(self, 
                combine_unisons_choice=True, 
                combine_rests_choice=False, 
                key_sig=False, 
                include_final=False):
    """
    Count occurrences of notes and rests in a corpus, including scaled (proportional) counts.

    Parameters
    ----------
    combine_unisons_choice : bool
        Passed to ImportedPiece.notes as `combineUnisons`.
    combine_rests_choice : bool
        Passed to ImportedPiece.notes as `combineRests`.
    key_sig : bool, optional (default False)
        If True, add a 'KeySig' column giving each piece's prevailing key
        signature (ImportedPiece.keySignatures(), music21 .sharps
        convention), repeated on every row for that piece. Defaults to
        False to keep existing output unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
        One row per (pitch/rest token, piece), with 'count' and
        'scaled_count' columns plus Composer/Title (and Final/KeySig if requested).
    """
    func = ImportedPiece.notes  # <- NB there are no parentheses here
    list_of_dfs = self.batch(func=func,
                              kwargs={'combineUnisons': combine_unisons_choice,
                                      'combineRests': combine_rests_choice},
                              metadata=False)
    func1 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func1,
                              kwargs={'df': list_of_dfs},
                              metadata=True)
    finals = self.batch(func=ImportedPiece.final, metadata=False) if include_final else None
    key_sigs = [self._prevailing_key_sig(score) for score in self.scores] if key_sig else None
    final_list_dfs = []
    for idx, df in enumerate(list_of_dfs):
        # clean up
        df = df.map(lambda x: '' if x == 'Rest' else x).fillna('')
        df['1'] = df['1'].map(lambda x: x[:-1])
        df['2'] = df['2'].map(lambda x: x[:-1])
        df = df[df.index != '']

        stacked_df = df.set_index(['Composer', 'Title', 'Date']).stack()
        counted_notes = Counter(stacked_df)
        first_key = next(iter(counted_notes))
        counted_notes.pop(first_key)

        total_n = sum(counted_notes.values())

        counted_notes = pd.Series(counted_notes).to_frame('count').sort_index()
        counted_notes['scaled'] = counted_notes['count'] / total_n
        counted_notes['scaled'] = counted_notes['scaled'].round(2)
        counted_notes.rename(columns={"count": "count", "scaled": "scaled_count"}, inplace=True)

        counted_notes['Composer'] = df.iloc[0]['Composer']
        counted_notes['Title'] = df.iloc[0]['Title']
        if include_final:
            counted_notes['Final'] = finals[idx]
        if key_sig:
            counted_notes['KeySig'] = key_sigs[idx]
        counted_notes = counted_notes[counted_notes.index != '']
        final_list_dfs.append(counted_notes)

    corpus_notes_counts = pd.concat(final_list_dfs)
    return corpus_notes_counts

note_weights

note_weights(include_rests=True, key_sig=False, include_final=False)

Calculate pitch class weights by duration in a corpus. Notes are grouped by pitch class and weighted by their total duration, yielding a scaled proportion for each pitch class per piece.

Parameters:

Name Type Description Default
include_rests bool, optional (default True)

Whether to include rests as a pitch class (labeled 'Rest') in the weighting, or drop them and scale proportions over sounding notes only.

True
key_sig bool, optional (default False)

If True, add a 'key_sig' column giving each piece's prevailing key signature (ImportedPiece.keySignatures(), music21 .sharps convention), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False
include_final bool, optional (default False)

If True, add a 'final' column giving each piece's final as a pitch class (e.g. 'G', matching voice_ranges and melodic_species), repeated on every row for that piece. Useful for grouping or filtering by final.

False

Returns:

Type Description
DataFrame

One row per (pitch_class, piece), with 'count' (summed duration), 'scaled' (proportion of the piece's total), 'composer', 'title' (and 'final'/'key_sig' if requested).

Source code in crim_intervals/main_objs.py
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
def note_weights(self, 
                 include_rests=True, 
                 key_sig=False, 
                 include_final=False):
    """
    Calculate pitch class weights by duration in a corpus.
    Notes are grouped by pitch class and weighted by their total duration,
    yielding a scaled proportion for each pitch class per piece.

    Parameters
    ----------
    include_rests : bool, optional (default True)
        Whether to include rests as a pitch class (labeled 'Rest') in the
        weighting, or drop them and scale proportions over sounding notes only.
    key_sig : bool, optional (default False)
        If True, add a 'key_sig' column giving each piece's prevailing key
        signature (ImportedPiece.keySignatures(), music21 .sharps
        convention), repeated on every row for that piece. Defaults to
        False to keep existing output unchanged.
    include_final : bool, optional (default False)
        If True, add a 'final' column giving each piece's final as a pitch
        class (e.g. 'G', matching voice_ranges and melodic_species), repeated
        on every row for that piece. Useful for grouping or filtering by final.

    Returns
    -------
    pd.DataFrame
        One row per (pitch_class, piece), with 'count' (summed duration),
        'scaled' (proportion of the piece's total), 'composer', 'title'
        (and 'final'/'key_sig' if requested).
    """
    list_of_dfs = self.batch(func=ImportedPiece.note_weights,
                             kwargs={'include_rests': include_rests, 'key_sig': key_sig,
                                     'include_final': include_final},
                             metadata=False)
    if not list_of_dfs:
        return pd.DataFrame(columns=['pitch_class', 'count', 'scaled', 'composer', 'title'])
    return pd.concat(list_of_dfs, ignore_index=True)

notes

notes(combine_unisons_choice=True, combine_rests_choice=False, key_sig=False, include_final=False)

Creates table of notes and rests in a corpus, one row per attack/rest offset and one column per numbered voice, with Composer/Title/Date columns prepended.

Parameters:

Name Type Description Default
combine_unisons_choice bool

Passed to ImportedPiece.notes as combineUnisons. If True, consecutive attacks on the same pitch in a voice are combined. Default False there, but this wrapper defaults to True.

True
combine_rests_choice bool

Passed to ImportedPiece.notes as combineRests. If True (the ImportedPiece default), consecutive rests in a voice are combined. Defaults to False here so that individual rests remain visible.

False
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, and flatten it into a 'KeySig' column. Defaults to False to keep the existing index/columns unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Useful for corpus studies that group or filter results by mode/final. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
def notes(self,
          combine_unisons_choice=True, 
          combine_rests_choice=False, 
          key_sig=False, 
          include_final=False):
    """
    Creates table of notes and rests in a corpus, one row per attack/rest
    offset and one column per numbered voice, with Composer/Title/Date
    columns prepended.

    Parameters
    ----------
    combine_unisons_choice : bool
        Passed to ImportedPiece.notes as `combineUnisons`. If True, consecutive
        attacks on the same pitch in a voice are combined. Default False there,
        but this wrapper defaults to True.
    combine_rests_choice : bool
        Passed to ImportedPiece.notes as `combineRests`. If True (the
        ImportedPiece default), consecutive rests in a voice are combined.
        Defaults to False here so that individual rests remain visible.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, and flatten it into a 'KeySig' column. Defaults to
        False to keep the existing index/columns unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece. Useful
        for corpus studies that group or filter results by mode/final.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    func = ImportedPiece.notes  # <- NB there are no parentheses here
    list_of_dfs = self.batch(func=func,
                              kwargs={'combineUnisons': combine_unisons_choice, 'combineRests': combine_rests_choice},
                              metadata=False)
    if key_sig:
        func_ks = ImportedPiece.detailIndex
        list_of_dfs = self.batch(func=func_ks,
                                  kwargs={'df': list_of_dfs, 'measure': False, 'beat': False, 'key_sig': True},
                                  metadata=False)
    func1 = ImportedPiece.numberParts
    list_of_dfs = self.batch(func=func1,
                              kwargs={'df': list_of_dfs},
                              metadata=True)
    if include_final:
        finals = self.batch(func=ImportedPiece.final, metadata=False)
        list_of_dfs = [df.assign(Final=final) for df, final in zip(list_of_dfs, finals)]

    nr = pd.concat(list_of_dfs)
    cols_to_move = ['Composer', 'Title', 'Date', 'Final'] if include_final else ['Composer', 'Title', 'Date']   
    nr = nr[cols_to_move + [col for col in nr.columns if col not in cols_to_move]]
    if key_sig:
        nr = nr.reset_index()
    return nr

presentation_types

presentation_types(limit_to_entries=True, head_flex=1, body_flex=0, include_hidden_types=False, combine_unisons=True, melodic_ngram_length=4, kind='d', end=False)

Return presentation types for all pieces in the corpus.

Source code in crim_intervals/main_objs.py
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
def presentation_types(self,
                        limit_to_entries=True,
                        head_flex=1,
                        body_flex=0,
                        include_hidden_types=False,
                        combine_unisons=True,
                        melodic_ngram_length=4,
                        kind='d',
                        end=False):
    """
    Return presentation types for all pieces in the corpus.
    """
    func = ImportedPiece.presentationTypes  # <- NB there are no parentheses here
    kwargs = {'limit_to_entries': limit_to_entries,
              'head_flex': head_flex,
              'body_flex': body_flex,
              'include_hidden_types': include_hidden_types,
              'combine_unisons': combine_unisons,
              'melodic_ngram_length': melodic_ngram_length,
              'kind': kind,
              'end': end}

    list_of_dfs = self.batch(func, kwargs, metadata=True)
    corpus_presentation_types = pd.concat(list_of_dfs)
    return corpus_presentation_types

sonority_ngrams

sonority_ngrams(ngram_length=4, metadata_choice=True, include_offset=False, include_progress=True, compound=True, sort=False, minimum_beat_strength=0.0, key_sig=False, include_final=False)

Generate sonority n-grams (plus bassline) in a corpus.
These are complex n-grams that combine the sonority (chord) formed by all tones sounding at each moment the melodic interval formed by the low line (bass) of each sonority.

We can also filter out any sonorities that occur on weak beats (below minimum_beat_strength).

These sonority ngrams are very useful for finding block repetitions within and among pieces, regardless of the specific voices in which they are heard.

Parameters:

Name Type Description Default
ngram_length

Passed through to ImportedPiece.sonorities/ImportedPiece.ngrams.

4
compound

Passed through to ImportedPiece.sonorities/ImportedPiece.ngrams.

4
sort

Passed through to ImportedPiece.sonorities/ImportedPiece.ngrams.

4
minimum_beat_strength

Passed through to ImportedPiece.sonorities/ImportedPiece.ngrams.

4
metadata_choice bool

Whether to attach Composer/Title/Date columns.

True
include_offset bool

Whether detailIndex should also include each row's raw offset.

False
include_progress bool

Whether detailIndex should include the 0-1 progress-through-piece column.

True
key_sig bool, optional (default False)

If True, add the prevailing system key signature (ImportedPiece .keySignatures(), music21 .sharps convention) to the row index via detailIndex, alongside Measure/Beat. Defaults to False to keep the existing index shape unchanged.

False
include_final bool, optional (default False)

If True, add a 'Final' column giving each piece's final tone (from ImportedPiece.final()), repeated on every row for that piece. Defaults to False to keep existing output unchanged.

False

Returns:

Type Description
DataFrame
Source code in crim_intervals/main_objs.py
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
def sonority_ngrams(self,
                     ngram_length=4,
                     metadata_choice=True,
                     include_offset=False,
                     include_progress=True,
                     compound=True,
                     sort=False,
                     minimum_beat_strength=0.0,
                     key_sig=False,
                     include_final=False):
    """
    Generate sonority n-grams (plus bassline) in a corpus.  
    These are complex n-grams that combine the sonority (chord) formed by all tones sounding at each moment 
    the melodic interval formed by the low line (bass) of each sonority.

    We can also filter out any sonorities that occur on weak beats (below `minimum_beat_strength`).

    These sonority ngrams are very useful for finding block repetitions within and among pieces, regardless of the specific voices in which they are heard. 

    Parameters
    ----------
    ngram_length, compound, sort, minimum_beat_strength
        Passed through to ImportedPiece.sonorities/ImportedPiece.ngrams.
    metadata_choice : bool
        Whether to attach Composer/Title/Date columns.
    include_offset : bool
        Whether detailIndex should also include each row's raw offset.
    include_progress : bool
        Whether detailIndex should include the 0-1 progress-through-piece column.
    key_sig : bool, optional (default False)
        If True, add the prevailing system key signature (ImportedPiece
        .keySignatures(), music21 .sharps convention) to the row index via
        detailIndex, alongside Measure/Beat. Defaults to False to keep the
        existing index shape unchanged.
    include_final : bool, optional (default False)
        If True, add a 'Final' column giving each piece's final tone (from
        ImportedPiece.final()), repeated on every row for that piece.
        Defaults to False to keep existing output unchanged.

    Returns
    -------
    pd.DataFrame
    """
    # Composer/Title/Date are always included, since they are what tell
    # the pieces apart; metadata_choice is kept for backward compatibility.
    kwargs = {'ngram_length': ngram_length, 'metadata_choice': True,
              'include_offset': include_offset, 'include_progress': include_progress,
              'compound': compound, 'sort': sort,
              'minimum_beat_strength': minimum_beat_strength,
              'key_sig': key_sig, 'include_final': include_final}
    list_of_dfs = self.batch(func=ImportedPiece.sonority_ngrams, kwargs=kwargs,
                             metadata=False, number_parts=False)
    corpus_son_bass_ngrams = pd.concat(list_of_dfs, ignore_index=True)
    return corpus_son_bass_ngrams

tuple_to_list

tuple_to_list(value, separator=None, cast=None)

Convert tuple-like values to a list using the shared helper.

Source code in crim_intervals/main_objs.py
5856
5857
5858
def tuple_to_list(self, value, separator=None, cast=None):
    """Convert tuple-like values to a list using the shared helper."""
    return tuple_to_list(value, separator=separator, cast=cast)

tuple_to_string

tuple_to_string(value, separator=', ')

Convert tuple-like values to a string using the shared helper.

Source code in crim_intervals/main_objs.py
5860
5861
5862
def tuple_to_string(self, value, separator=', '):
    """Convert tuple-like values to a string using the shared helper."""
    return tuple_to_string(value, separator=separator)

voice_ranges

voice_ranges(top_n=7, final=None, voices=None)

Return voice ranges for every piece in the corpus, as used to distinguish modal types. See ImportedPiece.voice_ranges for how the ranges are found.

Composer and title metadata are added from the source files.

Parameters:

Name Type Description Default
top_n int, optional (default 7)

How many of each voice's most prominent pitches to consider.

7
final str or list of str

Keep only pieces with this final (pitch class, e.g. 'G' or ['D', 'G']). Default: all pieces.

None
voices str, int, or list

Keep only these voices by staff number (1 = highest), e.g. 2 or ['1', '2']. Default: all voices.

None

Returns:

Type Description
DataFrame

Columns: Composer, Title, Date, Voice, Final, LowestNote, HighestNote, Range. Pass this to visualizations.voice_range_chart to plot it.

Source code in crim_intervals/main_objs.py
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
@_records_settings('voice_ranges', ('top_n', 'final', 'voices'), inherit=())
def voice_ranges(self, top_n=7, final=None, voices=None):
    """
    Return voice ranges for every piece in the corpus, as used to
    distinguish modal types. See `ImportedPiece.voice_ranges` for how the
    ranges are found.

    Composer and title metadata are added from the source files.

    Parameters
    ----------
    top_n : int, optional (default 7)
        How many of each voice's most prominent pitches to consider.
    final : str or list of str, optional
        Keep only pieces with this final (pitch class, e.g. 'G' or
        ['D', 'G']). Default: all pieces.
    voices : str, int, or list, optional
        Keep only these voices by staff number (1 = highest), e.g. 2 or
        ['1', '2']. Default: all voices.

    Returns
    -------
    pandas.DataFrame
        Columns: Composer, Title, Date, Voice, Final, LowestNote,
        HighestNote, Range. Pass this to `visualizations.voice_range_chart`
        to plot it.
    """
    list_of_dfs = self.batch(ImportedPiece.voice_ranges,
                             kwargs={'top_n': top_n}, metadata=True)
    result = pd.concat(list_of_dfs, ignore_index=True)
    if final is not None:
        finals = [final] if isinstance(final, str) else list(final)
        result = result[result['Final'].isin(finals)]
    if voices is not None:
        voices = [voices] if isinstance(voices, (str, int)) else voices
        result = result[result['Voice'].isin([str(v) for v in voices])]
    cols = ['Composer', 'Title', 'Date', 'Voice', 'Final', 'LowestNote', 'HighestNote', 'Range']
    return result[cols].reset_index(drop=True)

importScore

importScore(path, recurse=False, verbose=False)

Import piece or group of pieces and return an ImportedPiece or CorpusBase object respectively. Return None if there is an error. This function accepts piece urls, and local paths. A list of the accepted file formats can be found in the accepted_filetypes tuple. This function also accepts directories and will import all the score files within a passed directory. Set recurse=True (default False) to import all score files from the passed directory *and* those of all subdirectories. Setverbose=True` (default False) to print out confirmation of import success for each piece. If any errors are encountered, these issues will be printed out regardless of verbose setting.

Source code in crim_intervals/main_objs.py
 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
def importScore(path, recurse=False, verbose=False):
    """
    Import piece or group of pieces and return an `ImportedPiece` or `CorpusBase` object respectively.
    Return None if there is an error. This function accepts piece urls, and local paths. A list of
    the accepted file formats can be found in the accepted_filetypes tuple. This function also
    accepts directories and will import all the score files within a passed directory. Set
    `recurse=True (default False) to import all score files from the passed directory *and* those
    of all subdirectories. Set `verbose=True` (default False) to print out confirmation of import
    success for each piece. If any errors are encountered, these issues will be printed out
    regardless of verbose setting.
    """
    if os.path.isdir(path):
        files = os.listdir(path)
        files = [os.path.join(path, file) for file in files]
        scores = []
        for file in files:
            if os.path.isdir(file) and recurse:
                score_list = importScore(file, recurse, verbose)
                if score_list is not None and len(score_list.scores):
                    scores.extend(score_list.scores)
            elif os.path.isfile(file):
                score = importScore(file, verbose=verbose)
                if score is not None:
                    scores.append(score)

        if len(scores):
            return CorpusBase(scores)
        elif verbose:
            print('No scores found in this directory: {}'.format(path))
        return

    date = None
    if path in pathDict and verbose:
        print('Previously imported piece detected.')
    else:
        mei_doc = None
        if path.startswith('http'):
            if verbose:
                print('Downloading remote score...')
            try:
                to_import = httpx.get(path).text
                mei_doc = ET.fromstring(to_import) if path.endswith('.mei') else None
            except:
                print('Error downloading',  str(path) + ', please check',
                      'your url and try again. Continuing to next file.')
                return None
        elif os.path.isfile(path):  # `path` is formatted like a file path
            ending = path.rsplit('.', 1)[1]
            if ending not in accepted_filetypes:
                return None
            if path.endswith('.mei'):
                try:
                    with open(path, "r") as file:
                        to_import = file.read()
                        mei_doc = ET.fromstring(to_import)
                except ET.ParseError as err:
                    print('Error reading the mei file tree of {}'.format(path), err, sep='\n')
            else:
                to_import = path
        else: # `path` is actually the string of an entire piece, used for user-supplied piece in streamlit
            to_import = path
            if '<mei' in path[:1000]: # is an <mei> element in the beginning of the piece?
                try:
                    mei_doc = ET.fromstring(to_import)
                except ET.ParseError as err:
                    print('Error reading this mei file:'.format(path[:200], err, sep='\n'))
        try:
            if mei_doc is not None:
                to_import = re.sub(suppliedPattern, '\\1', to_import)
                _date = re.search(datePattern, to_import)
                if _date:
                    date = int(_date.group(1))
            score = converter.parse(to_import)
            pathDict[path] = ImportedPiece(score, path, mei_doc, date)
            if verbose:
                print("Successfully imported", path[:180])
        except:
            print("Import of", str(path[:180]), "failed, please check your file, path, or url.")
            return None

    return pathDict[path]

Crimport

Crimport(path, recurse=False, verbose=False)

Better naming convention for importing single files or directories of files. This is an alias for importScore. See that method's doc string for instructions.

Source code in crim_intervals/main_objs.py
152
153
154
155
156
def Crimport(path, recurse=False, verbose=False):
    '''
    Better naming convention for importing single files or directories of files. This is
    an alias for `importScore`. See that method's doc string for instructions.'''
    return importScore(path, recurse, verbose)

joiner

joiner(a)

This is used for visualization routines.

Source code in crim_intervals/main_objs.py
4893
4894
4895
def joiner(a):
    """This is used for visualization routines."""
    return tuple_to_string(a, separator='_')

clean_melody_new

clean_melody_new(c)

This gets used for visualization routines.

Source code in crim_intervals/main_objs.py
4896
4897
4898
4899
4900
def clean_melody_new(c):
    """This gets used for visualization routines."""
    first_soggetto = list(c[0])
    soggetto_as_word = joiner(first_soggetto)
    return soggetto_as_word