Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
500 lines (474 loc) · 24.3 KB
/
Copy pathscript.js
File metadata and controls
500 lines (474 loc) · 24.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
'use strict';
const byId = id => document.getElementById(id);
const parameterKeys = ['omega0', 'delta_omega', 'phi0', 'phi1', 'phi2', 'phi3'];
const sliders = Object.fromEntries(parameterKeys.map(key => [key, byId(key)]));
const numberInputs = Object.fromEntries(parameterKeys.map(key => [key, byId(`${key}_val`)]));
const charts = {};
const WAVE_OFFSET = 2.5;
const WAVE_COLORS = ['#e15d64', '#c48b27', '#7c9841', '#239c88', '#4285d4', '#8562cb', '#c4559e'];
const SPECTRUM_COLOR = '#4c7fe5';
const PHASE_COLOR = '#279d88';
const DEFAULT_AXES = { omegaMin: 1, omegaMax: 12, timeMin: -20, timeMax: 20 };
let axes = { ...DEFAULT_AXES };
let manualTimeBounds = { timeMin: DEFAULT_AXES.timeMin, timeMax: DEFAULT_AXES.timeMax };
let currentSpectrumMode = 'gaussian';
let customSpectrumDataPoints = [];
let pendingFrame = null;
let lastAutoTimeFrequency = null;
function readParameters() {
const p = {
mode: currentSpectrumMode, points: customSpectrumDataPoints,
center: Number(sliders.omega0.value), bandwidth: Number(sliders.delta_omega.value),
phi0: Number(sliders.phi0.value), phi1: Number(sliders.phi1.value),
phi2: Number(sliders.phi2.value), phi3: Number(sliders.phi3.value)
};
if (p.mode === 'custom') p.customCurve = PulseMath.createCustomCurve(p.points);
parameterKeys.forEach(key => { numberInputs[key].value = sliders[key].value; });
if (p.mode === 'custom' && byId('autoOmega0Custom').checked) {
p.center = PulseMath.customProperties(p.points, p.center, p.customCurve).center;
numberInputs.omega0.value = p.center.toFixed(3);
}
return p;
}
function requestPlotUpdate() {
if (pendingFrame !== null) return;
pendingFrame = requestAnimationFrame(() => { pendingFrame = null; updatePlots(); });
}
function plotData(times, values) {
return times.map((x, i) => ({ x, y: values[i] }));
}
function updatePlots() {
const p = readParameters();
let spectrum, times, pulse;
try {
const frequencyState = JSON.stringify([axes.omegaMin, axes.omegaMax, p.center]);
if (byId('autoTimeLimits').checked && frequencyState !== lastAutoTimeFrequency) {
Object.assign(axes, PulseMath.automaticTimeBounds(p));
lastAutoTimeFrequency = frequencyState;
syncTimeInputs();
}
spectrum = PulseMath.sampleSpectrum(p, axes.timeMin, axes.timeMax);
const waves = PulseMath.displayWaves(p);
times = PulseMath.timeGrid(axes.timeMin, axes.timeMax, Math.max(spectrum.max, ...waves.map(wave => wave.omega)));
pulse = PulseMath.synthesize(spectrum, times);
} catch (error) {
byId('calculationStatus').textContent = error.message;
byId('calculationStatus').classList.add('is-error');
// Clear old results so an unsupported request cannot display stale physics.
Object.values(charts).forEach(chart => {
chart.data.datasets.forEach(dataset => { dataset.data = []; });
chart.update('none');
});
byId('intensityWidth').textContent = '';
return;
}
byId('calculationStatus').classList.remove('is-error');
byId('calculationStatus').textContent = spectrum.samples.length
? `${spectrum.samples.length.toLocaleString()} spectral samples · amplitude cutoff 0.01% · 7 displayed waves`
: 'The spectrum is zero. Add spectral intensity by dragging the red points.';
// Add spectral landmarks so a narrow feature survives a wide frequency view.
const landmarks = p.mode === 'custom' ? p.customCurve.segments.flatMap(segment =>
PulseMath.linspace(segment.x, segment.x + segment.h, 17))
: PulseMath.linspace(Math.max(0, p.center - 3 * p.bandwidth), p.center + 3 * p.bandwidth, 401);
const frequencies = [...new Set([...PulseMath.linspace(axes.omegaMin, axes.omegaMax, 601),
...landmarks.filter(omega => omega >= axes.omegaMin && omega <= axes.omegaMax)])].sort((a, b) => a - b);
const spectrumChart = charts.spectrumAndPhase;
spectrumChart.data.datasets[0].data = frequencies.map(x => ({ x, y: PulseMath.spectrumValue(x, p) }));
spectrumChart.data.datasets[1].data = frequencies.map(x => ({ x, y: PulseMath.phase(x, p) }));
spectrumChart.data.datasets[1].hidden = !byId('showSpectralPhase').checked;
spectrumChart.options.scales.yPhi.display = byId('showSpectralPhase').checked;
spectrumChart.data.datasets[2].data = p.points;
spectrumChart.data.datasets[2].hidden = p.mode !== 'custom';
spectrumChart.options.scales.x.min = axes.omegaMin;
spectrumChart.options.scales.x.max = axes.omegaMax;
const waves = PulseMath.displayWaves(p);
charts.individualCosines.data.datasets = waves.map((wave, i) => ({
label: `ω = ${wave.omega.toFixed(2)}`, omega: wave.omega, baseline: -i * WAVE_OFFSET,
data: times.map(x => ({ x, y: wave.amplitude * Math.cos(wave.phase - wave.omega * x) - i * WAVE_OFFSET })),
borderColor: WAVE_COLORS[i], borderWidth: 1.65
}));
if (byId('showPeakConnector').checked) {
const peaks = waves.map((wave, i) => {
if (wave.omega === 0 || wave.amplitude === 0) return { x: axes.timeMin, y: null };
// Choose the carrier maximum nearest the group delay, only if visible.
const cycle = Math.round((wave.phase - wave.omega * p.phi1) / (2 * Math.PI));
const x = (wave.phase - 2 * Math.PI * cycle) / wave.omega;
return { x, y: x >= axes.timeMin && x <= axes.timeMax ? wave.amplitude - i * WAVE_OFFSET : null };
});
charts.individualCosines.data.datasets.push({ label: 'Peak connector', data: peaks,
borderColor: '#374151', borderDash: [4, 4], borderWidth: 1.2, pointRadius: 2 });
}
charts.sumCosines.data.datasets[0].data = plotData(times, pulse.real);
charts.sumCosines.data.datasets[1].data = plotData(times, pulse.envelope);
charts.sumCosines.data.datasets[2].data = plotData(times, pulse.envelope.map(value => -value));
charts.sumCosines.data.datasets[1].hidden = !byId('showEnvelopeE').checked;
charts.sumCosines.data.datasets[2].hidden = !byId('showEnvelopeE').checked;
charts.sumIntensity.data.datasets[0].data = plotData(times, pulse.intensity);
charts.sumIntensity.data.datasets[1].data = plotData(times, pulse.fieldSquared);
charts.sumIntensity.data.datasets[1].hidden = !byId('showFieldSquared').checked;
// Report the pulse duration measured from the same half-maximum crossings as the fit.
const measured = PulseMath.intensityFWHM(times, pulse.intensity);
const half = Math.max(...pulse.intensity) / 2;
const clipped = measured
&& (pulse.intensity[0] >= half || pulse.intensity[pulse.intensity.length - 1] >= half);
byId('intensityWidth').textContent = !measured ? 'Intensity FWHM: not defined for a zero field.'
: clipped ? `Intensity FWHM: more than ${measured.width.toPrecision(4)} a.u.; the pulse extends past the time limits.`
: `Intensity FWHM: ${measured.width.toPrecision(4)} a.u.`;
charts.instantaneousFrequency.data.datasets[0].data = plotData(times, pulse.frequency);
charts.instantaneousFrequency.data.datasets[1].data = [
{ x: axes.timeMin, y: p.center }, { x: axes.timeMax, y: p.center }
];
// Keep an unchirped pulse visibly flat instead of magnifying tiny tail changes.
charts.instantaneousFrequency.options.scales.y.suggestedMin = waves[0].omega;
charts.instantaneousFrequency.options.scales.y.suggestedMax = waves[waves.length - 1].omega;
Object.entries(charts).forEach(([name, chart]) => {
if (name !== 'spectrumAndPhase') {
chart.options.scales.x.min = axes.timeMin;
chart.options.scales.x.max = axes.timeMax;
}
chart.update('none');
});
}
// Draw the frequency at each wave's baseline in place of the offset axis.
const waveLabelsPlugin = {
id: 'wave-frequency-labels',
afterDraw(chart) {
const { ctx, chartArea, scales } = chart;
ctx.save();
ctx.font = '600 14px "Segoe UI", sans-serif';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
const waves = chart.data.datasets.filter(dataset => dataset.omega !== undefined);
waves.forEach(dataset => {
ctx.fillStyle = dataset.borderColor;
ctx.fillText(`ω = ${dataset.omega.toFixed(2)}`, chartArea.left - 10, scales.y.getPixelForValue(dataset.baseline));
});
if (waves.length) {
const x = chartArea.left - 43;
const top = scales.y.getPixelForValue(waves[0].baseline + 2.1);
const bottom = scales.y.getPixelForValue(waves[waves.length - 1].baseline - 2.1);
ctx.strokeStyle = '#8795a9';
ctx.fillStyle = '#8795a9';
ctx.lineWidth = 1.6;
// Three dots beside an arrow, continuing beyond the seven sample rows.
// The upward marker is dropped at zero frequency, where no spectrum lies below.
const markers = waves[0].omega > 0 ? [[top, -1], [bottom, 1]] : [[bottom, 1]];
for (const [y, direction] of markers) {
for (let dot = -1; dot <= 1; dot++) {
ctx.beginPath(); ctx.arc(x + dot * 6, y, 1.5, 0, 2 * Math.PI); ctx.fill();
}
const arrowX = x + 20, tipY = y + direction * 7;
ctx.beginPath(); ctx.moveTo(arrowX, y - direction * 7); ctx.lineTo(arrowX, tipY);
ctx.moveTo(arrowX - 4, tipY - direction * 4); ctx.lineTo(arrowX, tipY);
ctx.lineTo(arrowX + 4, tipY - direction * 4); ctx.stroke();
}
}
ctx.restore();
}
};
function baseOptions() {
return {
animation: false, responsive: true, maintainAspectRatio: false, parsing: false,
elements: { point: { radius: 0 }, line: { tension: 0, borderWidth: 2.2, borderCapStyle: 'round', borderJoinStyle: 'round' } },
layout: { padding: { top: 6, right: 8 } },
plugins: { tooltip: { enabled: false }, legend: { align: 'start', onClick: () => {}, labels: {
color: '#63738a', usePointStyle: true, pointStyle: 'line', boxWidth: 24, padding: 18,
font: { size: 13 }, filter: item => !item.hidden
} } },
scales: {
x: axisOptions('Time t (a.u.)'),
y: axisOptions('')
}
};
}
function axisOptions(title) {
return { type: 'linear', border: { display: false },
grid: { color: '#edf1f6', drawTicks: false },
title: { display: true, text: title, color: '#40516b', padding: 12, font: { size: 16, weight: '500' } },
ticks: { color: '#64748b', padding: 9, maxTicksLimit: 6, maxRotation: 0, font: { size: 14 } } };
}
// Tint an axis in its curve's color, so the two spectrum scales read at a glance.
function tintedAxis(title, color, extra = {}) {
const options = axisOptions(title);
options.title.color = color;
options.ticks.color = color;
return { ...options, ...extra };
}
function gradientFill(color) {
return context => {
const { ctx, chartArea } = context.chart;
if (!chartArea) return color + '18';
const gradient = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
gradient.addColorStop(0, color + '35');
gradient.addColorStop(1, color + '03');
return gradient;
};
}
function dataset(label, borderColor, extra = {}) {
return { label, borderColor, data: [], fill: false, ...extra };
}
function initCharts() {
Chart.defaults.font.family = '"Segoe UI", -apple-system, BlinkMacSystemFont, sans-serif';
Chart.defaults.font.size = 14;
const spectrumOptions = baseOptions();
spectrumOptions.scales = {
x: axisOptions('Angular frequency ω (a.u.)'),
yS: tintedAxis('S(ω)', SPECTRUM_COLOR, { position: 'left', min: 0, max: 1.1 }),
yPhi: tintedAxis('Φ(ω) (rad)', PHASE_COLOR, { position: 'right', grid: { drawOnChartArea: false, drawTicks: false } })
};
spectrumOptions.plugins.legend.labels.filter = item => item.datasetIndex !== 2 && !item.hidden;
// A larger legend for the spectrum, where two curves share one plot.
Object.assign(spectrumOptions.plugins.legend.labels,
{ font: { size: 16 }, boxWidth: 34, padding: 22 });
charts.spectrumAndPhase = new Chart(byId('spectrumChart'), {
type: 'line', options: spectrumOptions, data: { datasets: [
dataset('S(ω)', SPECTRUM_COLOR, { yAxisID: 'yS', fill: 'origin', backgroundColor: gradientFill(SPECTRUM_COLOR) }),
dataset('Φ(ω)', PHASE_COLOR, { yAxisID: 'yPhi' }),
dataset('Custom spectrum', '#e74c3c', { yAxisID: 'yS', showLine: false, pointRadius: 4,
pointHoverRadius: 6, backgroundColor: '#e74c3c', hidden: true, order: -1 })
] }
});
const waveOptions = baseOptions();
waveOptions.layout = { padding: { left: 96, top: 6, right: 8 } };
waveOptions.plugins.legend.display = false;
waveOptions.scales.y = { display: false, min: -6 * WAVE_OFFSET - 3, max: 3 };
waveOptions.scales.x.grid.color = '#f0f3f8';
charts.individualCosines = new Chart(byId('individualCosinesChart'), {
type: 'line', options: waveOptions, plugins: [waveLabelsPlugin], data: { datasets: [] }
});
const fieldOptions = baseOptions();
fieldOptions.scales.y.title.text = 'Electric field (a.u.)';
fieldOptions.plugins.legend.labels.filter = item => item.datasetIndex !== 2 && !item.hidden;
charts.sumCosines = new Chart(byId('sumCosinesChart'), {
type: 'line', options: fieldOptions, data: { datasets: [
dataset('E(t)', '#e15d64'),
dataset('±|F(t)| envelope', '#d99a9f', { borderDash: [5, 5], borderWidth: 1.4, fill: '+1', backgroundColor: '#e15d640b' }),
dataset('Lower envelope', '#d99a9f', { borderDash: [5, 5], borderWidth: 1.4 })
] }
});
const intensityOptions = baseOptions();
intensityOptions.scales.y.title.text = 'Intensity (a.u.)';
intensityOptions.scales.y.min = 0;
charts.sumIntensity = new Chart(byId('sumIntensityChart'), {
type: 'line', options: intensityOptions, data: { datasets: [
dataset('|F(t)|²', '#8b68c9', { fill: 'origin', backgroundColor: gradientFill('#8b68c9') }),
dataset('Instantaneous E(t)²', '#c396d2', { borderWidth: 1, hidden: true })
] }
});
const frequencyOptions = baseOptions();
frequencyOptions.scales.y.title.text = 'ωinst (rad / time unit)';
charts.instantaneousFrequency = new Chart(byId('instantaneousFrequencyChart'), {
type: 'line', options: frequencyOptions, data: { datasets: [
dataset('ωinst(t)', '#167e88', { spanGaps: false }),
dataset('Reference ω₀', '#94a3b8', { borderDash: [5, 5], borderWidth: 1 })
] }
});
}
function initializeCustomSpectrum() {
const p = readParameters();
// Capture full Gaussian support even when its tails lie outside the view.
const radius = p.bandwidth * Math.sqrt(-Math.log(PulseMath.AMPLITUDE_CUTOFF) / (2 * Math.LN2));
const min = Math.max(0, Math.min(axes.omegaMin, p.center - radius));
const max = Math.max(axes.omegaMax, p.center + radius);
const frequencies = [...new Set([...PulseMath.linspace(min, max, 25),
...PulseMath.linspace(Math.max(0, p.center - radius), p.center + radius, 49)])].sort((a, b) => a - b);
customSpectrumDataPoints = frequencies.map(x => ({ x, y: PulseMath.gaussian(x, p.center, p.bandwidth) }));
}
function updateModeControls() {
const custom = currentSpectrumMode === 'custom';
const auto = custom && byId('autoOmega0Custom').checked;
byId('gaussianControls').hidden = custom;
byId('resetCustomSpectrumButton').hidden = !custom;
byId('customSpectrumHelpText').hidden = !custom;
byId('autoOmega0Group').hidden = !custom;
byId('omega0_custom_note').hidden = !custom;
sliders.omega0.disabled = auto;
numberInputs.omega0.disabled = auto;
byId('omega0SliderGroup').classList.toggle('disabled-group', auto);
}
function syncAxisInputs() {
Object.keys(axes).forEach(key => { byId(key).value = axes[key]; });
syncTimeInputs();
}
function syncTimeInputs() {
for (const key of ['timeMin', 'timeMax']) {
byId(key).value = byId('autoTimeLimits').checked ? Number(axes[key].toPrecision(6)) : axes[key];
byId(key).disabled = byId('autoTimeLimits').checked;
}
byId('timeLimitsHint').textContent = byId('autoTimeLimits').checked
? 'Fits the pulse when frequency limits or ω₀ change; other controls keep this view fixed.'
: 'Time limits apply to all four time plots.';
}
function syncCentralFrequencyLimits() {
const current = Number(sliders.omega0.value);
sliders.omega0.min = Math.min(axes.omegaMin, current);
sliders.omega0.max = Math.max(axes.omegaMax, current);
sliders.omega0.value = current;
}
function setSliderValue(key, value) {
const slider = sliders[key];
const min = Number(slider.min), max = Number(slider.max);
if (value < min || value > max) {
const halfSpan = Math.max((max - min) / 2, Math.abs(value) / 2, 0.1);
let lower = value - halfSpan;
if (key === 'omega0') lower = Math.max(0, lower);
if (key === 'delta_omega') lower = Math.max(value * 0.1, lower);
slider.min = lower;
slider.max = value + halfSpan;
}
slider.value = value;
numberInputs[key].value = slider.value;
}
function recenterFrequencyAxis(center) {
const width = axes.omegaMax - axes.omegaMin;
axes.omegaMin = Math.max(0, center - width / 2);
axes.omegaMax = axes.omegaMin + width;
byId('omegaMin').value = axes.omegaMin;
byId('omegaMax').value = axes.omegaMax;
byId('axisError').textContent = '';
}
function applyAxisInputs(event) {
event.preventDefault();
const proposed = Object.fromEntries(Object.keys(axes).map(key => [key, byId(key).valueAsNumber]));
if (byId('autoTimeLimits').checked) Object.assign(proposed, { timeMin: axes.timeMin, timeMax: axes.timeMax });
const valid = Object.values(proposed).every(Number.isFinite) && proposed.omegaMin >= 0
&& proposed.omegaMax > proposed.omegaMin && proposed.timeMax > proposed.timeMin;
byId('axisError').textContent = valid ? '' : 'Use minimum < maximum, and an angular frequency minimum of zero or more.';
if (!valid) return;
axes = proposed;
if (!byId('autoTimeLimits').checked) manualTimeBounds = { timeMin: axes.timeMin, timeMax: axes.timeMax };
syncCentralFrequencyLimits();
requestPlotUpdate();
}
// Fit the shared time axis around the pulse, using the same rule as automatic limits.
function fitTimeAxis() {
const p = readParameters();
let bounds;
try {
bounds = PulseMath.automaticTimeBounds(p);
} catch (error) {
byId('axisError').textContent = error.message;
return;
}
Object.assign(axes, bounds);
manualTimeBounds = { timeMin: axes.timeMin, timeMax: axes.timeMax };
// Automatic limits already match this fit, so they should not redo it.
lastAutoTimeFrequency = JSON.stringify([axes.omegaMin, axes.omegaMax, p.center]);
syncTimeInputs();
byId('axisError').textContent = '';
requestPlotUpdate();
}
function setupControls() {
parameterKeys.forEach(key => {
// Number boxes are open-ended; range sliders adapt without quantizing input.
sliders[key].step = 'any';
numberInputs[key].step = 'any';
numberInputs[key].removeAttribute('min');
numberInputs[key].removeAttribute('max');
sliders[key].addEventListener('input', requestPlotUpdate);
numberInputs[key].addEventListener('input', () => numberInputs[key].setCustomValidity(''));
numberInputs[key].addEventListener('change', () => {
const value = numberInputs[key].valueAsNumber;
const error = !Number.isFinite(value) ? 'Enter a finite number.'
: key === 'delta_omega' && value <= 0 ? 'Bandwidth must be greater than zero.'
: key === 'omega0' && value < 0 ? 'Angular frequency cannot be negative.' : '';
numberInputs[key].setCustomValidity(error);
if (error) { numberInputs[key].reportValidity(); return; }
const previousValue = Number(sliders[key].value);
setSliderValue(key, value);
if (key === 'omega0' && value !== previousValue) recenterFrequencyAxis(value);
requestPlotUpdate();
});
});
['showPeakConnector', 'showSpectralPhase', 'showEnvelopeE', 'showFieldSquared'].forEach(id => {
byId(id).addEventListener('change', requestPlotUpdate);
});
['gaussian', 'custom'].forEach(mode => {
byId(`${mode}ModeRadio`).addEventListener('change', () => {
if (!byId(`${mode}ModeRadio`).checked) return;
if (mode === 'custom' && !customSpectrumDataPoints.length) initializeCustomSpectrum();
currentSpectrumMode = mode;
updateModeControls();
requestPlotUpdate();
});
});
byId('autoOmega0Custom').addEventListener('change', () => { updateModeControls(); requestPlotUpdate(); });
byId('resetCustomSpectrumButton').addEventListener('click', () => {
customSpectrumDataPoints.forEach(point => { point.y = 0; });
requestPlotUpdate();
});
byId('axisControls').addEventListener('submit', applyAxisInputs);
byId('autoTimeLimits').addEventListener('change', () => {
if (byId('autoTimeLimits').checked) {
manualTimeBounds = { timeMin: axes.timeMin, timeMax: axes.timeMax };
lastAutoTimeFrequency = null;
}
else Object.assign(axes, manualTimeBounds);
syncTimeInputs();
byId('axisError').textContent = '';
requestPlotUpdate();
});
byId('resetAxes').addEventListener('click', () => {
axes = { ...DEFAULT_AXES };
manualTimeBounds = { timeMin: DEFAULT_AXES.timeMin, timeMax: DEFAULT_AXES.timeMax };
lastAutoTimeFrequency = null;
syncCentralFrequencyLimits();
syncAxisInputs();
byId('axisError').textContent = '';
requestPlotUpdate();
});
byId('fitSpectrum').addEventListener('click', () => {
const p = readParameters();
const bounds = p.mode === 'custom' && p.points.length ? [p.points[0].x, p.points[p.points.length - 1].x]
: [p.center - 2 * p.bandwidth, p.center + 2 * p.bandwidth];
axes.omegaMin = Math.max(0, bounds[0]); axes.omegaMax = Math.max(axes.omegaMin + 0.1, bounds[1]);
syncCentralFrequencyLimits();
syncAxisInputs();
byId('axisError').textContent = '';
requestPlotUpdate();
});
byId('fitTime').addEventListener('click', fitTimeAxis);
}
function setupSpectrumDragging() {
const canvas = byId('spectrumChart');
let drag = null;
function position(event) {
const rect = canvas.getBoundingClientRect();
return { x: (event.clientX - rect.left) * charts.spectrumAndPhase.width / rect.width,
y: (event.clientY - rect.top) * charts.spectrumAndPhase.height / rect.height };
}
canvas.addEventListener('pointerdown', event => {
if (currentSpectrumMode !== 'custom') return;
const { x, y } = position(event), chart = charts.spectrumAndPhase;
let nearest = null, distance = 16;
customSpectrumDataPoints.forEach(point => {
if (point.x < axes.omegaMin || point.x > axes.omegaMax) return;
const dx = x - chart.scales.x.getPixelForValue(point.x);
const dy = y - chart.scales.yS.getPixelForValue(point.y);
const candidate = Math.hypot(dx, dy);
if (candidate < distance) { distance = candidate; nearest = point; }
});
if (!nearest) return;
drag = { point: nearest, offset: y - chart.scales.yS.getPixelForValue(nearest.y) };
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = 'grabbing';
event.preventDefault();
});
canvas.addEventListener('pointermove', event => {
if (!drag) return;
drag.point.y = Math.max(0, Math.min(1.1, charts.spectrumAndPhase.scales.yS.getValueForPixel(position(event).y - drag.offset)));
requestPlotUpdate();
});
function endDrag() { drag = null; canvas.style.cursor = 'default'; }
canvas.addEventListener('pointerup', endDrag);
canvas.addEventListener('pointercancel', endDrag);
canvas.addEventListener('lostpointercapture', endDrag);
}
byId('copyrightYear').textContent = new Date().getFullYear();
initCharts();
setupControls();
setupSpectrumDragging();
syncCentralFrequencyLimits();
syncAxisInputs();
updateModeControls();
updatePlots();