tuning-core 0.1.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.
- package/LICENSE +21 -0
- package/README.md +15 -0
- package/benches/fraction-performance.bench.ts +141 -0
- package/benches/spectrum-serialization.bench.ts +167 -0
- package/classes/Harmonic.ts +183 -0
- package/classes/IntervalSet.ts +361 -0
- package/classes/README.md +239 -0
- package/classes/Spectrum.ts +333 -0
- package/classes/index.ts +3 -0
- package/index.ts +2 -0
- package/lib/index.ts +2 -0
- package/lib/types.ts +13 -0
- package/lib/utils.ts +47 -0
- package/package.json +21 -0
- package/tests/Harmonic.test.ts +516 -0
- package/tests/IntervalSet.test.ts +728 -0
- package/tests/Spectrum.test.ts +710 -0
- package/tsconfig.json +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NewTonality
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# tuning-core
|
|
2
|
+
|
|
3
|
+
To install dependencies:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun install
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
To run:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun run index.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This project was created using `bun init` in bun v1.2.15. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
|
|
@@ -0,0 +1,141 @@
|
|
|
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 ? '✓' : '✗'}`);
|
|
@@ -0,0 +1,167 @@
|
|
|
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`);
|
|
@@ -0,0 +1,183 @@
|
|
|
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
|
+
}
|