## DEV Community is a community of 890,178 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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.

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)

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()

def fib(n):
"""Function that generates notes based off the Fibonnachi Series"""
a=0
b=1

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
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): '))
``````

## 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!

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

## Discussion (9)

Matthew Mack • Edited on

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).

Daniel McMahon

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

Daniel McMahon

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

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...

Daniel McMahon

Thats awesome great job Victor!

Ryan Palo

This is really neat, thanks for sharing!

Eoin Kenny

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

Hussein Duvigneau

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

Daniel McMahon

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