@libraz/libcantus 0.9.1 → 0.9.2

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 (154) hide show
  1. package/README.md +15 -0
  2. package/dist/analyze/index.cjs +1697 -0
  3. package/dist/analyze/index.cjs.map +1 -0
  4. package/dist/analyze/index.d.cts +429 -0
  5. package/dist/analyze/index.d.ts +429 -0
  6. package/dist/analyze/index.js +51 -0
  7. package/dist/analyze/index.js.map +1 -0
  8. package/dist/chunk-5HTNMQW4.js +653 -0
  9. package/dist/chunk-5HTNMQW4.js.map +1 -0
  10. package/dist/chunk-7Y7WF64D.js +410 -0
  11. package/dist/chunk-7Y7WF64D.js.map +1 -0
  12. package/dist/chunk-A4532ZFR.js +259 -0
  13. package/dist/chunk-A4532ZFR.js.map +1 -0
  14. package/dist/chunk-BHUT2S5G.js +22 -0
  15. package/dist/chunk-BHUT2S5G.js.map +1 -0
  16. package/dist/chunk-CCBLVAPK.js +42 -0
  17. package/dist/chunk-CCBLVAPK.js.map +1 -0
  18. package/dist/chunk-COKTX2G5.js +907 -0
  19. package/dist/chunk-COKTX2G5.js.map +1 -0
  20. package/dist/chunk-DYWFNC4A.js +152 -0
  21. package/dist/chunk-DYWFNC4A.js.map +1 -0
  22. package/dist/chunk-GQKN5KDT.js +159 -0
  23. package/dist/chunk-GQKN5KDT.js.map +1 -0
  24. package/dist/chunk-LN7ZZMD2.js +530 -0
  25. package/dist/chunk-LN7ZZMD2.js.map +1 -0
  26. package/dist/chunk-MSWFZF7J.js +118 -0
  27. package/dist/chunk-MSWFZF7J.js.map +1 -0
  28. package/dist/chunk-R3S2LUBH.js +2722 -0
  29. package/dist/chunk-R3S2LUBH.js.map +1 -0
  30. package/dist/chunk-SDM3VJJ5.js +41 -0
  31. package/dist/chunk-SDM3VJJ5.js.map +1 -0
  32. package/dist/chunk-XTC3X6MS.js +816 -0
  33. package/dist/chunk-XTC3X6MS.js.map +1 -0
  34. package/dist/chunk-ZXW5YIWK.js +55 -0
  35. package/dist/chunk-ZXW5YIWK.js.map +1 -0
  36. package/dist/core/index.cjs +432 -0
  37. package/dist/core/index.cjs.map +1 -0
  38. package/dist/core/index.d.cts +210 -0
  39. package/dist/core/index.d.ts +210 -0
  40. package/dist/core/index.js +73 -0
  41. package/dist/core/index.js.map +1 -0
  42. package/dist/function-2bJW1Zp_.d.ts +187 -0
  43. package/dist/function-r2sh-jOO.d.cts +187 -0
  44. package/dist/generate/index.cjs +3787 -0
  45. package/dist/generate/index.cjs.map +1 -0
  46. package/dist/generate/index.d.cts +980 -0
  47. package/dist/generate/index.d.ts +980 -0
  48. package/dist/generate/index.js +52 -0
  49. package/dist/generate/index.js.map +1 -0
  50. package/dist/index-BMPxwjwV.d.ts +151 -0
  51. package/dist/index-BOBXBNwP.d.cts +157 -0
  52. package/dist/index-BdeQ1r_p.d.cts +56 -0
  53. package/dist/index-BreoJRw0.d.ts +127 -0
  54. package/dist/index-CGMZNCx6.d.cts +140 -0
  55. package/dist/index-CGMZNCx6.d.ts +140 -0
  56. package/dist/index-CM5W4rcm.d.ts +157 -0
  57. package/dist/index-CP3wAfEH.d.ts +56 -0
  58. package/dist/index-Cl7mhOFM.d.cts +164 -0
  59. package/dist/index-Cl7mhOFM.d.ts +164 -0
  60. package/dist/index-DZ1M21do.d.cts +127 -0
  61. package/dist/index-D_ZTUNKp.d.cts +151 -0
  62. package/dist/index.cjs +3016 -2984
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +14 -3982
  65. package/dist/index.d.ts +14 -3982
  66. package/dist/index.js +170 -6504
  67. package/dist/index.js.map +1 -1
  68. package/dist/model/index.cjs +2435 -0
  69. package/dist/model/index.cjs.map +1 -0
  70. package/dist/model/index.d.cts +630 -0
  71. package/dist/model/index.d.ts +630 -0
  72. package/dist/model/index.js +21 -0
  73. package/dist/model/index.js.map +1 -0
  74. package/dist/styled-BjXtOFNk.d.cts +282 -0
  75. package/dist/styled-D7BAx3S3.d.ts +282 -0
  76. package/dist/theory/index.cjs +1677 -0
  77. package/dist/theory/index.cjs.map +1 -0
  78. package/dist/theory/index.d.cts +535 -0
  79. package/dist/theory/index.d.ts +535 -0
  80. package/dist/theory/index.js +149 -0
  81. package/dist/theory/index.js.map +1 -0
  82. package/dist/types-MGP29r3t.d.cts +30 -0
  83. package/dist/types-MGP29r3t.d.ts +30 -0
  84. package/package.json +27 -2
  85. package/src/analyze/arrange/index.ts +21 -0
  86. package/src/analyze/arrange/internal.ts +125 -0
  87. package/src/analyze/arrange/tension.ts +187 -0
  88. package/src/analyze/arrange/tracks.ts +279 -0
  89. package/src/{detect → analyze/detect}/index.ts +4 -4
  90. package/src/analyze/functional/borrowed.ts +84 -0
  91. package/src/analyze/functional/cadence.ts +66 -0
  92. package/src/analyze/functional/function.ts +184 -0
  93. package/src/analyze/functional/index.ts +23 -0
  94. package/src/analyze/functional/internal.ts +29 -0
  95. package/src/{functional/index.ts → analyze/functional/roman.ts} +9 -327
  96. package/src/analyze/index.ts +49 -0
  97. package/src/{timeline → analyze/timeline}/index.ts +7 -11
  98. package/src/{analysis → analyze/voice}/index.ts +8 -5
  99. package/src/core/index.ts +47 -0
  100. package/src/{bass → generate/bass}/index.ts +5 -5
  101. package/src/{countermelody → generate/countermelody}/index.ts +11 -11
  102. package/src/{drums → generate/drums}/index.ts +2 -2
  103. package/src/{drums → generate/drums}/rng.ts +2 -2
  104. package/src/{groove → generate/groove}/index.ts +3 -3
  105. package/src/{harmonize → generate/harmonize}/index.ts +13 -13
  106. package/src/generate/index.ts +59 -0
  107. package/src/{motif → generate/motif}/index.ts +7 -7
  108. package/src/{progression → generate/progression}/index.ts +11 -25
  109. package/src/{reharmony → generate/reharmony}/index.ts +11 -11
  110. package/src/{rhythm → generate/rhythm}/index.ts +2 -2
  111. package/src/index.ts +130 -117
  112. package/src/model/chord.ts +423 -0
  113. package/src/model/index.ts +5 -1096
  114. package/src/model/interval.ts +82 -0
  115. package/src/model/key.ts +266 -0
  116. package/src/model/note.ts +176 -0
  117. package/src/model/progression.ts +161 -0
  118. package/src/model/shared.ts +12 -0
  119. package/src/{chord → theory/chord}/index.ts +19 -1
  120. package/src/{counterpoint → theory/counterpoint}/index.ts +2 -2
  121. package/src/theory/index.ts +107 -0
  122. package/src/{safety → theory/safety}/index.ts +1 -1
  123. package/src/theory/scale/degrees.ts +123 -0
  124. package/src/theory/scale/index.ts +28 -0
  125. package/src/theory/scale/key.ts +56 -0
  126. package/src/theory/scale/masks.ts +153 -0
  127. package/src/{spelling → theory/spelling}/index.ts +3 -3
  128. package/src/{symbol → theory/symbol}/index.ts +8 -1
  129. package/src/theory/voicing/index.ts +5 -0
  130. package/src/theory/voicing/internal.ts +168 -0
  131. package/src/theory/voicing/leading.ts +112 -0
  132. package/src/theory/voicing/satb.ts +195 -0
  133. package/src/theory/voicing/styled.ts +176 -0
  134. package/src/arrange/index.ts +0 -571
  135. package/src/scale/index.ts +0 -331
  136. package/src/voicing/index.ts +0 -623
  137. /package/src/{interval → core/interval}/index.ts +0 -0
  138. /package/src/{meter → core/meter}/index.ts +0 -0
  139. /package/src/{pitch → core/pitch}/index.ts +0 -0
  140. /package/src/{random → core/random}/index.ts +0 -0
  141. /package/src/{tuning → core/tuning}/index.ts +0 -0
  142. /package/src/{types.ts → core/types.ts} +0 -0
  143. /package/src/{drums → generate/drums}/beat.ts +0 -0
  144. /package/src/{drums → generate/drums}/euclid.ts +0 -0
  145. /package/src/{drums → generate/drums}/fills.ts +0 -0
  146. /package/src/{drums → generate/drums}/ghost.ts +0 -0
  147. /package/src/{drums → generate/drums}/hihat.ts +0 -0
  148. /package/src/{drums → generate/drums}/hit.ts +0 -0
  149. /package/src/{drums → generate/drums}/internal.ts +0 -0
  150. /package/src/{drums → generate/drums}/kick.ts +0 -0
  151. /package/src/{drums → generate/drums}/percussion.ts +0 -0
  152. /package/src/{drums → generate/drums}/swing.ts +0 -0
  153. /package/src/{chordscale → theory/chordscale}/index.ts +0 -0
  154. /package/src/{harmony → theory/harmony}/index.ts +0 -0
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Arrangement track-role analysis: a single harmony is inferred from every
3
+ * track's notes pooled together, each track is then analysed against that shared
4
+ * harmony, and notes that clash with the sounding chord are collected as
5
+ * conflicts.
6
+ */
7
+
8
+ import { isStrongBeat, parseTimeSignature, type TimeSignature } from '../../core/meter/index.js';
9
+ import type { KeyScale, NoteEvent } from '../../core/types.js';
10
+ import {
11
+ evaluateSafety,
12
+ NoteSafety,
13
+ type SafetyProfile,
14
+ type VoiceSnapshot,
15
+ } from '../../theory/safety/index.js';
16
+ import {
17
+ type CadenceHit,
18
+ type ChordTimeline,
19
+ chordTimelineFromNotes,
20
+ detectCadences,
21
+ } from '../timeline/index.js';
22
+ import { type AnalyzedNote, analyzeVoice, type VoiceNote } from '../voice/index.js';
23
+ import { covers, EPS, type PreparedTrack, poolNotes, prepareTracks } from './internal.js';
24
+
25
+ /**
26
+ * The musical role a track plays in the arrangement.
27
+ *
28
+ * @category Arrangement & Analysis
29
+ */
30
+ export type TrackRole = 'melody' | 'harmony' | 'bass' | 'other';
31
+
32
+ /**
33
+ * One input track: its notes plus optional name and role.
34
+ *
35
+ * @category Arrangement & Analysis
36
+ */
37
+ export type ArrangementTrack = {
38
+ name?: string;
39
+ role?: TrackRole;
40
+ notes: NoteEvent[];
41
+ };
42
+
43
+ /**
44
+ * A track after analysis: its resolved name, role, and per-note annotations.
45
+ *
46
+ * @category Arrangement & Analysis
47
+ */
48
+ export type TrackAnalysis = {
49
+ name: string;
50
+ role: TrackRole;
51
+ /** One {@link AnalyzedNote} per note, labelled against the inferred chords. */
52
+ notes: AnalyzedNote[];
53
+ };
54
+
55
+ /**
56
+ * A note that clashes with the harmony sounding beneath it.
57
+ *
58
+ * @category Arrangement & Analysis
59
+ */
60
+ export type Conflict = {
61
+ beat: number;
62
+ trackName: string;
63
+ pitch: number;
64
+ /** The clash severity: {@link NoteSafety.Warning} or {@link NoteSafety.Dissonant}. */
65
+ safety: NoteSafety;
66
+ /** {@link import('../safety/index.js').SafetyResult.reasons} bitmask. */
67
+ reasons: number;
68
+ rationale?: string;
69
+ };
70
+
71
+ /**
72
+ * The full result of {@link analyzeArrangement}.
73
+ *
74
+ * @category Arrangement & Analysis
75
+ */
76
+ export type ArrangementAnalysis = {
77
+ key: KeyScale;
78
+ timeline: ChordTimeline;
79
+ segmentConfidence: number[];
80
+ cadences: CadenceHit[];
81
+ tracks: TrackAnalysis[];
82
+ /** Notes clashing with the sounding harmony, worst severity first. */
83
+ conflicts: Conflict[];
84
+ };
85
+
86
+ /**
87
+ * Options controlling {@link analyzeArrangement} and {@link tensionCurve}.
88
+ *
89
+ * @category Arrangement & Analysis
90
+ */
91
+ export type ArrangementOptions = {
92
+ /** Key context; inferred from the pooled notes when omitted. */
93
+ key?: KeyScale;
94
+ /**
95
+ * Time signature; defaults to 4/4.
96
+ *
97
+ * @defaultValue `4/4`
98
+ */
99
+ ts?: TimeSignature;
100
+ /**
101
+ * Chord-slot length in beats; defaults to one bar of `ts`.
102
+ *
103
+ * @defaultValue one bar of `ts`
104
+ */
105
+ harmonicRhythm?: number;
106
+ /**
107
+ * Safety profile used for conflict detection; defaults to `pop`.
108
+ *
109
+ * @defaultValue `'pop'`
110
+ */
111
+ profile?: SafetyProfile;
112
+ };
113
+
114
+ /**
115
+ * Sounding pitches of every sub-voice at a beat, excluding one sub-voice.
116
+ *
117
+ * Only the sub-voice under analysis is excluded — sibling sub-voices of the
118
+ * same track are included, so dissonant clusters inside a single polyphonic
119
+ * track are still detected.
120
+ */
121
+ function otherVoicesSounding(
122
+ prepared: PreparedTrack[],
123
+ excludeTrack: number,
124
+ excludeVoice: number,
125
+ beat: number,
126
+ ): VoiceSnapshot[] {
127
+ const out: VoiceSnapshot[] = [];
128
+ for (let t = 0; t < prepared.length; t += 1) {
129
+ const track = prepared[t];
130
+ if (!track) {
131
+ continue;
132
+ }
133
+ for (let v = 0; v < track.voices.length; v += 1) {
134
+ if (t === excludeTrack && v === excludeVoice) {
135
+ continue;
136
+ }
137
+ const subVoice = track.voices[v];
138
+ if (!subVoice) {
139
+ continue;
140
+ }
141
+ for (const note of subVoice.sounding) {
142
+ if (!covers(note, beat)) {
143
+ continue;
144
+ }
145
+ const snap: VoiceSnapshot = { pitch: note.pitch };
146
+ if (note.prevPitch !== undefined) {
147
+ snap.prevPitch = note.prevPitch;
148
+ }
149
+ out.push(snap);
150
+ }
151
+ }
152
+ }
153
+ return out;
154
+ }
155
+
156
+ /**
157
+ * The beats at which a note must be checked against the harmony: its onset,
158
+ * plus the onset of every later chord segment the note sustains across. Each
159
+ * crossed segment is visited exactly once (at its own start), so a boundary
160
+ * beat is never evaluated twice for the same note.
161
+ */
162
+ function evaluationBeats(note: VoiceNote, timeline: ChordTimeline): number[] {
163
+ const noteEnd = note.startBeat + note.durationBeat;
164
+ const beats = [note.startBeat];
165
+ for (const segment of timeline.segments) {
166
+ if (segment.startBeat > note.startBeat + EPS && segment.startBeat < noteEnd - EPS) {
167
+ beats.push(segment.startBeat);
168
+ }
169
+ }
170
+ return beats;
171
+ }
172
+
173
+ /**
174
+ * Analyse a whole arrangement against a single inferred harmony.
175
+ *
176
+ * The chord timeline and key are inferred from the pooled notes of every track
177
+ * (see {@link chordTimelineFromNotes}); pooling all voices is robust even when
178
+ * roles are absent or a track doubles the harmony, so it is preferred over
179
+ * deriving the harmony from a subset. Zero- and negative-length notes never
180
+ * sound, so they are dropped at ingest and appear in neither the annotations
181
+ * nor the conflicts.
182
+ *
183
+ * Voice analysis assumes one monophonic voice at a time, so each track is
184
+ * first partitioned into monophonic sub-voices (a polyphonic block-chord track
185
+ * fans out into one sub-voice per simultaneous note; a monophonic track is
186
+ * unaffected). Each sub-voice is labelled note-by-note against the harmony
187
+ * with {@link analyzeVoice}, seeing every other sub-voice — including siblings
188
+ * within the same track — as its accompaniment. Every note is then re-checked
189
+ * with {@link evaluateSafety} at its onset and again at each chord change it
190
+ * sustains across, so a held note that clashes with a later chord is caught:
191
+ * evaluations that are not {@link NoteSafety.Safe} become conflicts, one per
192
+ * clashing beat, sorted worst severity first and then by beat.
193
+ *
194
+ * @param tracks The tracks to analyse.
195
+ * @param opts Analysis options; see {@link ArrangementOptions}.
196
+ * @returns The inferred harmony, per-track annotations, cadences, and conflicts.
197
+ * @example
198
+ * ```ts
199
+ * import { analyzeArrangement } from '@libraz/libcantus';
200
+ * const melody = [
201
+ * { pitch: 60, startBeat: 0, durationBeat: 2 },
202
+ * { pitch: 67, startBeat: 2, durationBeat: 2 },
203
+ * ];
204
+ * const { key, conflicts } = analyzeArrangement([{ role: 'melody', notes: melody }]);
205
+ * conflicts; // notes clashing with the inferred harmony, worst severity first
206
+ * ```
207
+ * @category Arrangement & Analysis
208
+ */
209
+ export function analyzeArrangement(
210
+ tracks: ArrangementTrack[],
211
+ opts: ArrangementOptions = {},
212
+ ): ArrangementAnalysis {
213
+ const ts = opts.ts ?? parseTimeSignature('4/4');
214
+ const profile: SafetyProfile = opts.profile ?? 'pop';
215
+ const pooled = poolNotes(tracks);
216
+
217
+ const { timeline, key, segmentConfidence } = chordTimelineFromNotes(pooled, {
218
+ key: opts.key,
219
+ ts,
220
+ harmonicRhythm: opts.harmonicRhythm,
221
+ });
222
+ const cadences = detectCadences(timeline, key);
223
+ const prepared = prepareTracks(tracks);
224
+
225
+ const trackAnalyses: TrackAnalysis[] = [];
226
+ const conflicts: Conflict[] = [];
227
+
228
+ for (let t = 0; t < prepared.length; t += 1) {
229
+ const track = prepared[t];
230
+ if (!track) {
231
+ continue;
232
+ }
233
+ const notes: AnalyzedNote[] = [];
234
+ for (let v = 0; v < track.voices.length; v += 1) {
235
+ const subVoice = track.voices[v];
236
+ if (!subVoice) {
237
+ continue;
238
+ }
239
+ notes.push(
240
+ ...analyzeVoice(subVoice.voice, timeline.at, key, (beat) =>
241
+ otherVoicesSounding(prepared, t, v, beat),
242
+ ),
243
+ );
244
+
245
+ for (const note of subVoice.voice) {
246
+ for (const beat of evaluationBeats(note, timeline)) {
247
+ const result = evaluateSafety({
248
+ profile,
249
+ candidatePitch: note.pitch,
250
+ chord: timeline.at(beat),
251
+ key,
252
+ otherVoices: otherVoicesSounding(prepared, t, v, beat),
253
+ strongBeat: isStrongBeat(beat, ts),
254
+ });
255
+ if (result.safety !== NoteSafety.Safe) {
256
+ const conflict: Conflict = {
257
+ beat,
258
+ trackName: track.name,
259
+ pitch: note.pitch,
260
+ safety: result.safety,
261
+ reasons: result.reasons,
262
+ };
263
+ if (result.rationale !== undefined) {
264
+ conflict.rationale = result.rationale;
265
+ }
266
+ conflicts.push(conflict);
267
+ }
268
+ }
269
+ }
270
+ }
271
+ // Sub-voice results interleave; restore the track's onset-then-pitch order.
272
+ notes.sort((a, b) => a.noteId - b.noteId);
273
+ trackAnalyses.push({ name: track.name, role: track.role, notes });
274
+ }
275
+
276
+ conflicts.sort((a, b) => b.safety - a.safety || a.beat - b.beat);
277
+
278
+ return { key, timeline, segmentConfidence, cadences, tracks: trackAnalyses, conflicts };
279
+ }
@@ -4,8 +4,9 @@
4
4
  * which only go name -> notes.
