@libraz/libcantus 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +291 -0
  3. package/dist/index.cjs +6465 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +2621 -0
  6. package/dist/index.d.ts +2621 -0
  7. package/dist/index.js +6297 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +71 -0
  10. package/src/analysis/index.ts +261 -0
  11. package/src/arrange/index.ts +409 -0
  12. package/src/bass/index.ts +301 -0
  13. package/src/chord/index.ts +292 -0
  14. package/src/chordscale/index.ts +316 -0
  15. package/src/countermelody/index.ts +349 -0
  16. package/src/counterpoint/index.ts +209 -0
  17. package/src/detect/index.ts +176 -0
  18. package/src/drums/beat.ts +266 -0
  19. package/src/drums/euclid.ts +58 -0
  20. package/src/drums/fills.ts +345 -0
  21. package/src/drums/ghost.ts +119 -0
  22. package/src/drums/hihat.ts +285 -0
  23. package/src/drums/hit.ts +31 -0
  24. package/src/drums/index.ts +211 -0
  25. package/src/drums/internal.ts +251 -0
  26. package/src/drums/kick.ts +160 -0
  27. package/src/drums/percussion.ts +121 -0
  28. package/src/drums/rng.ts +7 -0
  29. package/src/drums/swing.ts +66 -0
  30. package/src/functional/index.ts +602 -0
  31. package/src/groove/index.ts +230 -0
  32. package/src/harmonize/index.ts +367 -0
  33. package/src/harmony/index.ts +75 -0
  34. package/src/index.ts +233 -0
  35. package/src/interval/index.ts +67 -0
  36. package/src/meter/index.ts +179 -0
  37. package/src/model/index.ts +957 -0
  38. package/src/motif/index.ts +321 -0
  39. package/src/pitch/index.ts +256 -0
  40. package/src/progression/index.ts +336 -0
  41. package/src/random/index.ts +41 -0
  42. package/src/reharmony/index.ts +299 -0
  43. package/src/rhythm/index.ts +131 -0
  44. package/src/safety/index.ts +372 -0
  45. package/src/scale/index.ts +215 -0
  46. package/src/spelling/index.ts +164 -0
  47. package/src/symbol/index.ts +213 -0
  48. package/src/timeline/index.ts +352 -0
  49. package/src/tuning/index.ts +129 -0
  50. package/src/types.ts +29 -0
  51. package/src/voicing/index.ts +523 -0
  52. package/tsconfig.json +23 -0
