Search code examples
pythonmusic21

Does music21 include a note transition counter?


I'm trying to get transition rates between note pitches (just name, no octave) in a given melody. For example, if my melody pitches are (in order) C D E D F C B C, I should get that the C-D transition occurs with 0.5 rate, B-C has rate 1, etc.

I should be able to write a function in Python to do this (probably using a lot of elifs...) but it looks like music21 must be able to do it easily too. I looked at the documentation, Google, other questions here... and I couldn't find how, but I suspect I'm missing a toolkit that may be really useful for me.


Solution

  • I'd suggest doing something like:

    from music21.ext.more_itertools import windowed
    from collections import Counter
    # assuming s is your Stream
    nameTuples = []
    for n1, n2 in windowed(s.recurse().notes, 2):
        nameTuples.append((n1.name, n2.name))
    c = Counter(nameTuples)
    totalNotes = len(s.recurse().notes) # py2 cast to float
    {k : v / totalNotes for k, v in c.items()}
    

    Nice thing about windowed is that it's easy to create Trigrams, etc.