tuning-core 1.0.0 → 1.0.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.
- package/README.md +251 -6
- package/dist/classes/Harmonic.d.ts +92 -0
- package/dist/classes/Harmonic.js +164 -0
- package/dist/classes/IntervalSet.d.ts +157 -0
- package/dist/classes/IntervalSet.js +304 -0
- package/dist/classes/Spectrum.d.ts +127 -0
- package/dist/classes/Spectrum.js +279 -0
- package/dist/classes/index.js +3 -0
- package/dist/index.js +2 -0
- package/dist/lib/index.js +2 -0
- package/dist/lib/types.d.ts +12 -0
- package/dist/lib/types.js +0 -0
- package/dist/lib/utils.d.ts +20 -0
- package/dist/lib/utils.js +38 -0
- package/package.json +5 -2
- package/benches/fraction-performance.bench.ts +0 -141
- package/benches/spectrum-serialization.bench.ts +0 -167
- package/classes/Harmonic.ts +0 -183
- package/classes/IntervalSet.ts +0 -361
- package/classes/README.md +0 -239
- package/classes/Spectrum.ts +0 -333
- package/lib/types.ts +0 -13
- package/lib/utils.ts +0 -47
- package/tests/Harmonic.test.ts +0 -516
- package/tests/IntervalSet.test.ts +0 -728
- package/tests/Spectrum.test.ts +0 -710
- package/tsconfig.json +0 -26
- /package/{classes/index.ts → dist/classes/index.d.ts} +0 -0
- /package/{index.ts → dist/index.d.ts} +0 -0
- /package/{lib/index.ts → dist/lib/index.d.ts} +0 -0
package/dist/index.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import Fraction, { type FractionInput } from 'fraction.js';
|
|
2
|
+
import type { HarmonicData } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Convert a frequency ratio to cents.
|
|
5
|
+
* @param ratio - The ratio as FractionInput (number, string, array, object, or Fraction)
|
|
6
|
+
* @param places - Number of decimal places to round to (default: 0, no decimals)
|
|
7
|
+
* @returns The ratio in cents (1200 * log2(ratio)), rounded to the specified number of decimals
|
|
8
|
+
*/
|
|
9
|
+
export declare function ratioToCents(ratio: FractionInput, places?: number): Fraction;
|
|
10
|
+
/**
|
|
11
|
+
* Convert cents to a frequency ratio.
|
|
12
|
+
* @param cents - The interval in cents as FractionInput (number, string, array, object, or Fraction)
|
|
13
|
+
* @param places - Number of decimal places to round to (default: 0, no decimals)
|
|
14
|
+
* @returns The ratio as a Fraction object (2^(cents/1200)), rounded to the specified number of decimals
|
|
15
|
+
*/
|
|
16
|
+
export declare function centsToRatio(cents: FractionInput, places?: number): Fraction;
|
|
17
|
+
/**
|
|
18
|
+
* Type guard to check if a value is HarmonicData
|
|
19
|
+
*/
|
|
20
|
+
export declare function isHarmonicData(value: unknown): value is HarmonicData;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import Fraction, {} from 'fraction.js';
|
|
2
|
+
function round(num, places = 0) {
|
|
3
|
+
return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Convert a frequency ratio to cents.
|
|
7
|
+
* @param ratio - The ratio as FractionInput (number, string, array, object, or Fraction)
|
|
8
|
+
* @param places - Number of decimal places to round to (default: 0, no decimals)
|
|
9
|
+
* @returns The ratio in cents (1200 * log2(ratio)), rounded to the specified number of decimals
|
|
10
|
+
*/
|
|
11
|
+
export function ratioToCents(ratio, places = 0) {
|
|
12
|
+
const val = new Fraction(ratio).valueOf();
|
|
13
|
+
const num = 1200 * Math.log2(val);
|
|
14
|
+
const rounded = round(num, places);
|
|
15
|
+
return new Fraction(rounded);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Convert cents to a frequency ratio.
|
|
19
|
+
* @param cents - The interval in cents as FractionInput (number, string, array, object, or Fraction)
|
|
20
|
+
* @param places - Number of decimal places to round to (default: 0, no decimals)
|
|
21
|
+
* @returns The ratio as a Fraction object (2^(cents/1200)), rounded to the specified number of decimals
|
|
22
|
+
*/
|
|
23
|
+
export function centsToRatio(cents, places = 0) {
|
|
24
|
+
const val = new Fraction(cents).valueOf();
|
|
25
|
+
const num = Math.pow(2, val / 1200);
|
|
26
|
+
const rounded = round(num, places);
|
|
27
|
+
return new Fraction(rounded);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Type guard to check if a value is HarmonicData
|
|
31
|
+
*/
|
|
32
|
+
export function isHarmonicData(value) {
|
|
33
|
+
return (typeof value === 'object' &&
|
|
34
|
+
value !== null &&
|
|
35
|
+
'frequency' in value &&
|
|
36
|
+
'amplitude' in value &&
|
|
37
|
+
'phase' in value);
|
|
38
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuning-core",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"module": "index.
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"module": "index.js",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
8
11
|
"scripts": {
|
|
9
12
|
"build": "npx tsc",
|
|
10
13
|
"publish": "npx tsc && bun publish --access public"
|
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
import Fraction from 'fraction.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Performance benchmark for Fraction.js constructor with different input types.
|
|
5
|
-
* Tests creating 10,000 Fraction objects from various input formats.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
const ITERATIONS = 100_000_000;
|
|
9
|
-
|
|
10
|
-
// A relatively complex ratio for testing
|
|
11
|
-
const COMPLEX_RATIO_STRING = '440';
|
|
12
|
-
const COMPLEX_RATIO_FLOAT = 440;
|
|
13
|
-
const COMPLEX_RATIO_ARRAY: [number, number] = [440, 1];
|
|
14
|
-
const COMPLEX_RATIO_OBJECT = { n: 440, d: 1 };
|
|
15
|
-
const COMPLEX_RATIO_FRACTION = new Fraction(440, 1);
|
|
16
|
-
|
|
17
|
-
interface BenchmarkResult {
|
|
18
|
-
inputType: string;
|
|
19
|
-
timeMs: number;
|
|
20
|
-
timePerOpNs: number;
|
|
21
|
-
iterations: number;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function benchmark(name: string, fn: () => void): BenchmarkResult {
|
|
25
|
-
// Warmup
|
|
26
|
-
for (let i = 0; i < 100; i++) {
|
|
27
|
-
fn();
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Actual benchmark
|
|
31
|
-
const start = performance.now();
|
|
32
|
-
for (let i = 0; i < ITERATIONS; i++) {
|
|
33
|
-
fn();
|
|
34
|
-
}
|
|
35
|
-
const end = performance.now();
|
|
36
|
-
|
|
37
|
-
const timeMs = end - start;
|
|
38
|
-
const timePerOpNs = (timeMs / ITERATIONS) * 1_000_000; // Convert to nanoseconds
|
|
39
|
-
|
|
40
|
-
return {
|
|
41
|
-
inputType: name,
|
|
42
|
-
timeMs,
|
|
43
|
-
timePerOpNs,
|
|
44
|
-
iterations: ITERATIONS,
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function runBenchmarks(): BenchmarkResult[] {
|
|
49
|
-
const results: BenchmarkResult[] = [];
|
|
50
|
-
|
|
51
|
-
// Test 1: String input
|
|
52
|
-
results.push(
|
|
53
|
-
benchmark('String ("440")', () => {
|
|
54
|
-
new Fraction(COMPLEX_RATIO_STRING);
|
|
55
|
-
})
|
|
56
|
-
);
|
|
57
|
-
|
|
58
|
-
// Test 2: Float input
|
|
59
|
-
results.push(
|
|
60
|
-
benchmark('Float (440)', () => {
|
|
61
|
-
new Fraction(COMPLEX_RATIO_FLOAT);
|
|
62
|
-
})
|
|
63
|
-
);
|
|
64
|
-
|
|
65
|
-
// Test 3: Array input
|
|
66
|
-
results.push(
|
|
67
|
-
benchmark('Array ([440, 1])', () => {
|
|
68
|
-
new Fraction(COMPLEX_RATIO_ARRAY);
|
|
69
|
-
})
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
// Test 4: Object input
|
|
73
|
-
results.push(
|
|
74
|
-
benchmark('Object ({n: 440, d: 1})', () => {
|
|
75
|
-
new Fraction(COMPLEX_RATIO_OBJECT);
|
|
76
|
-
})
|
|
77
|
-
);
|
|
78
|
-
|
|
79
|
-
// Test 5: Fraction input (copying)
|
|
80
|
-
results.push(
|
|
81
|
-
benchmark('Fraction (copying existing)', () => {
|
|
82
|
-
new Fraction(COMPLEX_RATIO_FRACTION);
|
|
83
|
-
})
|
|
84
|
-
);
|
|
85
|
-
|
|
86
|
-
return results;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function formatResults(results: BenchmarkResult[]): void {
|
|
90
|
-
console.log('\n' + '='.repeat(80));
|
|
91
|
-
console.log(`Fraction.js Constructor Performance Benchmark`);
|
|
92
|
-
console.log(`Iterations per test: ${ITERATIONS.toLocaleString()}`);
|
|
93
|
-
console.log('='.repeat(80));
|
|
94
|
-
console.log('\n');
|
|
95
|
-
|
|
96
|
-
// Find the fastest
|
|
97
|
-
const fastest = results.reduce((min, r) => (r.timeMs < min.timeMs ? r : min), results[0]!);
|
|
98
|
-
|
|
99
|
-
console.log('Results:');
|
|
100
|
-
console.log('-'.repeat(80));
|
|
101
|
-
console.log(
|
|
102
|
-
`${'Input Type'.padEnd(35)} ${'Total Time (ms)'.padEnd(18)} ${'Time per Op (ns)'.padEnd(18)} ${'Relative Speed'.padEnd(15)}`
|
|
103
|
-
);
|
|
104
|
-
console.log('-'.repeat(80));
|
|
105
|
-
|
|
106
|
-
for (const result of results) {
|
|
107
|
-
const relativeSpeed = (result.timeMs / fastest.timeMs).toFixed(2) + 'x';
|
|
108
|
-
const timeMsStr = result.timeMs.toFixed(2);
|
|
109
|
-
const timePerOpStr = result.timePerOpNs.toFixed(2);
|
|
110
|
-
|
|
111
|
-
console.log(
|
|
112
|
-
`${result.inputType.padEnd(35)} ${timeMsStr.padEnd(18)} ${timePerOpStr.padEnd(18)} ${relativeSpeed.padEnd(15)}`
|
|
113
|
-
);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
console.log('-'.repeat(80));
|
|
117
|
-
console.log(`\nFastest: ${fastest.inputType} (${fastest.timeMs.toFixed(2)} ms)`);
|
|
118
|
-
console.log('='.repeat(80) + '\n');
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Run benchmarks
|
|
122
|
-
const results = runBenchmarks();
|
|
123
|
-
formatResults(results);
|
|
124
|
-
|
|
125
|
-
// Verify all produce the same result
|
|
126
|
-
console.log('Verification: All input types produce the same Fraction:');
|
|
127
|
-
const f1 = new Fraction(COMPLEX_RATIO_STRING);
|
|
128
|
-
const f2 = new Fraction(COMPLEX_RATIO_FLOAT);
|
|
129
|
-
const f3 = new Fraction(COMPLEX_RATIO_ARRAY);
|
|
130
|
-
const f4 = new Fraction(COMPLEX_RATIO_OBJECT);
|
|
131
|
-
const f5 = new Fraction(COMPLEX_RATIO_FRACTION);
|
|
132
|
-
|
|
133
|
-
console.log(`String: ${f1.toFraction()} = ${f1.valueOf()}`);
|
|
134
|
-
console.log(`Float: ${f2.toFraction()} = ${f2.valueOf()}`);
|
|
135
|
-
console.log(`Array: ${f3.toFraction()} = ${f3.valueOf()}`);
|
|
136
|
-
console.log(`Object: ${f4.toFraction()} = ${f4.valueOf()}`);
|
|
137
|
-
console.log(`Fraction: ${f5.toFraction()} = ${f5.valueOf()}`);
|
|
138
|
-
|
|
139
|
-
const allEqual =
|
|
140
|
-
f1.equals(f2) && f2.equals(f3) && f3.equals(f4) && f4.equals(f5);
|
|
141
|
-
console.log(`\nAll results equal: ${allEqual ? '✓' : '✗'}`);
|
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { Spectrum } from '../classes';
|
|
2
|
-
import { type SpectrumData } from '../lib';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Performance benchmark for Spectrum serialization and deserialization.
|
|
6
|
-
* Tests creating a Spectrum with fundamental of 10 and 100 harmonics,
|
|
7
|
-
* then performing 1000 serialization/deserialization passes.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
const ITERATIONS = 10_000;
|
|
11
|
-
const HARMONIC_COUNT = 100;
|
|
12
|
-
const FUNDAMENTAL = 1234/567;
|
|
13
|
-
|
|
14
|
-
// Create a test spectrum with fundamental 10 and 100 harmonics
|
|
15
|
-
function createTestSpectrum(): Spectrum {
|
|
16
|
-
const spectrum = new Spectrum();
|
|
17
|
-
|
|
18
|
-
for (let i = 1; i <= HARMONIC_COUNT; i++) {
|
|
19
|
-
const frequency = FUNDAMENTAL * i;
|
|
20
|
-
const amplitude = 1 / i; // Natural decay
|
|
21
|
-
const phase = 0;
|
|
22
|
-
spectrum.add(frequency, amplitude, phase);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return spectrum;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
interface BenchmarkResult {
|
|
29
|
-
operation: string;
|
|
30
|
-
timeMs: number;
|
|
31
|
-
timePerOpMs: number;
|
|
32
|
-
iterations: number;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function benchmark(name: string, fn: () => void): BenchmarkResult {
|
|
36
|
-
// Warmup
|
|
37
|
-
for (let i = 0; i < 10; i++) {
|
|
38
|
-
fn();
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// Actual benchmark
|
|
42
|
-
const start = performance.now();
|
|
43
|
-
for (let i = 0; i < ITERATIONS; i++) {
|
|
44
|
-
fn();
|
|
45
|
-
}
|
|
46
|
-
const end = performance.now();
|
|
47
|
-
|
|
48
|
-
const timeMs = end - start;
|
|
49
|
-
const timePerOpMs = timeMs / ITERATIONS;
|
|
50
|
-
|
|
51
|
-
return {
|
|
52
|
-
operation: name,
|
|
53
|
-
timeMs,
|
|
54
|
-
timePerOpMs,
|
|
55
|
-
iterations: ITERATIONS,
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function runBenchmarks(): BenchmarkResult[] {
|
|
60
|
-
const results: BenchmarkResult[] = [];
|
|
61
|
-
|
|
62
|
-
// Create test spectrum once
|
|
63
|
-
const testSpectrum = createTestSpectrum();
|
|
64
|
-
console.log(`Created test spectrum with ${testSpectrum.size} harmonics`);
|
|
65
|
-
console.log(`Fundamental: ${FUNDAMENTAL} Hz, Highest harmonic: ${FUNDAMENTAL * HARMONIC_COUNT} Hz\n`);
|
|
66
|
-
|
|
67
|
-
// Benchmark 1: Serialization (toJSON)
|
|
68
|
-
let serializedData: SpectrumData | null = null;
|
|
69
|
-
results.push(
|
|
70
|
-
benchmark('Serialization (toJSON)', () => {
|
|
71
|
-
serializedData = testSpectrum.toJSON();
|
|
72
|
-
})
|
|
73
|
-
);
|
|
74
|
-
|
|
75
|
-
if (!serializedData) {
|
|
76
|
-
throw new Error('Serialization failed');
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// Benchmark 2: Deserialization (new Spectrum(data))
|
|
80
|
-
results.push(
|
|
81
|
-
benchmark('Deserialization (new Spectrum(data))', () => {
|
|
82
|
-
new Spectrum(serializedData!);
|
|
83
|
-
})
|
|
84
|
-
);
|
|
85
|
-
|
|
86
|
-
// Benchmark 3: Round-trip (serialize + deserialize)
|
|
87
|
-
results.push(
|
|
88
|
-
benchmark('Round-trip (serialize + deserialize)', () => {
|
|
89
|
-
const data = testSpectrum.toJSON();
|
|
90
|
-
new Spectrum(data);
|
|
91
|
-
})
|
|
92
|
-
);
|
|
93
|
-
|
|
94
|
-
// Benchmark 4: Verify correctness
|
|
95
|
-
const deserialized = new Spectrum(serializedData);
|
|
96
|
-
const isEqual = testSpectrum.size === deserialized.size &&
|
|
97
|
-
Array.from(testSpectrum.getHarmonics()).every((h1, i) => {
|
|
98
|
-
const h2 = deserialized.getHarmonics()[i];
|
|
99
|
-
if (!h2) return false;
|
|
100
|
-
return h1.frequencyStr === h2.frequencyStr &&
|
|
101
|
-
Math.abs(h1.amplitude - h2.amplitude) < 1e-10 &&
|
|
102
|
-
Math.abs(h1.phase - h2.phase) < 1e-10;
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
console.log(`Verification: Round-trip preserves data correctly: ${isEqual ? '✓' : '✗'}\n`);
|
|
106
|
-
|
|
107
|
-
return results;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function formatResults(results: BenchmarkResult[]): void {
|
|
111
|
-
console.log('='.repeat(80));
|
|
112
|
-
console.log(`Spectrum Serialization/Deserialization Performance Benchmark`);
|
|
113
|
-
console.log(`Test Spectrum: ${HARMONIC_COUNT} harmonics, fundamental ${FUNDAMENTAL} Hz`);
|
|
114
|
-
console.log(`Iterations per test: ${ITERATIONS.toLocaleString()}`);
|
|
115
|
-
console.log('='.repeat(80));
|
|
116
|
-
console.log('\n');
|
|
117
|
-
|
|
118
|
-
// Find the fastest
|
|
119
|
-
const fastest = results.reduce((min, r) => (r.timeMs < min.timeMs ? r : min), results[0]!);
|
|
120
|
-
|
|
121
|
-
console.log('Results:');
|
|
122
|
-
console.log('-'.repeat(80));
|
|
123
|
-
console.log(
|
|
124
|
-
`${'Operation'.padEnd(45)} ${'Total Time (ms)'.padEnd(18)} ${'Time per Op (ms)'.padEnd(18)} ${'Relative Speed'.padEnd(15)}`
|
|
125
|
-
);
|
|
126
|
-
console.log('-'.repeat(80));
|
|
127
|
-
|
|
128
|
-
for (const result of results) {
|
|
129
|
-
const relativeSpeed = (result.timeMs / fastest.timeMs).toFixed(2) + 'x';
|
|
130
|
-
const timeMsStr = result.timeMs.toFixed(2);
|
|
131
|
-
const timePerOpStr = result.timePerOpMs.toFixed(4);
|
|
132
|
-
|
|
133
|
-
console.log(
|
|
134
|
-
`${result.operation.padEnd(45)} ${timeMsStr.padEnd(18)} ${timePerOpStr.padEnd(18)} ${relativeSpeed.padEnd(15)}`
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
console.log('-'.repeat(80));
|
|
139
|
-
console.log(`\nFastest: ${fastest.operation} (${fastest.timeMs.toFixed(2)} ms)`);
|
|
140
|
-
console.log('='.repeat(80) + '\n');
|
|
141
|
-
|
|
142
|
-
// Additional statistics
|
|
143
|
-
const serialization = results.find(r => r.operation.includes('Serialization'));
|
|
144
|
-
const deserialization = results.find(r => r.operation.includes('Deserialization'));
|
|
145
|
-
const roundTrip = results.find(r => r.operation.includes('Round-trip'));
|
|
146
|
-
|
|
147
|
-
if (serialization && deserialization && roundTrip) {
|
|
148
|
-
console.log('Breakdown:');
|
|
149
|
-
console.log(` Serialization: ${serialization.timePerOpMs.toFixed(4)} ms per operation`);
|
|
150
|
-
console.log(` Deserialization: ${deserialization.timePerOpMs.toFixed(4)} ms per operation`);
|
|
151
|
-
console.log(` Round-trip: ${roundTrip.timePerOpMs.toFixed(4)} ms per operation`);
|
|
152
|
-
console.log(` Expected round-trip: ${(serialization.timePerOpMs + deserialization.timePerOpMs).toFixed(4)} ms`);
|
|
153
|
-
console.log(` Overhead: ${(roundTrip.timePerOpMs - serialization.timePerOpMs - deserialization.timePerOpMs).toFixed(4)} ms\n`);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// Run benchmarks
|
|
158
|
-
const results = runBenchmarks();
|
|
159
|
-
formatResults(results);
|
|
160
|
-
|
|
161
|
-
// Show sample of serialized data
|
|
162
|
-
const sampleSpectrum = createTestSpectrum();
|
|
163
|
-
const sampleData = sampleSpectrum.toJSON();
|
|
164
|
-
console.log('Sample serialized data (first 3 harmonics):');
|
|
165
|
-
console.log(JSON.stringify(sampleData.slice(0, 3), null, 2));
|
|
166
|
-
console.log(`\nTotal harmonics in serialized data: ${sampleData.length}`);
|
|
167
|
-
console.log(`Average size per harmonic: ${(JSON.stringify(sampleData).length / sampleData.length).toFixed(2)} bytes`);
|
package/classes/Harmonic.ts
DELETED
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
import Fraction, { type FractionInput } from 'fraction.js';
|
|
2
|
-
import { type HarmonicData, isHarmonicData } from '../lib';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Represents a single partial in an arbitrary spectrum.
|
|
6
|
-
* The name Harmonic does not imply a harmonic series but chosen over
|
|
7
|
-
* Partial to avoid coflict with the TypeScript's Partial type.
|
|
8
|
-
* Mutable for better real-time performance.
|
|
9
|
-
* Frequencies are stored as rational numbers for exact tuning mathematics.
|
|
10
|
-
*
|
|
11
|
-
* The constructor accepts either a HarmonicData object or individual parameters.
|
|
12
|
-
*
|
|
13
|
-
* @example
|
|
14
|
-
* // Using HarmonicData object
|
|
15
|
-
* const harmonic1 = new Harmonic({
|
|
16
|
-
* frequency: 440,
|
|
17
|
-
* amplitude: 0.5,
|
|
18
|
-
* phase: Math.PI
|
|
19
|
-
* });
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* // Using individual parameters
|
|
23
|
-
* const harmonic2 = new Harmonic(440, 0.5, Math.PI);
|
|
24
|
-
* const harmonic3 = new Harmonic("440"); // amplitude defaults to 1, phase defaults to 0
|
|
25
|
-
* const harmonic4 = new Harmonic("440 1/3"); // frequency as a string with whole and fractional part
|
|
26
|
-
* const harmonic4 = new Harmonic([107, 100]); // frequency as a fraction of two integers 107/100
|
|
27
|
-
* // Note that frequency is treated as a rational number from Fraction.js lib
|
|
28
|
-
* // so it accepts FractionInput type
|
|
29
|
-
*/
|
|
30
|
-
export class Harmonic {
|
|
31
|
-
private _frequency: Fraction; // Frequency as ratio (e.g., 3/2 for perfect fifth)
|
|
32
|
-
private _amplitude: number; // 0-1 normalized
|
|
33
|
-
private _phase: number; // 0-2π radians
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Get frequency as a Fraction
|
|
37
|
-
*/
|
|
38
|
-
get frequency(): Fraction {
|
|
39
|
-
return this._frequency;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Get frequency as a float number
|
|
44
|
-
*/
|
|
45
|
-
get frequencyNum(): number {
|
|
46
|
-
return this._frequency.valueOf();
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Get frequency as a simplified fraction string (e.g., "3/2")
|
|
51
|
-
*/
|
|
52
|
-
get frequencyStr(): string {
|
|
53
|
-
return this._frequency.toFraction();
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Get amplitude (0-1 normalized)
|
|
58
|
-
*/
|
|
59
|
-
get amplitude(): number {
|
|
60
|
-
return this._amplitude;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Get phase (0-2π radians)
|
|
65
|
-
*/
|
|
66
|
-
get phase(): number {
|
|
67
|
-
return this._phase;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
constructor(data: HarmonicData);
|
|
71
|
-
constructor(frequency: FractionInput, amplitude?: number, phase?: number);
|
|
72
|
-
constructor(frequencyOrData: FractionInput | HarmonicData, amplitude = 1, phase = 0) {
|
|
73
|
-
if (isHarmonicData(frequencyOrData)) {
|
|
74
|
-
// HarmonicData case
|
|
75
|
-
this._frequency = new Fraction(frequencyOrData.frequency);
|
|
76
|
-
this._amplitude = frequencyOrData.amplitude;
|
|
77
|
-
this._phase = frequencyOrData.phase;
|
|
78
|
-
} else {
|
|
79
|
-
// Original case: frequency, amplitude, phase
|
|
80
|
-
this._frequency = new Fraction(frequencyOrData);
|
|
81
|
-
this._amplitude = amplitude ?? 1;
|
|
82
|
-
this._phase = phase ?? 0;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
this.validate();
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
private validate(): void {
|
|
89
|
-
if (this._frequency.compare(0) <= 0) {
|
|
90
|
-
throw new Error('Frequency must be positive');
|
|
91
|
-
}
|
|
92
|
-
if (this._amplitude < 0 || this._amplitude > 1) {
|
|
93
|
-
throw new Error('Amplitude must be between 0 and 1');
|
|
94
|
-
}
|
|
95
|
-
if (this._phase < 0 || this._phase >= 2 * Math.PI) {
|
|
96
|
-
throw new Error('Phase must be between 0 and 2π');
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Sets frequency to the provided value
|
|
102
|
-
*/
|
|
103
|
-
setFrequency(frequency: FractionInput): this {
|
|
104
|
-
this._frequency = new Fraction(frequency);
|
|
105
|
-
if (this._frequency.compare(0) <= 0) {
|
|
106
|
-
throw new Error('Frequency must be positive');
|
|
107
|
-
}
|
|
108
|
-
return this;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Sets amplitude (0-1)
|
|
113
|
-
*/
|
|
114
|
-
setAmplitude(amplitude: number): this {
|
|
115
|
-
if (amplitude < 0 || amplitude > 1) {
|
|
116
|
-
throw new Error('Amplitude must be between 0 and 1');
|
|
117
|
-
}
|
|
118
|
-
this._amplitude = amplitude;
|
|
119
|
-
return this;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Sets phase (0-2π)
|
|
124
|
-
*/
|
|
125
|
-
setPhase(phase: number): this {
|
|
126
|
-
if (phase < 0 || phase >= 2 * Math.PI) {
|
|
127
|
-
throw new Error('Phase must be between 0 and 2π');
|
|
128
|
-
}
|
|
129
|
-
this._phase = phase;
|
|
130
|
-
return this;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Multiply frequency by a ratio (for transposition)
|
|
135
|
-
*/
|
|
136
|
-
transpose(ratio: FractionInput): this {
|
|
137
|
-
this._frequency = this._frequency.mul(ratio);
|
|
138
|
-
return this;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Multiply frequency by a ratio (for transposition)
|
|
143
|
-
*/
|
|
144
|
-
toTransposed(ratio: FractionInput): Harmonic {
|
|
145
|
-
return this.clone().transpose(ratio);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Scale amplitude by a factor
|
|
150
|
-
*/
|
|
151
|
-
scale(factor: number): this {
|
|
152
|
-
this._amplitude = Math.max(0, Math.min(1, this._amplitude * factor));
|
|
153
|
-
return this;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Create a copy of this harmonic
|
|
158
|
-
*/
|
|
159
|
-
clone(): Harmonic {
|
|
160
|
-
return new Harmonic(this._frequency, this._amplitude, this._phase);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Compare frequencies (for sorting)
|
|
165
|
-
*/
|
|
166
|
-
compareFrequency(other: Harmonic): number {
|
|
167
|
-
return this._frequency.compare(other._frequency);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Serializes the harmonic to a HarmonicData object
|
|
172
|
-
*/
|
|
173
|
-
toJSON(): HarmonicData {
|
|
174
|
-
return {
|
|
175
|
-
frequency: {
|
|
176
|
-
n: Number(this._frequency.n),
|
|
177
|
-
d: Number(this._frequency.d),
|
|
178
|
-
},
|
|
179
|
-
amplitude: this._amplitude,
|
|
180
|
-
phase: this._phase,
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
}
|