Metadata-Version: 2.4
Name: musictheory
Version: 0.7
Summary: Provides classes for "music set theory"-like analysis.
Home-page: http://pypi.python.org/pypi/musictheory/
Author: Peter Murphy
Author-email: peterkmurphy@gmail.com
License: BSD-3-Clause
Keywords: music set theory temperament scale chords
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: End Users/Desktop
Classifier: Intended Audience :: Other Audience
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Artistic Software
Classifier: Topic :: Education
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Topic :: Other/Nonlisted Topic
Classifier: Topic :: Software Development
Classifier: Topic :: Utilities
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: requires-python
Dynamic: summary

# Music Theory

**musictheory** is a package designed to investigate the question "Which chords
go with which scales?" A couple of years ago, the author was very interested
and obsessed in the question, and decided to put his Python skills to the task.
Along the way, the **musictheory** package was redesigned to be more flexible
and extendible.

The package has roughly the same philosophy as
[Music Set Theory](http://www.jaytomlin.com/music/settheory/help.html)
but uses different terminology.

## Documentation

The source code contains an *excess* of documentation strings. Hopefully it
makes things clearer. The sections below map the modules, types, and main call
paths.

The central question the library answers is: given a scale and a key,
which named chords (sonorities) sit on each degree?

```text
temperament (WestTemp)
    └── registers noteseq / noteseq_scale / noteseq_chord
            └── chordgenerator.populate_scale_chords → HTML via chordgentable
```

### Package layout

- **`temperament`** — Defines pitch classes, note spelling, and a
  registry of scales and chords.
- **`scales`** — Provides the base `noteseq` class, a scale subclass,
  and the built-in scales and modes.
- **`chords`** — Provides a chord subclass, the Western chord
  catalogue, and spelling patterns.
- **`chordgenerator`** — Builds scale-to-chord tables and renders them
  as HTML.
- **`musutility`** — Supplies small sequence helpers used throughout
  the package.

Chord registration runs when `chords` is imported (or when
`chordgenerator` imports it). Scales register themselves when `scales`
is imported.

### `temperament`

#### Constants (selection)

- **Accidentals:** `M_SHARP`, `M_FLAT`, `M_NATURAL`, the doubles and
  halves, the ASCII forms (`MNU_*`), and the `NOTESYMBOL_*` maps.
- **Sequence kinds:** `NSEQ_SCALE` and `NSEQ_CHORD`.
- **12-TET neutrals:** `CHROM_NAT_NOTES`, `CHROM_NAT_NOTE_POS`, and
  `CHROM_SIZE`.
- **Built-in instance:** `WestTemp` is the Western 12-tone temperament
  with the natural letters C–B.

#### `seq_dict`

The `seq_dict` class acts as a multi-key dictionary for registered
note-sequence objects. It allows lookups by name, by abbreviation, and
by the sorted semitone pattern.

- `add_elem(...)` — Registers a sequence under its names,
  abbreviations, and pattern.
- `check_nseqby_name` / `abbrv` / `seqpos` / `subdict` — Checks whether
  a matching entry is present.
- `get_nseqby_name` / `abbrv` / `seqpos` — Looks up a registered
  object.

#### `temperament`

A temperament defines how many pitch classes there are, what the
natural letter names are, and where those letters sit chromatically. It
also owns `seq_maps`, which keeps separate maps for scales and for
chords.

- `note_parse(key)` — Splits a note name into a natural letter and an
  accidental offset.
- `get_pos_of_key(key)` — Returns the chromatic position of a named
  note.
- `get_key_of_pos(pos, desired_nat=None, ...)` — Spells a position as
  a note name, optionally forcing a preferred letter.
- `get_note_sequence(key, pos_seq, nat_pos_seq=None)` — Returns note
  names for intervals from *key*; `nat_pos_seq` drives the letter
  spelling.
- `get_keyseq_notes(note_seq)` — Performs the inverse: notes become
  `[base_key, relative positions]`.
- `add_elem` / `check_*` / `get_nseqby_*` — Delegates to the
  appropriate `seq_dict`.

#### Function

- **`un_unicode_accdtls(str_note)`** turns Unicode accidentals into
  ASCII forms (`♯`→`#`, and so on).

### `scales`

#### `noteseq`

This represents a pattern of notes — a scale or a chord — each with a
specified position from a base key. The sound is given by relative
**semitone** positions (`nseq_posn`); the spelling is given by parallel
**letter offsets** (`nseq_nat_posns`). The same model is used for both
scales and chords.

- `nseq_posn` — The sounding intervals; for example, a major triad is
  `[0, 4, 7]`.
- `nseq_nat_posns` — The letter spelling; for a triad this is
  `[0, 2, 4]` (1st, 3rd, and 5th letters).

- `register_with_temp()` — Registers this pattern on its temperament so
  that it can be looked up by name, abbreviation, or pattern.
- `get_notes_for_key(key, rotate_by=0, indices=None)` — Returns the
  spelled notes in *key*, optionally rotated and sliced (`multislice`).
  The slice modulus is **`len(nseq_posn)`** (7 for Major, 8 for
  Diminished).
- `get_posn_for_offset(rotate_by=0, indices=None, raz=False)` —
  Applies the same rotate and slice to the semitone positions; if `raz`
  is `True`, the result is rezeroed so that the first kept tone is `0`.

#### `noteseq_scale`

This is a specialisation of `noteseq` used for scales. The constructor
can take mode names and registers each rotation as its own scale on the
temperament.

#### Built-in scales (examples)

These are created at import time on `WestTemp`:

- `MajorScale` (plus the modes in `MAJORMODES`)
- `MelMinorScale`, `HarmMinorScale`, `HarmMajorScale`
- `DiscMinorScale`, `HungarianScale`
- `DiminishedScale` (8 notes; Whole-Half / Half-Whole mode names live
  in `DIMINISHEDMODES`)

Related constants include `HEPT_NAT_POSNS`, `OCT_NAT_POSNS`, the
`*_NOTE_POS` lists, and the mode-name lists.

### `chords`

#### `noteseq_chord`

This is a specialisation of `noteseq` used exclusively for chords
(`NSEQ_CHORD`). It uses the same spelling and position model as scales.

#### `CHORDTYPE_DICT`

This is a spelling catalogue only, used when registering chords: each
pattern name maps onto an `nseq_nat_posns` list (for example,
`"Triad"` → `[0, 2, 4]`, `"Seventh"` → `[0, 2, 4, 6]`).

It is not used for scale-table row slicing; see `SONORITY_SLICES` in
`chordgenerator` for that.

#### `generate_west_chords()`

This builds the Western chord catalogue (triads, sevenths, suspensions,
adds, diminished stacks, and so on), registers each chord on
`WestTemp`, and returns the list. Importing the module runs this once
and stores the result in `ourchords`.

### `chordgenerator`

This module turns a named scale and a key into a table of sonorities
(rows) by scale degrees (columns), and can render that table as HTML.

#### Sonority catalogues (table rows)

- `SONORITY_SLICES` — Maps each display label onto the 0-based degree
  indices to take from the scale.
- `HEPTATONIC_SONORITIES` — Lists the row labels for 7-note scales, in
  display order.
- `HEPTATONIC_SONORITIES_RESERVE` — Holds parked heptatonic rows that
  are not used in the tables.
- `DIMINISHED_SONORITIES` — Lists the row labels for 8-note diminished
  scales.
- `DIMINISHED_SONORITIES_RESERVE` — Holds parked octatonic rows that
  are not used in the tables.
- `OCTATONIC_SONORITIES` — Is an alias of `DIMINISHED_SONORITIES`.

Sonority labels look like `1–3–5 (Triad chords)`: a degree pattern
plus a gloss.

- `sonorities_for_nseq_len(n, priority="all")` — Returns the heptatonic
  list if `n` is not 8, otherwise the diminished list; an optional
  `essential` / `important` / `all` filter may be applied.
- `sonorities_for_scale(scale, priority="all")` — Does the same, using
  `len(scale.nseq_posn)`.
- `filter_sonorities_by_priority(labels, level)` — Keeps labels whose
  priority is at most `essential` (1), `important` (2), or `all` (3).
- `SONORITY_PRIORITY` — Maps each display label onto a priority band of
  1, 2, or 3.
- `SONORITY_PRIORITY_LEVELS` — Maps `essential` / `important` / `all`
  onto a maximum priority.

#### Table model

- `scale_chords` — Represents all the chords associated with a scale.
  This is used to make a tabular representation (scale name, key, full
  note list, Roman headers, and `rows`).
- `scale_chordrow` — Represents one sonority row (`chord_type` label
  plus a list of `notes` cells).
- `scale_chordcell` — Represents one cell: a full name, an
  abbreviation, and a note list (empty names if unmatched).

#### Building and rendering

- `populate_scale_chords(scale_name, key, possiblechords=None)` —
  Returns a `scale_chords` table: for each sonority and degree it
  slices notes and positions, then looks up the chord via
  `WestTemp.get_nseqby_seqpos`.
- `chordgentable(scales, ...)` — Generates an HTML table
  representation; factories can customise the `<th>` / `<td>` /
  caption output (as used by the Django chordgenerator app).
- `int_to_roman` / `make_roman_numeral_list` — Produce the
  Roman-numeral column headers (`I`, `II`, …).
- `makebaserep` — Provides an optional numeric degree spelling when
  *key* is an integer base.

The print-mode constants `PRINT_ABBRV`, `PRINT_FNAME`, and
`PRINT_BOTH` exist for callers that choose name versus abbreviation
display.

### `musutility`

These are generic sequence tools with no music-domain knowledge of
their own:

- `rotate(seq, offset)` — Rotates a sequence to the left by *offset*
  places.
- `rotate_and_zero(seq, offset, mod)` — Rotates the sequence, then
  shifts values so that the first element is `0` (modulo *mod* when
  *mod* is non-zero).
- `multislice(seq, indices, mod=0, offset=0)` — Gathers elements by
  index after an optional rotate; indices may be taken modulo *mod*.
- `scalar_addition(seq, scalar)` — Adds a constant to each element.
- `norm_seq(seq, mod)` — Returns the sorted unique residues modulo
  *mod*.
- `enl_seq(seq_of_seq, otherentries)` — Appends entries in a Cartesian
  fashion (used when expanding chord-tone patterns).
- `seqtostr` / `repseq` — Produce comma-separated string forms of a
  sequence.

### Typical usage sketch

```python
from musictheory.chordgenerator import populate_scale_chords, chordgentable

table = populate_scale_chords("Major", "C")
# table.rows[i].chord_type  → e.g. "1–3–5 (Triad-like chords)"
# table.rows[i].notes[j]    → scale_chordcell for degree j

html = chordgentable([table])

# Or look up patterns directly:
from musictheory.temperament import WestTemp, NSEQ_SCALE, NSEQ_CHORD

scale = WestTemp.get_nseqby_name("Dorian", NSEQ_SCALE)
chord = WestTemp.get_nseqby_seqpos([0, 3, 7], NSEQ_CHORD)  # minor triad shape
```

### Mental model: two “pattern” dictionaries

- `CHORDTYPE_DICT` (`chords`) — Used for spelling when **registering**
  a chord (for example, `"Triad"` → `[0, 2, 4]`).
- `SONORITY_SLICES` (`chordgenerator`) — Used for **slicing** a scale
  for a table row (for example,
  `"1–3–5 (Triad-like chords)"` → `[0, 2, 4]`).

Cell chord *qualities* (Major, Minor, dim7, and so on) come from
matching the sliced semitone shapes against the registered chord map —
not from the row label itself.

## Installation

```bash
pip install musictheory
```

## Testing

Testing can be performed by executing the following code in the setup directory:

```bash
python -m test.test_all
```

## License

The software has been released using a 3-clause Berkeley Software
Distribution (BSD) license. See `LICENSE.txt` for more information.

## Versions

* 0.1 (May 1st 2011) - Create setup script for files.
* 0.2 (May 11th 2011) - Remove bugs for working with chordgenerator.
* 0.3 (June 6th 2011) - Add license information. Add more scales.
* 0.4 (April 24th 2013) - Try to make a half-decent PyPI package.
* 0.5 (August 14th 2014) - Add some experimental suspended chords.
* 0.6 (December 6th 2020) - Updated for Python 3.0 compatibility.
* 0.7 (October 30th 2026) - General Pyright code cleanup; sonority sets for heptatonic vs octatonic (diminished) scales; `chordgentable` variable columns and extension hooks.

## Copyright

The **musictheory** package is copyright (c) 2008-2026
[Peter Murphy](http://www.pkmurphy.com.au/)
<peterkmurphy@gmail.com>.
