MNX Document Model
Loading...
Searching...
No Matches
music_theory.hpp
1/*
2 * Copyright (C) 2025, Robert Patterson
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23 // Do not use `#pragma once` here, because the file may be included in multiple projects
24#ifndef MUSIC_THEORY_HPP
25#define MUSIC_THEORY_HPP
26
27#include <array>
28#include <vector>
29#include <cmath>
30#include <algorithm>
31#include <optional>
32#include <stdexcept>
33#include <string>
34
35/*
36This header-only library has no dependencies and can be shared into any other library merely
37by including it.
38*/
39
42namespace music_theory {
43
45constexpr int STANDARD_DIATONIC_STEPS = 7;
46constexpr int STANDARD_12EDO_STEPS = 12;
47
48constexpr std::array<int, STANDARD_DIATONIC_STEPS> MAJOR_KEYMAP = { 0, 2, 4, 5, 7, 9, 11 };
49constexpr std::array<int, STANDARD_DIATONIC_STEPS> MINOR_KEYMAP = { 0, 2, 3, 5, 7, 8, 10 };
50
54constexpr std::array<std::array<int, 2>, STANDARD_DIATONIC_STEPS> DIATONIC_INTERVAL_ADJUSTMENTS = { {
55 { 0, 0 }, // unison
56 { 2, -1 }, // second
57 { 4, -2 }, // third
58 {-1, 1 }, // fourth
59 { 1, 0 }, // fifth
60 { 3, -1 }, // sixth
61 { 5, -2 } // seventh
62}};
63
65enum class NoteName : int
66{
67 C = 0,
68 D = 1,
69 E = 2,
70 F = 3,
71 G = 4,
72 A = 5,
73 B = 6
74};
75
82struct Pitch
83{
85 constexpr Pitch() = default;
86
91 constexpr Pitch(NoteName pitchName, int pitchOctave, int pitchAlteration = 0)
92 : noteName(pitchName), octave(pitchOctave), alteration(pitchAlteration)
93 {
94 }
95
97 int octave{};
98 int alteration{};
99};
100
101static constexpr std::array<music_theory::NoteName, music_theory::STANDARD_DIATONIC_STEPS> noteNames = {
102 NoteName::C, NoteName::D, NoteName::E, NoteName::F, NoteName::G, NoteName::A, NoteName::B
103};
104
109enum class DiatonicMode : int
110{
111 Ionian = 0,
112 Dorian = 1,
113 Phrygian = 2,
114 Lydian = 3,
115 Mixolydian = 4,
116 Aeolian = 5,
117 Locrian = 6
118};
119
122enum class ClefType
123{
124 Unknown,
125 G,
126 C,
127 F,
130 Tab,
131 TabSerif
132};
133
137constexpr int calcDisplacement(const Pitch& pitch)
138{
139 int pitchClassVal = int(pitch.noteName) % STANDARD_DIATONIC_STEPS;
140 const int relativeOctave = pitch.octave - 4;
141
142 return pitchClassVal + (STANDARD_DIATONIC_STEPS * relativeOctave);
143}
144
148template <typename T>
149constexpr T sign(T n)
150{
151 static_assert(std::is_arithmetic_v<T>, "sign requires a numeric type");
152 return n < T(0) ? T(-1) : T(1);
153}
154
160template <typename T>
161constexpr T signedModulus(T n, T d)
162{
163 static_assert(std::is_integral_v<T>, "signedModulus requires an integer type");
164 return sign(n) * (std::abs(n) % d);
165}
166
173template <typename T>
174constexpr T positiveModulus(T n, T d, T* q = nullptr)
175{
176 static_assert(std::is_integral_v<T>, "positiveModulus requires an integer type");
177 if (q) *q = n / d;
178 T result = signedModulus(n, d);
179 if (result < 0) {
180 result += d;
181 if (q) --(*q);
182 }
183 return result;
184}
185
190constexpr int calc12EdoHalfstepsInInterval(int interval, int chromaticAlteration)
191{
192 int octaves{};
193 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS, &octaves);
194 return MAJOR_KEYMAP[diatonic] + (octaves * STANDARD_12EDO_STEPS) + chromaticAlteration;
195}
196
201constexpr int calcAlterationFrom12EdoHalfsteps(int interval, int halfsteps)
202{
203 int octaves{};
204 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS, &octaves);
205 int expectedHalfsteps = MAJOR_KEYMAP[diatonic] + (octaves * STANDARD_12EDO_STEPS);
206 return halfsteps - expectedHalfsteps;
207}
208
213constexpr int calcAlterationFromKeySigChange(int interval, int keySigChange)
214{
215 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS);
216 int expectedKeyChange = DIATONIC_INTERVAL_ADJUSTMENTS[diatonic][0];
217 if (interval < 0) {
218 if (std::abs(expectedKeyChange) > 1) { // imperfect intervals
219 expectedKeyChange -= STANDARD_DIATONIC_STEPS;
220 }
221 }
222 int alteration = (keySigChange - expectedKeyChange) / STANDARD_DIATONIC_STEPS;
223 return alteration;
224}
225
232constexpr int calcKeySigChangeFromInterval(int interval, int chromaticAlteration)
233{
234 const int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS);
235 int expectedKeyChange = DIATONIC_INTERVAL_ADJUSTMENTS[diatonic][0];
236 if (interval < 0) {
237 if (std::abs(expectedKeyChange) > 1) { // imperfect intervals
238 expectedKeyChange -= STANDARD_DIATONIC_STEPS;
239 }
240 }
241 return expectedKeyChange + (chromaticAlteration * STANDARD_DIATONIC_STEPS);
242}
243
247constexpr bool calcTranspositionIsOctave(int displacement, int alteration)
248{
249 return (displacement % STANDARD_DIATONIC_STEPS) == 0 && alteration == 0;
250}
251
260{
261private:
262 int m_displacement;
263 int m_alteration; // alteration from key signature
264 int m_numberOfEdoDivisions; // number of divisions in the EDO (default 12)
265 std::vector<int> m_keyMap; // step map for the EDO
266
267public:
270 explicit Transposer(const Pitch& pitch)
271 : Transposer(calcDisplacement(pitch), pitch.alteration)
272 {
273 }
274
284 bool isMinor = false, int numberOfEdoDivisions = STANDARD_12EDO_STEPS,
285 const std::optional <std::vector<int>>& keyMap = std::nullopt)
286 : m_displacement(displacement), m_alteration(alteration), m_numberOfEdoDivisions(numberOfEdoDivisions)
287 {
288 if (keyMap) {
289 if (keyMap.value().size() != STANDARD_DIATONIC_STEPS) {
290 throw std::invalid_argument("The Transposer class only supports key map arrays of " + std::to_string(STANDARD_DIATONIC_STEPS) + " elements");
291 }
292 m_keyMap = keyMap.value();
293 } else if (isMinor) {
294 m_keyMap.assign(MINOR_KEYMAP.begin(), MINOR_KEYMAP.end());
295 } else {
296 m_keyMap.assign(MAJOR_KEYMAP.begin(), MAJOR_KEYMAP.end());
297 }
298 }
299
301 int displacement() const { return m_displacement; }
302
304 int alteration() const { return m_alteration; }
305
308 void diatonicTranspose(int interval)
309 {
310 m_displacement += interval;
311 }
312
315 void enharmonicTranspose(int diatonicSteps)
316 {
317 const int stepSign = sign(diatonicSteps);
318 for (int i = 0; i < std::abs(diatonicSteps); ++i) {
319 const int keyStepEnharmonic = calcStepsBetweenScaleDegrees(m_displacement, m_displacement + stepSign);
320 diatonicTranspose(stepSign);
321 m_alteration -= stepSign * keyStepEnharmonic;
322 }
323 }
324
346 void chromaticTranspose(int interval, int chromaticAlteration)
347 {
348 const int intervalNormalized = signedModulus(interval, STANDARD_DIATONIC_STEPS);
349 const int stepsInAlteration = calcStepsInAlteration(interval, chromaticAlteration);
350 const int stepsInInterval = calcStepsInNormalizedInterval(intervalNormalized);
351 const int stepsInDiatonicInterval = calcStepsBetweenScaleDegrees(m_displacement, m_displacement + intervalNormalized);
352
353 const int effectiveAlteration = stepsInAlteration + stepsInInterval - sign(interval) * stepsInDiatonicInterval;
354
355 diatonicTranspose(interval);
356 m_alteration += effectiveAlteration;
357 }
358
366 {
367 while (std::abs(m_alteration) > 0) {
368 const int currSign = sign(m_alteration);
369 const int currAbsDisp = std::abs(m_alteration);
370 enharmonicTranspose(currSign);
371 if (std::abs(m_alteration) >= currAbsDisp) {
372 enharmonicTranspose(-currSign);
373 return;
374 }
375 if (currSign != sign(m_alteration)) {
376 break;
377 }
378 }
379 }
380
390 void stepwiseTranspose(int numberOfEdoDivisions)
391 {
392 m_alteration += numberOfEdoDivisions;
394 }
395
407 return calcAbsoluteDivision(displacement, alteration) == calcAbsoluteDivision(m_displacement, m_alteration);
408 }
409
410private:
411 int calcFifthSteps() const
412 {
413 // std::log(3.0 / 2.0) / std::log(2.0) is 0.5849625007211562.
414 static constexpr double kFifthsMultiplier = 0.5849625007211562;
415 return static_cast<int>(std::floor(m_numberOfEdoDivisions * kFifthsMultiplier) + 0.5);
416 }
417
418 int calcScaleDegree(int interval) const
419 { return positiveModulus(interval, int(m_keyMap.size())); }
420
421 int calcStepsBetweenScaleDegrees(int firstDisplacement, int secondDisplacement) const
422 {
423 const int firstScaleDegree = calcScaleDegree(firstDisplacement);
424 const int secondScaleDegree = calcScaleDegree(secondDisplacement);
425 int result = sign(secondDisplacement - firstDisplacement) * (m_keyMap[secondScaleDegree] - m_keyMap[firstScaleDegree]);
426 if (result < 0) {
427 result += m_numberOfEdoDivisions;
428 }
429 return result;
430 }
431
432 int calcStepsInAlteration(int interval, int alteration) const
433 {
434 const int fifthSteps = calcFifthSteps();
435 const int plusFifths = sign(interval) * alteration * 7; // number of fifths to add for a chromatic halfstep alteration (in any EDO)
436 const int minusOctaves = sign(interval) * alteration * -4; // number of octaves to subtract for a chromatic halfstep alteration (in any EDO)
437 const int result = sign(interval) * ((plusFifths * fifthSteps) + (minusOctaves * m_numberOfEdoDivisions));
438 return result;
439 }
440
441 int calcStepsInNormalizedInterval(int intervalNormalized) const
442 {
443 const int fifthSteps = calcFifthSteps();
444 const int index = std::abs(intervalNormalized);
445 const int plusFifths = DIATONIC_INTERVAL_ADJUSTMENTS[index][0]; // number of fifths
446 const int minusOctaves = DIATONIC_INTERVAL_ADJUSTMENTS[index][1]; // number of octaves
447
448 return sign(intervalNormalized) * ((plusFifths * fifthSteps) + (minusOctaves * m_numberOfEdoDivisions));
449 }
450
451 int calcAbsoluteDivision(int displacement, int alteration) const {
452 const int scaleDegree = calcScaleDegree(displacement); // 0..6
453 const int baseStep = m_keyMap[scaleDegree];
454
455 const int octaveCount = (displacement < 0 && displacement % STANDARD_DIATONIC_STEPS != 0)
458 const int octaveSteps = octaveCount * m_numberOfEdoDivisions;
459 const int chromaticSteps = calcStepsInAlteration(/*interval=*/+1, alteration);
460
461 return baseStep + chromaticSteps + octaveSteps;
462 }
463};
464
465} // namespace music_theory
466
467#endif // MUSIC_THEORY_HPP
Provides dependency-free transposition utilities that work with any scale that has 7 diatonic steps a...
Definition music_theory.hpp:260
int displacement() const
Return the current displacement value.
Definition music_theory.hpp:301
void chromaticTranspose(int interval, int chromaticAlteration)
Chromatically transposes by a specified chromatic interval.
Definition music_theory.hpp:346
void stepwiseTranspose(int numberOfEdoDivisions)
Transposes by the given number of EDO divisions and simplifies the spelling.
Definition music_theory.hpp:390
int alteration() const
Return the current chromatic alteration value.
Definition music_theory.hpp:304
Transposer(const Pitch &pitch)
Constructs a 12-EDO major-scale transposer for a spelled pitch.
Definition music_theory.hpp:270
void simplifySpelling()
Simplifies the spelling by reducing its alteration while preserving pitch.
Definition music_theory.hpp:365
Transposer(int displacement, int alteration, bool isMinor=false, int numberOfEdoDivisions=STANDARD_12EDO_STEPS, const std::optional< std::vector< int > > &keyMap=std::nullopt)
Constructor function.
Definition music_theory.hpp:283
void diatonicTranspose(int interval)
Transposes the displacement by the specified interval.
Definition music_theory.hpp:308
bool isEnharmonicEquivalent(int displacement, int alteration) const
Determines if the given displacement and alteration refer to the same pitch as the current state.
Definition music_theory.hpp:406
void enharmonicTranspose(int diatonicSteps)
Transposes enharmonically relative to the current values.
Definition music_theory.hpp:315
A dependency-free, header-only collection of useful functions for music theory.
DiatonicMode
Represents the seven standard diatonic musical modes.
Definition music_theory.hpp:110
@ Phrygian
minor with flat 2
@ Locrian
diminished with flat 2 and 5
@ Lydian
major with raised 4
@ Dorian
minor with raised 6
@ Mixolydian
major with flat 7
constexpr T signedModulus(T n, T d)
Calculates the modulus of positive and negative numbers in a predictable manner.
Definition music_theory.hpp:161
constexpr int STANDARD_NUMBER_OF_STAFFLINES
The standard number of lines on a staff.
Definition music_theory.hpp:44
constexpr int calcDisplacement(const Pitch &pitch)
Calculates the displacement value for a spelled pitch.
Definition music_theory.hpp:137
constexpr int calcAlterationFrom12EdoHalfsteps(int interval, int halfsteps)
Calculates the alteration in chromatic halfsteps for the specified interval/halfsteps combination.
Definition music_theory.hpp:201
constexpr std::array< int, STANDARD_DIATONIC_STEPS > MAJOR_KEYMAP
keymap for 12-EDO major keys
Definition music_theory.hpp:48
constexpr T sign(T n)
Calculates the sign of an integer.
Definition music_theory.hpp:149
ClefType
Represents the possible types of clef, irrespective of octave transposition.
Definition music_theory.hpp:123
@ TabSerif
Tablature clef (TAB) with serif font.
@ Percussion2
Narrow rectangle centered on middle staff line (corresponds to SMuFL glyph unpitchedPercussionClef2)
@ Tab
Tablature clef (TAB) with non-serif font.
@ Unknown
Unknown clef type (default value with {} initializer)
@ Percussion1
2 thick vertical lines centered on middle staff line (corresponds to SMuFL glyph unpitchedPercussionC...
constexpr int STANDARD_12EDO_STEPS
this can be overriden when constructing a Transposer instance.
Definition music_theory.hpp:46
constexpr int calcKeySigChangeFromInterval(int interval, int chromaticAlteration)
Calculates the resulting key signature change (sharps/flats) produced by a diatonic interval and chro...
Definition music_theory.hpp:232
constexpr int calcAlterationFromKeySigChange(int interval, int keySigChange)
Determines the chromatic alteration needed for a diatonic interval to produce a desired key signature...
Definition music_theory.hpp:213
constexpr bool calcTranspositionIsOctave(int displacement, int alteration)
Determines if the transposition values result in trasposing by one or more octaves.
Definition music_theory.hpp:247
constexpr int STANDARD_DIATONIC_STEPS
currently this is the only supported number of diatonic steps.
Definition music_theory.hpp:45
NoteName
The available note names in array order.
Definition music_theory.hpp:66
constexpr std::array< std::array< int, 2 >, STANDARD_DIATONIC_STEPS > DIATONIC_INTERVAL_ADJUSTMENTS
Array of chromatic intervals. Each member array contains.
Definition music_theory.hpp:54
constexpr int calc12EdoHalfstepsInInterval(int interval, int chromaticAlteration)
Calculates the number of 12-EDO chromatic halfsteps in the specified interval.
Definition music_theory.hpp:190
constexpr T positiveModulus(T n, T d, T *q=nullptr)
Calculates a positive modulus in the range [0, d-1], even for negative dividends.
Definition music_theory.hpp:174
constexpr std::array< int, STANDARD_DIATONIC_STEPS > MINOR_KEYMAP
keymap for 12-EDO minor keys
Definition music_theory.hpp:49
A spelled pitch, expressed relative to C4.
Definition music_theory.hpp:83
NoteName noteName
The diatonic note name.
Definition music_theory.hpp:96
constexpr Pitch()=default
Creates an unspecified pitch.
int octave
The octave number, where C4 is middle C.
Definition music_theory.hpp:97
constexpr Pitch(NoteName pitchName, int pitchOctave, int pitchAlteration=0)
Creates a spelled pitch.
Definition music_theory.hpp:91
int alteration
The alteration relative to the natural note name, in EDO divisions.
Definition music_theory.hpp:98