@@ -0,0 +1,336 @@
1
+ import type { ChordQuality } from '../chord/index.js';
2
+ import { diatonicTriad } from '../chord/index.js';
3
+ import { scaleTonesInDegreeOrder } from '../scale/index.js';
4
+ import type { KeyScale } from '../types.js';
5
+
6
+ /** Broad production style a progression preset suits. */
7
+ export type ProgStyle = 'minimal' | 'dance' | 'idol' | 'rock';
8
+
9
+ /** Harmonic-function role of a progression as a whole. */
10
+ export type ProgFunction = 'loop' | 'tensionBuild' | 'cadenceStrong' | 'stable';
11
+
12
+ /** A named chord-progression preset expressed in scale degrees. */
13
+ export type ProgressionPreset = {
14
+ id: string;
15
+ name: string;
16
+ degrees: number[];
17
+ functional: ProgFunction;
18
+ styles: ProgStyle[];
19
+ };
20
+
21
+ /** A chord placed on the timeline by {@link generateProgression}. */
22
+ export type GeneratedChord = {
23
+ rootPc: number;
24
+ quality: ChordQuality;
25
+ startBeat: number;
26
+ bassPc?: number;
27
+ /** 0-based scale degree of the chord root, when known. */
28
+ degree?: number;
29
+ /** True when the chord is a secondary dominant tonicizing another degree. */
30
+ secondaryDominant?: boolean;
31
+ };
32
+
33
+ /** Options controlling {@link generateProgression}. */
34
+ export type GenerateProgressionOptions = {
35
+ key: KeyScale;
36
+ style: ProgStyle;
37
+ bars: number;
38
+ presetId?: string;
39
+ ext?: ChordQuality | 'auto';
40
+ reharmonize?: boolean;
41
+ seed?: number;
42
+ };
43
+
44
+ const PRESETS: ProgressionPreset[] = [
45
+ {
46
+ id: 'fourChordPop',
47
+ name: 'Four Chord Pop',
48
+ degrees: [0, 4, 5, 3],
49
+ functional: 'loop',
50
+ styles: ['minimal', 'dance', 'idol'],
51
+ },
52
+ {
53
+ id: 'pop1',
54
+ name: 'Pop 1',
55
+ degrees: [0, 5, 3, 4],
56
+ functional: 'loop',
57
+ styles: ['minimal', 'dance', 'idol'],
58
+ },
59
+ {
60
+ id: 'axis',
61
+ name: 'Axis',
62
+ degrees: [5, 3, 0, 4],
63
+ functional: 'loop',
64
+ styles: ['minimal', 'dance', 'idol', 'rock'],
65
+ },
66
+ {
67
+ id: 'pop2',
68
+ name: 'Pop 2',
69
+ degrees: [3, 0, 4, 5],
70
+ functional: 'loop',
71
+ styles: ['minimal', 'dance', 'idol'],
72
+ },
73
+ {
74
+ id: 'classic',
75
+ name: 'Classic',
76
+ degrees: [0, 3, 4, 0],
77
+ functional: 'cadenceStrong',
78
+ styles: ['dance', 'idol', 'rock'],
79
+ },
80
+ {
81
+ id: 'pop3',
82
+ name: 'Pop 3',
83
+ degrees: [0, 3, 5, 4],
84
+ functional: 'loop',
85
+ styles: ['minimal', 'dance', 'idol'],
86
+ },
87
+ {
88
+ id: 'royalRoad',
89
+ name: 'Royal Road',
90
+ degrees: [3, 4, 2, 5],
91
+ functional: 'tensionBuild',
92
+ styles: ['dance', 'idol'],
93
+ },
94
+ {
95
+ id: 'minor1',
96
+ name: 'Minor 1',
97
+ degrees: [5, 4, 3, 4],
98
+ functional: 'tensionBuild',
99
+ styles: ['idol', 'rock'],
100
+ },
101
+ {
102
+ id: 'minor2',
103
+ name: 'Minor 2',
104
+ degrees: [5, 3, 4, 0],
105
+ functional: 'tensionBuild',
106
+ styles: ['idol', 'rock'],
107
+ },
108
+ {
109
+ id: 'pop4',
110
+ name: 'Pop 4',
111
+ degrees: [0, 4, 2, 3],
112
+ functional: 'loop',
113
+ styles: ['minimal', 'dance', 'idol'],
114
+ },
115
+ {
116
+ id: 'pop5',
117
+ name: 'Pop 5',
118
+ degrees: [0, 2, 3, 4],
119
+ functional: 'stable',
120
+ styles: ['minimal', 'dance', 'idol'],
121
+ },
122
+ {
123
+ id: 'rock1',
124
+ name: 'Rock 1',
125
+ degrees: [0, 10, 3, 0],
126
+ functional: 'tensionBuild',
127
+ styles: ['rock'],
128
+ },
129
+ {
130
+ id: 'rock2',
131
+ name: 'Rock 2',
132
+ degrees: [0, 3, 10, 0],
133
+ functional: 'tensionBuild',
134
+ styles: ['rock'],
135
+ },
136
+ {
137
+ id: 'extended4',
138
+ name: 'Extended 4',
139
+ degrees: [0, 4, 5, 2],
140
+ functional: 'stable',
141
+ styles: ['minimal', 'dance'],
142
+ },
143
+ {
144
+ id: 'minor3',
145
+ name: 'Minor 3',
146
+ degrees: [5, 0, 4, 3],
147
+ functional: 'loop',
148
+ styles: ['dance', 'idol'],
149
+ },
150
+ {
151
+ id: 'aeolianPop',
152
+ name: 'Aeolian Pop',
153
+ degrees: [5, 8, 10, 0],
154
+ functional: 'tensionBuild',
155
+ styles: ['minimal', 'dance', 'idol', 'rock'],
156
+ },
157
+ {
158
+ id: 'animeHighEnergy1',
159
+ name: 'Anime High Energy 1',
160
+ degrees: [5, 2, 3, 0],
161
+ functional: 'loop',
162
+ styles: ['dance', 'idol'],
163
+ },
164
+ {
165
+ id: 'jazzPop',
166
+ name: 'Jazz Pop',
167
+ degrees: [1, 4, 0, 5],
168
+ functional: 'cadenceStrong',
169
+ styles: ['minimal', 'dance'],
170
+ },
171
+ {
172
+ id: 'animeHighEnergy2',
173
+ name: 'Anime High Energy 2',
174
+ degrees: [5, 1, 4, 0],
175
+ functional: 'cadenceStrong',
176
+ styles: ['dance', 'idol'],
177
+ },
178
+ {
179
+ id: 'cityPop',
180
+ name: 'City Pop',
181
+ degrees: [0, 5, 1, 4],
182
+ functional: 'stable',
183
+ styles: ['minimal', 'dance'],
184
+ },
185
+ {
186
+ id: 'extended5',
187
+ name: 'Extended 5',
188
+ degrees: [0, 4, 5, 2, 3],
189
+ functional: 'loop',
190
+ styles: ['minimal', 'dance', 'idol'],
191
+ },
192
+ {
193
+ id: 'neapolitanPop',
194
+ name: 'Neapolitan Pop',
195
+ degrees: [5, 12, 13, 4, 0],
196
+ functional: 'cadenceStrong',
197
+ styles: ['minimal', 'dance', 'idol'],
198
+ },
199
+ ];
200
+
201
+ /** Chromatic semitone offset from the tonic for borrowed (non-diatonic) degrees. */
202
+ const BORROWED_OFFSET: Record<number, number> = {
203
+ 8: 8, // bVI
204
+ 10: 10, // bVII
205
+ 11: 3, // bIII
206
+ 12: 5, // iv
207
+ 13: 1, // bII
208
+ 14: 6, // #IV
209
+ };
210
+
211
+ /** All built-in progression presets. */
212
+ export function progressions(): ProgressionPreset[] {
213
+ return PRESETS.map((p) => ({ ...p, degrees: [...p.degrees], styles: [...p.styles] }));
214
+ }
215
+
216
+ /** Presets whose style list includes the given style. */
217
+ export function progressionsByStyle(style: ProgStyle): ProgressionPreset[] {
218
+ return progressions().filter((p) => p.styles.includes(style));
219
+ }
220
+
221
+ /** Deterministic 32-bit PRNG producing a float in [0, 1). */
222
+ function mulberry32(seed: number): () => number {
223
+ let state = seed >>> 0;
224
+ return () => {
225
+ state = (state + 0x6d2b79f5) >>> 0;
226
+ let t = state;
227
+ t = Math.imul(t ^ (t >>> 15), t | 1);
228
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
229
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
230
+ };
231
+ }
232
+
233
+ /** Root pitch class of a scale degree in the given key, including borrowed degrees. */
234
+ function degreeToRootPc(degree: number, key: KeyScale): number {
235
+ if (degree >= 0 && degree <= 6) {
236
+ const tones = scaleTonesInDegreeOrder(key);
237
+ return tones.length > 0 ? (tones[degree % tones.length] ?? key.rootPc % 12) : key.rootPc % 12;
238
+ }
239
+ const offset = BORROWED_OFFSET[degree] ?? 0;
240
+ return ((((key.rootPc % 12) + offset) % 12) + 12) % 12;
241
+ }
242
+
243
+ /**
244
+ * Diatonic (or borrowed) triad quality of a degree in the given key.
245
+ *
246
+ * Diatonic degrees (0-6) take their scale-correct triad quality, so non-major
247
+ * keys yield diatonic chords. Borrowed degrees keep their fixed chromatic
248
+ * qualities (`#IV` diminished, `iv` minor, the rest major).
249
+ */
250
+ function autoQuality(degree: number, key: KeyScale): ChordQuality {
251
+ if (degree >= 0 && degree <= 6) {
252
+ return diatonicTriad(degree, key).quality;
253
+ }
254
+ if (degree === 14) {
255
+ return 'dim';
256
+ }
257
+ if (degree === 12) {
258
+ return 'min';
259
+ }
260
+ return 'maj';
261
+ }
262
+
263
+ /**
264
+ * Generate a chord progression laid out one chord per bar.
265
+ *
266
+ * A preset is chosen by `presetId` when given, otherwise deterministically from
267
+ * the presets matching `style`, seeded by `seed`. The preset's degrees cycle to
268
+ * fill `bars`; each bar is four beats, so `startBeat` is `barIndex * 4`. Chord
269
+ * roots come from the key's diatonic scale-degree mapping. When `ext` is
270
+ * omitted or `'auto'`, each chord takes its diatonic triad quality; otherwise
271
+ * `ext` is forced on every chord. When `reharmonize` is set, some chords are
272
+ * deterministically replaced with the secondary dominant (V7) of the following
273
+ * chord, flagged with `secondaryDominant`.
274
+ *
275
+ * @param opts Generation options.
276
+ * @returns One chord per bar in timeline order.
277
+ */
278
+ export function generateProgression(opts: GenerateProgressionOptions): GeneratedChord[] {
279
+ const seed = opts.seed ?? 0;
280
+ let preset: ProgressionPreset | undefined;
281
+ if (opts.presetId !== undefined) {
282
+ preset = PRESETS.find((p) => p.id === opts.presetId);
283
+ }
284
+ if (preset === undefined) {
285
+ const pool = PRESETS.filter((p) => p.styles.includes(opts.style));
286
+ const candidates = pool.length > 0 ? pool : PRESETS;
287
+ const rng = mulberry32(seed);
288
+ const index = Math.floor(rng() * candidates.length) % candidates.length;
289
+ preset = candidates[index] ?? PRESETS[0];
290
+ }
291
+ const degrees = preset?.degrees ?? [0];
292
+ const chords: GeneratedChord[] = [];
293
+ for (let bar = 0; bar < opts.bars; bar += 1) {
294
+ const degree = degrees[bar % degrees.length] ?? 0;
295
+ const quality =
296
+ opts.ext !== undefined && opts.ext !== 'auto' ? opts.ext : autoQuality(degree, opts.key);
297
+ const chord: GeneratedChord = {
298
+ rootPc: degreeToRootPc(degree, opts.key),
299
+ quality,
300
+ startBeat: bar * 4,
301
+ degree: degree >= 0 && degree <= 6 ? degree : undefined,
302
+ };
303
+ chords.push(chord);
304
+ }
305
+
306
+ if (opts.reharmonize) {
307
+ const tonicPc = (((opts.key.rootPc % 12) + 12) % 12) as number;
308
+ const rrng = mulberry32((seed ^ 0x9e3779b9) >>> 0);
309
+ for (let i = 0; i < chords.length - 1; i += 1) {
310
+ const cur = chords[i];
311
+ const next = chords[i + 1];
312
+ if (!cur || !next) {
313
+ continue;
314
+ }
315
+ const domRoot = (next.rootPc + 7) % 12;
316
+ const targetsTonic = (next.rootPc - tonicPc + 12) % 12 === 0;
317
+ const alreadySecondary = cur.rootPc === domRoot && cur.quality === 'dom7';
318
+ // A secondary dominant inserted at i-1 resolves onto this chord; replacing
319
+ // it here would orphan that dominant.
320
+ const isResolutionTarget = chords[i - 1]?.secondaryDominant === true;
321
+ if (targetsTonic || alreadySecondary || isResolutionTarget) {
322
+ continue;
323
+ }
324
+ if (rrng() < 0.5) {
325
+ chords[i] = {
326
+ rootPc: domRoot,
327
+ quality: 'dom7',
328
+ startBeat: cur.startBeat,
329
+ secondaryDominant: true,
330
+ };
331
+ }
332
+ }
333
+ }
334
+
335
+ return chords;
336
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Deterministic seeded pseudo-random number generation shared across the
3
+ * generative modules (rhythm, drums, bass, groove, counter-melody). A single
4
+ * mulberry32 core exposes the small set of samplers those modules need; given a
5
+ * seed the stream is fully reproducible.
6
+ */
7
+
8
+ /** A deterministic PRNG with the sampling helpers the generators need. */
9
+ export type Rng = {
10
+ /** Next float in [0, 1). */
11
+ next: () => number;
12
+ /** True with probability `p`. */
13
+ prob: (p: number) => boolean;
14
+ /** Integer in the inclusive range [lo, hi]. */
15
+ range: (lo: number, hi: number) => number;
16
+ /** Float in [lo, hi). */
17
+ float: (lo: number, hi: number) => number;
18
+ };
19
+
20
+ /**
21
+ * Create a seeded PRNG (mulberry32) exposing the shared samplers.
22
+ *
23
+ * @param seed The 32-bit seed; the same seed always yields the same stream.
24
+ * @returns The seeded generator.
25
+ */
26
+ export function createRng(seed: number): Rng {
27
+ let state = seed >>> 0;
28
+ const next = () => {
29
+ state = (state + 0x6d2b79f5) >>> 0;
30
+ let t = state;
31
+ t = Math.imul(t ^ (t >>> 15), t | 1);
32
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
33
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
34
+ };
35
+ return {
36
+ next,
37
+ prob: (p) => next() < p,
38
+ range: (lo, hi) => lo + Math.floor(next() * (hi - lo + 1)),
39
+ float: (lo, hi) => lo + next() * (hi - lo),
40
+ };
41
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Reharmonization: chord substitution, modal-interchange palettes, and negative
3
+ * harmony. These transforms take an existing chord (or a key) and propose
4
+ * alternative harmonies that preserve a chosen relationship — a shared function,
5
+ * a common tone, a tonicizing dominant, or a reflection across the key axis.
6
+ *
7
+ * Roots are pitch classes (0..11); no spelled key signature is required.
8
+ */
9
+
10
+ import {
11
+ type Chord,
12
+ type ChordQuality,
13
+ chordPitchClasses,
14
+ diatonicTriad,
15
+ makeChord,
16
+ } from '../chord/index.js';
17
+ import { detectChordBest } from '../detect/index.js';
18
+ import {
19
+ type BorrowedSource,
20
+ borrowedSource,
21
+ chordToRoman,
22
+ functionOf,
23
+ type HarmonicFunction,
24
+ isDiatonic,
25
+ parallelKey,
26
+ } from '../functional/index.js';
27
+ import { scaleTonesInDegreeOrder } from '../scale/index.js';
28
+ import type { KeyScale } from '../types.js';
29
+
30
+ /** Reduce a value to a pitch class in [0, 11]. */
31
+ function mod12(n: number): number {
32
+ return ((n % 12) + 12) % 12;
33
+ }
34
+
35
+ /** The kind of substitution relationship a candidate realizes. */
36
+ export type SubstitutionType =
37
+ | 'tritone'
38
+ | 'relative'
39
+ | 'borrowed'
40
+ | 'chromatic-mediant'
41
+ | 'secondary-dominant';
42
+
43
+ /** A proposed chord substitution with its relationship, numeral, and function. */
44
+ export type Substitution = {
45
+ chord: Chord;
46
+ type: SubstitutionType;
47
+ roman: string;
48
+ function: HarmonicFunction;
49
+ };
50
+
51
+ /** Options controlling which substitutions {@link substituteChord} returns. */
52
+ export type SubstituteOptions = {
53
+ /**
54
+ * Melody pitch classes that must remain chord tones. When given, only
55
+ * substitutions whose pitch classes contain every listed pitch class are
56
+ * kept, so the melody stays consonant against the new harmony.
57
+ */
58
+ melodyPcs?: number[];
59
+ };
60
+
61
+ /** Whether the chord's template carries a given interval (mod 12). */
62
+ function hasInterval(chord: Chord, semitone: number): boolean {
63
+ return chord.intervals.some((iv) => mod12(iv) === semitone);
64
+ }
65
+
66
+ /** Whether a chord is a dominant type: a major third with a minor seventh. */
67
+ function isDominantType(chord: Chord): boolean {
68
+ return hasInterval(chord, 4) && hasInterval(chord, 10);
69
+ }
70
+
71
+ /**
72
+ * A chord that can be tonicized: it has a perfect fifth and a third but is not
73
+ * itself a dominant seventh (which is an unstable, tonicizing sonority rather
74
+ * than a stable target).
75
+ */
76
+ function isStableTarget(chord: Chord): boolean {
77
+ const hasFifth = hasInterval(chord, 7);
78
+ const hasThird = hasInterval(chord, 3) || hasInterval(chord, 4);
79
+ return hasFifth && hasThird && !isDominantType(chord);
80
+ }
81
+
82
+ /** The triad pitch classes (root, third, fifth) implied by a chord's template. */
83
+ function triadPitchClasses(chord: Chord): number[] {
84
+ const third = hasInterval(chord, 4) ? 4 : hasInterval(chord, 3) ? 3 : 4;
85
+ const fifth = hasInterval(chord, 8) ? 8 : hasInterval(chord, 6) ? 6 : 7;
86
+ return [mod12(chord.rootPc), mod12(chord.rootPc + third), mod12(chord.rootPc + fifth)];
87
+ }
88
+
89
+ /** Count the pitch classes shared between two pitch-class sets. */
90
+ function commonToneCount(a: number[], b: number[]): number {
91
+ const set = new Set(b);
92
+ return a.filter((pc) => set.has(pc)).length;
93
+ }
94
+
95
+ /** The diatonic triads of a key, one per scale degree. */
96
+ function diatonicTriadsOf(key: KeyScale): Chord[] {
97
+ const degrees = scaleTonesInDegreeOrder(key).length;
98
+ const triads: Chord[] = [];
99
+ for (let degree = 0; degree < degrees; degree += 1) {
100
+ triads.push(diatonicTriad(degree, key));
101
+ }
102
+ return triads;
103
+ }
104
+
105
+ /** Whether two chords share the same root pitch class and quality. */
106
+ function sameChord(a: Chord, b: Chord): boolean {
107
+ return mod12(a.rootPc) === mod12(b.rootPc) && a.quality === b.quality;
108
+ }
109
+
110
+ /** Root offsets (semitones) that form a third above or below a root. */
111
+ const THIRD_OFFSETS = [3, 4, 8, 9] as const;
112
+
113
+ /**
114
+ * Propose substitutions for a chord within a key.
115
+ *
116
+ * Candidates are generated by several relationships and deduplicated against the
117
+ * original chord and each other:
118
+ *
119
+ * - `tritone`: for a dominant-type chord, the dominant seventh a tritone away.
120
+ * - `secondary-dominant`: for a stable target, the dominant seventh a fifth
121
+ * above its root (tonicizing it).
122
+ * - `relative`: a diatonic triad a third away that shares two common tones.
123
+ * - `borrowed`: a triad from the parallel mode with the same harmonic function.
124
+ * - `chromatic-mediant`: a major/minor triad a third away sharing one common
125
+ * tone.
126
+ *
127
+ * Each result carries its Roman numeral and harmonic function in `key`. When
128
+ * `opts.melodyPcs` is given, only substitutions whose pitch classes contain all
129
+ * of those pitch classes are returned.
130
+ *
131
+ * @param chord The chord to reharmonize.
132
+ * @param key The prevailing key.
133
+ * @param opts Optional melody-preservation constraint.
134
+ * @returns The deduplicated substitution candidates.
135
+ */
136
+ export function substituteChord(
137
+ chord: Chord,
138
+ key: KeyScale,
139
+ opts?: SubstituteOptions,
140
+ ): Substitution[] {
141
+ const original = triadPitchClasses(chord);
142
+ const candidates: { chord: Chord; type: SubstitutionType }[] = [];
143
+
144
+ // Tritone substitution: only for dominant-type chords.
145
+ if (isDominantType(chord)) {
146
+ candidates.push({ chord: makeChord(mod12(chord.rootPc + 6), 'dom7'), type: 'tritone' });
147
+ }
148
+
149
+ // Secondary dominant: the V7 tonicizing a stable target.
150
+ if (isStableTarget(chord)) {
151
+ candidates.push({
152
+ chord: makeChord(mod12(chord.rootPc + 7), 'dom7'),
153
+ type: 'secondary-dominant',
154
+ });
155
+ }
156
+
157
+ // Relative: a diatonic triad a third away sharing two common tones.
158
+ for (const triad of diatonicTriadsOf(key)) {
159
+ const offset = mod12(triad.rootPc - chord.rootPc);
160
+ if (
161
+ (THIRD_OFFSETS as readonly number[]).includes(offset) &&
162
+ commonToneCount(original, chordPitchClasses(triad)) === 2
163
+ ) {
164
+ candidates.push({ chord: triad, type: 'relative' });
165
+ }
166
+ }
167
+
168
+ // Borrowed: a parallel-mode triad sharing the original's harmonic function.
169
+ const targetFunction = functionOf(chord, key);
170
+ for (const triad of diatonicTriadsOf(parallelKey(key))) {
171
+ if (functionOf(triad, key) === targetFunction && !isDiatonic(triad, key)) {
172
+ candidates.push({ chord: triad, type: 'borrowed' });
173
+ }
174
+ }
175
+
176
+ // Chromatic mediants: major/minor triads a third away sharing one common tone.
177
+ for (const offset of THIRD_OFFSETS) {
178
+ for (const quality of ['maj', 'min'] as const) {
179
+ const mediant = makeChord(mod12(chord.rootPc + offset), quality);
180
+ if (
181
+ commonToneCount(original, chordPitchClasses(mediant)) === 1 &&
182
+ !isDiatonic(mediant, key)
183
+ ) {
184
+ candidates.push({ chord: mediant, type: 'chromatic-mediant' });
185
+ }
186
+ }
187
+ }
188
+
189
+ const melodyPcs = opts?.melodyPcs?.map(mod12);
190
+ const seen = new Set<string>();
191
+ const results: Substitution[] = [];
192
+ for (const candidate of candidates) {
193
+ if (sameChord(candidate.chord, chord)) {
194
+ continue;
195
+ }
196
+ const dedupeKey = `${mod12(candidate.chord.rootPc)}:${candidate.chord.quality}`;
197
+ if (seen.has(dedupeKey)) {
198
+ continue;
199
+ }
200
+ seen.add(dedupeKey);
201
+ if (melodyPcs !== undefined) {
202
+ const pcs = new Set(chordPitchClasses(candidate.chord));
203
+ if (!melodyPcs.every((pc) => pcs.has(pc))) {
204
+ continue;
205
+ }
206
+ }
207
+ results.push({
208
+ chord: candidate.chord,
209
+ type: candidate.type,
210
+ roman: chordToRoman(candidate.chord, key),
211
+ function: functionOf(candidate.chord, key),
212
+ });
213
+ }
214
+ return results;
215
+ }
216
+
217
+ /** A borrowed chord in the modal-interchange palette of a key. */
218
+ export type BorrowedChord = {
219
+ chord: Chord;
220
+ roman: string;
221
+ source: BorrowedSource;
222
+ };
223
+
224
+ /**
225
+ * The modal-interchange palette of a key.
226
+ *
227
+ * Lists the diatonic triads of the {@link parallelKey} that are not diatonic to
228
+ * `key` (the classic borrowed chords such as `iv`, `bVI`, and `bVII` in a major
229
+ * key), plus the Neapolitan (a major triad on the flat second degree). Each
230
+ * carries its Roman numeral and {@link borrowedSource} relative to `key`.
231
+ *
232
+ * @param key The prevailing key.
233
+ * @returns The borrowed-chord palette.
234
+ */
235
+ export function modalInterchangePalette(key: KeyScale): BorrowedChord[] {
236
+ const palette: BorrowedChord[] = [];
237
+ const seen = new Set<string>();
238
+ const add = (chord: Chord) => {
239
+ const dedupeKey = `${mod12(chord.rootPc)}:${chord.quality}`;
240
+ if (seen.has(dedupeKey)) {
241
+ return;
242
+ }
243
+ seen.add(dedupeKey);
244
+ palette.push({
245
+ chord,
246
+ roman: chordToRoman(chord, key),
247
+ source: borrowedSource(chord, key),
248
+ });
249
+ };
250
+
251
+ for (const triad of diatonicTriadsOf(parallelKey(key))) {
252
+ if (!isDiatonic(triad, key)) {
253
+ add(triad);
254
+ }
255
+ }
256
+ // The Neapolitan (major triad on b2) sits outside both parallel modes, so it
257
+ // is added explicitly — unless b2 is already diatonic (e.g. in a Phrygian key,
258
+ // where it is a native chord rather than a borrowing).
259
+ const neapolitan = makeChord(mod12(key.rootPc + 1), 'maj');
260
+ if (!isDiatonic(neapolitan, key)) {
261
+ add(neapolitan);
262
+ }
263
+ return palette;
264
+ }
265
+
266
+ /**
267
+ * Reflect a chord across the tonic–dominant axis of a key (negative harmony).
268
+ *
269
+ * Every pitch class `p` maps to `(2*T + 7 - p) mod 12`, where `T` is the key
270
+ * tonic — the reflection that swaps the tonic with the dominant. The mirrored
271
+ * pitch classes (including the bass, if set) are reassembled into a chord by
272
+ * {@link detectChordBest}; when no chord is recognized, the mirrored root and
273
+ * the original quality are used as a fallback.
274
+ *
275
+ * @param chord The chord to reflect.
276
+ * @param key The prevailing key.
277
+ * @returns The negative-harmony counterpart of the chord.
278
+ */
279
+ export function negativeHarmonyMirror(chord: Chord, key: KeyScale): Chord {
280
+ const tonic = mod12(key.rootPc);
281
+ const mirror = (p: number) => mod12(2 * tonic + 7 - p);
282
+ const pcs = chordPitchClasses(chord).map(mirror);
283
+ const bassPc = chord.bassPc !== undefined ? mirror(chord.bassPc) : undefined;
284
+ // Place the mirrored bass an octave below so it is recognized as the lowest
285
+ // note and preserved through detection.
286
+ const pitches = bassPc !== undefined ? [bassPc - 12, ...pcs] : pcs;
287
+ const detected = detectChordBest(pitches);
288
+ if (detected) {
289
+ // Without an input bass the mirrored tones are octave-less, so detection may
290
+ // read the lowest pitch class as a slash bass and report a spurious
291
+ // inversion. Restore the recognized chord to root position in that case.
292
+ if (bassPc === undefined && detected.bassPc !== undefined) {
293
+ return makeChord(detected.rootPc, detected.quality);
294
+ }
295
+ return detected;
296
+ }
297
+ const quality: ChordQuality = chord.quality;
298
+ return makeChord(mirror(chord.rootPc), quality, bassPc);
299
+ }