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
164template <typename T>
165constexpr T signedModulus(T n, T d)
166{
167 static_assert(std::is_integral_v<T>, "signedModulus requires an integer type");
168 return n % d;
169}
170
177template <typename T>
178constexpr T positiveModulus(T n, T d, T* q = nullptr)
179{
180 static_assert(std::is_integral_v<T>, "positiveModulus requires an integer type");
181 if (q) *q = n / d;
182 T result = signedModulus(n, d);
183 if (result < 0) {
184 result += d;
185 if (q) --(*q);
186 }
187 return result;
188}
189
205constexpr int calcPitchClass(NoteName noteName, int alteration = 0,
206 int numberOfEdoDivisions = STANDARD_12EDO_STEPS,
207 const std::array<int, STANDARD_DIATONIC_STEPS>& keyMap = MAJOR_KEYMAP)
208{
209 const int natural = keyMap[positiveModulus(int(noteName), STANDARD_DIATONIC_STEPS)];
210 return positiveModulus(natural + alteration, numberOfEdoDivisions);
211}
212
218constexpr int calcPitchClass(const Pitch& pitch,
219 int numberOfEdoDivisions = STANDARD_12EDO_STEPS,
220 const std::array<int, STANDARD_DIATONIC_STEPS>& keyMap = MAJOR_KEYMAP)
221{
222 return calcPitchClass(pitch.noteName, pitch.alteration, numberOfEdoDivisions, keyMap);
223}
224
229constexpr int calc12EdoHalfstepsInInterval(int interval, int chromaticAlteration)
230{
231 int octaves{};
232 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS, &octaves);
233 return MAJOR_KEYMAP[diatonic] + (octaves * STANDARD_12EDO_STEPS) + chromaticAlteration;
234}
235
240constexpr int calcAlterationFrom12EdoHalfsteps(int interval, int halfsteps)
241{
242 int octaves{};
243 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS, &octaves);
244 int expectedHalfsteps = MAJOR_KEYMAP[diatonic] + (octaves * STANDARD_12EDO_STEPS);
245 return halfsteps - expectedHalfsteps;
246}
247
252constexpr int calcAlterationFromKeySigChange(int interval, int keySigChange)
253{
254 int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS);
255 int expectedKeyChange = DIATONIC_INTERVAL_ADJUSTMENTS[diatonic][0];
256 if (interval < 0) {
257 if (std::abs(expectedKeyChange) > 1) { // imperfect intervals
258 expectedKeyChange -= STANDARD_DIATONIC_STEPS;
259 }
260 }
261 int alteration = (keySigChange - expectedKeyChange) / STANDARD_DIATONIC_STEPS;
262 return alteration;
263}
264
271constexpr int calcKeySigChangeFromInterval(int interval, int chromaticAlteration)
272{
273 const int diatonic = positiveModulus(interval, STANDARD_DIATONIC_STEPS);
274 int expectedKeyChange = DIATONIC_INTERVAL_ADJUSTMENTS[diatonic][0];
275 if (interval < 0) {
276 if (std::abs(expectedKeyChange) > 1) { // imperfect intervals
277 expectedKeyChange -= STANDARD_DIATONIC_STEPS;
278 }
279 }
280 return expectedKeyChange + (chromaticAlteration * STANDARD_DIATONIC_STEPS);
281}
282
286constexpr bool calcTranspositionIsOctave(int displacement, int alteration)
287{
288 return (displacement % STANDARD_DIATONIC_STEPS) == 0 && alteration == 0;
289}
290
299{
300private:
301 int m_displacement;
302 int m_alteration; // alteration from key signature
303 int m_numberOfEdoDivisions; // number of divisions in the EDO (default 12)
304 std::vector<int> m_keyMap; // step map for the EDO
305
306public:
309 explicit Transposer(const Pitch& pitch)
310 : Transposer(calcDisplacement(pitch), pitch.alteration)
311 {
312 }
313
323 bool isMinor = false, int numberOfEdoDivisions = STANDARD_12EDO_STEPS,
324 const std::optional <std::vector<int>>& keyMap = std::nullopt)
325 : m_displacement(displacement), m_alteration(alteration), m_numberOfEdoDivisions(numberOfEdoDivisions)
326 {
327 if (keyMap) {
328 if (keyMap.value().size() != STANDARD_DIATONIC_STEPS) {
329 throw std::invalid_argument("The Transposer class only supports key map arrays of " + std::to_string(STANDARD_DIATONIC_STEPS) + " elements");
330 }
331 m_keyMap = keyMap.value();
332 } else if (isMinor) {
333 m_keyMap.assign(MINOR_KEYMAP.begin(), MINOR_KEYMAP.end());
334 } else {
335 m_keyMap.assign(MAJOR_KEYMAP.begin(), MAJOR_KEYMAP.end());
336 }
337 }
338
340 int displacement() const { return m_displacement; }
341
343 int alteration() const { return m_alteration; }
344
347 void diatonicTranspose(int interval)
348 {
349 m_displacement += interval;
350 }
351
354 void enharmonicTranspose(int diatonicSteps)
355 {
356 const int stepSign = sign(diatonicSteps);
357 for (int i = 0; i < std::abs(diatonicSteps); ++i) {
358 const int keyStepEnharmonic = calcStepsBetweenScaleDegrees(m_displacement, m_displacement + stepSign);
359 diatonicTranspose(stepSign);
360 m_alteration -= stepSign * keyStepEnharmonic;
361 }
362 }
363
385 void chromaticTranspose(int interval, int chromaticAlteration)
386 {
387 const int intervalNormalized = signedModulus(interval, STANDARD_DIATONIC_STEPS);
388 const int stepsInAlteration = calcStepsInAlteration(interval, chromaticAlteration);
389 const int stepsInInterval = calcStepsInNormalizedInterval(intervalNormalized);
390 const int stepsInDiatonicInterval = calcStepsBetweenScaleDegrees(m_displacement, m_displacement + intervalNormalized);
391
392 const int effectiveAlteration = stepsInAlteration + stepsInInterval - sign(interval) * stepsInDiatonicInterval;
393
394 diatonicTranspose(interval);
395 m_alteration += effectiveAlteration;
396 }
397
405 {
406 while (std::abs(m_alteration) > 0) {
407 const int currSign = sign(m_alteration);
408 const int currAbsDisp = std::abs(m_alteration);
409 enharmonicTranspose(currSign);
410 if (std::abs(m_alteration) >= currAbsDisp) {
411 enharmonicTranspose(-currSign);
412 return;
413 }
414 if (currSign != sign(m_alteration)) {
415 break;
416 }
417 }
418 }
419
429 void stepwiseTranspose(int numberOfEdoDivisions)
430 {
431 m_alteration += numberOfEdoDivisions;
433 }
434
446 return calcAbsoluteDivision(displacement, alteration) == calcAbsoluteDivision(m_displacement, m_alteration);
447 }
448
449private:
450 int calcFifthSteps() const
451 {
452 // std::log(3.0 / 2.0) / std::log(2.0) is 0.5849625007211562.
453 static constexpr double kFifthsMultiplier = 0.5849625007211562;
454 return static_cast<int>(std::floor(m_numberOfEdoDivisions * kFifthsMultiplier) + 0.5);
455 }
456
457 int calcScaleDegree(int interval) const
458 { return positiveModulus(interval, int(m_keyMap.size())); }
459
460 int calcStepsBetweenScaleDegrees(int firstDisplacement, int secondDisplacement) const
461 {
462 const int firstScaleDegree = calcScaleDegree(firstDisplacement);
463 const int secondScaleDegree = calcScaleDegree(secondDisplacement);
464 int result = sign(secondDisplacement - firstDisplacement) * (m_keyMap[secondScaleDegree] - m_keyMap[firstScaleDegree]);
465 if (result < 0) {
466 result += m_numberOfEdoDivisions;
467 }
468 return result;
469 }
470
471 int calcStepsInAlteration(int interval, int alteration) const
472 {
473 const int fifthSteps = calcFifthSteps();
474 const int plusFifths = sign(interval) * alteration * 7; // number of fifths to add for a chromatic halfstep alteration (in any EDO)
475 const int minusOctaves = sign(interval) * alteration * -4; // number of octaves to subtract for a chromatic halfstep alteration (in any EDO)
476 const int result = sign(interval) * ((plusFifths * fifthSteps) + (minusOctaves * m_numberOfEdoDivisions));
477 return result;
478 }
479
480 int calcStepsInNormalizedInterval(int intervalNormalized) const
481 {
482 const int fifthSteps = calcFifthSteps();
483 const int index = std::abs(intervalNormalized);
484 const int plusFifths = DIATONIC_INTERVAL_ADJUSTMENTS[index][0]; // number of fifths
485 const int minusOctaves = DIATONIC_INTERVAL_ADJUSTMENTS[index][1]; // number of octaves
486
487 return sign(intervalNormalized) * ((plusFifths * fifthSteps) + (minusOctaves * m_numberOfEdoDivisions));
488 }
489
490 int calcAbsoluteDivision(int displacement, int alteration) const {
491 const int scaleDegree = calcScaleDegree(displacement); // 0..6
492 const int baseStep = m_keyMap[scaleDegree];
493
494 const int octaveCount = (displacement < 0 && displacement % STANDARD_DIATONIC_STEPS != 0)
497 const int octaveSteps = octaveCount * m_numberOfEdoDivisions;
498 const int chromaticSteps = calcStepsInAlteration(/*interval=*/+1, alteration);
499
500 return baseStep + chromaticSteps + octaveSteps;
501 }
502};
503
504} // namespace music_theory
505
506#endif // MUSIC_THEORY_HPP
Provides dependency-free transposition utilities that work with any scale that has 7 diatonic steps a...
Definition music_theory.hpp:299
int displacement() const
Return the current displacement value.
Definition music_theory.hpp:340
void chromaticTranspose(int interval, int chromaticAlteration)
Chromatically transposes by a specified chromatic interval.
Definition music_theory.hpp:385
void stepwiseTranspose(int numberOfEdoDivisions)
Transposes by the given number of EDO divisions and simplifies the spelling.
Definition music_theory.hpp:429
int alteration() const
Return the current chromatic alteration value.
Definition music_theory.hpp:343
Transposer(const Pitch &pitch)
Constructs a 12-EDO major-scale transposer for a spelled pitch.
Definition music_theory.hpp:309
void simplifySpelling()
Simplifies the spelling by reducing its alteration while preserving pitch.
Definition music_theory.hpp:404
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:322
void diatonicTranspose(int interval)
Transposes the displacement by the specified interval.
Definition music_theory.hpp:347
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:445
void enharmonicTranspose(int diatonicSteps)
Transposes enharmonically relative to the current values.
Definition music_theory.hpp:354
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:165
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 calcPitchClass(NoteName noteName, int alteration=0, int numberOfEdoDivisions=STANDARD_12EDO_STEPS, const std::array< int, STANDARD_DIATONIC_STEPS > &keyMap=MAJOR_KEYMAP)
Calculates the pitch class of a spelled note name.
Definition music_theory.hpp:205
constexpr int calcAlterationFrom12EdoHalfsteps(int interval, int halfsteps)
Calculates the alteration in chromatic halfsteps for the specified interval/halfsteps combination.
Definition music_theory.hpp:240
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:271
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:252
constexpr bool calcTranspositionIsOctave(int displacement, int alteration)
Determines if the transposition values result in trasposing by one or more octaves.
Definition music_theory.hpp:286
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:229
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:178
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