# Pitch / Scale Theory Toolkit
A spelling-aware music-theory layer: intervals, scales and modes, pitch collections (melodic cells, atonal sets, 12-tone rows), and diatonic-vs-chromatic transposition — all preserving **correct enharmonic spelling**. Transposing `A` up an augmented second gives `B♯`, never `C♮`.
It is a pure, language-side value layer — no RT thread, no engine, no Generators. Everything is built on the existing `Letter` / `Accidental` / `NoteName` / `Pitch` foundation and outputs `NoteName` / `Pitch`, so results drop straight into the **Score DSL** for notation/MusicXML, or convert to **Hz and seconds** to drive synthesis parameters.
Files live under `Sources/Lyrebird/Score/Theory/`. All types are `Sendable` + `Hashable`.
```swift
import LyrebirdSynth
```
---
## Core types
| Type | Role |
|---|---|
| `Interval` | Spelled diatonic interval: `number` (1 = unison … 8 = octave, compounds allowed) + `IntervalQuality`. |
| `IntervalQuality` | `.diminished(n)` / `.minor` / `.perfect` / `.major` / `.augmented(n)`. |
| `IntervalDirection` | `.up` / `.down`. |
| `Scale` | A tonic + ordered spelled `degrees`. Modes, symmetric scales, pentatonics, or arbitrary pitch sets. |
| `ScaleDegree` | A located degree: `index` + chromatic `alteration` (semitones off the degree). |
| `PitchCollection` | An ordered list of `Pitch` (cell / set / row) + optional `referenceScale`. |
Most operations **throw** (`IntervalError`, `ScaleError`, `ToneRowError`). Intervals are 12-TET; quarter-tone accidentals are rejected (`IntervalError.quarterToneUnsupported`). A correct spelling that would need an accidental beyond double-flat / double-sharp throws `IntervalError.unrepresentableSpelling`.
---
## Intervals
A static catalogue covers the common simple intervals; build others with `init(number:quality:)`.
```swift
Interval.majorThird.semitones // 4
Interval.augmentedSecond.semitones // 3 (same SOUND as a minor third…)
Interval.minorThird.semitones // 3 (…but a different SPELLING)
Interval.majorThird.diatonicSteps // 2 (letter distance)
let majorNinth = try Interval(number: 9, quality: .major) // compound
majorNinth.semitones // 14
```
Validity is enforced: perfect-class numbers (unison / 4th / 5th / octave) reject `.major` / `.minor`; imperfect-class numbers (2nd / 3rd / 6th / 7th) reject `.perfect`.
```swift
try Interval(number: 5, quality: .major) // throws .qualityNumberMismatch
```
Analyse the spelled interval between two names or pitches:
```swift
try Interval.between(.c, .e) // major third
try Interval.between(.a, .bSharp) // augmented second (not minor third)
// Directed, possibly-compound, between two named pitches:
let (interval, dir) = try Interval.directed(from: .named(.c, 4), to: .named(.e, 5))
// interval = major tenth, dir = .up
```
### Transposition
`transposed(by:_:)` advances the letter by the interval's `diatonicSteps`, then picks the accidental that makes the chromatic distance equal `interval.semitones` — so the spelling is always correct.
```swift
try NoteName.a.transposed(by: .augmentedSecond) // B♯ (NOT C)
try NoteName.e.transposed(by: .majorThird) // G♯
try NoteName.fSharp.transposed(by: .minorThird, .down) // D♯
// Pitch keeps spelling AND tracks the octave:
try Pitch.named(.b, 4).transposed(by: .perfectFourth) // .named(.e, 5) (letter wraps past C)
try Pitch.named(.c, 4).transposed(by: majorNinth) // .named(.d, 5)
```
`.midi` / `.freq` pitches shift numerically (spelling is lost — documented on the method).
### Folding into a register
`Pitch.mapIntoRange(low:high:)` shifts a pitch into the inclusive register `[low, high]` by whole octaves, taking the fewest octaves. The pitch class is preserved, and for `.named` pitches **spelling survives** — a `B♭` maps to a `B♭`, never an enharmonic `A♯` (unlike the scalar `Double`/`Int` `mapIntoRange`, which only knows MIDI numbers). There is no `modulo:` parameter: the fold is octave-only by design, which is exactly what keeps the pitch class and spelling intact.
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 5)) // .named(.c, 5)
Pitch.named(.bFlat, 2).mapIntoRange(low: .named(.c, 4), high: .named(.c, 5)) // .named(.bFlat, 4)
```
When the range is wider than an octave the fewest-octaves rule returns the first representative reached from `self`:
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 5) — folds up
Pitch.named(.c, 7).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 6) — folds down
```
When no octave lands inside the range (the bounds span less than an octave and this pitch class has no member there), or when an endpoint / the pitch is a rest or out-of-MIDI-range, **the original pitch is returned unchanged**. `.midi` / `.freq` pitches fold numerically and keep their case (`.freq` keeps sub-semitone cents).
---
## Scales and modes
Factories build a scale from a tonic + interval pattern. Seven-note diatonic modes use seven distinct letters, so spelling is guaranteed.
```swift
let dMajor = try Scale.major(.d)
dMajor.degrees // [D, E, F♯, G, A, B, C♯] ← one letter per degree
try Scale.dorian(.eFlat).degrees // [E♭, F, G♭, A♭, B♭, C, D♭]
try Scale.harmonicMinor(.a).degrees // [A, B, C, D, E, F, G♯]
```
Symmetric scales have more notes than letters; each factory fixes a canonical spelling:
```swift
try Scale.wholeTone(.c).degrees // [C, D, E, F♯, G♯, A♯]
try Scale.octatonicHalfWhole(.c).degrees // [C, D♭, E♭, E, F♯, G, A, B♭]
try Scale.majorPentatonic(.c).degrees // [C, D, E, G, A]
try Scale.blues(.c).degrees // [C, E♭, F, G♭, G, B♭]
```
Available: `major`/`ionian`, `dorian`, `phrygian`, `lydian`, `mixolydian`, `aeolian`/`naturalMinor`, `locrian`, `harmonicMinor`, `melodicMinor`, `wholeTone`, `chromatic`, `octatonicHalfWhole`, `octatonicWholeHalf`, `augmentedScale`, `majorPentatonic`, `minorPentatonic`, `blues`. Or build from explicit degrees / intervals / named pitches:
```swift
let custom = try Scale(tonic: .c, intervals: [.unison, .majorSecond, .minorThird])
let set = try Scale(tonic: .c, pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
```
### Queries
```swift
let cMajor = try Scale.major(.c)
cMajor.contains(.fSharp) // false (pitch-class membership)
cMajor.degree(of: .g) // ScaleDegree(index: 4, alteration: 0)
cMajor.degree(of: .fSharp) // ScaleDegree(index: 3, alteration: +1) ← raised 4th
cMajor.noteName(atDegree: 9) // E (wraps mod 7)
cMajor.pitch(atDegree: 2, octave: 4) // .named(.e, 4)
```
`degree(of:)` resolves exact spelling → enharmonic pitch-class → same letter → nearest pitch-class, carrying any chromatic `alteration` so non-scale pitches survive the round trip.
---
## Pitch collections
Order matters — a `PitchCollection` is a melodic cell, an atonal set, or a 12-tone row.
```swift
let cell = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
cell.retrograde.pitches // G E C
try cell.transposedChromatic(by: .majorThird).pitches // E G♯ B (every pitch +M3)
try cell.inverted(around: .named(.c, 4)).pitches // C A♭3 F3 (mirror, spelled)
cell.octaveReduced.pitches // fold to one octave
```
### 12-tone rows
When a collection is twelve named pitches across all twelve pitch-classes, the row's own spelling defines a pitch-class → note-name map, so **every derived form stays spelling-consistent** with the prime row.
```swift
let row = PitchCollection(pitches: [
.named(.c, 4), .named(.dFlat, 4), .named(.d, 4), .named(.eFlat, 4),
.named(.e, 4), .named(.f, 4), .named(.gFlat, 4), .named(.g, 4),
.named(.aFlat, 4), .named(.a, 4), .named(.bFlat, 4), .named(.b, 4),
])
row.isToneRow // true
try row.toneRowInversion() // I0
try row.toneRowRetrograde() // R0
try row.toneRowTransposed(3) // T3 (pc + 3, spelled via the row's map → G♭ stays G♭)
try row.toneRowTransposedInversion(5) // T5I
let matrix = try row.toneRowMatrix() // [[NoteName]] 12×12 (top = prime, left = inversion)
```
---
## Diatonic vs. chromatic transposition
This is the distinction the toolkit exists to get right.
- **Chromatic** — `PitchCollection.transposedChromatic(by:_:)` moves every pitch by the *same spelled interval*.
- **Diatonic (modal)** — `Scale.transposeDiatonic(_:byDegrees:)` moves every pitch by the *same number of scale steps*, staying in the scale.
```swift
let cMajor = try Scale.major(.c)
let line = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.e, 4)])
try cMajor.transposeDiatonic(line, byDegrees: 2).pitches // E F G (in-scale thirds)
try line.transposedChromatic(by: .majorThird).pitches // E F♯ G♯ (three equal M3s)
```
### Scale-to-scale mapping
`PitchCollection.mapped(from:to:)` re-assigns each pitch by degree from one scale to another, carrying alteration and octave register.
```swift
let triad = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.d)).pitches // D F♯ A
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.eFlat)).pitches // E♭ G B♭
try triad.mapped(from: try Scale.major(.c), to: try Scale.aeolian(.c)).pitches // C E♭ G (major→minor triad)
```
Degree-count mismatch (e.g. pentatonic → heptatonic) maps by index with wrap.
---
## Notation — feeding the Score / MusicXML pipeline
Theory output is `NoteName` / `Pitch`, which the **Score DSL** consumes directly. Build a transposed phrase, then export to MusicXML — the spellings survive the round trip (sharps stay sharp, `B♯` does not collapse to `C`).
```swift
// A phrase, transposed up a major third with correct spelling.
let phrase = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.a, 4)])
let up = try phrase.transposedChromatic(by: .majorThird) // E F♯ C♯
let score = Score(bpm: 120) {
Part("theory") {
for pitch in up.pitches {
Note(pitch, dur: .quarter) // Note(_ pitch: Pitch, dur:) takes .named directly
}
}
}
let xml = score.toMusicXMLString()
// E → E, F♯ → F1, C♯ → C1
// Round-trips losslessly:
let decoded = try Score.fromMusicXML(data: Data(xml.utf8))
```
Build a whole scale or a chord the same way:
```swift
let scale = try Scale.dorian(.d)
let part = Part("dorian") {
for i in 0..