Skip to content

Melodic Attraction

melodic_attraction

melodic_attraction(
    score: Score, key: int | None = None
) -> Score | None

Calculate melodic attraction for each note according to Lerdahl (1996). Return the transposed score, where every note is annotated with the melodic attraction values (between 0 and 1). The annotated field within each note of the annotated transposed score if successful is "melodic_attraction."

The algorithm works as follows: Each tone in key has a certain anchoring strength ("weight") in tonal pitch space. Melodic attraction strength is dependent on the anchor values dependent on the pitch-classes in a two-note window, while is affected by the distance between tones.

The algorithm has two extensions (also ported from miditoolbox): Extension 1: attraction is modified not only by subsequent neighbor but also on the pitch's other potential neighbors (this is realized in the way Lerdahl suggested, not only limiting the attraction to one neighbor but to all possible neighbors within a specific window). Extension 2: directed motion also affects melodic attraction (this is done somewhat differently than in Lerdahl's paper due to modification of the first extension).

One thing of note is that, our implementation makes extensive use of generators, because the author found it to be the easiest way to keep track of all the components while minimizing the amount of data structures needed to keep track of score notes.

TODO: Should we include parameter space for more pitch profiles?

Parameters:

  • score (Score) –

    A Score object containing the melody to analyze

  • key (int, default: None ) –

    MIDI pitch number representing the key. If None, first note is used as tonic

Returns:

  • Score –

    Transpose of the original score to C-major, where all the notes are annotated with attraction values between 0 and 1

References
Lerdahl, F. (1996). Calculating tonal tension. Music Perception, 13(3),
    319-363.
Source code in amads/melody/melodic_attraction.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def melodic_attraction(score: Score, key: int | None = None) -> Score | None:
    """
    Calculate melodic attraction for each note according to Lerdahl (1996).
    Return the transposed score, where every note is annotated with the
    melodic attraction values (between 0 and 1).
    The annotated field within each note of the annotated transposed score if
    successful is "melodic_attraction."

    The algorithm works as follows:
    Each tone in key has a certain anchoring strength ("weight") in tonal pitch
    space. Melodic attraction strength is dependent on the anchor values dependent
    on the pitch-classes in a two-note window, while is affected by the distance
    between tones.

    The algorithm has two extensions (also ported from miditoolbox):
    Extension 1: attraction is modified not only by subsequent neighbor but also
    on the pitch's other potential neighbors (this is realized in the way
    Lerdahl suggested, not only limiting the attraction to one neighbor but to
    all possible neighbors within a specific window).
    Extension 2: directed motion also affects melodic attraction (this is done somewhat
    differently than in Lerdahl's paper due to modification of the first extension).

    One thing of note is that, our implementation makes extensive use of
    generators, because the author found it to be the easiest way to keep track
    of all the components while minimizing the amount of data structures needed
    to keep track of score notes.

    TODO: Should we include parameter space for more pitch profiles?

    Parameters
    ----------
    score : Score
        A Score object containing the melody to analyze
    key : int, optional
        MIDI pitch number representing the key. If None, first note is used as tonic

    Returns
    -------
    Score
        Transpose of the original score to C-major, where all the notes are
        annotated with attraction values between 0 and 1

    References
    ----------
        Lerdahl, F. (1996). Calculating tonal tension. Music Perception, 13(3),
            319-363.
    """

    if next(score.find_all(Note), None) is None:
        return None
    if not score.ismonophonic():
        return None

    transposed_score = transpose2c(score)
    if transposed_score is None:
        return None
    mode_strs = keymode(transposed_score)
    if mode_strs is None:
        return None

    note_gen = transposed_score.find_all(Note)
    # generate 4 independent tee iterators to generate the new feature iterators
    tee_note_gens = tee(note_gen, 4)

    anchorweights, anchorweights_gen = _get_anchorweights(
        tee_note_gens[0], mode_strs
    )
    direct_motion_gen = _get_directed_motion_indices(tee_note_gens[1])
    proximity_gen = _get_proximity(tee_note_gens[2])

    throwaway_aw_gen, anchorweights_gen = tee(anchorweights_gen)
    first_anchorweight = next(throwaway_aw_gen, None)
    if first_anchorweight is None:
        return None

    # set first note value to 0.0 as in miditoolbox
    annotation_str = "melodic_attraction"
    first_note_gen, transposed_score_iter = tee(tee_note_gens[3])
    first_note = next(first_note_gen, None)
    assert first_note is not None
    first_note.set(annotation_str, 0.0)

    iterators = []
    iterators.append(pairwise(anchorweights_gen))
    iterators.append(direct_motion_gen)
    iterators.append(pairwise(proximity_gen))
    iterators.append(pairwise(transposed_score_iter))

    for anchors, motion_val, proximities, notes in zip(*iterators):
        if anchors[0] >= anchors[1]:
            anchoring_val = 0
        else:
            anchoring_val = _get_lerdahl_attraction(
                anchors[0], anchors[1], proximities[1]
            )
        # pitch window for finding a more stable alternative
        # pitch difference x >= -4 and x < 5
        stable_candidates_window = (-4, 5)

        # check condition for neighbors
        neighbors = [
            anchorweights[(i + notes[0].pitch_class) % 12]
            for i in range(*stable_candidates_window)
        ]

        neighbor_checks = [
            first_anchorweight < neighbor
            for i, neighbor in enumerate(neighbors)
        ]
        neighbor_checks[len(neighbor_checks) // 2] = False

        correction = 0
        # algorithmic extensions that were present in midi_toolbox
        if any(check for check in neighbor_checks):
            original_anchor = notes[1].midi_num - notes[0].midi_num
            new_anchor = neighbor_checks.index(True)
            # checks if the anchor is within the stable candidates window
            if (
                original_anchor < stable_candidates_window[1]
                and original_anchor >= stable_candidates_window[0]
                and new_anchor != original_anchor
            ):
                neighbor_checks[new_anchor] = False
            best_alternative = 0
            sum_of_alternatives = 0.0
            all_alternative_attraction = []
            for i, (neighbor, check) in enumerate(
                zip(neighbors, neighbor_checks)
            ):
                if check:
                    alternative_anchor = neighbor
                    assert alternative_anchor > 0
                    assert anchors[0] > 0
                    distance = abs(i + stable_candidates_window[0])
                    alternative_attraction = _get_lerdahl_attraction(
                        anchors[0], alternative_anchor, distance
                    )
                    sum_of_alternatives += alternative_attraction
                    all_alternative_attraction.append(alternative_attraction)
                    best_alternative = max(
                        best_alternative, alternative_attraction
                    )

            correction = (
                sum_of_alternatives - best_alternative
            ) * 0.5 + best_alternative

        anchoring_val -= correction
        attraction = (motion_val + anchoring_val + 1) / 5
        # clips attraction to be within 0.0 and 1.0
        attraction = max(min(attraction, 1.0), 0.0)
        notes[1].set(annotation_str, attraction)

    return transposed_score