.. _installIPython:

.. WARNING: DO NOT EDIT THIS FILE:
   AUTOMATICALLY GENERATED.
   PLEASE EDIT THE .py FILE DIRECTLY.


Using ``music21`` with the Jupyter (iPython) Notebook
=====================================================

Setting up the Jupyter environment
----------------------------------

To get ``music21`` to work it's best to have a good pip installation
first. Then you should be able to simply install jupyter (and IPython if
you don't have it):

``$ sudo pip install jupyter $ sudo pip install ipython``

Using the web-based Jupyter Notebook
------------------------------------

Start jupyter in a directory you want to save files by typing.

```$ jupyter notebook```

Now in the webbrowser you can type commands such as the ones below:

.. code:: python

    from music21 import *

.. code:: python

    c = chord.Chord("C4 E4 G4")
    c.isConsonant()




.. parsed-literal::
   :class: ipython-result

    True



All other normal ``music21`` commands will work as they should

Displaying graphics inline
--------------------------

By default, you cannot just call .show() because you'll open up your
MusicXML reader locally...

.. code:: python

    c.show()




.. parsed-literal::
   :class: ipython-result

    <music21.ipython21.objects.IPythonPNGObject at 0x1054dcf60>



Nor does just generating a lilypond PNG or PDF work as you'd like --
this will display it on the screen but not in your browser:

.. code:: python

    c.show('lily.pdf')

Instead do this:

.. code:: python

    %load_ext music21.ipython21

Now this will work:

.. code:: python

    c.show()




.. image:: installIPython_18_0.png



If you don't want to do that, then instead do this...

.. code:: python

    from IPython.core.display import Image

.. code:: python

    #_DOCS_SHOW Image(filename=c.write('lily.png'))

SVG is much faster, but it doesn't work, sadly...

.. code:: python

    Image(filename=c.write('lily.svg'))


::


    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    <ipython-input-9-a78ad09b705c> in <module>()
    ----> 1 Image(filename=c.write('lily.svg'))
    

    /Users/cuthbert/anaconda/lib/python3.4/site-packages/IPython/core/display.py in __init__(self, data, url, filename, format, embed, width, height, retina, unconfined, metadata)
        731 
        732         if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
    --> 733             raise ValueError("Cannot embed the '%s' image format" % (self.format))
        734         self.width = width
        735         self.height = height


    ValueError: Cannot embed the 'svg' image format


Whole pieces will show properly also now that the extension module is
loaded

.. code:: python

    b = corpus.parse('bach/bwv66.6')
    b.show()




.. image:: installIPython_25_0.png



And that is basically it! We use ``sphinx`` for interwiki links, which,
sadly, won't show up on the notebook, but should render properly.

But I did make a sphinx-markdown Notebook extension. When it's ready,
I'll put it up. Make a directory "sphinx-markdown" in a "usability"
directory in "nbextensions" (mine is at
"~/Library/Jupyter/nbextensions"). And put this file there as "main.js":

// Allow sphinx rst references in markdown cells

// TODO: Markdown cells will only be reevaluated when a notebook is dirty
//       (i.e. you have made changes). If you save it before reevaluating MD cells,
//       they will show the old value.

define([
    'base/js/namespace',
    'jquery',
    'notebook/js/cell',
    'base/js/security',
    'components/marked/lib/marked',
    'base/js/events',
    'notebook/js/textcell'

], function(IPython, $, cell, security, marked, events,textcell) {
    "use strict";

    /*
     * Find Sphinx expressions and add to text as <a href> tags
     *
     * @method execute_sphinx
     * @param cell {Cell} notebook cell
     * @param text {String} text in cell
     */
    var execute_sphinx = function(cell,text) {
        /* always clear stored variables if notebook is dirty */
        if (IPython.notebook.dirty === true ) delete cell.metadata.sphinx_links;

        // search for code in mangled <code> blocks
	var found = false;
        var newtext = text.replace(/:ref:<code>(.*?)\s*&lt;(.*?)\&gt;<\/code>/g, function(match, info, link, cha) {
		found = true;
		link = link.replace(/\.html$/, '');
		if (link.indexOf('.') == -1) {
		    link = link + ".ipynb";
		}
		console.log(link);
		return '<a href="' + link + '" target=_new>' + info + '</a>';
        });
	if (found) {
            if (typeof cell.metadata.sphinx_links === "undefined") {
                cell.metadata.sphinx_links = {any: true}
            }
	}
	return newtext

    };

    /*
     * Render markdown cell and replace {{...}} with python code
     *
     */
    var render_cell = function(cell) {
        var element = cell.element.find('div.text_cell_render');
        var text = execute_sphinx(cell, element[0].innerHTML);
        if (text !== undefined) {
            element[0].innerHTML = text;
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,element[0]]);
        }
    };

	/* force rendering of markdown cell if notebook is dirty */
	var original_render = textcell.MarkdownCell.prototype.render;
	textcell.MarkdownCell.prototype.render = function() {
		if (IPython.notebook.dirty === true) {
			this.rendered = false
		}
		return original_render.apply(this)
	};

    var load_ipython_extension = function() {
        events.on("rendered.MarkdownCell", function (event, data) {
            render_cell(data.cell)
        });

        /* show values stored in metadata on reload */
        events.on("kernel_ready.Kernel", function () {
		var ncells = IPython.notebook.ncells();
		var cells = IPython.notebook.get_cells();
		for (var i = 0; i < ncells; i++) {
		    var cell = cells[i];
		    if (cell.metadata.hasOwnProperty('sphinx_links')) {
			render_cell(cell);
		    }
		}
        });
    };

    return {
        load_ipython_extension : load_ipython_extension
    };

});

Check to see if it exists:

.. code:: python

    import notebook
    notebook.nbextensions.check_nbextension('usability/sphinx-markdown', user=True)




.. parsed-literal::
   :class: ipython-result

    True



Load it with:

.. code:: python

    E = notebook.nbextensions.EnableNBExtensionApp()
    E.enable_nbextension('usability/sphinx-markdown/main')

Save, and reload. Then test it with a markdown cell like:

For more information, see, :ref:`installing IPython/Jupyter for Music21 <installIPython>`.

And you should get:

For more information, see,
:ref:`installing IPython/Jupyter for Music21 <installIPython>`. :-)
