pax_global_header00006660000000000000000000000064126042667200014517gustar00rootroot0000000000000052 comment=4bd67c1432490f1ccd535ed84bb0abacf0c9e097 pyknon-version1.2/000077500000000000000000000000001260426672000143055ustar00rootroot00000000000000pyknon-version1.2/.gitignore000066400000000000000000000000711260426672000162730ustar00rootroot00000000000000*.swp *.pyc .coverage htmlcov .tox _build/ .cache build/ pyknon-version1.2/LICENSE000066400000000000000000000020401260426672000153060ustar00rootroot00000000000000Copyright (C) 2012 Pedro Kroger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pyknon-version1.2/MANIFEST000066400000000000000000000005341260426672000154400ustar00rootroot00000000000000# file GENERATED by distutils, do NOT edit README.md setup.py pyknon/MidiFile.py pyknon/__init__.py pyknon/genmidi.py pyknon/music.py pyknon/notation.py pyknon/pc_sets.py pyknon/pcset.py pyknon/plot.py pyknon/simplemusic.py test/test_genmidi.py test/test_midi.py test/test_music.py test/test_notation.py test/test_pcset.py test/test_simplemusic.py pyknon-version1.2/MANIFEST.in000066400000000000000000000000601260426672000160370ustar00rootroot00000000000000include README.md recursive-include pyknon *.py pyknon-version1.2/Makefile000066400000000000000000000005301260426672000157430ustar00rootroot00000000000000.PHONY: coverage test coverage docs test: py.test coverage: py.test --cov=pyknon --cov-report=html docs: cd docs && make html view: docs open docs/_build/html/index.html clean: find . -name "*.pyc" | xargs rm -f find . -name "__pycache__" | xargs rm -rf rm -rf .cache .coverage htmlcov cleanall: clean rm -rf htmlcov docs/_build pyknon-version1.2/README.md000066400000000000000000000017621260426672000155720ustar00rootroot00000000000000# Introduction Pyknon is a simple music library for Python hackers. With Pyknon you can generate Midi files quickly and reason about musical properties. Pyknon works with Python 2.7 and 3.2. # Usage Pyknon is very simple to use, here's a basic example to create 4 notes and save into a MIDI file:: ```python from pyknon.genmidi import Midi from pyknon.music import NoteSeq notes1 = NoteSeq("D4 F#8 A Bb4") midi = Midi(1, tempo=90) midi.seq_notes(notes1, track=0) midi.write("demo.mid") ``` See the documentation for more details. # Documentation Pyknon needs better documentation. Meanwhile you can download [this free chapter](https://s3.amazonaws.com/musicforgeeksandnerds.com/Pyknon+from+Music+for+Geeks+and+Nerds.pdf) from [Music for Geeks and Nerds](http://musicforgeeksandnerds.com) that explains how to use Pyknon. # License This library is released under a MIT license. See the [LICENSE](LICENSE) file for more details. Pyknon's MIDI module is heavily based on Mark Conway Wirt's MIDIUtil. pyknon-version1.2/TODO000066400000000000000000000001051260426672000147710ustar00rootroot00000000000000* Fix music.intervals and music.stretch_intervals to work with rests pyknon-version1.2/demo.py000077500000000000000000000003121260426672000156020ustar00rootroot00000000000000#!/usr/bin/env python from pyknon.genmidi import Midi from pyknon.music import NoteSeq notes1 = NoteSeq("D4 F#8 A Bb4") midi = Midi(1, tempo=90) midi.seq_notes(notes1, track=0) midi.write("demo.mid") pyknon-version1.2/demo_tracks.py000066400000000000000000000020401260426672000171460ustar00rootroot00000000000000from pyknon.genmidi import Midi from pyknon.music import NoteSeq # Notes on two tracks using the defaults notes1 = NoteSeq("C4.'' B8' A4 D") notes2 = NoteSeq("E4 F G4. A8") m = Midi(2, tempo=100, instrument=[12, 14]) m.seq_notes(notes1, track=0) m.seq_notes(notes2, track=1) m.write("tracks.mid") # Chords on two tracks using the defaults chords1 = [NoteSeq("C2 E G"), NoteSeq("G2 B D")] chords2 = [NoteSeq("C,4 E"), NoteSeq("E, G"), NoteSeq("G, B"), NoteSeq("B, D'")] midi = Midi(2, tempo=60, instrument=[40, 20]) midi.seq_chords(chords1, track=0) midi.seq_chords(chords2, track=1) midi.write("chords.mid") # Notes on two tracks using percussion # In the MIDI library, the tracks and channels are numbered from 0, # While the MIDI Standard is numbered from 1, # So to use percussion you must use channel 9 in the library n1 = NoteSeq("C4 D E F") n2 = NoteSeq("C8 C G, G C' C G, G") m2 = Midi(2, tempo=123, channel=[0, 9], instrument=[20, 40]) m2.seq_notes(n1, track=0, channel=0) m2.seq_notes(n2, track=1, channel=9) m2.write("percussion.mid") pyknon-version1.2/docs/000077500000000000000000000000001260426672000152355ustar00rootroot00000000000000pyknon-version1.2/docs/Makefile000066400000000000000000000107011260426672000166740ustar00rootroot00000000000000# Makefile for Sphinx documentation # SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/musiclib.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/musiclib.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/musiclib" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/musiclib" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." pyknon-version1.2/docs/conf.py000066400000000000000000000150111260426672000165320ustar00rootroot00000000000000# -*- coding: utf-8 -*- import sys, os sys.path.append(os.path.abspath('extensions')) sys.path.append(os.path.abspath("../pyknon")) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath'] dir = os.path.dirname(os.path.abspath( __file__ )) doctest_path = os.path.join(dir, "../pyknon") # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] pngmath_latex = "/usr/texbin/latex" pngmath_dvipng = "/usr/texbin/dvipng" # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pyknon' copyright = u'2011, Pedro Kroger' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.3' # The full version, including alpha/beta/rc tags. release = '0.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'agogo' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pyknondoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pyknon.tex', u'pyknon Documentation', u'Pedro Kroger', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pyknon', u'pyknon Documentation', [u'Pedro Kroger'], 1) ] pyknon-version1.2/docs/index.rst000066400000000000000000000016351260426672000171030ustar00rootroot00000000000000====================== Pyknon Documentation ====================== .. rubric:: Make music with Python. Pyknon is a simple music library for Python hackers. With Pyknon you can generate Midi files quickly and reason about musical proprieties. It works with Python 2.6, 2.7, and 3.2. Pyknon has modules for different things. I recommend you start by checking the section :ref:`tutorial`. It's a hands on approach on how to use this library. You'll almost always want to work with the modules :mod:`music` and :mod:`genmidi` (see section :ref:`music`). The module :mod:`simplemusic` is a simple numeric library for music operations. It's intended mainly for teaching because it's simple. If you want to learn more about Set Theory in Music, you may want to look at the module :mod:`pcset` (see section :ref:`simplemusic`) Contents: --------- .. toctree:: :maxdepth: 1 tutorial.rst music.rst simplemusic.rst pyknon-version1.2/docs/music.rst000066400000000000000000000001451260426672000171070ustar00rootroot00000000000000.. _music: ============================= Notes, Rests, and Sequences ============================= pyknon-version1.2/docs/simplemusic.rst000066400000000000000000000030121260426672000203150ustar00rootroot00000000000000.. _simplemusic: ================================== Simplemusic and Pitch Class Sets ================================== Simplemusic =========== .. autofunction:: simplemusic.mod12 >>> simplemusic.mod12(13) 1 .. autofunction:: simplemusic.interval Return the numeric interval between two notes. .. autofunction:: simplemusic.transposition Transpose a set of notes by a numerical index. .. autofunction:: simplemusic.transposition_startswith Transpose a set of notes so it begins with `start` note. .. autofunction:: simplemusic.is_related_by_transposition Check if two groups of notes are related by transposition. We use brute force here; the best way is to check for the normal or prime forms. .. autofunction:: simplemusic.inversion Invert a set of notes though an inversion index. The inversion index is not very musical. the function :func:`inversion_startswith` is probably more useful. .. autofunction:: simplemusic.inversion_startswith Invert a set of notes so it begins with `start` note. >>> simplemusic.inversion_startswith([0, 4, 7], 2) [2, 10, 7] .. autofunction:: simplemusic.rotate_set Return all rotations of a collection of notes. Pitch Class Set =============== .. autofunction:: simplemusic.name_to_diatonic Return a number from 0 to 6 for the note name without the accidental. .. autofunction:: simplemusic.dotted_duration Sn = a(1 - r^n)/1 - r where a is the first term, r is the common ration (1/2 in our case) and n is the number of terms. pyknon-version1.2/docs/tutorial.rst000066400000000000000000000002261260426672000176320ustar00rootroot00000000000000.. _tutorial: ============================================ Writing your first composition with Python ============================================ pyknon-version1.2/pyknon/000077500000000000000000000000001260426672000156235ustar00rootroot00000000000000pyknon-version1.2/pyknon/MidiFile.py000066400000000000000000001154251260426672000176670ustar00rootroot00000000000000#----------------------------------------------------------------------------- # Name: MidiFile.py # Purpose: MIDI file manipulation utilities # # Author: Mark Conway Wirt # # Created: 2008/04/17 # Copyright: (c) 2009 Mark Conway Wirt # License: Please see License.txt for the terms under which this # software is distributed. #----------------------------------------------------------------------------- import struct import sys import math PYTHON3 = True if sys.version_info[0] == 3 else False # TICKSPERBEAT is the number of "ticks" (time measurement in the MIDI file) that # corresponds to one beat. This number is somewhat arbitrary, but should be chosen # to provide adequate temporal resolution. TICKSPERBEAT = 128 controllerEventTypes = { 'pan' : 0x0a } class MIDIEvent: ''' The class to contain the MIDI Event (placed on MIDIEventList. ''' def __init__(self): self.type='unknown' self.time=0 self.ord = 0 def __lt__(self, other): ''' Sorting function for events.''' if self.time < other.time: return True elif self.time > other.time: return False else: if self.ord < other.ord: return True elif self.ord > other.ord: return False else: return False def __cmp__(self, other): ''' Sorting function for events.''' if self.time < other.time: return -1 elif self.time > other.time: return 1 else: if self.ord < other.ord: return -1 elif self.ord > other.ord: return 1 else: return 0 class GenericEvent(): '''The event class from which specific events are derived ''' def __init__(self,time): self.time = time self.type = 'Unknown' def __eq__(self, other): ''' Equality operator for Generic Events and derived classes. In the processing of the event list, we have need to remove duplicates. To do this we rely on the fact that the classes are hashable, and must therefore have an equality operator (__hash__() and __eq__() must both be defined). This is the most embarrassing portion of the code, and anyone who knows about OO programming would find this almost unbelievable. Here we have a base class that knows specifics about derived classes, thus breaking the very spirit of OO programming. I suppose I should go back and restructure the code, perhaps removing the derived classes altogether. At some point perhaps I will. ''' if self.time != other.time or self.type != other.type: return False # What follows is code that encodes the concept of equality for each derived # class. Believe it f you dare. if self.type == 'note': if self.pitch != other.pitch or self.channel != other.channel: return False if self.type == 'tempo': if self.tempo != other.tempo: return False if self.type == 'programChange': if self.programNumber != other.programNumber or self.channel != other.channel: return False if self.type == 'trackName': if self.trackName != other.trackName: return False if self.type == 'controllerEvent': if self.parameter1 != other.parameter1 or \ self.parameter2 != other.parameter2 or \ self.channel != other.channel or \ self.eventType != other.eventType: return False if self.type == 'SysEx': if self.manID != other.manID: return False if self.type == 'UniversalSysEx': if self.code != other.code or\ self.subcode != other.subcode or \ self.sysExChannel != other.sysExChannel: return False return True def __hash__(self): ''' Return a hash code for the object. This is needed for the removal of duplicate objects from the event list. The only real requirement for the algorithm is that the hash of equal objects must be equal. There is probably great opportunity for improvements in the hashing function. ''' # Robert Jenkin's 32 bit hash. a = int(self.time) a = (a+0x7ed55d16) + (a<<12) a = (a^0xc761c23c) ^ (a>>19) a = (a+0x165667b1) + (a<<5) a = (a+0xd3a2646c) ^ (a<<9) a = (a+0xfd7046c5) + (a<<3) a = (a^0xb55a4f09) ^ (a>>16) return a class MIDITrack: '''A class that encapsulates a MIDI track ''' # Nested class definitions. class note(GenericEvent): '''A class that encapsulates a note ''' def __init__(self,channel, pitch,time,duration,volume): GenericEvent.__init__(self,time) self.pitch = pitch self.duration = duration self.volume = volume self.type = 'note' self.channel = channel def compare(self, other): '''Compare two notes for equality. ''' if self.pitch == other.pitch and \ self.time == other.time and \ self.duration == other.duration and \ self.volume == other.volume and \ self.type == other.type and \ self.channel == other.channel: return True else: return False class tempo(GenericEvent): '''A class that encapsulates a tempo meta-event ''' def __init__(self,time,tempo): GenericEvent.__init__(self,time) self.type = 'tempo' self.tempo = int(60000000 / tempo) class programChange(GenericEvent): '''A class that encapsulates a program change event. ''' def __init__(self, channel, time, programNumber): GenericEvent.__init__(self, time,) self.type = 'programChange' self.programNumber = programNumber self.channel = channel class SysExEvent(GenericEvent): '''A class that encapsulates a System Exclusive event. ''' def __init__(self, time, manID, payload): GenericEvent.__init__(self, time,) self.type = 'SysEx' self.manID = manID self.payload = payload class UniversalSysExEvent(GenericEvent): '''A class that encapsulates a Universal System Exclusive event. ''' def __init__(self, time, realTime, sysExChannel, code, subcode, payload): GenericEvent.__init__(self, time,) self.type = 'UniversalSysEx' self.realTime = realTime self.sysExChannel = sysExChannel self.code = code self.subcode = subcode self.payload = payload class ControllerEvent(GenericEvent): '''A class that encapsulates a program change event. ''' def __init__(self, channel, time, eventType, parameter1,): GenericEvent.__init__(self, time,) self.type = 'controllerEvent' self.parameter1 = parameter1 self.channel = channel self.eventType = eventType class trackName(GenericEvent): '''A class that encapsulates a program change event. ''' def __init__(self, time, trackName): GenericEvent.__init__(self, time,) self.type = 'trackName' self.trackName = trackName def __init__(self, removeDuplicates, deinterleave): '''Initialize the MIDITrack object. ''' self.headerString = struct.pack('cccc',b'M',b'T',b'r',b'k') self.dataLength = 0 # Is calculated after the data is in place if PYTHON3: self.MIDIdata = b"" else: self.MIDIdata = "" self.closed = False self.eventList = [] self.MIDIEventList = [] self.remdep = removeDuplicates self.deinterleave = deinterleave def addNoteByNumber(self,channel, pitch,time,duration,volume): '''Add a note by chromatic MIDI number ''' self.eventList.append(MIDITrack.note(channel, pitch,time,duration,volume)) def addControllerEvent(self,channel,time,eventType, paramerter1): ''' Add a controller event. ''' self.eventList.append(MIDITrack.ControllerEvent(channel,time,eventType, \ paramerter1)) def addTempo(self,time,tempo): ''' Add a tempo change (or set) event. ''' self.eventList.append(MIDITrack.tempo(time,tempo)) def addSysEx(self,time,manID, payload): ''' Add a SysEx event. ''' self.eventList.append(MIDITrack.SysExEvent(time, manID, payload)) def addUniversalSysEx(self,time,code, subcode, payload, sysExChannel=0x7F, \ realTime=False): ''' Add a Universal SysEx event. ''' self.eventList.append(MIDITrack.UniversalSysExEvent(time, realTime, \ sysExChannel, code, subcode, payload)) def addProgramChange(self,channel, time, program): ''' Add a program change event. ''' self.eventList.append(MIDITrack.programChange(channel, time, program)) def addTrackName(self,time,trackName): ''' Add a track name event. ''' self.eventList.append(MIDITrack.trackName(time,trackName)) def changeNoteTuning(self, tunings, sysExChannel=0x7F, realTime=False, \ tuningProgam=0): '''Change the tuning of MIDI notes ''' payload = struct.pack('>B', tuningProgam) payload = payload + struct.pack('>B', len(tunings)) for (noteNumber, frequency) in tunings: payload = payload + struct.pack('>B', noteNumber) MIDIFreqency = frequencyTransform(frequency) for byte in MIDIFreqency: payload = payload + struct.pack('>B', byte) self.eventList.append(MIDITrack.UniversalSysExEvent(0, realTime, sysExChannel,\ 8, 2, payload)) def processEventList(self): ''' Process the event list, creating a MIDIEventList For each item in the event list, one or more events in the MIDIEvent list are created. ''' # Loop over all items in the eventList for thing in self.eventList: if thing.type == 'note': event = MIDIEvent() event.type = "NoteOn" event.time = thing.time * TICKSPERBEAT event.pitch = thing.pitch event.volume = thing.volume event.channel = thing.channel event.ord = 3 self.MIDIEventList.append(event) event = MIDIEvent() event.type = "NoteOff" event.time = (thing.time + thing.duration) * TICKSPERBEAT event.pitch = thing.pitch event.volume = thing.volume event.channel = thing.channel event.ord = 2 self.MIDIEventList.append(event) elif thing.type == 'tempo': event = MIDIEvent() event.type = "Tempo" event.time = thing.time * TICKSPERBEAT event.tempo = thing.tempo event.ord = 3 self.MIDIEventList.append(event) elif thing.type == 'programChange': event = MIDIEvent() event.type = "ProgramChange" event.time = thing.time * TICKSPERBEAT event.programNumber = thing.programNumber event.channel = thing.channel event.ord = 1 self.MIDIEventList.append(event) elif thing.type == 'trackName': event = MIDIEvent() event.type = "TrackName" event.time = thing.time * TICKSPERBEAT event.trackName = thing.trackName event.ord = 0 self.MIDIEventList.append(event) elif thing.type == 'controllerEvent': event = MIDIEvent() event.type = "ControllerEvent" event.time = thing.time * TICKSPERBEAT event.eventType = thing.eventType event.channel = thing.channel event.paramerter1 = thing.parameter1 event.ord = 1 self.MIDIEventList.append(event) elif thing.type == 'SysEx': event = MIDIEvent() event.type = "SysEx" event.time = thing.time * TICKSPERBEAT event.manID = thing.manID event.payload = thing.payload event.ord = 1 self.MIDIEventList.append(event) elif thing.type == 'UniversalSysEx': event = MIDIEvent() event.type = "UniversalSysEx" event.realTime = thing.realTime event.sysExChannel = thing.sysExChannel event.time = thing.time * TICKSPERBEAT event.code = thing.code event.subcode = thing.subcode event.payload = thing.payload event.ord = 1 self.MIDIEventList.append(event) else: print ("Error in MIDITrack: Unknown event type") sys.exit(2) # Assumptions in the code expect the list to be time-sorted. # self.MIDIEventList.sort(lambda x, y: x.time - y.time) if PYTHON3: self.MIDIEventList.sort(key=lambda x: (x.time)) else: self.MIDIEventList.sort(lambda x, y: int( 1000 * (x.time - y.time))) if self.deinterleave: self.deInterleaveNotes() def removeDuplicates(self): ''' Remove duplicates from the eventList. This function will remove duplicates from the eventList. This is necessary because we the MIDI event stream can become confused otherwise. ''' # For this algorithm to work, the events in the eventList must be hashable # (that is, they must have a __hash__() and __eq__() function defined). tempDict = {} for item in self.eventList: tempDict[item] = 1 if PYTHON3: self.eventList = list(tempDict.keys()) else: self.eventList = tempDict.keys() # Sort on type, them on time. Necessary because keys() has no requirement to return # things in any order. if PYTHON3: self.eventList.sort(key=lambda x: (x.type)) self.eventList.sort(key=lambda x: (x.time)) #A bit of a hack. else: self.eventList.sort(lambda x, y: cmp(x.type , y.type)) self.eventList.sort(lambda x, y: int( 1000 * (x.time - y.time))) #A bit of a hack. def closeTrack(self): '''Called to close a track before writing This function should be called to "close a track," that is to prepare the actual data stream for writing. Duplicate events are removed from the eventList, and the MIDIEventList is created. Called by the parent MIDIFile object. ''' if self.closed == True: return self.closed = True if self.remdep: self.removeDuplicates() self.processEventList() def writeMIDIStream(self): ''' Write the meta data and note data to the packed MIDI stream. ''' #Process the events in the eventList self.writeEventsToStream() # Write MIDI close event. self.MIDIdata = self.MIDIdata + struct.pack('BBBB',0x00,0xFF, \ 0x2F,0x00) # Calculate the entire length of the data and write to the header self.dataLength = struct.pack('>L',len(self.MIDIdata)) def writeEventsToStream(self): ''' Write the events in MIDIEvents to the MIDI stream. ''' for event in self.MIDIEventList: if event.type == "NoteOn": code = 0x9 << 4 | event.channel varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B',code) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) elif event.type == "NoteOff": code = 0x8 << 4 | event.channel varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B',code) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.pitch) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.volume) elif event.type == "Tempo": code = 0xFF subcode = 0x51 fourbite = struct.pack('>L', event.tempo) threebite = fourbite[1:4] # Just discard the MSB varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B',code) self.MIDIdata = self.MIDIdata + struct.pack('>B',subcode) self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x03) # Data length: 3 self.MIDIdata = self.MIDIdata + threebite elif event.type == 'ProgramChange': code = 0xC << 4 | event.channel varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B',code) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.programNumber) elif event.type == 'TrackName': varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('B',0xFF) # Meta-event self.MIDIdata = self.MIDIdata + struct.pack('B',0X03) # Event Type dataLength = len(event.trackName) dataLenghtVar = writeVarLength(dataLength) for i in range(0,len(dataLenghtVar)): self.MIDIdata = self.MIDIdata + struct.pack("b",dataLenghtVar[i]) if PYTHON3: self.MIDIdata = self.MIDIdata + event.trackName.encode() else: self.MIDIdata = self.MIDIdata + event.trackName elif event.type == "ControllerEvent": code = 0xB << 4 | event.channel varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B',code) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.eventType) self.MIDIdata = self.MIDIdata + struct.pack('>B',event.paramerter1) elif event.type == "SysEx": code = 0xF0 varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B', code) payloadLength = writeVarLength(len(event.payload)+2) for lenByte in payloadLength: self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) self.MIDIdata = self.MIDIdata + struct.pack('>B', event.manID) self.MIDIdata = self.MIDIdata + event.payload self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) elif event.type == "UniversalSysEx": code = 0xF0 varTime = writeVarLength(event.time) for timeByte in varTime: self.MIDIdata = self.MIDIdata + struct.pack('>B',timeByte) self.MIDIdata = self.MIDIdata + struct.pack('>B', code) # Do we need to add a length? payloadLength = writeVarLength(len(event.payload)+5) for lenByte in payloadLength: self.MIDIdata = self.MIDIdata + struct.pack('>B',lenByte) if event.realTime : self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7F) else: self.MIDIdata = self.MIDIdata + struct.pack('>B', 0x7E) self.MIDIdata = self.MIDIdata + struct.pack('>B', event.sysExChannel) self.MIDIdata = self.MIDIdata + struct.pack('>B', event.code) self.MIDIdata = self.MIDIdata + struct.pack('>B', event.subcode) self.MIDIdata = self.MIDIdata + event.payload self.MIDIdata = self.MIDIdata + struct.pack('>B',0xF7) def deInterleaveNotes(self): '''Correct Interleaved notes. Because we are writing multiple notes in no particular order, we can have notes which are interleaved with respect to their start and stop times. This method will correct that. It expects that the MIDIEventList has been time-ordered. ''' tempEventList = [] stack = {} for event in self.MIDIEventList: if event.type == 'NoteOn': if str(event.pitch)+str(event.channel) in stack: stack[str(event.pitch)+str(event.channel)].append(event.time) else: stack[str(event.pitch)+str(event.channel)] = [event.time] tempEventList.append(event) elif event.type == 'NoteOff': if len(stack[str(event.pitch)+str(event.channel)]) > 1: event.time = stack[str(event.pitch)+str(event.channel)].pop() tempEventList.append(event) else: stack[str(event.pitch)+str(event.channel)].pop() tempEventList.append(event) else: tempEventList.append(event) self.MIDIEventList = tempEventList # A little trickery here. We want to make sure that NoteOff events appear # before NoteOn events, so we'll do two sorts -- on on type, one on time. # This may have to be revisited, as it makes assumptions about how # the internal sort works, and is in essence creating a sort on a primary # and secondary key. if PYTHON3: self.MIDIEventList.sort(key=lambda x: (x.type)) self.MIDIEventList.sort(key=lambda x: (x.time)) else: self.MIDIEventList.sort(lambda x, y: cmp(x.type , y.type)) self.MIDIEventList.sort(lambda x, y: int( 1000 * (x.time - y.time))) def adjustTime(self,origin): ''' Adjust Times to be relative, and zero-origined ''' if len(self.MIDIEventList) == 0: return tempEventList = [] runningTime = 0 for event in self.MIDIEventList: adjustedTime = event.time - origin event.time = adjustedTime - runningTime runningTime = adjustedTime tempEventList.append(event) self.MIDIEventList = tempEventList def writeTrack(self,fileHandle): ''' Write track to disk. ''' if not self.closed: self.closeTrack() fileHandle.write(self.headerString) fileHandle.write(self.dataLength) fileHandle.write(self.MIDIdata) class MIDIHeader: ''' Class to encapsulate the MIDI header structure. This class encapsulates a MIDI header structure. It isn't used for much, but it will create the appropriately packed identifier string that all MIDI files should contain. It is used by the MIDIFile class to create a complete and well formed MIDI pattern. ''' def __init__(self,numTracks): ''' Initialize the data structures ''' self.headerString = struct.pack('cccc',b'M',b'T',b'h',b'd') self.headerSize = struct.pack('>L',6) # Format 1 = multi-track file self.format = struct.pack('>H',1) self.numTracks = struct.pack('>H',numTracks) self.ticksPerBeat = struct.pack('>H',TICKSPERBEAT) def writeFile(self,fileHandle): fileHandle.write(self.headerString) fileHandle.write(self.headerSize) fileHandle.write(self.format) fileHandle.write(self.numTracks) fileHandle.write(self.ticksPerBeat) class MIDIFile: '''Class that represents a full, well-formed MIDI pattern. This is a container object that contains a header, one or more tracks, and the data associated with a proper and well-formed MIDI pattern. Calling: MyMIDI = MidiFile(tracks, removeDuplicates=True, deinterleave=True) normally MyMIDI = MidiFile(tracks) Arguments: tracks: The number of tracks this object contains removeDuplicates: If true (the default), the software will remove duplicate events which have been added. For example, two notes at the same channel, time, pitch, and duration would be considered duplicate. deinterleave: If True (the default), overlapping notes (same pitch, same channel) will be modified so that they do not overlap. Otherwise the sequencing software will need to figure out how to interpret NoteOff events upon playback. ''' def __init__(self, numTracks, removeDuplicates=True, deinterleave=True): ''' Initialize the class ''' self.header = MIDIHeader(numTracks) self.tracks = list() self.numTracks = numTracks self.closed = False for i in range(0,numTracks): self.tracks.append(MIDITrack(removeDuplicates, deinterleave)) # Public Functions. These (for the most part) wrap the MIDITrack functions, where most # Processing takes place. def addNote(self,track, channel, pitch,time,duration,volume): """ Add notes to the MIDIFile object Use: MyMIDI.addNotes(track,channel,pitch,time, duration, volume) Arguments: track: The track to which the note is added. channel: the MIDI channel to assign to the note. [Integer, 0-15] pitch: the MIDI pitch number [Integer, 0-127]. time: the time (in beats) at which the note sounds [Float]. duration: the duration of the note (in beats) [Float]. volume: the volume (velocity) of the note. [Integer, 0-127]. """ self.tracks[track].addNoteByNumber(channel, pitch, time, duration, volume) def addTrackName(self,track, time,trackName): """ Add a track name to a MIDI track. Use: MyMIDI.addTrackName(track,time,trackName) Argument: track: The track to which the name is added. [Integer, 0-127]. time: The time at which the track name is added, in beats [Float]. trackName: The track name. [String]. """ self.tracks[track].addTrackName(time,trackName) def addTempo(self,track, time,tempo): """ Add a tempo event. Use: MyMIDI.addTempo(track, time, tempo) Arguments: track: The track to which the event is added. [Integer, 0-127]. time: The time at which the event is added, in beats. [Float]. tempo: The tempo, in Beats per Minute. [Integer] """ self.tracks[track].addTempo(time,tempo) def addProgramChange(self,track, channel, time, program): """ Add a MIDI program change event. Use: MyMIDI.addProgramChange(track,channel, time, program) Arguments: track: The track to which the event is added. [Integer, 0-127]. channel: The channel the event is assigned to. [Integer, 0-15]. time: The time at which the event is added, in beats. [Float]. program: the program number. [Integer, 0-127]. """ self.tracks[track].addProgramChange(channel, time, program) def addControllerEvent(self,track, channel,time,eventType, paramerter1): """ Add a MIDI controller event. Use: MyMIDI.addControllerEvent(track, channel, time, eventType, parameter1) Arguments: track: The track to which the event is added. [Integer, 0-127]. channel: The channel the event is assigned to. [Integer, 0-15]. time: The time at which the event is added, in beats. [Float]. eventType: the controller event type. parameter1: The event's parameter. The meaning of which varies by event type. """ self.tracks[track].addControllerEvent(channel,time,eventType, paramerter1) def changeNoteTuning(self, track, tunings, sysExChannel=0x7F, \ realTime=False, tuningProgam=0): """ Change a note's tuning using SysEx change tuning program. Use: MyMIDI.changeNoteTuning(track,[tunings],realTime=False, tuningProgram=0) Arguments: track: The track to which the event is added. [Integer, 0-127]. tunings: A list of tuples in the form (pitchNumber, frequency). [[(Integer,Float]] realTime: Boolean which sets the real-time flag. Defaults to false. sysExChannel: do note use (see below). tuningProgram: Tuning program to assign. Defaults to zero. [Integer, 0-127] In general the sysExChannel should not be changed (parameter will be depreciated). Also note that many software packages and hardware packages do not implement this standard! """ self.tracks[track].changeNoteTuning(tunings, sysExChannel, realTime,\ tuningProgam) def writeFile(self,fileHandle): ''' Write the MIDI File. Use: MyMIDI.writeFile(filehandle) Arguments: filehandle: a file handle that has been opened for binary writing. ''' self.header.writeFile(fileHandle) #Close the tracks and have them create the MIDI event data structures. self.close() #Write the MIDI Events to file. for i in range(0,self.numTracks): self.tracks[i].writeTrack(fileHandle) def addSysEx(self,track, time, manID, payload): """ Add a SysEx event Use: MyMIDI.addSysEx(track,time,ID,payload) Arguments: track: The track to which the event is added. [Integer, 0-127]. time: The time at which the event is added, in beats. [Float]. ID: The SysEx ID number payload: the event payload. Note: This is a low-level MIDI function, so care must be used in constructing the payload. It is recommended that higher-level helper functions be written to wrap this function and construct the payload if a developer finds him or herself using the function heavily. """ self.tracks[track].addSysEx(time,manID, payload) def addUniversalSysEx(self,track, time,code, subcode, payload, \ sysExChannel=0x7F, realTime=False): """ Add a Universal SysEx event. Use: MyMIDI.addUniversalSysEx(track, time, code, subcode, payload,\ sysExChannel=0x7f, realTime=False) Arguments: track: The track to which the event is added. [Integer, 0-127]. time: The time at which the event is added, in beats. [Float]. code: The even code. [Integer] subcode The event sub-code [Integer] payload: The event payload. [Binary string] sysExChannel: The SysEx channel. realTime: Sets the real-time flag. Defaults to zero. Note: This is a low-level MIDI function, so care must be used in constructing the payload. It is recommended that higher-level helper functions be written to wrap this function and construct the payload if a developer finds him or herself using the function heavily. As an example of such a helper function, see the changeNoteTuning function, both here and in MIDITrack. """ self.tracks[track].addUniversalSysEx(time,code, subcode, payload, sysExChannel,\ realTime) def shiftTracks(self, offset=0): """Shift tracks to be zero-origined, or origined at offset. Note that the shifting of the time in the tracks uses the MIDIEventList -- in other words it is assumed to be called in the stage where the MIDIEventList has been created. This function, however, it meant to operate on the eventList itself. """ origin = 1000000 # A little silly, but we'll assume big enough for track in self.tracks: if len(track.eventList) > 0: for event in track.eventList: if event.time < origin: origin = event.time for track in self.tracks: tempEventList = [] #runningTime = 0 for event in track.eventList: adjustedTime = event.time - origin #event.time = adjustedTime - runningTime + offset event.time = adjustedTime + offset #runningTime = adjustedTime tempEventList.append(event) track.eventList = tempEventList #End Public Functions ######################## def close(self): '''Close the MIDIFile for further writing. To close the File for events, we must close the tracks, adjust the time to be zero-origined, and have the tracks write to their MIDI Stream data structure. ''' if self.closed == True: return for i in range(0,self.numTracks): self.tracks[i].closeTrack() # We want things like program changes to come before notes when they are at the # same time, so we sort the MIDI events by their ordinality self.tracks[i].MIDIEventList.sort() origin = self.findOrigin() for i in range(0,self.numTracks): self.tracks[i].adjustTime(origin) self.tracks[i].writeMIDIStream() self.closed = True def findOrigin(self): '''Find the earliest time in the file's tracks.append. ''' origin = 1000000 # A little silly, but we'll assume big enough # Note: This code assumes that the MIDIEventList has been sorted, so this should be insured # before it is called. It is probably a poor design to do this. # TODO: -- Consider making this less efficient but more robust by not assuming the list to be sorted. for track in self.tracks: if len(track.MIDIEventList) > 0: if track.MIDIEventList[0].time < origin: origin = track.MIDIEventList[0].time return origin def writeVarLength(i): '''Accept an input, and write a MIDI-compatible variable length stream The MIDI format is a little strange, and makes use of so-called variable length quantities. These quantities are a stream of bytes. If the most significant bit is 1, then more bytes follow. If it is zero, then the byte in question is the last in the stream ''' input = int(i) output = [0,0,0,0] reversed = [0,0,0,0] count = 0 result = input & 0x7F output[count] = result count = count + 1 input = input >> 7 while input > 0: result = input & 0x7F result = result | 0x80 output[count] = result count = count + 1 input = input >> 7 reversed[0] = output[3] reversed[1] = output[2] reversed[2] = output[1] reversed[3] = output[0] return reversed[4-count:4] def frequencyTransform(freq): '''Returns a three-byte transform of a frequencyTransform ''' resolution = 16384 freq = float(freq) dollars = 69 + 12 * math.log(freq/(float(440)), 2) firstByte = int(dollars) lowerFreq = 440 * pow(2.0, ((float(firstByte) - 69.0)/12.0)) if freq != lowerFreq: centDif = 1200 * math.log( (freq/lowerFreq), 2) else: centDif = 0 cents = round(centDif/100 * resolution) # round? secondByte = min([int(cents)>>7, 0x7F]) thirdByte = cents - (secondByte << 7) thirdByte = min([thirdByte, 0x7f]) if thirdByte == 0x7f and secondByte == 0x7F and firstByte == 0x7F: thirdByte = 0x7e thirdByte = int(thirdByte) return [firstByte, secondByte, thirdByte] def returnFrequency(freqBytes): '''The reverse of frequencyTransform. Given a byte stream, return a frequency. ''' resolution = 16384.0 baseFrequency = 440 * pow(2.0, (float(freqBytes[0]-69.0)/12.0)) frac = (float((int(freqBytes[1]) << 7) + int(freqBytes[2])) * 100.0) / resolution frequency = baseFrequency * pow(2.0, frac/1200.0) return frequency pyknon-version1.2/pyknon/__init__.py000066400000000000000000000000001260426672000177220ustar00rootroot00000000000000pyknon-version1.2/pyknon/genmidi.py000066400000000000000000000050051260426672000176110ustar00rootroot00000000000000from pyknon.MidiFile import MIDIFile from pyknon.music import Note, NoteSeq, Rest class MidiError(Exception): pass class Midi(object): def __init__(self, number_tracks=1, tempo=60, instrument=0, channel=None): """ instrument: can be an integer or a list channel: can be an integer or a list """ self.number_tracks = number_tracks self.midi_data = MIDIFile(number_tracks) for track in range(number_tracks): self.midi_data.addTrackName(track, 0, "Track {0}".format(track)) self.midi_data.addTempo(track, 0, tempo) instr = instrument[track] if isinstance(instrument, list) else instrument if channel is None: _channel = track elif isinstance(channel, list): _channel = channel[track] else: _channel = channel self.midi_data.addProgramChange(track, _channel, 0, instr) def seq_chords(self, seqlist, track=0, time=0, channel=None): if track + 1 > self.number_tracks: raise MidiError("You are trying to use more tracks than we have.") _channel = channel if channel is not None else track for item in seqlist: if isinstance(item, NoteSeq): volume = item[0].volume dur = item[0].midi_dur for note in item: self.midi_data.addNote(track, _channel, note.midi_number, time, dur, volume) time += dur elif isinstance(item, Rest): time += item.midi_dur else: raise MidiError("The input should be a list of NoteSeq but yours is a {0}: {1}".format(type(seqlist), seqlist)) return time def seq_notes(self, noteseq, track=0, time=0, channel=None): if track + 1 > self.number_tracks: raise MidiError("You are trying to use more tracks than we have.") _channel = channel if channel is not None else track for note in noteseq: if isinstance(note, Note): self.midi_data.addNote(track, _channel, note.midi_number, time, note.midi_dur, note.volume) else: # we ignore the rests pass time += note.midi_dur return time def write(self, filename): if isinstance(filename, str): with open(filename, 'wb') as midifile: self.midi_data.writeFile(midifile) else: self.midi_data.writeFile(filename) pyknon-version1.2/pyknon/music.py000066400000000000000000000171311260426672000173200ustar00rootroot00000000000000import collections import copy from pyknon import notation class MusiclibError(Exception): pass class Rest(object): def __init__(self, dur=0.25): self.dur = dur def __repr__(self): return "".format(self.dur) def __eq__(self, other): return self.dur == other.dur @property def verbose(self): return "".format(self.dur) @property def midi_dur(self): # The MIDI library uses 1 for quarter note but we use 0.25 return self.dur * 4 def stretch_dur(self, factor): return Rest(self.dur * factor) class Note(object): def __init__(self, value=0, octave=5, dur=0.25, volume=100): if isinstance(value, str): self.value, self.octave, self.dur, self.volume = notation.parse_note(value) else: offset, val = divmod(value, 12) self.value = val self.octave = octave + offset self.dur = dur self.volume = volume def __eq__(self, other): return self.value == other.value and self.dur == other.dur and self.octave == other.octave def __sub__(self, other): return self.midi_number - other.midi_number def __repr__(self): return "<{0}>".format(self.name) @property def verbose(self): return "".format(self.value, self.octave, self.dur) @property def name(self): note_names = "C C# D D# E F F# G G# A A# B".split() return note_names[self.value % 12] @property def midi_number(self): return self.value + (self.octave * 12) @property def midi_dur(self): # The MIDI library uses 1 for quarter note but we use 0.25 return self.dur * 4 def __note_octave(self, octave): """Return a note value in terms of a given octave octave n = Note(11, 4) __note_octave(n, 5) = -1 """ return self.value + ((self.octave - octave) * 12) def transposition(self, index): return Note(self.value + index, self.octave, self.dur, self.volume) ## FIXME: transpose down def tonal_transposition(self, index, scale): pos = index + scale.index(self) - 1 octave, rest = divmod(pos, 7) note = copy.copy(scale[pos % len(scale)]) note.octave += octave return note def harmonize(self, scale, interval=3, size=3): i = (interval - 1) indices = range(1, size*i, i) return [self.tonal_transposition(x, scale) for x in indices] def inversion(self, index=0, initial_octave=None): value = self.__note_octave(initial_octave) if initial_octave else self.value octv = initial_octave if initial_octave else self.octave note_value = (2 * index) - value return Note(note_value, octv, self.dur, self.volume) def stretch_dur(self, factor): return Note(self.value, self.octave, self.dur * factor, self.volume) class NoteSeq(collections.MutableSequence): @staticmethod def _is_note_or_rest(args): return all([True if isinstance(x, Note) or isinstance(x, Rest) else False for x in args]) @staticmethod def _make_note_or_rest(note_list): if note_list[0] is not None: return Note(*note_list) else: return Rest(note_list[2]) @staticmethod def _parse_score(filename): with open(filename) as score: notes = [] for line in score: notes.extend([note for note in line.split()]) return notes def __init__(self, args=None): if isinstance(args, str): if args.startswith("file://"): filename = args.replace("file://", "") note_lists = notation.parse_notes(self._parse_score(filename)) else: note_lists = notation.parse_notes(args.split()) self.items = [self._make_note_or_rest(x) for x in note_lists] elif isinstance(args, collections.Iterable): if self._is_note_or_rest(args): self.items = args else: raise MusiclibError("Every argument have to be a Note or a Rest.") elif args is None: self.items = [] else: raise MusiclibError("NoteSeq doesn't accept this type of data.") def __iter__(self): for x in self.items: yield x def __delitem__(self, i): del self.items[i] def __getitem__(self, i): if isinstance(i, int): return self.items[i] else: return NoteSeq(self.items[i]) def __len__(self): return len(self.items) def __setitem__(self, i, value): self.items[i] = value def __repr__(self): return "".format(self.items) def __eq__(self, other): if len(self) == len(other): return all(x == y for x, y in zip(self.items, other.items)) def __add__(self, other): if isinstance(other, NoteSeq): return NoteSeq(self.items + other.items) elif isinstance(other, Note) or isinstance(other, Rest): return NoteSeq(self.items + [other]) def __radd__(self, other): if isinstance(other, NoteSeq): # This should never be called because the other NoteSeq should # handle the concatenation, but it's here for completness sake return NoteSeq(other.items + self.items) elif isinstance(other, Note) or isinstance(other, Rest): return NoteSeq([other] + self.items) def __mul__(self, n): return NoteSeq(self.items * n) @property def verbose(self): string = ", ".join([note.verbose for note in self.items]) return "".format(string) def retrograde(self): return NoteSeq(list(reversed(self.items))) def insert(self, i, value): self.items.insert(i, value) def transposition(self, index): return NoteSeq([x.transposition(index) if isinstance(x, Note) else x for x in self.items]) def _make_note(self, item): return Note(item) if (isinstance(item, int) or isinstance(item, str)) else item def transposition_startswith(self, note_start): note = self._make_note(note_start) return self.transposition(note - self.items[0]) def inversion(self, index=0): initial_octave = self.items[0].octave return NoteSeq([x.inversion(index, initial_octave) if isinstance(x, Note) else x for x in self.items]) def inversion_startswith(self, note_start): note = self._make_note(note_start) inv = self.transposition_startswith(Note(0, note.octave)).inversion() return inv.transposition_startswith(note) def harmonize(self, interval=3, size=3): return [NoteSeq(note.harmonize(self, interval, size)) for note in self] def rotate(self, n=1): modn = n % len(self) result = self.items[modn:] + self.items[0:modn] return NoteSeq(result) def stretch_dur(self, factor): return NoteSeq([x.stretch_dur(factor) for x in self.items]) ## TODO: gives an error with rests def intervals(self): v1 = self[:] v2 = self.rotate() return [y - x for x, y in zip(v1, v2[:-1])] def stretch_interval(self, factor): intervals = [x + factor for x in self.intervals()] note = copy.copy(self[0]) result = NoteSeq([note]) for i in intervals: note = note.transposition(i) result.append(note) return result # Aliases transp = transposition_startswith inv = inversion_startswith pyknon-version1.2/pyknon/notation.py000066400000000000000000000035401260426672000200320ustar00rootroot00000000000000import re from fractions import Fraction REGEX_NOTE = re.compile("([a-gA-GRr])([b#]*)([0-9]*)([.]*)([',]*)") class NotationError(Exception): pass def parse_accidental(acc): n = len(acc) if acc else 0 return -n if "b" in acc else n def parse_octave(string): """5 is central octave. Return 5 as a fall-back""" if string: size = string.count(string[0]) return size + 4 if string[0] == "'" else -size + 5 else: return 5 def parse_dur(dur, dots=""): if dur == 0 or dur == "breve" or dur == "brevis": base = 2 elif dur == "longa": base = 4 elif dur == "maxima": base = 8 else: base = int(dur) ** -1 return sum([base / (2 ** x) for x in range(0, len(dots) + 1)]) def parse_note(note, volume=120, prev_octave=5, prev_dur=0.25): note_names = "c # d # e f # g # a # b".split() m = REGEX_NOTE.match(note) if m: pitch, acc, dur, dots, octv = m.groups() else: raise NotationError("You need to enter at least one note.") octave = parse_octave(octv) if octv else prev_octave duration = parse_dur(dur, dots) if dur else prev_dur if pitch in ["r", "R"]: return None, octave, duration, None else: pitch_number = note_names.index(pitch.lower()) acc_number = parse_accidental(acc) note_number = (pitch_number + acc_number) % 12 return note_number, octave, duration, volume def parse_notes(notes, volume=120): # (number, octave, dur, volume) prev_oct = 5 # default octave prev_dur = 0.25 # default duration is 1/4, but it's 1 in the MIDI library result = [] for item in notes: number, octave, dur, vol = parse_note(item, volume, prev_oct, prev_dur) result.append((number, octave, dur, vol)) prev_oct = octave prev_dur = dur return result pyknon-version1.2/pyknon/pc_sets.py000066400000000000000000000150171260426672000176410ustar00rootroot00000000000000PC_SETS = { '3-1': [0, 1, 2], '3-10': [0, 3, 6], '3-11': [0, 3, 7], '3-12': [0, 4, 8], '3-2': [0, 1, 3], '3-3': [0, 1, 4], '3-4': [0, 1, 5], '3-5': [0, 1, 6], '3-6': [0, 2, 4], '3-7': [0, 2, 5], '3-8': [0, 2, 6], '3-9': [0, 2, 7], '4-1': [0, 1, 2, 3], '4-10': [0, 2, 3, 5], '4-11': [0, 1, 3, 5], '4-12': [0, 2, 3, 6], '4-13': [0, 1, 3, 6], '4-14': [0, 2, 3, 7], '4-16': [0, 1, 5, 7], '4-17': [0, 3, 4, 7], '4-18': [0, 1, 4, 7], '4-19': [0, 1, 4, 8], '4-2': [0, 1, 2, 4], '4-20': [0, 1, 5, 8], '4-21': [0, 2, 4, 6], '4-22': [0, 2, 4, 7], '4-23': [0, 2, 5, 7], '4-24': [0, 2, 4, 8], '4-25': [0, 2, 6, 8], '4-26': [0, 3, 5, 8], '4-27': [0, 2, 5, 8], '4-28': [0, 3, 6, 9], '4-3': [0, 1, 3, 4], '4-4': [0, 1, 2, 5], '4-5': [0, 1, 2, 6], '4-6': [0, 1, 2, 7], '4-7': [0, 1, 4, 5], '4-8': [0, 1, 5, 6], '4-9': [0, 1, 6, 7], '4-Z15': [0, 1, 4, 6], '4-Z29': [0, 1, 3, 7], '5-1': [0, 1, 2, 3, 4], '5-10': [0, 1, 3, 4, 6], '5-11': [0, 2, 3, 4, 7], '5-13': [0, 1, 2, 4, 8], '5-14': [0, 1, 2, 5, 7], '5-15': [0, 1, 2, 6, 8], '5-16': [0, 1, 3, 4, 7], '5-19': [0, 1, 3, 6, 7], '5-2': [0, 1, 2, 3, 5], '5-20': [0, 1, 5, 6, 8], '5-21': [0, 1, 4, 5, 8], '5-22': [0, 1, 4, 7, 8], '5-23': [0, 2, 3, 5, 7], '5-24': [0, 1, 3, 5, 7], '5-25': [0, 2, 3, 5, 8], '5-26': [0, 2, 4, 5, 8], '5-27': [0, 1, 3, 5, 8], '5-28': [0, 2, 3, 6, 8], '5-29': [0, 1, 3, 6, 8], '5-3': [0, 1, 2, 4, 5], '5-30': [0, 1, 4, 6, 8], '5-31': [0, 1, 3, 6, 9], '5-32': [0, 1, 4, 6, 9], '5-33': [0, 2, 4, 6, 8], '5-34': [0, 2, 4, 6, 9], '5-35': [0, 2, 4, 7, 9], '5-4': [0, 1, 2, 3, 6], '5-5': [0, 1, 2, 3, 7], '5-6': [0, 1, 2, 5, 6], '5-7': [0, 1, 2, 6, 7], '5-8': [0, 2, 3, 4, 6], '5-9': [0, 1, 2, 4, 6], '5-Z12': [0, 1, 3, 5, 6], '5-Z17': [0, 1, 3, 4, 8], '5-Z18': [0, 1, 4, 5, 7], '5-Z36': [0, 1, 2, 4, 7], '5-Z37': [0, 3, 4, 5, 8], '5-Z38': [0, 1, 2, 5, 8], '6-1': [0, 1, 2, 3, 4, 5], '6-14': [0, 1, 3, 4, 5, 8], '6-15': [0, 1, 2, 4, 5, 8], '6-16': [0, 1, 4, 5, 6, 8], '6-18': [0, 1, 2, 5, 7, 8], '6-2': [0, 1, 2, 3, 4, 6], '6-20': [0, 1, 4, 5, 8, 9], '6-21': [0, 2, 3, 4, 6, 8], '6-22': [0, 1, 2, 4, 6, 8], '6-27': [0, 1, 3, 4, 6, 9], '6-30': [0, 1, 3, 6, 7, 9], '6-31': [0, 1, 4, 5, 7, 9], '6-32': [0, 2, 4, 5, 7, 9], '6-33': [0, 2, 3, 5, 7, 9], '6-34': [0, 1, 3, 5, 7, 9], '6-35': [0, 2, 4, 6, 8, 10], '6-5': [0, 1, 2, 3, 6, 7], '6-7': [0, 1, 2, 6, 7, 8], '6-8': [0, 2, 3, 4, 5, 7], '6-9': [0, 1, 2, 3, 5, 7], '6-Z10': [0, 1, 3, 4, 5, 7], '6-Z11': [0, 1, 2, 4, 5, 7], '6-Z12': [0, 1, 2, 4, 6, 7], '6-Z13': [0, 1, 3, 4, 6, 7], '6-Z17': [0, 1, 2, 4, 7, 8], '6-Z19': [0, 1, 3, 4, 7, 8], '6-Z23': [0, 2, 3, 5, 6, 8], '6-Z24': [0, 1, 3, 4, 6, 8], '6-Z25': [0, 1, 3, 5, 6, 8], '6-Z26': [0, 1, 3, 5, 7, 8], '6-Z28': [0, 1, 3, 5, 6, 9], '6-Z29': [0, 2, 3, 6, 7, 9], '6-Z3': [0, 1, 2, 3, 5, 6], '6-Z36': [0, 1, 2, 3, 4, 7], '6-Z37': [0, 1, 2, 3, 4, 8], '6-Z38': [0, 1, 2, 3, 7, 8], '6-Z39': [0, 2, 3, 4, 5, 8], '6-Z4': [0, 1, 2, 4, 5, 6], '6-Z40': [0, 1, 2, 3, 5, 8], '6-Z41': [0, 1, 2, 3, 6, 8], '6-Z42': [0, 1, 2, 3, 6, 9], '6-Z43': [0, 1, 2, 5, 6, 8], '6-Z44': [0, 1, 2, 5, 6, 9], '6-Z45': [0, 2, 3, 4, 6, 9], '6-Z46': [0, 1, 2, 4, 6, 9], '6-Z47': [0, 1, 2, 4, 7, 9], '6-Z48': [0, 1, 2, 5, 7, 9], '6-Z49': [0, 1, 3, 4, 7, 9], '6-Z50': [0, 1, 4, 6, 7, 9], '6-Z6': [0, 1, 2, 5, 6, 7], '7-1': [0, 1, 2, 3, 4, 5, 6], '7-10': [0, 1, 2, 3, 4, 6, 9], '7-11': [0, 1, 3, 4, 5, 6, 8], '7-13': [0, 1, 2, 4, 5, 6, 8], '7-14': [0, 1, 2, 3, 5, 7, 8], '7-15': [0, 1, 2, 4, 6, 7, 8], '7-16': [0, 1, 2, 3, 5, 6, 9], '7-19': [0, 1, 2, 3, 6, 7, 9], '7-2': [0, 1, 2, 3, 4, 5, 7], '7-20': [0, 1, 2, 5, 6, 7, 9], '7-21': [0, 1, 2, 4, 5, 8, 9], '7-22': [0, 1, 2, 5, 6, 8, 9], '7-23': [0, 2, 3, 4, 5, 7, 9], '7-24': [0, 1, 2, 3, 5, 7, 9], '7-25': [0, 2, 3, 4, 6, 7, 9], '7-26': [0, 1, 3, 4, 5, 7, 9], '7-27': [0, 1, 2, 4, 5, 7, 9], '7-28': [0, 1, 3, 5, 6, 7, 9], '7-29': [0, 1, 2, 4, 6, 7, 9], '7-3': [0, 1, 2, 3, 4, 5, 8], '7-30': [0, 1, 2, 4, 6, 8, 9], '7-31': [0, 1, 3, 4, 6, 7, 9], '7-32': [0, 1, 3, 4, 6, 8, 9], '7-33': [0, 1, 2, 4, 6, 8, 10], '7-34': [0, 1, 3, 4, 6, 8, 10], '7-35': [0, 1, 3, 5, 6, 8, 10], '7-4': [0, 1, 2, 3, 4, 6, 7], '7-5': [0, 1, 2, 3, 5, 6, 7], '7-6': [0, 1, 2, 3, 4, 7, 8], '7-7': [0, 1, 2, 3, 6, 7, 8], '7-8': [0, 2, 3, 4, 5, 6, 8], '7-9': [0, 1, 2, 3, 4, 6, 8], '7-Z12': [0, 1, 2, 3, 4, 7, 9], '7-Z17': [0, 1, 2, 4, 5, 6, 9], '7-Z18': [0, 2, 3, 4, 5, 8, 9], '7-Z36': [0, 1, 2, 3, 5, 6, 8], '7-Z37': [0, 1, 3, 4, 5, 7, 8], '7-Z38': [0, 1, 2, 4, 5, 7, 8], '8-1': [0, 1, 2, 3, 4, 5, 6, 7], '8-10': [0, 2, 3, 4, 5, 6, 7, 9], '8-11': [0, 1, 2, 3, 4, 5, 7, 9], '8-12': [0, 1, 3, 4, 5, 6, 7, 9], '8-13': [0, 1, 2, 3, 4, 6, 7, 9], '8-14': [0, 1, 2, 4, 5, 6, 7, 9], '8-16': [0, 1, 2, 3, 5, 7, 8, 9], '8-17': [0, 1, 3, 4, 5, 6, 8, 9], '8-18': [0, 1, 2, 3, 5, 6, 8, 9], '8-19': [0, 1, 2, 4, 5, 6, 8, 9], '8-2': [0, 1, 2, 3, 4, 5, 6, 8], '8-20': [0, 1, 2, 4, 5, 7, 8, 9], '8-21': [0, 1, 2, 3, 4, 6, 8, 10], '8-22': [0, 1, 2, 3, 5, 6, 8, 10], '8-23': [0, 1, 2, 3, 5, 7, 8, 10], '8-24': [0, 1, 2, 4, 5, 6, 8, 10], '8-25': [0, 1, 2, 4, 6, 7, 8, 10], '8-26': [0, 1, 3, 4, 5, 7, 8, 10], '8-27': [0, 1, 2, 4, 5, 7, 8, 10], '8-28': [0, 1, 3, 4, 6, 7, 9, 10], '8-3': [0, 1, 2, 3, 4, 5, 6, 9], '8-4': [0, 1, 2, 3, 4, 5, 7, 8], '8-5': [0, 1, 2, 3, 4, 6, 7, 8], '8-6': [0, 1, 2, 3, 5, 6, 7, 8], '8-7': [0, 1, 2, 3, 4, 5, 8, 9], '8-8': [0, 1, 2, 3, 4, 7, 8, 9], '8-9': [0, 1, 2, 3, 6, 7, 8, 9], '8-Z15': [0, 1, 2, 3, 4, 6, 8, 9], '8-Z29': [0, 1, 2, 3, 5, 6, 7, 9], '9-1': [0, 1, 2, 3, 4, 5, 6, 7, 8], '9-10': [0, 1, 2, 3, 4, 6, 7, 9, 10], '9-11': [0, 1, 2, 3, 5, 6, 7, 9, 10], '9-12': [0, 1, 2, 4, 5, 6, 8, 9, 10], '9-2': [0, 1, 2, 3, 4, 5, 6, 7, 9], '9-3': [0, 1, 2, 3, 4, 5, 6, 8, 9], '9-4': [0, 1, 2, 3, 4, 5, 7, 8, 9], '9-5': [0, 1, 2, 3, 4, 6, 7, 8, 9], '9-6': [0, 1, 2, 3, 4, 5, 6, 8, 10], '9-7': [0, 1, 2, 3, 4, 5, 7, 8, 10], '9-8': [0, 1, 2, 3, 4, 6, 7, 8, 10], '9-9': [0, 1, 2, 3, 5, 6, 7, 8, 10] } pyknon-version1.2/pyknon/pcset.py000066400000000000000000000035561260426672000173240ustar00rootroot00000000000000from pyknon.pc_sets import PC_SETS from pyknon.simplemusic import (mod12, interval, rotate, all_intervals, rotate_set, inversion, transposition_startswith, inversion_first_note) def set_sizes(pset): return [interval(x, y) for x,y in zip(rotate(pset, len(pset) - 1), pset)] def set_size(pset): ## pset must be sorted return mod12(pset[-1] - pset[0]) def interval_vector(notes): vector = [0, 0, 0, 0, 0, 0] for i in all_intervals(notes): vector[i-1] += 1 return vector def order_set(notes): # it doesn't eliminate repetition return sorted([mod12(n) for n in notes]) def interval_tie(pset): # return interval of between second-to-last and first, according to Straus. return interval(pset[-2], pset[0]) def normal_form(notes): oset = order_set(notes) rotations = rotate_set(oset) min_size = min(set_sizes(oset)) smallest_sets = [x for x in rotations if set_size(x) == min_size] if len(smallest_sets) == 1: return smallest_sets[0] else: min_pack_size = min([interval_tie(x) for x in smallest_sets]) packed_sets = [x for x in smallest_sets if interval_tie(x) == min_pack_size] return packed_sets[0] def prime_form(notes): set_zero = transposition_startswith(normal_form(notes), 0) set_inv = transposition_startswith(normal_form(inversion(set_zero)), 0) if interval_tie(set_zero) <= interval_tie(set_inv): return set_zero else: return set_inv def matrix(row): return [transposition_startswith(row, n) for n in inversion_first_note(row)] def row_matrix_search(matrix, notes): # return positions return [[row.index(note) for note in notes] for row in matrix] def column_matrix_search(matrix, notes): return [[row.index(note) for note in notes] for row in zip(*matrix)] pyknon-version1.2/pyknon/plot.py000077500000000000000000000046211260426672000171610ustar00rootroot00000000000000import math from pyknon.simplemusic import inversion import Tkinter as Tk MARGIN = 30 def x_y_points(tick, number_points, radius): angle = tick * (360.0 / number_points) rad_angle = math.radians(angle) x = radius * math.sin(rad_angle) y = radius * math.cos(rad_angle) return int(round(x)), int(round(y)) def points_in_a_circle(n_points, radius): return [x_y_points(n, n_points, radius) for n, p in enumerate(range(n_points))] def scaled_points(radius): points = points_in_a_circle(12, radius) return [(x + radius + MARGIN, radius - y + MARGIN) for x, y in points] def plot_circle(canvas, width, points): canvas.create_oval(MARGIN, width, width, MARGIN) def plot_points(canvas, points): for x, y in points: canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill="black") def plot_numbers(canvas, points): for n, (x, y) in enumerate(points): canvas.create_text(x, y-10, text=str(n), font=("Helvetica Bold", 14)) def plot_notes(notes, canvas, points, color="black", dash=None): p = points for n1, n2 in zip(notes, notes[1:]): p = points[n1] + points[n2] canvas.create_line(*p, width=3, fill=color, dash=dash) def canvas_notes(notes_list, width=400, is_black_and_white=False): canvas = Tk.Canvas(width=width, height=width) canvas.pack(side=Tk.TOP) radius = (width / 2) - MARGIN points = scaled_points(radius) plot_points(canvas, points) plot_numbers(canvas, points) plot_circle(canvas, width - MARGIN, points) if is_black_and_white: for notes, dash in notes_list: plot_notes(notes, canvas, points, dash=dash) else: for notes, color in notes_list: plot_notes(notes, canvas, points, color) return canvas def view(notes_list, width=400): canvas = canvas_notes(notes_list, width) def notes_ps(notes_list, filename, width=400, is_black_and_white=False): canvas = canvas_notes(notes_list, width, is_black_and_white=is_black_and_white) L, T, R, B = canvas.bbox(Tk.ALL) canvas.postscript(file=filename, height=B, width=R, pageheight=B, pagewidth=R, x=0, y=0) def plot2(notes1, notes2, filename): notes_list = [(notes1, "black"), (notes2, "red")] notes_ps(notes_list, filename) def plot2_bw(notes1, notes2, filename): notes_list = [(notes1, None), (notes2, (4, 4))] notes_ps(notes_list, filename, is_black_and_white=True) pyknon-version1.2/pyknon/simplemusic.py000066400000000000000000000071751260426672000205410ustar00rootroot00000000000000""" A simple numeric library for music computation. This module is good for teaching, demonstrations, and quick hacks. To generate actual music you should use the music module. """ from __future__ import division from itertools import combinations, chain from fractions import Fraction class SimpleMusicError(Exception): pass def mod12(n): return n % 12 def interval(x, y): return mod12(x - y) def interval_class(x, y): return min(interval(x, y), interval(y, x)) def intervals(notes): return [interval_class(y, x) for x,y in zip(notes, rotate(notes)[:-1])] def all_intervals(notes): intervals_list = [intervals(n) for n in combinations(sorted(notes), 2)] return sorted(chain.from_iterable(intervals_list)) def transposition(notes, index): return [mod12(n + index) for n in notes] def transposition_startswith(notes, start): return transposition(notes, start - notes[0]) def is_related_by_transposition(notes1, notes2): rotations = rotate_set(sorted(notes2)) transpositions = [transposition(sorted(notes1), n) for n in range(0, 12)] return any(True for rotation in rotations if rotation in transpositions) def inversion(notes, index=0): return [mod12(index - n) for n in notes] def inversion_startswith(notes, start): transp = transposition_startswith(notes, 0) return transposition_startswith(inversion(transp), start) def inversion_first_note(notes): return inversion(notes, 2 * notes[0]) def rotate(item, n=1): modn = n % len(item) return item[modn:] + item[0:modn] def rotate_set(notes): return [rotate(notes, x) for x in range(0, len(notes))] def retrograde(notes): return list(reversed(notes)) def note_name(number): notes = "C C# D D# E F F# G G# A A# B".split() return notes[mod12(number)] def notes_names(notes): return [note_name(x) for x in notes] def accidentals(note_string): acc = len(note_string[1:]) if "#" in note_string: return acc elif "b" in note_string: return -acc else: return 0 def name_to_number(note_string): notes = "C . D . E F . G . A . B".split() name = note_string[0:1].upper() number = notes.index(name) acc = accidentals(note_string) return mod12(number + acc) def name_to_diatonic(note_string): notes = "C D E F G A B".split() name = note_string[0:1].upper() return notes.index(name) def note_duration(note_value, unity, tempo): return (60.0 * note_value) / (tempo * unity) def dotted_duration(duration, dots): ratio = Fraction(1, 2) return duration * (1 - ratio ** (dots + 1)) / ratio def durations(notes_values, unity, tempo): return [note_duration(nv, unity, tempo) for nv in notes_values] def get_quality(diatonic_interval, chromatic_interval): if diatonic_interval in [0, 3, 4]: quality_map = ["Diminished", "Perfect", "Augmented"] else: quality_map = ['Diminished', 'Minor', 'Major', 'Augmented'] index_map = [-1, 0, 2, 4, 6, 7, 9] try: return quality_map[chromatic_interval - index_map[diatonic_interval]] except IndexError: raise SimpleMusicError("Sorry, I can't deal with this interval :-(") def interval_name(note1, note2): quantities = ["Unison", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh"] n1, n2 = name_to_number(note1), name_to_number(note2) d1, d2 = name_to_diatonic(note1), name_to_diatonic(note2) chromatic_interval = interval(n2, n1) diatonic_interval = (d2 - d1) % 7 quantity_name = quantities[diatonic_interval] quality_name = get_quality(diatonic_interval, chromatic_interval) return "%s %s" % (quality_name, quantity_name) pyknon-version1.2/requirements-dev.txt000066400000000000000000000000451260426672000203440ustar00rootroot00000000000000pytest sphinx pytest-pep8 pytest-cov pyknon-version1.2/setup.py000077500000000000000000000004651260426672000160270ustar00rootroot00000000000000#!/usr/bin/env python from distutils.core import setup setup( name='pyknon', version='1.2', packages=['pyknon',], url="http://kroger.github.com/pyknon", license='MIT', author='Pedro Kroger', author_email='kroger@pedrokroger.net', long_description=open('README.md').read(), ) pyknon-version1.2/test/000077500000000000000000000000001260426672000152645ustar00rootroot00000000000000pyknon-version1.2/test/__init__.py000066400000000000000000000000001260426672000173630ustar00rootroot00000000000000pyknon-version1.2/test/test_genmidi.py000066400000000000000000000023641260426672000203160ustar00rootroot00000000000000import unittest import tempfile from pyknon.MidiFile import MIDIFile from pyknon.genmidi import Midi, MidiError from pyknon.music import NoteSeq, Note, Rest class TestMidi(unittest.TestCase): def test_init(self): midi = Midi(1, tempo=120) self.assertEqual(midi.number_tracks, 1) self.assertIsInstance(midi.midi_data, MIDIFile) def test_seq_notes_with_more_tracks_than_exists(self): midi = Midi(1) with self.assertRaises(MidiError): midi.seq_notes(NoteSeq("C D"), track=0) midi.seq_notes(NoteSeq("D E"), track=1) def test_seq_notes(self): midi = Midi(2) midi.seq_notes(NoteSeq("C D"), track=0) midi.seq_notes(NoteSeq("D E"), track=1) def test_seq_chords(self): chords = [NoteSeq("C E G"), NoteSeq("G B D")] midi = Midi() midi.seq_chords(chords) def test_seq_chords_with_rest(self): chords = [Rest(), NoteSeq("G B D")] midi = Midi() midi.seq_chords(chords) class TestWriteMidi(unittest.TestCase): def test_write_midifile(self): notes1 = NoteSeq("D4 F#8 R A") midi = Midi(1, tempo=133) midi.seq_notes(notes1, track=0) midi.write(tempfile.TemporaryFile()) pyknon-version1.2/test/test_midi.py000066400000000000000000000252541260426672000176270ustar00rootroot00000000000000#----------------------------------------------------------------------------- # Name: miditest.py # Purpose: Unit testing harness for midiutil # # Author: Mark Conway Wirt # # Created: 2008/04/17 # Copyright: (c) 2009, Mark Conway Wirt # License: Please see License.txt for the terms under which this # software is distributed. #----------------------------------------------------------------------------- # Next few lines are necessary owing to limitations of the IDE and the # directory structure of the project. import sys, struct sys.path.append('..') PYTHON3 = True if sys.version_info[0] == 3 else False import unittest from pyknon.MidiFile import MIDIFile, MIDIHeader, MIDITrack, writeVarLength, \ frequencyTransform, returnFrequency import sys def get_byte(midi, track, data): if PYTHON3: return struct.unpack('>B', bytes([midi.tracks[track].MIDIdata[data]]))[0] else: return struct.unpack('>B', midi.tracks[track].MIDIdata[data])[0] class TestMIDIUtils(unittest.TestCase): def testWriteVarLength(self): self.assertEquals(writeVarLength(0x70), [0x70]) self.assertEquals(writeVarLength(0x80), [0x81, 0x00]) self.assertEquals(writeVarLength(0x1FFFFF), [0xFF, 0xFF, 0x7F]) self.assertEquals(writeVarLength(0x08000000), [0xC0, 0x80, 0x80, 0x00]) def testAddNote(self): MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100,0,1,100) self.assertEquals(MyMIDI.tracks[0].eventList[0].type, "note") self.assertEquals(MyMIDI.tracks[0].eventList[0].pitch, 100) self.assertEquals(MyMIDI.tracks[0].eventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].eventList[0].duration, 1) self.assertEquals(MyMIDI.tracks[0].eventList[0].volume, 100) def testDeinterleaveNotes(self): MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100, 0, 2, 100) MyMIDI.addNote(0, 0, 100, 1, 2, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[2].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[3].time, 256) def testTimeShift(self): # With one track MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100, 5, 1, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) # With two tracks MyMIDI = MIDIFile(2) MyMIDI.addNote(0, 0, 100, 5, 1, 100) MyMIDI.addNote(1, 0, 100, 6, 1, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time, 128) self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time, 128) # Negative Time MyMIDI = MIDIFile(1) MyMIDI.addNote(0, 0, 100, -5, 1, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) # Negative time, two tracks MyMIDI = MIDIFile(2) MyMIDI.addNote(0, 0, 100, -1, 1, 100) MyMIDI.addNote(1, 0, 100, 0, 1, 100) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].time, 0) self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[0].MIDIEventList[1].time, 128) self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].type, 'NoteOn') self.assertEquals(MyMIDI.tracks[1].MIDIEventList[0].time, 128) self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].type, 'NoteOff') self.assertEquals(MyMIDI.tracks[1].MIDIEventList[1].time, 128) def testFrequency(self): freq = frequencyTransform(8.1758) self.assertEquals(freq[0], 0x00) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x00) freq = frequencyTransform(8.66196) # 8.6620 in MIDI documentation self.assertEquals(freq[0], 0x01) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x00) freq = frequencyTransform(440.00) self.assertEquals(freq[0], 0x45) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x00) freq = frequencyTransform(440.0016) self.assertEquals(freq[0], 0x45) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x01) freq = frequencyTransform(439.9984) self.assertEquals(freq[0], 0x44) self.assertEquals(freq[1], 0x7f) self.assertEquals(freq[2], 0x7f) freq = frequencyTransform(8372.0190) self.assertEquals(freq[0], 0x78) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x00) freq = frequencyTransform(8372.062) #8372.0630 in MIDI documentation self.assertEquals(freq[0], 0x78) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x01) freq = frequencyTransform(13289.7300) self.assertEquals(freq[0], 0x7F) self.assertEquals(freq[1], 0x7F) self.assertEquals(freq[2], 0x7E) freq = frequencyTransform(12543.8760) self.assertEquals(freq[0], 0x7F) self.assertEquals(freq[1], 0x00) self.assertEquals(freq[2], 0x00) freq = frequencyTransform(8.2104) # Just plain wrong in documentation, as far as I can tell. #self.assertEquals(freq[0], 0x0) #self.assertEquals(freq[1], 0x0) #self.assertEquals(freq[2], 0x1) # Test the inverse testFreq = 15.0 accuracy = 0.00001 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 200.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 400.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 440.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 1200.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 5000.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) testFreq = 12000.0 x = returnFrequency(frequencyTransform(testFreq)) delta = abs(testFreq - x) self.assertEquals(delta < (accuracy*testFreq), True) def testSysEx(self): MyMIDI = MIDIFile(1) MyMIDI.addSysEx(0,0, 0, struct.pack('>B', 0x01)) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'SysEx') self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00) self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0) self.assertEquals(get_byte(MyMIDI, 0, 2), 3) self.assertEquals(get_byte(MyMIDI, 0, 3), 0x00) self.assertEquals(get_byte(MyMIDI, 0, 4), 0x01) self.assertEquals(get_byte(MyMIDI, 0, 5), 0xf7) def testUniversalSysEx(self): MyMIDI = MIDIFile(1) MyMIDI.addUniversalSysEx(0,0, 1, 2, struct.pack('>B', 0x01)) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx') self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00) self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0) self.assertEquals(get_byte(MyMIDI, 0, 2), 6) self.assertEquals(get_byte(MyMIDI, 0, 3), 0x7E) self.assertEquals(get_byte(MyMIDI, 0, 4), 0x7F) self.assertEquals(get_byte(MyMIDI, 0, 5), 0x01) self.assertEquals(get_byte(MyMIDI, 0, 6), 0x02) self.assertEquals(get_byte(MyMIDI, 0, 7), 0x01) self.assertEquals(get_byte(MyMIDI, 0, 8), 0xf7) def testTuning(self): MyMIDI = MIDIFile(1) MyMIDI.changeNoteTuning(0, [(1, 440), (2, 880)]) MyMIDI.close() self.assertEquals(MyMIDI.tracks[0].MIDIEventList[0].type, 'UniversalSysEx') self.assertEquals(get_byte(MyMIDI, 0, 0), 0x00) self.assertEquals(get_byte(MyMIDI, 0, 1), 0xf0) self.assertEquals(get_byte(MyMIDI, 0, 2), 15) self.assertEquals(get_byte(MyMIDI, 0, 3), 0x7E) self.assertEquals(get_byte(MyMIDI, 0, 4), 0x7F) self.assertEquals(get_byte(MyMIDI, 0, 5), 0x08) self.assertEquals(get_byte(MyMIDI, 0, 6), 0x02) self.assertEquals(get_byte(MyMIDI, 0, 7), 0x00) self.assertEquals(get_byte(MyMIDI, 0, 8), 0x2) self.assertEquals(get_byte(MyMIDI, 0, 9), 0x1) self.assertEquals(get_byte(MyMIDI, 0, 10), 69) self.assertEquals(get_byte(MyMIDI, 0, 11), 0) self.assertEquals(get_byte(MyMIDI, 0, 12), 0) self.assertEquals(get_byte(MyMIDI, 0, 13), 0x2) self.assertEquals(get_byte(MyMIDI, 0, 14), 81) self.assertEquals(get_byte(MyMIDI, 0, 15), 0) self.assertEquals(get_byte(MyMIDI, 0, 16), 0) self.assertEquals(get_byte(MyMIDI, 0, 17), 0xf7) MIDISuite = unittest.TestLoader().loadTestsFromTestCase(TestMIDIUtils) if __name__ == '__main__': unittest.TextTestRunner(verbosity=1).run(MIDISuite) pyknon-version1.2/test/test_music.py000066400000000000000000000272621260426672000200260ustar00rootroot00000000000000import unittest from pyknon.music import MusiclibError, Note, NoteSeq, Rest class TestRest(unittest.TestCase): def test_stretch_dur(self): n1 = Rest(dur=0.25) n2 = n1.stretch_dur(2) n3 = n1.stretch_dur(0.5) self.assertEqual(n2.dur, 0.5) self.assertEqual(n3.dur, 0.125) def test_repr(self): representation = Rest(0.5).__repr__() self.assertEqual(representation, "") def test_verbose(self): result = Rest(0.5).verbose self.assertEqual(result, "") class TestNote(unittest.TestCase): def test_init(self): n1 = Note("C") n2 = Note(value=6, octave=6, dur=0.125, volume=120) n3 = Note() n4 = Note(2) self.assertEqual(n1, Note(0)) self.assertEqual(n2, Note(6, 6, 0.125, 120)) self.assertEqual(n2, Note("F#8''", volume=120)) self.assertEqual(n3, n1) self.assertEqual(n4, Note("D")) def test_repr(self): representation = Note(value=3, octave=5).__repr__() self.assertEqual(representation, "") def test_verbose(self): result = Note("Eb2''").verbose self.assertEqual(result, "") def test_note_equal(self): self.assertFalse(Note(3) == Note(15)) self.assertTrue(Note(3) == Note(3)) def test_note_sub(self): self.assertEqual(Note(4) - Note(3), 1) self.assertEqual(Note(3) - Note(4), -1) self.assertEqual(Note(25) - Note(1), 24) def test_transposition(self): c = Note(value=0) self.assertEqual(c.transposition(2), Note(value=2)) self.assertEqual(c.transposition(0), Note(value=0)) self.assertEqual(c.transposition(11), Note(value=11)) def test_tonal_transposition(self): scale = NoteSeq("C D E F G A B") c = Note("C") c_transp_fifth_up = c.tonal_transposition(5, scale) c_transp_second_up = c.tonal_transposition(2, scale) a = Note("A") a_transp_fourth_up = a.tonal_transposition(4, scale) a_transp_fifth_up = a.tonal_transposition(5, scale) self.assertEqual(c_transp_fifth_up, Note("G")) self.assertEqual(c_transp_second_up, Note("D")) self.assertEqual(a_transp_fourth_up, Note("D''")) self.assertEqual(a_transp_fifth_up, Note("E''")) def test_harmonize(self): c_major_scale = NoteSeq("C D E F G A B") scale_as_list = [Note("C"), Note("D"), Note("E"), Note("F"), Note("G"), Note("A"), Note("B")] c_major = Note("C").harmonize(c_major_scale, 3, 3) a_minor = Note("A").harmonize(scale_as_list, 3, 4) self.assertEqual(NoteSeq(c_major), NoteSeq("C E G")) self.assertEqual(NoteSeq(a_minor), NoteSeq("A C'' E G")) def test_transposition_octave(self): e = Note(value=4, dur=0.25, octave=7) self.assertNotEqual(e.transposition(2), Note(value=6)) self.assertEqual(e.transposition(2), Note(value=6, dur=0.25, octave=7)) self.assertEqual(e.transposition(10), Note(value=2, dur=0.25, octave=8)) def test_inversion(self): self.assertEqual(Note(3, 5).inversion(0), Note(9, 4)) def test_stretch_dur(self): n1 = Note(value=4, dur=0.25, octave=3) n2 = n1.stretch_dur(2) n3 = n1.stretch_dur(0.5) self.assertEqual(n2.dur, 0.5) self.assertEqual(n3.dur, 0.125) class TestNoteSeqOperations(unittest.TestCase): def test_sum(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("F G A") seq3 = NoteSeq("C D E F G A") self.assertEqual(seq1 + seq2, seq3) def test_sum_with_note(self): # Test adding in regular order note1 = Note("G1") seq = NoteSeq("C2 D8 E4") expected = NoteSeq("C2 D8 E4 G1") self.assertEqual(seq + note1, expected) # Test reverse adding, note first seq = NoteSeq("C2 D8 E4") expected = NoteSeq("G1 C2 D8 E4") self.assertEqual(note1 + seq, expected) def test_sum_with_rest(self): # Test adding in regular order rest1 = Rest(1) seq = NoteSeq("C2 D8 E4") expected = NoteSeq("C2 D8 E4 R1") self.assertEqual(seq + rest1, expected) # Test reverse adding, rest first seq = NoteSeq("C2 D8 E4") expected = NoteSeq("R1 C2 D8 E4") self.assertEqual(rest1 + seq, expected) def test_multiplication(self): seq1 = NoteSeq("C4 D8 E8") seq2 = NoteSeq("C4 D8 E8 C4 D8 E8 C4 D8 E8") self.assertEqual(seq1 * 3, seq2) def test_iteration(self): seq1 = NoteSeq("C D E F G A B") numbers = [x.value for x in seq1] self.assertEqual(numbers, [0, 2, 4, 5, 7, 9, 11]) def test_delitem(self): seq1 = NoteSeq("C D E") del seq1[0] seq2 = NoteSeq("D E") self.assertEqual(seq1, seq2) def test_setitem(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("C D# E") seq1[1] = Note("D#") self.assertEqual(seq1, seq2) def test_len(self): seq = NoteSeq("C D E F") self.assertEqual(len(seq), 4) def test_append(self): seq1 = NoteSeq("C# D#") seq1.append(Note("F#")) seq2 = NoteSeq("C# D# F#") self.assertEqual(seq1, seq2) def test_insert(self): seq1 = NoteSeq("Ab Bb Eb") seq1.insert(2, Note("C#")) seq2 = NoteSeq("Ab Bb C# Eb") self.assertEqual(seq1, seq2) def test_getitem(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("D E") self.assertEqual(seq1[0], Note("C")) self.assertEqual(seq1[1:], seq2) def test_repr(self): representation = NoteSeq("C D E").__repr__() self.assertEqual(representation, ", , ]>") def test_verbose(self): result = NoteSeq("C2 D E").verbose self.assertEqual(result, ", , ]>") class TestNoteSeq(unittest.TestCase): def test_init(self): notes = [Note(0, 5), Note(2, 5)] seq1 = NoteSeq(notes) seq2 = NoteSeq("C#2' D#4''") seq3 = NoteSeq([Note(1, 5, 0.5), Note(3, 6, 0.25)]) self.assertEqual(seq1, NoteSeq(notes)) self.assertEqual(seq2, seq3) self.assertNotEqual(seq1, NoteSeq(notes + [Note(3, 5)])) self.assertRaises(MusiclibError, NoteSeq, [Note(1, 5, 0.5), Rest(2), 1]) self.assertRaises(MusiclibError, NoteSeq, 1) def test_init_empty(self): """Test if NoteSeq without arguments will clean previous values.""" seq = NoteSeq() seq.append(Note("C")) seq = NoteSeq() seq.append(Note("D")) self.assertEqual(seq, NoteSeq("D")) def test_init_string(self): seq1 = NoteSeq([Note(0, 4, 0.125), Note(2, 4, 0.125)]) seq2 = NoteSeq([Note(0, 6, 0.125), Rest(0.25)]) seq3 = NoteSeq([Note(0, 5, 0.25), Note(2, 5, 0.25)]) self.assertEqual(NoteSeq("C8, D"), seq1) self.assertEqual(NoteSeq("c8, d"), seq1) self.assertEqual(NoteSeq("c8'' r4"), seq2) self.assertEqual(NoteSeq("C8'' R4"), seq2) self.assertEqual(NoteSeq("C D"), seq3) def test_init_with_rest(self): seq1 = NoteSeq("C4 R4 D4") seq2 = NoteSeq("C8 R D") seq3 = NoteSeq([Note(0, dur=0.25), Rest(0.25), Note(2, dur=0.25)]) self.assertEqual(seq1[0].dur, 0.25) self.assertEqual(seq1[1].dur, 0.25) self.assertEqual(seq1[2].dur, 0.25) self.assertEqual(seq2[0].dur, 0.125) self.assertEqual(seq2[1].dur, 0.125) self.assertEqual(seq2[2].dur, 0.125) self.assertEqual(seq3[0].dur, 0.25) self.assertEqual(seq3[1].dur, 0.25) self.assertEqual(seq3[2].dur, 0.25) def test_transposition(self): seq = NoteSeq("C E G") self.assertEqual(seq.transposition(3), NoteSeq("Eb G Bb")) self.assertEqual(seq.transposition(5), NoteSeq("F A C''")) def test_transposition_with_rest(self): seq1 = NoteSeq("C8 D R E") self.assertEqual(seq1.transposition(3), NoteSeq("Eb8 F R G")) def test_transposition_startswith(self): seq1 = NoteSeq("E G C#") seq2 = NoteSeq([Note(2, 5), Note(5, 5), Note(11, 4)]) seq3 = NoteSeq([Note(2, 4), Note(5, 4), Note(11, 3)]) self.assertEqual(seq1.transposition_startswith(Note(2, 5)), seq2) self.assertEqual(seq1.transposition_startswith(Note(2, 4)), seq3) def test_transposition_startswith_integer(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("D E F#") self.assertEqual(seq1.transposition_startswith(2), seq2) def test_transposition_startswith_string(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("D E F#") self.assertEqual(seq1.transposition_startswith("D"), seq2) def test_transposition_startswith_rest(self): seq1 = NoteSeq("E G R C#") seq2 = NoteSeq([Note(2, 5), Note(5, 5), Rest(), Note(11, 4)]) self.assertEqual(seq1.transposition_startswith(Note(2, 5)), seq2) def test_inversion(self): seq1 = NoteSeq("C E G") seq2 = NoteSeq([Note(0, 5), Note(8, 4), Note(5, 4)]) self.assertEqual(seq1.inversion(0), seq2) def test_inversion_octave(self): seq1 = NoteSeq("G Ab B,") seq2 = NoteSeq("G F# Eb''") self.assertEqual(seq1.inversion(7), seq2) def test_inversion_rest(self): seq1 = NoteSeq("C E R G") seq2 = NoteSeq([Note(0, 5), Note(8, 4), Rest(), Note(5, 4)]) self.assertEqual(seq1.inversion(0), seq2) def test_inversion_startswith(self): seq1 = NoteSeq("C E G") seq2 = NoteSeq([Note(1, 5), Note(9, 4), Note(6, 4)]) self.assertEqual(seq1.inversion_startswith(Note(1, 5)), seq2) def test_inversion_startswith_integer(self): seq1 = NoteSeq("C E G") seq2 = NoteSeq("C Ab, F,") self.assertEqual(seq1.inversion_startswith(0), seq2) def test_inversion_startswith_octave(self): seq1 = NoteSeq("G Ab B,") seq2 = NoteSeq("E Eb C''") self.assertEqual(seq1.inversion_startswith(Note(4, 5)), seq2) def test_inversion_startswith_string(self): seq1 = NoteSeq("C E G") seq2 = NoteSeq("C Ab, F,") self.assertEqual(seq1.inversion_startswith("C"), seq2) def test_harmonize(self): c_major = NoteSeq("C D E F G A B") c_major_harmonized = [NoteSeq("C E G"), NoteSeq("D F A"), NoteSeq("E G B"), NoteSeq("F A C''"), NoteSeq("G B D''"), NoteSeq("A C'' E"), NoteSeq("B D'' F''")] self.assertEqual(c_major.harmonize(), c_major_harmonized) def test_rotate(self): seq1 = NoteSeq("C E G") seq2 = NoteSeq("E G C") seq3 = NoteSeq("G C E") self.assertEqual(seq1.rotate(0), seq1) self.assertEqual(seq1.rotate(1), seq2) self.assertEqual(seq1.rotate(2), seq3) self.assertEqual(seq1.rotate(3), seq1) def test_stretch_dur(self): seq1 = NoteSeq("C4 D8 E8") seq2 = NoteSeq("C8 D16 E16") seq3 = NoteSeq("C2 D4 E4") self.assertEqual(seq1.stretch_dur(.5), seq2) self.assertEqual(seq1.stretch_dur(2), seq3) def test_retrograde(self): seq1 = NoteSeq("C4 D8 E8") seq2 = NoteSeq("E8 D8 C4") self.assertEqual(seq1.retrograde(), seq2) def test_intervals(self): seq1 = NoteSeq("C D E F#") seq2 = NoteSeq("B' C''") self.assertEqual(seq1.intervals(), [2, 2, 2]) self.assertEqual(seq2.intervals(), [1]) def test_stretch_interval(self): seq1 = NoteSeq("C D E") seq2 = NoteSeq("C E G#") seq3 = NoteSeq("A Bb F#") seq4 = NoteSeq("A C#'' C''") self.assertEqual(seq1.stretch_interval(2), seq2) self.assertEqual(seq3.stretch_interval(3), seq4) pyknon-version1.2/test/test_notation.py000066400000000000000000000043311260426672000205310ustar00rootroot00000000000000import unittest from pyknon import notation class TestNotation(unittest.TestCase): def test_parse_accidental(self): acc1 = notation.parse_accidental("###") acc2 = notation.parse_accidental("bbb") acc3 = notation.parse_accidental("") self.assertEqual(acc1, 3) self.assertEqual(acc2, -3) self.assertEqual(acc3, 0) def test_parse_octave(self): oct1 = notation.parse_octave("'") oct2 = notation.parse_octave("''") oct3 = notation.parse_octave("") oct4 = notation.parse_octave(",") oct5 = notation.parse_octave(",,") self.assertEqual(oct1, 5) self.assertEqual(oct2, 6) self.assertEqual(oct3, 5) self.assertEqual(oct4, 4) self.assertEqual(oct5, 3) def test_parse_dur(self): dur1 = notation.parse_dur("8") dur2 = notation.parse_dur("4") dur3 = notation.parse_dur("4", ".") dur4 = notation.parse_dur("4", "..") dur5 = notation.parse_dur("2") self.assertEqual(dur1, 0.125) self.assertEqual(dur2, 0.25) self.assertEqual(dur3, 0.375) self.assertEqual(dur4, 0.4375) self.assertEqual(dur5, 0.5) def test_parse_note(self): note1 = notation.parse_note("C#'") note2 = notation.parse_note("C2") note3 = notation.parse_note("Cb8,") note4 = notation.parse_note("B#16''") self.assertEqual(note1, (1, 5, 0.25, 120)) self.assertEqual(note2, (0, 5, 0.5, 120)) self.assertEqual(note3, (11, 4, 0.125, 120)) self.assertEqual(note4, (0, 6, 0.0625, 120)) def test_parse_notes(self): notes1 = notation.parse_notes(["C", "D", "E"]) notes2 = notation.parse_notes(["Cb4'", "D#8,", "E#16,"]) list_notes1 = [(0, 5, 0.25, 120), (2, 5, 0.25, 120), (4, 5, 0.25, 120)] list_notes2 = [(11, 5, 0.25, 120), (3, 4, 0.125, 120), (5, 4, 0.0625, 120)] self.assertEqual(notes1, list_notes1) self.assertEqual(notes2, list_notes2) def test_parse_notes_dur_dot(self): notes1 = notation.parse_notes(["C4.''", "D4..", "E8."]) list_notes1 = [(0, 6, 0.375, 120), (2, 6, 0.4375, 120), (4, 6, 0.1875, 120)] self.assertEqual(notes1, list_notes1) pyknon-version1.2/test/test_pcset.py000066400000000000000000000054411260426672000200170ustar00rootroot00000000000000import unittest from pyknon import pcset class PcSetTest(unittest.TestCase): def test_set_sizes(self): self.assertEqual(pcset.set_sizes([0, 4, 8, 9, 11]), [11, 8, 8, 11, 10]) def test_set_size(self): self.assertEqual(pcset.set_size([0, 3, 11]), 11) self.assertEqual(pcset.set_size([3, 4, 11]), 8) self.assertEqual(pcset.set_size([4, 5, 10]), 6) def test_interval_vector(self): self.assertEqual(pcset.interval_vector([0, 4, 7]), [0, 0, 1, 1, 1, 0]) def test_order_set(self): self.assertEqual(pcset.order_set([13, 14, 1, 3, 4]), [1, 1, 2, 3, 4]) def test_interval_tie(self): self.assertEqual(pcset.interval_tie([0, 1, 4, 7]), 4) def test_normal_form(self): self.assertEqual(pcset.normal_form([9, 8, 11, 4, 0]), [8, 9, 11, 0, 4]) self.assertEqual(pcset.normal_form([0, 1, 6]), [0, 1, 6]) self.assertEqual(pcset.normal_form([3, 6, 9, 0]), [0, 3, 6, 9]) self.assertEqual(pcset.normal_form([4, 8, 0]), [0, 4, 8]) def test_prime_form(self): self.assertEqual(pcset.prime_form([0, 4, 7]), [0, 3, 7]) # those are from previous bugs, keep'em self.assertEqual(pcset.prime_form([0, 1, 2, 4, 5]), [0, 1, 2, 4, 5]) self.assertEqual(pcset.prime_form([0, 2, 3, 6, 7, 9]), [0, 2, 3, 6, 7, 9]) class MatrixTest(unittest.TestCase): def setUp(self): self.webern_row = [4, 5, 7, 1, 6, 3, 8, 2, 11, 0, 9, 10] self.webern_matrix = [[4, 5, 7, 1, 6, 3, 8, 2, 11, 0, 9, 10], [3, 4, 6, 0, 5, 2, 7, 1, 10, 11, 8, 9], [1, 2, 4, 10, 3, 0, 5, 11, 8, 9, 6, 7], [7, 8, 10, 4, 9, 6, 11, 5, 2, 3, 0, 1], [2, 3, 5, 11, 4, 1, 6, 0, 9, 10, 7, 8], [5, 6, 8, 2, 7, 4, 9, 3, 0, 1, 10, 11], [0, 1, 3, 9, 2, 11, 4, 10, 7, 8, 5, 6], [6, 7, 9, 3, 8, 5, 10, 4, 1, 2, 11, 0], [9, 10, 0, 6, 11, 8, 1, 7, 4, 5, 2, 3], [8, 9, 11, 5, 10, 7, 0, 6, 3, 4, 1, 2], [11, 0, 2, 8, 1, 10, 3, 9, 6, 7, 4, 5], [10, 11, 1, 7, 0, 9, 2, 8, 5, 6, 3, 4]] def test_matrix(self): self.assertEqual(pcset.matrix(self.webern_row), self.webern_matrix) def test_row_matrix_search(self): result = [[9, 3, 5], [3, 7, 0], [5, 0, 4], [10, 11, 9], [7, 5, 1], [8, 9, 7], [0, 1, 2], [11, 8, 3], [2, 6, 11], [6, 10, 8], [1, 4, 6], [4, 2, 10]] self.assertEqual(pcset.row_matrix_search(self.webern_matrix, [0, 1, 3]), result) def test_column_matrix_search(self): result = [[6, 2, 1], [10, 6, 4], [8, 11, 6], [1, 0, 7], [11, 10, 2], [2, 4, 0], [9, 8, 10], [4, 1, 5], [5, 7, 9], [0, 5, 3], [3, 9, 11], [7, 3, 8]] self.assertEqual(pcset.column_matrix_search(self.webern_matrix, [0, 1, 3]), result) pyknon-version1.2/test/test_simplemusic.py000066400000000000000000000170231260426672000212320ustar00rootroot00000000000000from __future__ import division from fractions import Fraction as F try: import unittest2 as unittest except: import unittest import pyknon.simplemusic as music class TestSimplemusic(unittest.TestCase): def test_mod12(self): self.assertEqual(music.mod12(0), 0) self.assertEqual(music.mod12(1), 1) self.assertEqual(music.mod12(13), 1) self.assertEqual(music.mod12(14), 2) self.assertEqual(music.mod12(-1), 11) def test_interval(self): self.assertEqual(music.interval(3, 4), 11) self.assertEqual(music.interval(4, 3), 1) self.assertEqual(music.interval(0, 12), 0) self.assertEqual(music.interval(1, 10), 3) self.assertEqual(music.interval(10, 1), 9) def test_interval_class(self): self.assertEqual(music.interval_class(1, 9), 4) self.assertEqual(music.interval_class(9, 1), 4) self.assertEqual(music.interval_class(11, 1), 2) self.assertEqual(music.interval_class(1, 11), 2) self.assertEqual(music.interval_class(1, -1), 2) self.assertEqual(music.interval_class(3, 2), 1) def test_intervals(self): self.assertEqual(music.intervals([1, 2, 3]), [1, 1]) self.assertEqual(music.intervals([0, 4, 7]), [4, 3]) self.assertEqual(music.intervals([0, 11, 3]), [1, 4]) def test_all_intervals(self): self.assertEqual(music.all_intervals([0, 1, 4]), [1, 3, 4]) self.assertEqual(music.all_intervals([4, 1, 0]), [1, 3, 4]) def test_transposition(self): n1 = [3, 7, 11, 10] n2 = [6, 10, 2, 1] self.assertEqual(music.transposition(n1, 3), n2) def test_is_related_by_transposition(self): self.assertTrue(music.is_related_by_transposition([0, 4, 7], [1, 5, 8])) self.assertTrue(music.is_related_by_transposition([0, 7, 4], [5, 8, 1])) self.assertTrue(music.is_related_by_transposition([4, 0, 7], [5, 1, 8])) self.assertFalse(music.is_related_by_transposition([4, 0, 7], [0, 3, 7])) def test_inversion(self): n1 = [0, 4, 7] n2 = [0, 8, 5] n3 = music.inversion(n1, 0) self.assertEqual(n3, n2) self.assertEqual(music.inversion(n3), n1) def test_transposition_startswith(self): n1 = [3, 7, 11, 10] n2 = [4, 8, 0, 11] self.assertEqual(music.transposition_startswith(n1, 4), n2) def test_inversion_startswith(self): n1 = [3, 7, 11, 10] n2 = [3, 11, 7, 8] self.assertEqual(music.inversion_startswith(n1, 3), n2) self.assertEqual(music.inversion_startswith([11, 10, 7], 1), [1, 2, 5]) def test_inversion_first_note(self): self.assertEqual(music.inversion_first_note([3, 7, 9]), [3, 11, 9]) def test_rotate(self): n1 = [0, 1, 3, 7] self.assertEqual(music.rotate(n1, 0), n1) self.assertEqual(music.rotate(n1, 1), [1, 3, 7, 0]) self.assertEqual(music.rotate(n1, 2), [3, 7, 0, 1]) self.assertEqual(music.rotate(n1, 3), [7, 0, 1, 3]) self.assertEqual(music.rotate(n1, 4), [0, 1, 3, 7]) def test_rotate_set(self): all_rotations = [[1,2,3], [2,3,1], [3,1,2]] self.assertEqual(music.rotate_set([1,2,3]), all_rotations) def test_retrograde(self): self.assertEqual(music.retrograde([0, 4, 7, 10]), [10, 7, 4, 0]) def test_note_name(self): self.assertEqual(music.note_name(0), "C") self.assertEqual(music.note_name(12), "C") self.assertEqual(music.note_name(1), "C#") self.assertEqual(music.note_name(3), "D#") def test_notes_names(self): notes = [0, 4, 8, 10, 14] self.assertEqual(music.notes_names(notes), ['C', 'E', 'G#', 'A#', 'D']) def test_accidentals(self): self.assertEqual(music.accidentals("C##"), 2) self.assertEqual(music.accidentals("D##"), 2) self.assertEqual(music.accidentals("Ebb"), -2) self.assertEqual(music.accidentals("Ab"), -1) def test_name_to_number(self): self.assertEqual(music.name_to_number("D###"), 5) self.assertEqual(music.name_to_number("D"), 2) self.assertEqual(music.name_to_number("A"), 9) self.assertEqual(music.name_to_number("Eb"), 3) self.assertEqual(music.name_to_number("Cbbb"), 9) def test_name_to_diatonic(self): self.assertEqual(music.name_to_diatonic("C"), 0) self.assertEqual(music.name_to_diatonic("D###"), 1) self.assertEqual(music.name_to_diatonic("Bb"), 6) def test_note_duration(self): self.assertEqual(music.note_duration(1/4, 1/4, 60), 1.0) self.assertEqual(music.note_duration(1/2, 1/4, 60), 2.0) def test_dotted_duration(self): self.assertEqual(music.dotted_duration(F(1/4), 0), F(1/4)) self.assertEqual(music.dotted_duration(F(1/4), 1), F(3/8)) self.assertEqual(music.dotted_duration(F(1/4), 2), F(7/16)) def test_durations(self): self.assertEqual(music.durations([1/2, 1/4, 1/8], 1/4, 60), [2.0, 1.0, 0.5]) self.assertEqual(music.durations([1/2, 1/4, 1/8], 1/4, 120), [1.0, 0.5, 0.25]) class TestIntervalName(unittest.TestCase): def test_interval_name_unison(self): self.assertEqual(music.interval_name("C", "C"), "Perfect Unison") self.assertEqual(music.interval_name("C", "C#"), "Augmented Unison") def test_interval_name_second(self): self.assertEqual(music.interval_name("D", "E"), "Major Second") self.assertEqual(music.interval_name("D", "Eb"), "Minor Second") self.assertEqual(music.interval_name("E", "F"), "Minor Second") self.assertEqual(music.interval_name("E", "F#"), "Major Second") self.assertEqual(music.interval_name("Eb", "F#"), "Augmented Second") self.assertEqual(music.interval_name("E", "Fb"), "Diminished Second") def test_interval_name_third(self): self.assertEqual(music.interval_name("D", "F"), "Minor Third") self.assertEqual(music.interval_name("D", "F#"), "Major Third") self.assertEqual(music.interval_name("D", "Fb"), "Diminished Third") self.assertEqual(music.interval_name("C", "E"), "Major Third") self.assertEqual(music.interval_name("C", "Eb"), "Minor Third") self.assertEqual(music.interval_name("Db", "F#"), "Augmented Third") def test_interval_name_fourth(self): self.assertEqual(music.interval_name("C", "F"), "Perfect Fourth") self.assertEqual(music.interval_name("C", "F#"), "Augmented Fourth") self.assertEqual(music.interval_name("C", "Fb"), "Diminished Fourth") self.assertEqual(music.interval_name("F", "B"), "Augmented Fourth") def test_interval_name_fifth(self): self.assertEqual(music.interval_name("D", "A"), "Perfect Fifth") self.assertEqual(music.interval_name("C", "Gb"), "Diminished Fifth") self.assertEqual(music.interval_name("B", "F"), "Diminished Fifth") self.assertEqual(music.interval_name("Bb", "F#"), "Augmented Fifth") def test_interval_name_sixth(self): self.assertEqual(music.interval_name("D", "B"), "Major Sixth") self.assertEqual(music.interval_name("E", "C"), "Minor Sixth") self.assertEqual(music.interval_name("D", "B#"), "Augmented Sixth") self.assertEqual(music.interval_name("E", "Cb"), "Diminished Sixth") def test_interval_name_seventh(self): self.assertEqual(music.interval_name("C", "B"), "Major Seventh") self.assertEqual(music.interval_name("E", "D#"), "Major Seventh") self.assertEqual(music.interval_name("D", "C"), "Minor Seventh") self.assertEqual(music.interval_name("D", "Cb"), "Diminished Seventh") pyknon-version1.2/tox.ini000066400000000000000000000002361260426672000156210ustar00rootroot00000000000000[tox] envlist = py26,py27,py33 [testenv] deps=nose commands=nosetests setenv = MACOSX_DEPLOYMENT_TARGET=10.8 [testenv:py26] deps = unittest2 nose