DEV Community

Daniel McMahon
Daniel McMahon

Posted on

Visualizing Fibonacci: For the Music Lover in You!

First time article so excuse the typos and errors!

A Common Problem: Programming the Fibonacci Series

Throughout my recent computer science conversion course I studied introductions to both Python and Java. Across both languages one of the common challenges presented was to be to write a program to display up to the n-th number of the Fibonacci Series. This seems to be a common stepping stone for most programmers when learning a new language.

The Fibonacci Series

Having found myself wanting to apply what I was learning in class to an independent project, I had stumbled across this idea of visualizing the Fibonacci Series as sheet music. I don't quite remember where or when I had heard of the idea - possibly from Matt Parker, Hannah Fry or one of my lecturers in passing. I had googled the topic and didn't find any immediate practical implementation of the Fibonacci series being visualized on sheet music. Therein lay my task. In retrospect perhaps a quick github search would have yielded more results - but again I was a younger and more naive developer then I am today.

Python - Which Libraries?

Ok so I had the overall project idea - generate up to the n-th number of the Fibonacci series and somehow visualize that data on sheet music. After some quick research I had settled on using a Python library called Mingus in combination with the program Lilypond

How not to waste time rebuilding a python2 library to work with python3...

This should go without saying, at the time I was less experienced and prone to these errors. I ended up downloading a version of Mingus that ran on Python2 while I was running Python3. Rather than looking up if a Python 3 package existed, I ended up doing some manual tweaking of the package to make it work. D'oh! For the younger Dev's out there be sure to check the python versions of any installed packages!

The Chromatic Scale

While not the most elegant solution I ended up essentially modifying a previously developed college solution that outputted the Fibonacci series up to the n-th number, and used a modulus of that number to determine which note it would represent. Using a modulus of 12 I was able to associate the various numbers to all the notes in a chromatic scale starting on a base note of C (I only used sharps for convenience sake)

The Chromatic Scale

After establishing the connection between the Fibonacci series and the chromatic notes of the scale the only 'difficult part' from there was essentially figuring out how to translate these generated notes into sheet music.

After importing the Mingus library this was actually pretty straight forward!
The code looked a little like this (yes I know its a little inefficient - I haven't gone back and refactored the code since it was originally thrown together):

from mingus.containers import Bar
from mingus.containers import Composition
from mingus.containers import Track
from mingus.containers import NoteContainer
import mingus.extra.LilyPond as LilyPond

x = int(input('Song Length (number of notes): '))

song = []
b = Bar() # creates new bar element for Mingus = has limit of 4/4 timing by default
b.set_meter((4,4))

c = Composition()
c.set_author('Daniel McMahon', 'daniel40392@gmail.com')
c.set_title('Ode to Fibonnachi')
t = Track()
t.add_bar(b)
c.add_track(t)

def fib(n):
    """Function that generates notes based off the Fibonnachi Series"""
    a=0
    b=1
    print('Generating Music.... Please Wait....',end='')

    for i in range (1,n+1):
        fib=a+b
        if fib%12==1:
            song.append('C')
        elif fib%12==2:
            song.append('C#')
        elif fib%12==3:
            song.append('D')
        elif fib%12==4:
            song.append('D#')
        elif fib%12==5:
            song.append('E')
        elif fib%12==6:
            song.append( 'F')
        elif fib%12==7:
            song.append('F#')
        elif fib%12==8:
            song.append('G')
        elif fib%12==9:
            song.append('G#')
        elif fib%12==10:
            song.append( 'A')
        elif fib%12==11:
            song.append('A#')
        elif fib%12==0:
            song.append('B')
        a=b
        b=fib

    #this code will print song in reverse
    #for i in reversed(song):
    #    print (i + ' ,', end='')

    n = NoteContainer(song)

while x != '':
    fib(x)
    print()
    for note in song:
            b + note
            c.add_note(note)
    comp = LilyPond.from_Composition(c)
    LilyPond.to_pdf(comp, "Ode_to _Fibonnachi")
    print("Song completed - check desktop for exported PDF")
    x = int(input('Song Length (number of notes): '))
Enter fullscreen mode Exit fullscreen mode

The Result?

Below is a small snapshot of the result - an interesting pattern emerges for the outputted music showing a repeated pattern every 25 or so notes!

Ode to Fibonacci

A link to the GitHub repo is available here with the sample output available as a PDF file.

Some additional ideas and experiments...

This sheet music generation approach would work well with other mathematical series - the immediate ones that I thought of adopting include the Catalan and Figurate series. Some sample Fibonacci note generations for these are also included in the linked repo above.

It may also be worth experimenting with starting on a different note of the chromatic scale - however the intervals will still remain the same between the notes.

The next logical step in this project is to get musical output from the generated sheet music. I had initially tried this when working on the project 2 years ago on an old Windows laptop, I will have to go back to it soon and see if I can get some live musical feedback integrated.

Another interesting approach I've taken in the repository is using the NLTK library to generate the frequency of note appearances in different series of Fibonacci numbers. You get some fascinating results using different mathematical series - I recommend experimenting with it yourself!

Some Final Thoughts

The project itself was used as a basic way to integrate my love of music into my coding. The Fibonacci series can be considered quite a boring topic when attempting to implement it in a new language, but when you add in some of these basic additional steps you can generate something really interesting and creative!

I would always encourage new developers to explore the basic building blocks of programming languages in new and creative ways. Personally you may find it more rewarding - plus its a great way to build up your personal portfolio and have something extra to chat about in any future job interviews!

Perhaps you've tried programming something similar in different languages with interesting results - I'd love to hear about it - be sure to leave any feedback or comments below.

Again excuse any typos or formatting issues - its my first of hopefully many posts here!

Warmest Regards,
Daniel McMahon

Top comments (9)

Collapse
 
matthras profile image
Matthew Mack • Edited

Haven't done it myself due to time/distractions/other projects, but have been wanting to convert the digits of pi or e into sheet music. The only catch is that there are only 10 single digits, but 12 notes of the chromatic scale. This is easily solved by converting the aforementioned numbers into base 12 (our normal numbers are in base 10, binary is in base 2, hexadecimal is in base 16, etc.) but I haven't looked into how to do that for decimal places.

I might whip up a web version of this if OP is OK with it, but for any interested others, you can do it entirely front-end using Vexflow (for displaying the music) and Band.js (for generating the audio).

Collapse
 
danku profile image
Daniel McMahon

Go for it! Be sure to post your updates here would love to see and hear the results!

Collapse
 
danku profile image
Daniel McMahon

really like the idea of converting to a different base as well, could have some other potential implications!

Collapse
 
vdaluz profile image
Victor Da Luz • Edited

Great article!

I was inspired to output this to midi and also to restrict it so that the generated notes are in key. There's a lot to be explored in this topic, thanks for sharing.

gist.github.com/vdaluz/1baa55edcfb...

Collapse
 
danku profile image
Daniel McMahon

Thats awesome great job Victor!

Collapse
 
rpalo profile image
Ryan Palo

This is really neat, thanks for sharing!

Collapse
 
eoinkenny profile image
Eoin Kenny

I'll have an "Ode to Dan" tonight.

Collapse
 
hdv profile image
Hussein Duvigneau

Away from home and don't have my piano handy; how does this sound?

Collapse
 
danku profile image
Daniel McMahon

Its a little disccordant to my ears but definitely try it out next time your at a piano!