-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathfourier.html
189 lines (170 loc) · 8.05 KB
/
fourier.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1D Signal Generator and FFT Demo</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<h2>1D Signal Generator and FFT Demo</h2>
<div>
<label for="numFrequencies">Number of Frequencies: </label>
<input type="number" id="numFrequencies" min="1" max="10" value="3">
<button onclick="generateInputFields()">Set Frequencies</button>
</div>
<div id="frequencyControls"></div>
<button onclick="generateSignal()">Generate Signal</button>
<div>
<label for="magnitudeThreshold">Magnitude Threshold: </label>
<input type="number" id="magnitudeThreshold" step="0.0001" value="0.001" oninput="generateSignal()">
</div>
<div id="individualSignalsPlot"></div>
<div id="signalPlot"></div>
<div id="fftMagnitudePlot"></div>
<div id="fftPhasePlot"></div>
<script>
// Generate input fields for frequency, amplitude, and phase controls
function generateInputFields() {
const numFrequencies = parseInt(document.getElementById("numFrequencies").value);
const frequencyControls = document.getElementById("frequencyControls");
frequencyControls.innerHTML = '';
for (let i = 1; i <= numFrequencies; i++) {
frequencyControls.innerHTML += `
<h4>Frequency ${i}</h4>
<label>Amplitude:</label>
<input type="number" id="amplitude${i}" step="0.1" value="1" oninput="generateSignal()">
<label>Phase (degrees):</label>
<input type="number" id="phase${i}" step="1" value="0" oninput="generateSignal()">
<label>Frequency:</label>
<input type="number" id="frequency${i}" step="1" value="${i}" oninput="generateSignal()">
<br>
`;
}
}
// Function to generate and plot the signal, FFT magnitude, and phase
function generateSignal() {
const numFrequencies = parseInt(document.getElementById("numFrequencies").value);
const sampleRate = 256;
const time = [...Array(sampleRate).keys()].map(i => i / sampleRate);
let signal = Array(sampleRate).fill(0);
let individualSignals = [];
// Build the signal by summing cosines and store individual components
for (let i = 1; i <= numFrequencies; i++) {
const amplitude = parseFloat(document.getElementById(`amplitude${i}`).value);
const phase = parseFloat(document.getElementById(`phase${i}`).value) * Math.PI / 180; // Convert to radians
const frequency = parseFloat(document.getElementById(`frequency${i}`).value);
let componentSignal = [];
for (let j = 0; j < sampleRate; j++) {
const value = amplitude * Math.cos(2 * Math.PI * frequency * time[j] + phase);
signal[j] += value;
componentSignal.push(value);
}
individualSignals.push({ time, y: componentSignal, name: `Freq ${frequency} Hz` });
}
plotIndividualSignals(individualSignals);
plotSignal(time, signal);
computeAndPlotFFT(signal, sampleRate);
}
// Plot individual frequency components
function plotIndividualSignals(individualSignals) {
const traces = individualSignals.map(({ time, y, name }) => ({
x: time,
y,
mode: 'lines',
name
}));
const layout = {
title: 'Individual Frequency Components',
xaxis: { title: 'Time' },
yaxis: { title: 'Amplitude' }
};
Plotly.newPlot('individualSignalsPlot', traces, layout);
}
// Plot the combined signal
function plotSignal(time, signal) {
const trace = {
x: time,
y: signal,
mode: 'lines',
name: 'Combined Signal'
};
const layout = {
title: 'Generated Signal',
xaxis: { title: 'Time' },
yaxis: { title: 'Amplitude' }
};
Plotly.newPlot('signalPlot', [trace], layout);
}
// Compute FFT, adjust frequency range and plot magnitude and phase
function computeAndPlotFFT(signal, sampleRate) {
const fft = fftReal(signal);
const N = signal.length;
const halfN = Math.floor(N / 2);
// Normalize magnitude and adjust phase to -180 to 180
const magnitude = fft.map(z => (2 / N) * Math.sqrt(z[0] ** 2 + z[1] ** 2));
const phase = fft.map(z => {
let angle = Math.atan2(z[1], z[0]) * (180 / Math.PI); // Convert phase to degrees
if (angle > 180) angle -= 360; // Wrap phase to -180 to 180
return angle;
});
// Adjust frequency range to [-fs/2, fs/2]
const freq = Array.from({ length: N }, (_, i) => (i - halfN) * sampleRate / N);
const shiftedMagnitude = [...magnitude.slice(halfN), ...magnitude.slice(0, halfN)];
const shiftedPhase = [...phase.slice(halfN), ...phase.slice(0, halfN)];
const magnitudeThreshold = parseFloat(document.getElementById("magnitudeThreshold").value);
// Plot FFT magnitude with circles on endpoints of significant frequencies
const magnitudeLineTrace = {
x: freq,
y: shiftedMagnitude,
mode: 'lines',
name: 'FFT Magnitude'
};
const magnitudeCirclesTrace = {
x: freq.filter((_, i) => shiftedMagnitude[i] > magnitudeThreshold),
y: shiftedMagnitude.filter(value => value > magnitudeThreshold),
mode: 'markers',
marker: { symbol: 'circle', size: 8 },
name: 'Significant Magnitudes'
};
const magnitudeLayout = {
title: 'FFT Magnitude (Centered)',
xaxis: { title: 'Frequency (Hz)' },
yaxis: { title: 'Magnitude' }
};
Plotly.newPlot('fftMagnitudePlot', [magnitudeLineTrace, magnitudeCirclesTrace], magnitudeLayout);
// Plot FFT phase only for significant frequencies, but keep full x-axis range
const significantPhases = shiftedPhase.map((value, i) => shiftedMagnitude[i] > magnitudeThreshold ? value : null); // Set non-significant phases to null
const phaseTrace = {
x: freq,
y: significantPhases,
mode: 'markers+lines',
marker: { symbol: 'circle', size: 8 },
name: 'FFT Phase (Significant)'
};
const phaseLayout = {
title: 'FFT Phase (Degrees, Significant)',
xaxis: { title: 'Frequency (Hz)' },
yaxis: { title: 'Phase (degrees)', range: [-180, 180] }
};
Plotly.newPlot('fftPhasePlot', [phaseTrace], phaseLayout);
}
// FFT implementation using DFT
function fftReal(signal) {
const N = signal.length;
const result = [];
for (let k = 0; k < N; k++) {
let real = 0;
let imag = 0;
for (let n = 0; n < N; n++) {
const angle = (2 * Math.PI * k * n) / N;
real += signal[n] * Math.cos(angle);
imag -= signal[n] * Math.sin(angle);
}
result.push([real, imag]);
}
return result;
}
</script>
</body>
</html>