-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtune.js
More file actions
1152 lines (1126 loc) · 43.3 KB
/
Copy pathtune.js
File metadata and controls
1152 lines (1126 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.tune = factory());
}(this, (function () { 'use strict';
const Util = {
// ====== Math Utils ======
/** Round `n` to a certain number of decimal `places`. */
round: (n, places = 0) => {
let c = Math.pow(10, places);
return Math.round(n * c) / c;
},
/** Calculate the logarithm of `n` to a certain `base`. */
log: (n, base) => Math.log(n) / Math.log(base),
/** Calculate the log of `n`, base 2. */
log2: (n) => Util.log(n, 2),
/** Calculate the modulo of two numbers. In contrast to `%`, this never returns a negative number. */
mod: (n, base) => {
//correct for rounding err
let m = (n % base);
m = (Math.abs(m) < 1e-14) ? 0 : m;
return (m + base) % base;
},
/**
* Calculate the quotient and remainder when dividing two numbers
* @returns A pair with the form `[quotient, remainder]`
*/
divide: (n, d) => [Math.floor(n / d), Util.mod(n, d)],
/**
* Perform an operation analagous to modulo but with exponentiation instead of multiplication.
* Essentially finds the "remainder" of calculating a logarithm.
*/
powerMod: (n, base) => Math.pow(base, (Util.mod(Util.log(n, base), 1))),
/** Calculate the next furthest integer away from zero. */
absCeil: (n) => (n >= 0) ? Math.ceil(n) : Math.floor(n),
// ====== Pitch / Frequency Conversion ======
/** The frequency equal to A4 (MIDI note 69). */
refA: 440,
/**
* Calculate the frequency representation of an equal-tempered pitch.
* Equates MIDI pitch 69 with `Util.refA`, and equates all equal-tempered zero values.
*/
ETToFreq: (pitch, base = 12) => Util.refA * Math.pow(2, (pitch / base - 69 / 12)),
/**
* Calculate the equal-tempered pitch representation of a frequency.
* Equates MIDI pitch 69 with `Util.refA`, and equates all equal-tempered zero values.
*/
freqToET: (freq, base = 12) => base * (Util.log2(freq / Util.refA) + 69 / 12),
/**
* Return the chromatic (12-ET) note name of a pitch.
*
* @param pitch A MIDI pitch.
* @returns The note name as a string (always using sharps).
*/
pitchToChromaticNoteName: (pitch) => {
let noteNames = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
let pitchClass = Math.round(Util.mod(pitch, 12));
return noteNames[pitchClass];
},
/**
* Convert a decimal to a fraction.
* Give the rational approximation of a number using continued fractions.
*
* @param n A floating-point number.
* @param places The number of places at which to round. Defaults to 9.
*
* @return A pair of numbers in the form `[numerator, denominator]`.
*/
dtf(n, places = 9) {
let err = Math.pow(10, -places);
let x = n, a = Math.floor(x), h1 = 1, h2, k1 = 0, k2, h = a, k = 1;
while (x - a > err * k * k) {
x = 1 / (x - a);
a = Math.floor(x);
h2 = h1;
h1 = h;
k2 = k1;
k1 = k;
h = h2 + a * h1;
k = k2 + a * k1;
}
return [h, k];
},
// ====== Prime Numbers ======
/** All previously calculated prime numbers. */
__primes__: [],
/** Generate all prime numbers up to `limit` (inclusive). */
primesUpTo(limit) {
if (limit < 2)
return [];
let primes = Util.__primes__;
let i = primes.length - 1;
// select already generated primes less than limit
/**
* TODO: use binary search instead
*/
if (i >= 0 && limit <= primes[i]) {
while (limit < primes[i])
i--;
return primes.slice(0, i + 1);
}
i = (i == -1) ? 2 : primes[i] + 1;
// append primes up to limit
outer: for (; i <= limit; i++) {
for (let p of primes) {
if (p > Math.sqrt(i))
break;
if (i % p == 0)
continue outer;
}
primes.push(i);
}
return primes.slice();
},
/** Find the largest prime factor of an integer. */
largestPrimeFactor(n) {
if (n % 1 !== 0)
return 1;
let primes = Util.primesUpTo(n);
for (let i = primes.length - 1; i >= 0; i--) {
if (n % primes[i] == 0)
return primes[i];
}
return 1;
},
// ====== Array Utils ======
/** Get all possible unordered pairs (2-combinations) of an array. */
getPairs(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
result.push([arr[i], arr[j]]);
}
}
return result;
},
/**
* Find the minimum element in an array.
*
* @param lessThan Custom callback for comparing non-numeric types.
*
* @returns The minimum value and its index, wrapped in an object `{index, value}`.
*/
getMin(arr, lessThan) {
lessThan = (a, b) => a < b;
let minIndex = 0, minValue = arr[0];
for (let i = 0; i < arr.length; i++) {
if (lessThan(arr[i], minValue)) {
minIndex = i;
minValue = arr[i];
}
}
return { index: minIndex, value: minValue };
},
/** Check whether `index` is an integer in the interval `[0, length)`. */
isValidIndex: (index, length) => (index >= 0) && (Util.mod(index, 1) == 0) && (index < length),
};
class PitchedObj {
constructor() {
this.__name__ = "";
}
/** Checks if two `PitchedObj`'s are the same size. */
equals(other) {
return this.cents() == other.cents();
}
toString() {
return this.name;
}
}
class Note extends PitchedObj {
constructor() {
super(...arguments);
this.isStructural = false; // structural notes are not played back and exist purely to give structure to the pitch tree
}
/**
* Returns a function that checks whether a `Note` is within a frequency range, inclusive.
* The returned function can be passed to `Array.prototype.filter()`.
*/
static inFreqRange(lo, hi) {
return function (note) {
let freq = note.getFrequency();
return freq >= lo && freq <= hi;
};
}
/**
* Returns a function that checks whether a `Note` is within a 12ET pitch range, inclusive.
* The returned function can be passed to `Array.prototype.filter()`.
*/
static inPitchRange(lo, hi) {
return function (note) {
let pitch = note.getETPitch();
return pitch >= lo && pitch <= hi;
};
}
// not sure about this
getAllNotes() {
return [this];
}
/**
* Create an equal division of an `Interval` into `div` parts, place them above the note,
* and collect the resulting `Notes` in an array.
*
* @param interval The interval to divide
* @param div The number of divisons
*/
dividedNotesAbove(interval, div) {
let innerCount = Math.ceil(div) - 1, divided = interval.divide(div), result = [], curr = this;
// add all divided bits
for (let i = 0; i < innerCount; i++) {
curr = curr.noteAbove(divided);
result.push(curr);
}
// add the top note
result.push(this.noteAbove(interval));
return result;
}
/**
* Create an equal division of an `Interval` into `div` parts, place them below the note,
* and collect the resulting `Notes` in an array.
*
* @param interval The interval to divide
* @param div The number of divisons
*/
dividedNotesBelow(interval, div) {
return this.dividedNotesAbove(interval.inverse(), div);
}
/** Return the `Note` that is a given `Interval` below. */
noteBelow(interval) {
return this.noteAbove(interval.inverse());
}
/** Return the `FreqRatio` between this `Note` and another. */
intervalTo(other) {
return new FreqRatio(other.getFrequency(), this.getFrequency());
}
getRoot() { return this; }
asFrequency() {
return new Frequency(this.getFrequency());
}
asET(base) {
return new ETPitch(this.getETPitch(base), base);
}
errorInET(base = 12, from = new MIDINote(0)) {
let interval = from.intervalTo(this);
return interval.errorInET(base);
}
cents() {
return (new ETPitch(0)).intervalTo(this).cents();
}
connect(other, by) {
let result = new TreeComponent(this);
return result.connect(other, by);
}
}
/**
* A `Note` with no pitch, used for interval structures without a definite transposition.
*/
class NullNote extends Note {
/** Either an empty string or a custom name. */
get name() {
return this.__name__;
}
set name(val) { this.__name__ = val; }
/** Does nothing. */
transposeBy(interval) { }
/** Returns a new `NullNote`. */
noteAbove(interval) {
return new NullNote();
}
/** Returns `NaN`. */
getETPitch(base) {
return NaN;
}
/** Returns `NaN`. */
getFrequency() {
return NaN;
}
/** Returns `null`. */
intervalTo(other) {
return null;
}
/** Returns `null`. */
asFrequency() {
return null;
}
/** Returns `null`. */
asET() {
return null;
}
/** Returns `NaN`. */
errorInET(base = 12, from) {
return NaN;
}
/** Returns `NaN`. */
cents() {
return NaN;
}
}
class Frequency extends Note {
constructor(freq) {
super();
this.freq = freq;
if (!(freq > 0))
throw new RangeError("Frequencies must be greater than zero.");
}
/** The frequency of the note, e.g. "500 Hz" */
get name() {
return this.__name__ || this.freq.toFixed() + " Hz";
}
/** or a custom name. */
set name(val) { this.__name__ = val; }
noteAbove(interval) {
let copy = new this.constructor(this.freq);
copy.transposeBy(interval);
return copy;
}
transposeBy(interval) {
this.freq *= interval.asFrequency().decimal();
}
getETPitch(base = 12) {
return Util.freqToET(this.freq, base);
}
getFrequency() {
return this.freq;
}
}
class ETPitch extends Note {
constructor(pitch, base = 12) {
super();
this.pitch = pitch;
this.base = base;
if (isNaN(pitch / base))
throw new RangeError("ET pitch indices must be numeric.");
if (base == 0)
throw new RangeError("Cannot create an equal division of base zero.");
}
/** The chromatic note name, e.g. "C#" */
get name() {
return this.__name__ || Util.pitchToChromaticNoteName(this.getETPitch());
}
/** or a custom name. */
set name(val) { this.__name__ = val; }
noteAbove(interval) {
let newPitch = this.pitch + interval.asET(this.base).n;
return new this.constructor(newPitch, this.base);
}
transposeBy(interval) {
this.pitch += interval.asET(this.base).n;
}
getETPitch(base = 12) {
return this.pitch * base / this.base;
}
getFrequency() {
return Util.ETToFreq(this.pitch, this.base);
}
intervalTo(other) {
return new ETInterval(other.getETPitch(this.base) - this.pitch, this.base);
}
}
Note.middleC = new ETPitch(60);
class MIDINote extends ETPitch {
constructor(pitch, velocity = 60) {
super(pitch);
this.pitch = pitch;
this.velocity = velocity;
}
}
class AbstractComponent {
constructor(root) {
this.root = root;
}
getRoot() { return this.root; }
getAllNotes() { return this.notes; }
getNoteByName(name) {
for (let note of this.notes) {
if (note.name == name)
return note;
}
}
transposeBy(interval) {
for (let note of this.notes)
note.transposeBy(interval);
}
filter(callback) {
return this.notes.filter(callback);
}
}
class TreeComponent extends AbstractComponent {
setInterval(a, b, interval) {
let diff = interval.subtract(a.intervalTo(b)), descendants = this.getSubTree(b, a);
// transpose b and all its descendants (to preserve other intervals)
for (let note of descendants)
note.transposeBy(diff);
}
getNeighbors(note) {
return this.edges.get(note).keys();
}
getSubTree(curr = this.getRoot(), parent) {
let result = [curr];
// DFS style tree traversal
for (let note of this.getNeighbors(curr)) {
if (note != parent)
result = result.concat(this.getSubTree(note, curr));
}
return result;
}
// BFS traversal, may be useful at some point
/* transposeTree(interval: Interval, curr: Note = this.root, parent?: Note): void {
let neighbors: IterableIterator<Note> = this.edges.get(curr).keys();
for (let note of neighbors) {
if (note != parent) {
note.transposeBy(interval);
this.transposeTree(interval, note, curr);
}
}
} */
connect(other, by) {
let a = this.getRoot(), b = other.getRoot();
by = by || a.intervalTo(b);
// copy all edges and notes into this instance
this.notes = this.notes.concat(other.getAllNotes());
if (other instanceof TreeComponent) {
for (let [key, val] of other.edges)
this.edges.set(key, val);
}
else {
this.edges.set(b, new Map());
}
// connect b and a
this.edges.get(a).set(b, by);
this.edges.get(b).set(a, by.inverse());
// adjust connected bit
let diff = by.subtract(a.intervalTo(b));
other.transposeBy(diff);
return this;
}
add() {
/**
*
* do something here
*/
}
remove(v) {
let hasKey = this.edges.delete(v);
if (hasKey) {
for (let m of this.edges.values())
m.delete(v);
// reassess roots etc.??
//
//
}
return hasKey;
}
}
class Fraction {
constructor(n, d = 1) {
this.n = n;
this.d = d;
}
toString() {
return `${this.n}/${this.d}`;
}
static dtf(n) {
let [a, b] = Util.dtf(n);
return new Fraction(a, b);
}
simplified() {
return null;
}
decimal() { return this.n / this.d; }
plus(other) { return Fraction.dtf(this.decimal() + other.decimal()); }
minus(other) { return Fraction.dtf(this.decimal() - other.decimal()); }
times(other) { return Fraction.dtf(this.decimal() * other.decimal()); }
divide(other) { return Fraction.dtf(this.decimal() / other.decimal()); }
}
/**
* An interval with a size and mathematical operations that work in the pitch/log-frequency domain.
*
* Designed to be immutable.
*/
class Interval extends PitchedObj {
// ====== static comparison functions for sorting ======
/**
* Compare two intervals by size, producing a number.
* A positive result means `a` is larger, and vice versa.
*
* Used for sorting.
*/
static compareSize(_a, _b) {
let a = _a.asET(), b = _b.asET();
return a.n - b.n;
}
/**
* Compare two intervals by complexity of their frequency ratios, producing a number.
* A positive result means `a` is more complex, and vice versa.
*
* Used for sorting.
*/
static compareComplexity(_a, _b) {
let a = _a.asFrequency(), b = _b.asFrequency(), x = a.largestPrimeFactor(), y = b.largestPrimeFactor();
return (x != y) ? x - y : (a.n + a.d) - (b.n + b.d);
}
/** Compress it to be an ascending interval less than an octave. */
normalized() {
return this.mod(Interval.octave);
}
/** Flip the direction of the interval. */
inverse() {
return this.multiply(-1);
}
/** Subtract the other interval from this interval. */
subtract(other) {
return this.add(other.inverse());
}
/** Divide the interval by a certain number. */
divide(n) {
return this.multiply(1 / n);
}
/** Divide the interval by another Interval. */
divideByInterval(other) {
return this.cents() / other.cents();
}
cents() {
return Util.round(this.asET().n * 100, 2);
}
/** Returns the `ETInterval` closest in size. */
getNearestET(base = 12) {
let et = this.asET(base);
et.n = Math.round(et.n);
return et;
}
errorInET(base = 12) {
let et = this.getNearestET(base);
return this.subtract(et).cents();
}
}
/** Any `Interval` type that has an internal `Fraction` representation, whether in pitch or frequency space. */
class FracInterval extends Interval {
constructor(n, d = 1) {
super();
this.frac = new Fraction(n, d);
}
get n() { return this.frac.n; }
get d() { return this.frac.d; }
set n(val) { this.frac.n = val; }
set d(val) { this.frac.d = val; }
}
/**
* An representation of an interval that stores the number of steps in a certain "ET" system.
*
* *immutable*
*/
class ETInterval extends FracInterval {
constructor(steps, base = 12) {
super(steps, base);
this.base = base;
if (isNaN(steps / base))
throw new RangeError("ET pitch indices must be numeric.");
if (base <= 0)
throw new RangeError("Cannot create an equal division with base <= 0.");
}
/** The size in steps (interval class) and base, e.g. "4 [12ET]", */
get name() {
return this.__name__ || `${this.n.toFixed(2)} [${this.d}ET]`;
}
/** or a custom name. */
set name(val) { this.__name__ = val; }
/**
* Creates a string representation of the interval class, e.g. "4 [12ET]""
*/
toString() {
return this.name;
}
mod(modulus) {
let other = modulus.asET(this.base), remainder = Util.mod(this.n, other.n);
return new this.constructor(remainder, this.d);
}
multiply(factor) {
if (isNaN(factor))
throw new RangeError("Factors must be numeric.");
return new this.constructor(this.n * factor, this.d);
}
asFrequency() {
let decimal = Math.pow(2, (this.n / this.base));
let [a, b] = Util.dtf(decimal);
return new FreqRatio(a, b);
}
asET(base = 12) {
if (base == this.base)
return this;
return new ETInterval(this.frac.decimal() * base, base);
}
inverse() {
return new this.constructor(-this.n, this.d);
}
add(other) {
let _other = other.asET(this.base);
return new this.constructor(this.n + _other.n, this.base);
}
}
/**
* An representation of an interval as a frequency ratio.
*
* *immutable*
*/
class FreqRatio extends FracInterval {
// FreqRatio methods
constructor(n, d = 1) {
if (!(n > 0 && d > 0))
throw new RangeError("Frequency ratios must be positive.");
// simplify ratio
if (n % 1 || d % 1) {
[n, d] = Util.dtf(n / d);
}
super(n, d);
}
/** The frequency ratio, e.g. "3:2", */
get name() {
return this.__name__ || this.n + ":" + this.d;
}
/** or a custom name. */
set name(val) { this.__name__ = val; }
/** Creates a `FreqRatio` from a `Fraction`. */
static fromFraction(frac) {
return new FreqRatio(frac.n, frac.d);
}
/** Returns the largest prime number involved in the ratio. */
largestPrimeFactor() {
// turn it into a ratio of integers
let norm = this.normalized();
return Util.largestPrimeFactor(norm.n * norm.d);
}
/** Return the frequency ratio as a decimal. */
decimal() {
return this.frac.decimal();
}
valueOf() {
return `${this.n}:${this.d}`;
}
mod(modulus) {
let decimalBase = modulus.asFrequency().decimal(), remainder = Util.powerMod(this.decimal(), decimalBase);
return new this.constructor(remainder);
}
multiply(factor) {
if (isNaN(factor))
throw new RangeError("Factors must be numeric.");
return new this.constructor(Math.pow(this.n, factor), Math.pow(this.d, factor));
}
asFrequency() { return this; }
asET(base = 12) {
let num = base * Util.log2(this.decimal());
return new ETInterval(num, base);
}
inverse() {
return new this.constructor(this.d, this.n);
}
add(other) {
let ratio = other.asFrequency(), product = this.frac.times(ratio.frac);
return FreqRatio.fromFraction(product);
}
}
Interval.octave = new FreqRatio(2);
class IntervalStructure {
constructor() {
this.edges = new Map();
}
}
// seperate class for non-null notes?
class IntervalTree extends IntervalStructure {
constructor(root = new NullNote()) {
super();
this.root = root;
this.edges.set(root, new Map());
}
/**
* Generate an ET scale as an `IntervalTree`, connected like a linked list.
*
* @param base The number of divisions per octave.
* @param root The `Note` upon which to start the scale. The default value is a `NullNote`, which creates a purely structural `IntervalTree`.
*/
static ET(base, root = new NullNote()) {
let result = (root instanceof NullNote) ? new IntervalTree(root) : new RootedIntervalTree(root);
let curr = root;
for (let i = 0; i < base - 1; i++) {
curr = result.connectAbove(curr, new ETInterval(1, base));
}
return result;
}
/**
* Generate a set of partials from the harmonic series.
*
* @param range Range of partial numbers, either specified as an upper bound (inclusive) or an array
* @param fundamental The `Note` to set as the fundamental (root of the tree). The default value is a `NullNote`, which creates a purely structural `IntervalTree`.
*/
static harmonicSeries(range, fundamental = new NullNote()) {
let result = (fundamental instanceof NullNote) ? new IntervalTree(fundamental) : new RootedIntervalTree(fundamental);
fundamental.isStructural = true;
if (typeof range == "number") {
// Array of numbers from 1 to range, inclusive
range = Array.from(Array(range), (_, i) => i + 1);
}
for (let i of range) {
if (i == 1)
fundamental.isStructural = false;
result.connectAbove(result.root, new FreqRatio(i));
}
return result;
}
getAllNotes() {
return Array.from(this.edges.keys());
}
addEdge(from, by, to) {
this.edges.get(from).set(to, by);
this.edges.set(to, new Map());
this.edges.get(to).set(from, by.inverse());
}
/**
* Check if the `IntervalTree` contains the specified `Note`, either by reference or by frequency value.
*
* @param note The `Note` to search for.
*/
contains(note) {
// check by reference
if (this.getAllNotes().indexOf(note) != -1)
return true;
// check by frequency value
for (let n of this.getAllNotes()) {
if (n.equals(note))
return true;
}
return false;
}
/**
* Create a new `Note` a certain interval from a note already in the tree, and add it.
*
* @param from The `Note` to connect from
* @param by The `Interval` to connect by
* @returns The newly created `Note`.
*/
connectAbove(from, by) {
if (this.contains(from)) {
let newNote = from.noteAbove(by);
this.addEdge(from, by, newNote);
return newNote;
}
else {
throw new Error("Cannot connect from a note not in tree.");
}
}
connectBelow(from, by) {
return this.connectAbove(from, by.inverse());
}
// doesn't work for pitch collections, only NullNotes
inverse() {
let result = new IntervalTree(this.root);
for (let a of this.edges.keys()) {
result.edges.set(a, new Map());
let map = this.edges.get(a);
let resultMap = result.edges.get(a);
for (let b of map.keys()) {
resultMap.set(b, map.get(b).inverse());
}
}
return result;
}
getNeighbors(note) {
return this.edges.get(note).keys();
}
getInterval(from, to) {
return this.edges.get(from).get(to);
}
withRoot(root) {
let result = new RootedIntervalTree(root), thisQueue = [this.root], resultQueue = [root], visited = new Map();
for (let note of this.getAllNotes())
visited.set(note, false);
while (thisQueue.length) {
let c1 = thisQueue.pop(), c2 = resultQueue.pop();
visited.set(c1, true);
for (let neighbor of this.getNeighbors(c1)) {
if (!visited.get(neighbor)) {
// add the current interval to get the next note
let currInterval = this.getInterval(c1, neighbor);
let next = result.connectAbove(c2, currInterval);
thisQueue.unshift(neighbor);
resultQueue.unshift(next);
}
}
}
return result;
}
}
class RootedIntervalTree extends IntervalTree {
inverse() {
return super.inverse().withRoot(this.root);
}
constructor(root) {
super(root);
}
}
/**
* Higher level functions for dealing with equal-tempered collections.
*/
const ET = {
/**
* Generate the equally divided (n-ET) scale that best approximates the given `Interval` or `Notes`.
* `Notes` are compared to a fixed scale beginning on C, `MIDIPitch(0)`.
*
* @param pitched `Note(s)` or `Interval(s)`
* @param maxBase The maximum number of divisions of the octave. Defaults to 53.
*
* @return The ET base whose scale best approximates the given pitch(es).
*/
bestFitET(pitched, maxBase = 53) {
if (!(pitched instanceof Array))
pitched = [pitched];
let best = 0, minError = Infinity;
for (let base = 1; base <= maxBase; base++) {
let error = ET.errorInET(pitched, base);
if (error < minError) {
best = base;
minError = error;
}
}
return best;
},
/**
* Generate the equally divided (n-ET) scales that best approximate the given `Interval` or `Notes`.
* `Notes` are compared to a fixed scale beginning on C, `MIDIPitch(0)`.
*
* @param pitched `Note(s)` or `Interval(s)`
* @param maxBase The maximum number of divisions of the octave. Defaults to 53.
* @param howMany How many bases to return.
*
* @return An array of ET bases, sorted by the degree to which they fit the input.
*/
bestFitETs(pitched, maxBase = 53, howMany = 10) {
if (!(pitched instanceof Array))
pitched = [pitched];
if (howMany < 1)
howMany = maxBase;
let errorArr = [];
for (let base = 1; base <= maxBase; base++) {
let error = ET.errorInET(pitched, base);
errorArr.push([base, error]);
}
// sort by ascending error, or base if error is equal
let sorted = errorArr.sort((a, b) => (a[1] === b[1]) ? a[0] - b[0] : a[1] - b[1]);
return sorted.map((pair) => pair[0]).slice(0, howMany);
},
/**
* Calculate the mean error of a set of pitches compared to `base`-ET.
* `Notes` are compared to a fixed scale beginning on C, `MIDIPitch(0)`.
* @param pitched `Note(s)` or `Interval(s)`
* @param base Number of divisions for the equally divided scaled. Defaults to 12.
* @param metric Error measure, either `rms` (Root Mean Square Error) or `abs` (Mean Absolute Error)
*
* @returns The mean error in cents.
*/
errorInET(pitched, base = 12, metric = "rms") {
if (!(pitched instanceof Array))
pitched = [pitched];
let sum = 0;
metric = metric.toLowerCase();
if (metric == "rms") {
for (let pitch of pitched)
sum += Math.pow(pitch.errorInET(base), 2);
sum = Math.sqrt(sum);
}
else if (metric == "abs") {
for (let pitch of pitched)
sum += Math.abs(pitch.errorInET(base));
}
return sum / pitched.length;
},
/**
* Calculates the step size in cents for an equal division of the octave.
*/
stepSizeForET(base) {
return (new ETInterval(1, base)).cents();
}
};
const JI = {
third: new FreqRatio(5, 4),
fifth: new FreqRatio(3, 2),
seventh: new FreqRatio(7, 4),
eleventh: new FreqRatio(11, 8)
};
/** Namespace for methods that perform various types of adaptive tuning operations. */
const AdaptiveTuning = {
/*
// ====== Timbre-based Analysis ======
currTimbre: null,
calculateDissonance(notes: Note[]) {
// assuming it's practical to implement sethares's algorithm
},
*/
/**
* Find the subset of the harmonic series that most closely matches the provided pitch collection.
*
* @param notes The pitches to be analyzed.
* @param error Allowable rounding error (in semitones).
*
* @returns An object containing calculated partial numbers of the input array as well as the fundamental frequency in Hertz.
*/
bestFitPartials(notes, error = 0.5) {
let freqs = notes.map(n => n.getFrequency());
return AdaptiveTuning.bestFitPartialsFromFreq(freqs, error);
},
/**
* Find the subset of the harmonic series that most closely matches the provided pitch collection.
*
* @param freqs An array of pitches to be analyzed, expressed in Hertz.
* @param error Allowable rounding error (in semitones).
*
* @returns An object containing calculated partial numbers of the input array as well as the fundamental frequency in Hertz.
*/
bestFitPartialsFromFreq(freqs, error = 0.5) {
let min = Util.getMin(freqs).value, ratios = freqs.map(n => n / min), partials = Array(freqs.length), i = 1;
for (;; i++) {
let j;
for (j = 0; j < freqs.length; j++) {
let partial = ratios[j] * i, freqError = partial / Math.round(partial), pitchError = 12 * Util.log2(freqError);
if (Math.abs(pitchError) < error)
partials[j] = Math.round(partial);
else
break;
}
if (j == freqs.length)
break;
}
let fundamental = min / i;
return {
partials,
fundamental,
asTree() {
return IntervalTree.harmonicSeries(partials, new Frequency(fundamental));
}
};
}
};
/**
* Maps integers (MIDI pitches) to `Notes` according a musical scale.
* Intervals of repetition may be set for both the input (`notesPerOctave`) and the output (`octaveSize`).
*
* Scales are modified by passing `set()` a sample input and a `Note` or `Interval` from the root to map it to.
*
* Alternatively, they can be modified by passing `setByIndex()` a scale index and an `Interval` relative to the root.
*
* Examples:
* - `new Scale(19)` creates an octave-repeating 19 note scale which may be mapped to any intervals (defaults to 19TET).
* - `new Scale(12, JI.fifth)` creates a 12-note scale that repeats at a fifth and whose 12 indices
* may be remapped to any interval smaller than a fifth (defaults to equal division).
*/
class Scale {
constructor(notesPerOctave = 12, octaveSize = Interval.octave, middleCPitch = Note.middleC.asET(notesPerOctave)) {
/**
* The input note at which to begin the scale.
* Any integer equivalent mod `notesPerOctave` will produce the same result.
*/
this.root = 60;
/**
* `Scale.fixedInput` and `Scale.fixedOutput` create the link between the input `number`
* and the output `Note` and determine the pitch level of the output.
*/
this.fixedInput = 60;
if (!Number.isInteger(notesPerOctave))
throw new Error("Number of notes per octave must be an integer.");
this.octaveSize = octaveSize;
this.notesPerOctave = notesPerOctave;
this.map = new Array(notesPerOctave);
this.equallyDivide(); // default to `notesPerOctave`-ET
this.setRoot(60);
this.setFixedMapping(60, middleCPitch);
}
/**
* Retrieve a `Note` from the input `number` using the `Scale`'s predefined mapping.
*
* @param input The `number` whose corresponding `Note` should be retrieved.
* @return The corresponding `Note`.