5
5
  */
6
6
 
7
- import type { Chord, ChordQuality } from '../chord/index.js';
8
- import { chordPitchClasses, chordQualities, makeChord } from '../chord/index.js';
7
+ import type { KeyScale } from '../../core/types.js';
8
+ import type { Chord, ChordQuality } from '../../theory/chord/index.js';
9
+ import { chordPitchClasses, chordQualities, makeChord } from '../../theory/chord/index.js';
9
10
  import {
10
11
  HARMONIC_MINOR_MASK,
11
12
  MAJOR_MASK,
@@ -13,8 +14,7 @@ import {
13
14
  majorKey,
14
15
  minorKey,
15
16
  NATURAL_MINOR_MASK,
16
- } from '../scale/index.js';
17
- import type { KeyScale } from '../types.js';
17
+ } from '../../theory/scale/index.js';
18
18
 
19
19
  /**
20
20
  * A candidate chord interpretation of a pitch set.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Borrowed chords (modal interchange) and the Neapolitan.
3
+ *
4
+ * Roots are pitch classes measured against the key tonic, so borrowed and
5
+ * chromatic chords are handled by their semitone offset rather than requiring a
6
+ * spelled key signature.
7
+ */
8
+
9
+ import type { KeyScale } from '../../core/types.js';
10
+ import type { Chord } from '../../theory/chord/index.js';
11
+ import { HARMONIC_MINOR_MASK } from '../../theory/scale/index.js';
12
+ import { isDiatonic, isMinorKey, parallelKey } from './function.js';
13
+ import { isNeapolitan, mod12 } from './internal.js';
14
+
15
+ /**
16
+ * The origin of a recognized non-diatonic chord, or null when none applies.
17
+ *
18
+ * @category Functional Harmony
19
+ */
20
+ export type BorrowedSource = 'parallel-minor' | 'parallel-major' | 'neapolitan' | null;
21
+
22
+ /**
23
+ * In a minor key, whether a non-diatonic chord is explained by the harmonic
24
+ * minor scale on the same tonic (major V, V7, the raised-leading-tone viio).
25
+ * Such chords are in-key chromatic alterations, not modal interchange.
26
+ */
27
+ function isHarmonicMinorAlteration(chord: Chord, key: KeyScale): boolean {
28
+ return (
29
+ isMinorKey(key) &&
30
+ isDiatonic(chord, { rootPc: mod12(key.rootPc), modeMask12: HARMONIC_MINOR_MASK })
31
+ );
32
+ }
33
+
34
+ /**
35
+ * Whether a chord is borrowed from the parallel mode (modal interchange).
36
+ *
37
+ * True when the chord is not diatonic to `key` but is diatonic to its
38
+ * {@link parallelKey} — e.g. iv, bVI, or bVII in a major key, or the Picardy
39
+ * tonic and major IV in a minor key. Two non-diatonic families are excluded:
40
+ * chords diatonic to neither mode (they are chromatic, not borrowed), and, in
41
+ * a minor key, chords explained by the harmonic minor scale (the major
42
+ * dominant and raised-leading-tone chords), which are in-key alterations
43
+ * rather than interchange even though they happen to fit the parallel major.
44
+ *
45
+ * @param chord The chord to test.
46
+ * @param key The prevailing key.
47
+ * @returns True if the chord is borrowed from the parallel mode.
48
+ * @category Functional Harmony
49
+ */
50
+ export function isBorrowedChord(chord: Chord, key: KeyScale): boolean {
51
+ if (isDiatonic(chord, key)) {
52
+ return false;
53
+ }
54
+ if (isHarmonicMinorAlteration(chord, key)) {
55
+ return false;
56
+ }
57
+ return isDiatonic(chord, parallelKey(key));
58
+ }
59
+
60
+ /**
61
+ * Identify where a non-diatonic chord comes from.
62
+ *
63
+ * The Neapolitan (major triad on b2) is recognized first, since it sits
64
+ * outside both parallel modes; parallel-mode borrowing follows the
65
+ * {@link isBorrowedChord} rules. Diatonic chords, harmonic-minor alterations,
66
+ * and unrecognized chromatic chords all yield null.
67
+ *
68
+ * @param chord The chord to classify.
69
+ * @param key The prevailing key.
70
+ * @returns The borrowing source, or null.
71
+ * @category Functional Harmony
72
+ */
73
+ export function borrowedSource(chord: Chord, key: KeyScale): BorrowedSource {
74
+ if (isDiatonic(chord, key)) {
75
+ return null;
76
+ }
77
+ if (isNeapolitan(chord, key)) {
78
+ return 'neapolitan';
79
+ }
80
+ if (isBorrowedChord(chord, key)) {
81
+ return isMinorKey(key) ? 'parallel-major' : 'parallel-minor';
82
+ }
83
+ return null;
84
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Cadence detection between two successive chords.
3
+ *
4
+ * Roots are pitch classes measured against the key tonic, so borrowed and
5
+ * chromatic chords are handled by their semitone offset rather than requiring a
6
+ * spelled key signature.
7
+ */
8
+
9
+ import type { KeyScale } from '../../core/types.js';
10
+ import type { Chord } from '../../theory/chord/index.js';
11
+ import { isMinorKey } from './function.js';
12
+ import { mod12 } from './internal.js';
13
+
14
+ /**
15
+ * A recognized cadence type, or null when a chord pair forms none.
16
+ *
17
+ * @category Functional Harmony
18
+ */
19
+ export type Cadence = 'authentic' | 'plagal' | 'half' | 'deceptive' | null;
20
+
21
+ /**
22
+ * Classify the cadence formed by moving from one chord to the next.
23
+ *
24
+ * - authentic: V (dominant a fifth above the tonic) to I
25
+ * - plagal: IV (a fourth above the tonic) to I
26
+ * - deceptive: V to the submediant (diatonic vi or borrowed bVI in major, VI in
27
+ * minor)
28
+ * - half: any chord other than the dominant itself to V
29
+ *
30
+ * A static V-to-V repeat with no root motion is not a cadence and yields null.
31
+ *
32
+ * @param from The penultimate chord.
33
+ * @param to The final chord.
34
+ * @param key The prevailing key.
35
+ * @returns The cadence type, or null.
36
+ * @example
37
+ * ```ts
38
+ * import { detectCadence, makeChord, majorKey } from '@libraz/libcantus';
39
+ * detectCadence(makeChord(7, 'maj'), makeChord(0, 'maj'), majorKey(0)); // => 'authentic'
40
+ * ```
41
+ * @category Functional Harmony
42
+ */
43
+ export function detectCadence(from: Chord, to: Chord, key: KeyScale): Cadence {
44
+ const tonic = mod12(key.rootPc);
45
+ const fromOffset = mod12(from.rootPc - tonic);
46
+ const toOffset = mod12(to.rootPc - tonic);
47
+ // Deceptive targets: the diatonic submediant (vi at offset 9 in major, VI at
48
+ // offset 8 in minor) plus, in a major key, the borrowed flat-submediant bVI
49
+ // at offset 8.
50
+ const deceptiveTargets = isMinorKey(key) ? [8] : [8, 9];
51
+ if (fromOffset === 7 && toOffset === 0) {
52
+ return 'authentic';
53
+ }
54
+ if (fromOffset === 5 && toOffset === 0) {
55
+ return 'plagal';
56
+ }
57
+ if (fromOffset === 7 && deceptiveTargets.includes(toOffset)) {
58
+ return 'deceptive';
59
+ }
60
+ // A move to the dominant is a half cadence, but a no-root-motion V-to-V repeat
61
+ // is not a cadence at all.
62
+ if (toOffset === 7 && fromOffset !== 7) {
63
+ return 'half';
64
+ }
65
+ return null;
66
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Harmonic function (tonic / subdominant / dominant), diatonicity, parallel-key
3
+ * mirroring, and full chord analysis.
4
+ *
5
+ * Roots are pitch classes measured against the key tonic, so borrowed and
6
+ * chromatic chords are handled by their semitone offset rather than requiring a
7
+ * spelled key signature.
8
+ */
9
+
10
+ import type { KeyScale } from '../../core/types.js';
11
+ import type { Chord, ChordQuality } from '../../theory/chord/index.js';
12
+ import { chordPitchClasses, makeChord } from '../../theory/chord/index.js';
13
+ import { isScaleTone, MAJOR_MASK, NATURAL_MINOR_MASK } from '../../theory/scale/index.js';
14
+ import { type BorrowedSource, borrowedSource } from './borrowed.js';
15
+ import { degreeRootPc, isNeapolitan, mod12 } from './internal.js';
16
+ import { chordToRoman } from './roman.js';
17
+
18
+ /**
19
+ * The three broad harmonic functions of tonal music.
20
+ *
21
+ * @category Functional Harmony
22
+ */
23
+ export type HarmonicFunction = 'tonic' | 'subdominant' | 'dominant';
24
+
25
+ /** Harmonic function of each semitone offset above the tonic (major context). */
26
+ const FUNCTION_BY_OFFSET: readonly HarmonicFunction[] = [
27
+ 'tonic', // 0 I
28
+ 'subdominant', // 1 bII (Neapolitan)
29
+ 'subdominant', // 2 ii
30
+ 'tonic', // 3 bIII
31
+ 'tonic', // 4 iii
32
+ 'subdominant', // 5 IV
33
+ 'dominant', // 6 #IV / bV
34
+ 'dominant', // 7 V
35
+ 'subdominant', // 8 bVI
36
+ 'tonic', // 9 vi
37
+ 'subdominant', // 10 bVII
38
+ 'dominant', // 11 vii
39
+ ];
40
+
41
+ /**
42
+ * Whether a key's scale has a minor third and no major third (a minor key).
43
+ *
44
+ * @category Functional Harmony
45
+ */
46
+ export function isMinorKey(key: KeyScale): boolean {
47
+ const hasMinorThird = (key.modeMask12 >> 3) & 1;
48
+ const hasMajorThird = (key.modeMask12 >> 4) & 1;
49
+ return Boolean(hasMinorThird) && !hasMajorThird;
50
+ }
51
+
52
+ /**
53
+ * The harmonic function of a chord in a key, from its root's offset above the
54
+ * tonic. The mapping follows common-practice major-key function and is a useful
55
+ * approximation in minor and for borrowed chords.
56
+ *
57
+ * @param chord The chord.
58
+ * @param key The prevailing key.
59
+ * @returns The harmonic function.
60
+ * @category Functional Harmony
61
+ */
62
+ export function functionOf(chord: Chord, key: KeyScale): HarmonicFunction {
63
+ return FUNCTION_BY_OFFSET[mod12(chord.rootPc - key.rootPc)] ?? 'tonic';
64
+ }
65
+
66
+ /**
67
+ * The result of {@link analyzeChord}: function, borrowing, and Roman numeral.
68
+ *
69
+ * @category Functional Harmony
70
+ */
71
+ export type ChordAnalysis = {
72
+ function: HarmonicFunction;
73
+ borrowed: boolean;
74
+ source: BorrowedSource;
75
+ roman: string;
76
+ };
77
+
78
+ /**
79
+ * Whether every pitch class of a chord belongs to the key's scale.
80
+ *
81
+ * The test is strict against the key's own mode mask: in a natural-minor key
82
+ * the harmonic-minor dominant (major V) is *not* diatonic, since the raised
83
+ * leading tone lies outside the mask. Borrowing predicates treat that case as
84
+ * an in-key alteration separately (see {@link isBorrowedChord}).
85
+ *
86
+ * @param chord The chord to test.
87
+ * @param key The prevailing key.
88
+ * @returns True if all chord pitch classes are scale tones.
89
+ * @category Functional Harmony
90
+ */
91
+ export function isDiatonic(chord: Chord, key: KeyScale): boolean {
92
+ return chordPitchClasses(chord).every((pc) => isScaleTone(pc, key));
93
+ }
94
+
95
+ /**
96
+ * The parallel key: same tonic, opposite mode.
97
+ *
98
+ * A key with a minor third (natural/harmonic/melodic minor, dorian, phrygian)
99
+ * maps to the parallel major; any other key maps to the parallel natural minor.
100
+ *
101
+ * @param key The key to mirror.
102
+ * @returns The parallel major or natural-minor key on the same tonic.
103
+ * @category Functional Harmony
104
+ */
105
+ export function parallelKey(key: KeyScale): KeyScale {
106
+ return {
107
+ rootPc: mod12(key.rootPc),
108
+ modeMask12: isMinorKey(key) ? MAJOR_MASK : NATURAL_MINOR_MASK,
109
+ };
110
+ }
111
+
112
+ /** Diminished-family qualities: diminished triad, dim7, half-diminished. */
113
+ function isDiminishedQuality(quality: ChordQuality): boolean {
114
+ return quality === 'dim' || quality === 'dim7' || quality === 'm7b5';
115
+ }
116
+
117
+ /** Whether the chord's interval template carries a major third above the root. */
118
+ function hasMajorThird(chord: Chord): boolean {
119
+ return chord.intervals.some((interval) => mod12(interval) === 4);
120
+ }
121
+
122
+ /**
123
+ * Quality-aware harmonic function, refining the offset table where chord
124
+ * quality disambiguates: diminished chords on the leading tone or the raised
125
+ * subdominant resolve by semitone and act as dominants; the Neapolitan and the
126
+ * major-third chords on bVI/bVII borrowed from the parallel minor act as
127
+ * subdominant (predominant) harmony. All other chords keep {@link functionOf}.
128
+ */
129
+ function qualityAwareFunction(chord: Chord, key: KeyScale): HarmonicFunction {
130
+ const offset = mod12(chord.rootPc - key.rootPc);
131
+ if (isDiminishedQuality(chord.quality) && (offset === 11 || offset === 6)) {
132
+ return 'dominant';
133
+ }
134
+ if (isNeapolitan(chord, key)) {
135
+ return 'subdominant';
136
+ }
137
+ if (!isMinorKey(key) && hasMajorThird(chord) && (offset === 8 || offset === 10)) {
138
+ return 'subdominant';
139
+ }
140
+ return functionOf(chord, key);
141
+ }
142
+
143
+ /**
144
+ * Analyze a chord in a key: harmonic function, borrowing, and Roman numeral.
145
+ *
146
+ * The function is quality-aware (see the predicates behind it), the source
147
+ * follows {@link borrowedSource}, and the numeral comes from
148
+ * {@link chordToRoman}. `borrowed` is true whenever a source is identified —
149
+ * including the Neapolitan, which the stricter parallel-mode predicate
150
+ * {@link isBorrowedChord} does not count.
151
+ *
152
+ * @param chord The chord to analyze.
153
+ * @param key The prevailing key.
154
+ * @returns The chord analysis.
155
+ * @example
156
+ * ```ts
157
+ * import { analyzeChord, makeChord, majorKey } from '@libraz/libcantus';
158
+ * analyzeChord(makeChord(7, 'dom7'), majorKey(0));
159
+ * // { function: 'dominant', borrowed: false, source: null, roman: 'V7' }
160
+ * ```
161
+ * @category Functional Harmony
162
+ */
163
+ export function analyzeChord(chord: Chord, key: KeyScale): ChordAnalysis {
164
+ const source = borrowedSource(chord, key);
165
+ return {
166
+ function: qualityAwareFunction(chord, key),
167
+ borrowed: source !== null,
168
+ source,
169
+ roman: chordToRoman(chord, key),
170
+ };
171
+ }
172
+
173
+ /**
174
+ * The secondary dominant (V7) that tonicizes a scale degree.
175
+ *
176
+ * @param targetDegree 0-based scale degree to tonicize.
177
+ * @param key The prevailing key.
178
+ * @returns A dominant-seventh chord a fifth above the target's root.
179
+ * @category Functional Harmony
180
+ */
181
+ export function secondaryDominant(targetDegree: number, key: KeyScale): Chord {
182
+ const targetRoot = degreeRootPc(targetDegree + 1, key);
183
+ return makeChord(mod12(targetRoot + 7), 'dom7');
184
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Functional harmony: Roman-numeral parsing and formatting, harmonic function
3
+ * (tonic / subdominant / dominant), cadence detection, and borrowed chords.
4
+ *
5
+ * Roots are pitch classes measured against the key tonic, so borrowed and
6
+ * chromatic chords are handled by their semitone offset rather than requiring a
7
+ * spelled key signature.
8
+ */
9
+
10
+ export type { BorrowedSource } from './borrowed.js';
11
+ export { borrowedSource, isBorrowedChord } from './borrowed.js';
12
+ export type { Cadence } from './cadence.js';
13
+ export { detectCadence } from './cadence.js';
14
+ export type { ChordAnalysis, HarmonicFunction } from './function.js';
15
+ export {
16
+ analyzeChord,
17
+ functionOf,
18
+ isDiatonic,
19
+ isMinorKey,
20
+ parallelKey,
21
+ secondaryDominant,
22
+ } from './function.js';
23
+ export { chordToRoman, romanToChord } from './roman.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Shared helpers for the functional-harmony modules.
3
+ *
4
+ * Roots are pitch classes measured against the key tonic, so borrowed and
5
+ * chromatic chords are handled by their semitone offset rather than requiring a
6
+ * spelled key signature.
7
+ */
8
+
9
+ import type { KeyScale } from '../../core/types.js';
10
+ import type { Chord } from '../../theory/chord/index.js';
11
+ import { scaleTonesInDegreeOrder } from '../../theory/scale/index.js';
12
+
13
+ export function mod12(n: number): number {
14
+ return ((n % 12) + 12) % 12;
15
+ }
16
+
17
+ /** Diatonic pitch class of a 1-based scale degree in a key. */
18
+ export function degreeRootPc(degreeNumber: number, key: KeyScale): number {
19
+ const tones = scaleTonesInDegreeOrder(key);
20
+ if (tones.length === 0) {
21
+ return mod12(key.rootPc);
22
+ }
23
+ return tones[(degreeNumber - 1) % tones.length] ?? mod12(key.rootPc);
24
+ }
25
+
26
+ /** Whether a chord is the Neapolitan: a major triad on the flat second degree. */
27
+ export function isNeapolitan(chord: Chord, key: KeyScale): boolean {
28
+ return mod12(chord.rootPc - key.rootPc) === 1 && chord.quality === 'maj';
29
+ }