Files
Lyrebird/Sources/Lyrebird/Score/Theory/Scale.swift
T

183 lines
7.8 KiB
Swift

// Scale.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// An ordered set of spelled pitch-classes built on a tonic — a diatonic mode,
/// a symmetric scale, or any arbitrary collection treated as a scale.
///
/// `degrees[0]` is always the tonic; each subsequent entry is one scale degree,
/// correctly spelled. Diatonic 7-note scales use seven distinct letters (the
/// interval pattern guarantees the letter progression — `D major` →
/// `D E F♯ G A B C♯`). Symmetric scales (whole-tone, octatonic, …) have no
/// one-letter-per-degree mapping; their factories define a canonical spelling.
///
/// Pure value type — no octave is stored; degrees are pitch-classes. Octave is
/// supplied per query via ``pitch(atDegree:octave:)``.
public struct Scale: Sendable, Hashable {
/// The tonic — always equal to `degrees[0]`.
public let tonic: NoteName
/// The spelled scale degrees in ascending order, one per degree.
public let degrees: [NoteName]
/// Number of degrees in the scale.
public var count: Int { degrees.count }
// MARK: - Initializers
/// Build a scale from a tonic and a list of intervals measured from the
/// tonic. The first interval is normally ``Interval/unison`` so
/// `degrees[0] == tonic`. Each degree is spelled by transposing the tonic
/// by its interval, which guarantees the per-degree letter progression.
///
/// - Parameters:
/// - tonic: The tonic note name.
/// - intervals: Intervals from the tonic, ascending. Must be non-empty.
/// - Throws: ``ScaleError/emptyDegrees`` if `intervals` is empty; any
/// ``IntervalError`` from spelling a degree.
public init(
tonic: NoteName,
intervals: [Interval]
) throws {
guard !intervals.isEmpty else { throw ScaleError.emptyDegrees }
self.tonic = tonic
self.degrees = try intervals.map { try tonic.transposed(by: $0, .up) }
}
/// Build a scale from an explicit list of spelled degrees.
///
/// - Parameters:
/// - tonic: The tonic; must equal `degrees[0]`.
/// - degrees: Ascending spelled degrees. Must be non-empty.
/// - Throws: ``ScaleError/emptyDegrees`` or ``ScaleError/tonicMismatch(tonic:firstDegree:)``.
public init(
tonic: NoteName,
degrees: [NoteName]
) throws {
guard let first: NoteName = degrees.first else { throw ScaleError.emptyDegrees }
guard first == tonic else {
throw ScaleError.tonicMismatch(tonic: tonic, firstDegree: first)
}
self.tonic = tonic
self.degrees = degrees
}
/// Build a scale from an arbitrary ordered set of named pitches (item a).
/// Octaves are discarded — only the spelled note names are kept.
///
/// - Parameters:
/// - tonic: The tonic; must equal the first pitch's note name.
/// - pitches: Ordered pitches. Each must be ``Pitch/named(_:_:)``.
/// - Throws: ``ScaleError/emptyDegrees``, ``ScaleError/nonNamedPitch(_:)``,
/// or ``ScaleError/tonicMismatch(tonic:firstDegree:)``.
public init(
tonic: NoteName,
pitches: [Pitch]
) throws {
guard !pitches.isEmpty else { throw ScaleError.emptyDegrees }
var names: [NoteName] = []
names.reserveCapacity(pitches.count)
for pitch: Pitch in pitches {
guard case .named(let name, _) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
names.append(name)
}
try self.init(tonic: tonic, degrees: names)
}
// MARK: - Queries
/// Whether `name` is a member of the scale, by pitch-class (enharmonic
/// equivalents count — `F♯` matches a `G♭` degree).
public func contains(_ name: NoteName) -> Bool {
let pc: Int = Scale.pitchClass(name)
return degrees.contains { Scale.pitchClass($0) == pc }
}
/// Locate `name` within the scale as a ``ScaleDegree`` — a degree index plus
/// the chromatic alteration needed to reach a non-scale pitch.
///
/// Resolution order: exact spelling → enharmonic pitch-class → same letter
/// (alteration = accidental difference) → nearest pitch-class by signed
/// semitone distance. Returns `nil` only for an empty scale (which the
/// initializers forbid).
public func degree(of name: NoteName) -> ScaleDegree? {
guard !degrees.isEmpty else { return nil }
// 1. Exact spelling.
if let i: Int = degrees.firstIndex(of: name) {
return ScaleDegree(index: i, alteration: 0)
}
let targetPc: Int = Scale.pitchClass(name)
// 2. Enharmonic pitch-class.
if let i: Int = degrees.firstIndex(where: { Scale.pitchClass($0) == targetPc }) {
return ScaleDegree(index: i, alteration: 0)
}
// 3. Same letter — alteration is the accidental difference.
if let i: Int = degrees.firstIndex(where: { $0.letter == name.letter }) {
let alteration: Int = Int((name.semitones - degrees[i].semitones).rounded())
return ScaleDegree(index: i, alteration: alteration)
}
// 4. Nearest pitch-class by signed circular distance. The seed exceeds
// every valid signed distance ([-6, 5]) and is always overwritten on the
// first degree (the scale is non-empty), so it is a sentinel only.
var bestIndex: Int = 0
var bestDistance: Int = Scale.semitonesPerOctave
for (i, degree): (Int, NoteName) in degrees.enumerated() {
let raw: Int = targetPc - Scale.pitchClass(degree)
let signed: Int = ((raw + Scale.semitonesPerOctave + Scale.semitonesPerOctave / 2)
% Scale.semitonesPerOctave) - Scale.semitonesPerOctave / 2
if abs(signed) < abs(bestDistance) {
bestDistance = signed
bestIndex = i
}
}
return ScaleDegree(index: bestIndex, alteration: bestDistance)
}
/// The spelled note name at a degree index, wrapping modulo ``count`` so
/// indices beyond the scale (or negative) map back into it.
public func noteName(atDegree index: Int) -> NoteName {
let wrapped: Int = ((index % count) + count) % count
return degrees[wrapped]
}
/// The pitch at a degree index in a given base octave. Degree indices beyond
/// the scale add octaves; degrees whose letter sits below the tonic's letter
/// are placed in the next octave so the scale ascends from the tonic.
///
/// - Parameters:
/// - index: Degree index (0 = tonic); may exceed ``count`` or be negative.
/// - octave: Base octave of the tonic (4 = middle-C octave).
public func pitch(atDegree index: Int, octave: Int) -> Pitch {
let octaveSpan: Int = Int((Double(index) / Double(count)).rounded(.down))
let name: NoteName = noteName(atDegree: index)
return .named(name, octave + octaveSpan + letterBump(name))
}
// MARK: - Helpers
/// `1` when `name`'s letter sits below the tonic's letter (so it belongs in
/// the next octave when ascending from the tonic), else `0`. Shared by the
/// octave bookkeeping in ``pitch(atDegree:octave:)`` and diatonic / mapping
/// operations.
func letterBump(_ name: NoteName) -> Int {
name.letter.diatonicIndex < tonic.letter.diatonicIndex ? 1 : 0
}
/// Pitch-class `[0, 11]` of a note name (`C = 0`), folding the octave wrap
/// of `C♭` / `B♯` and any accidental back into range.
static func pitchClass(_ name: NoteName) -> Int {
let raw: Int = Int(name.semitones.rounded())
return ((raw % semitonesPerOctave) + semitonesPerOctave) % semitonesPerOctave
}
/// Semitones per octave (`12`).
static let semitonesPerOctave: Int = 12
}