«GUI: Time-domain continuous vs sampled signals, and FFT representation» by jamshark70

on 14 Aug'19 05:32 in guitheorynyquistfourieroversamplingteachingfft

Here's a demo I cooked up for a synthesis theory class. Textbooks say that the Nyquist theorem proves there is one only one way to draw a band-limited continuous signal through a set of samples. This GUI lets you see it for yourself.

In the multislider for the samples, you can set the sample values arbitrarily and watch the 16x oversampled curve change. (Set only one point, all others 0, and you see a band-limited impulse AKA sinc function. Or, you can programmatically put in a geometrically perfect sawtooth or pulse wave, and see the Gibbs effect.)

Or you can adjust the cosine partials' magnitudes and phases directly.

And, turn up the volume and listen to the wavetable.

If you read the code, you can pick up a lot of tricks for manipulating FFT data on the client side. For instance, I'm doing the 16x oversampling by expanding a 32-point FFT out to 512 points (inserting zeros in the middle, so that the 12th partial is still the 12th partial). The trick that wasn't obvious at first is that the phases of the top half of an FFT (the frequency-aliased mirror image) are inverted. Tricks like that.

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
(
s.waitForBoot {
	var size = 32, oversampling = 16,
	fftCosTable = Signal.fftCosTable(size),
	bigCosTable = Signal.fftCosTable(size * oversampling);
	var data;
	var userView, sampleView, spectrumLayouts, spectrumViews;

	// [DC, bin1, bin2, nyquist]
	// --> [DC, bin1, bin2, nyquist, 0, 0, 0, nyquist, bin2, bin1]
	var mirrorExpandArray = { |array, outSize|
		array.extend(outSize div: 2 + 1, 0).foldExtend(outSize)
	};
	var ifft = { |polar, outSize(size * oversampling)|
		var halfSize = size div: 2,
		halfExpanded = outSize div: 2,
		factor = outSize / size,
		rho, expanded,
		table = case
		{ factor == 1 } { fftCosTable }
		{ factor == oversampling } { bigCosTable }
		{ Signal.fftCosTable(outSize) };
		rho = mirrorExpandArray.(polar.rho[0 .. halfSize] * factor, outSize);
		// if factor > 1, then the nyquist bin is copied by foldExtend
		// but the base fft does not copy -- so the expanded one is doubling it, we must halve it
		// if factor <= 1, nyquist is not doubled so leave it alone
		if(factor > 1.0) {
			rho[halfSize] = rho[halfSize] * 0.5;
			rho[outSize - halfSize] = rho[halfSize];
		};
		expanded = Polar(
			rho,
			// mirror image should invert the phases
			// 'lace' takes all the first elements, then all the second elements
			// so you get first half = 1, second half = -1
			// doesn't this mess with Nyquist? No...
			// Nyquist phase must be one of 0, pi or -pi.
			// 0.0 * -1 = 0.0, no problem
			// cos(k * theta - pi) == cos(k * theta + pi) so again, no problem
			Array.fill(halfExpanded, [1, -1]).lace(outSize)
			* mirrorExpandArray.(polar.theta[0 .. halfSize], outSize)
		).asComplex;
		expanded.real.as(Signal).ifft(expanded.imag.as(Signal), table)
		.real
	};

	var showSpectrum = { |polar|
		spectrumViews.do { |column, i|
			column[0].value = polar.rho[i] / size * 2;
			column[1].value = polar.theta[i] / 2pi + 0.5;
		};
	};

	var buffer = Buffer.alloc(s, size * oversampling * 2, 1), synth, ampSlider, freqSlider;

	z = size;  // data size, make available outside

	// data/fft interface, available outside
	e = data = (
		data: nil,
		data_: { |self, array|
			if(array.size == size) {
				self[\data] = array.as(Signal);
				self[\fft] = self[\data].fft(
					Signal.newClear(array.size),
					fftCosTable
				).asPolar;
				self[\expanded] = ifft.(self[\fft], size * oversampling);
				self.changed(\data);
			} {
				Error("Container got % values, expected %".format(array.size, size)).throw;
			};
			self
		},
		fft_: { |self, polar|
			self[\fft] = polar;
			self[\data] = ifft.(polar, size);
			self[\expanded] = ifft.(polar, size * oversampling);
			self.changed(\data);
		},
	);

	data.data = Array.fill(size, 0);

	w = Window("Signal lab", Rect.aboutPoint(Window.screenBounds.center, 400, 300));
	w.layout = VLayout(
		HLayout(
			StaticText().fixedWidth_(50).align_(\center).string_("amp:"),
			ampSlider = Slider().orientation_(\horizontal).fixedHeight_(24),
			StaticText().fixedWidth_(50).align_(\center).string_("freq:"),
			freqSlider = Slider().orientation_(\horizontal).fixedHeight_(24)
		),
		StackLayout(
			sampleView = MultiSliderView(),
			userView = UserView()
		).mode_(\stackAll),
		HLayout(*(
			spectrumLayouts = Array.fill(size div: 2 + 1, {
				VLayout().spacing_(2)
			})
		)).spacing_(2)
	);

	spectrumViews = Array.fill(spectrumLayouts.size, { |i|
		var out = [
			Slider().action_({ |view|
				var rho = data[\fft].rho;
				rho[i] = view.value * size * 0.5;
				if(i.inclusivelyBetween(1, size div: 2 - 1)) {
					rho[size - i] = rho[i];
				};
				data.fft = Polar(rho, data[\fft].theta);
			}),
			Knob().mode_(\vert).action_({ |view|
				var theta = data[\fft].theta;
				theta[i] = (view.value - 0.5) * 2pi;
				if(i.inclusivelyBetween(1, size div: 2 - 1)) {
					theta[size - i] = theta[i].neg;
				};
				data.fft = Polar(data[\fft].rho, theta);
			}),
			StaticText().fixedHeight_(18).string_("k=" ++ i).align_(\center)
		];
		out.do { |view| spectrumLayouts[i].add(view) };
		out
	});

	userView
	.background_(Color.white)
	.drawFunc_({ |view|
		var extent = view.bounds.extent,
		hardcodedMultiSliderMargin = 6,  // don't change this
		xSize = extent.x, ySize = extent.y - hardcodedMultiSliderMargin - sampleView.valueThumbSize,
		bigSize = size * oversampling,
		xWidth = (xSize - hardcodedMultiSliderMargin) / bigSize,
		adjustment = ((xSize - hardcodedMultiSliderMargin) / size + hardcodedMultiSliderMargin) * 0.5,
		yAdjustment = (hardcodedMultiSliderMargin + sampleView.valueThumbSize) * 0.5,
		polar = data[\fft],
		halfSize = size div: 2,
		timeDomain,
		unmapX = { |x|
			((x - adjustment) / xWidth) % bigSize
		},
		mapY = { |y|
			(0.5 - (0.5 * y)) * ySize + yAdjustment
		},
		// new func: x is horizontal view position
		mapPoint = { |x|
			Point(x, mapY.(timeDomain.blendAt(unmapX.(x), \wrapAt)))
		};

		timeDomain = data[\expanded];

		Pen.moveTo(mapPoint.(hardcodedMultiSliderMargin div: 2));
		(hardcodedMultiSliderMargin div: 2 .. xSize - (hardcodedMultiSliderMargin div: 2)).do { |x|
			Pen.lineTo(mapPoint.(x))
		};
		Pen.stroke;
	});

	sampleView.background_(Color(1, 1, 1, 0))  // Color.clear has a bug
	.fillColor_(Color.black).strokeColor_(Color.black)
	.elasticMode_(true)
	.drawRects_(true).drawLines_(false)
	.thumbSize_(8)
	.gap_(0)
	.value_(data[\data] * 0.5 + 0.5)
	.action_({ |view|
		data.data = view.value * 2 - 1;
		showSpectrum.(data[\fft]);
	});

	data.addDependant {
		sampleView.value = data[\data] * 0.5 + 0.5;
		showSpectrum.(data[\fft]);
		buffer.setn(0, data[\expanded].as(Signal).asWavetable);
		userView.refresh;
	};

	data.changed(\data);  // force refresh all views

	w.onClose = { data.releaseDependants; synth.release; buffer.free };

	w.front;

	synth = { |bufnum, freq = 100, amp = 0|
		(Osc.ar(bufnum, freq) * amp).dup
	}.play(args: [bufnum: buffer]);

	freqSlider.value_(100.explin(5, 500, 0, 1))
	.action_({ |view| synth.set(\freq, view.value.linexp(0, 1, 5, 500)) });

	ampSlider.value_(0)
	.action_({ |view| synth.set(\amp, view.value.lincurve(0, 1, 0, 1, 3)) });

	~ifft = ifft;
};
)

// programmatic manipulation
// e is the data object; z is number of samples

// set sample points directly
e.data = Array.fill(z, { |i| i.linlin(0, z, 0.8, -0.8) });  // saw
e.data = Array.fill(z div: 2, [0.7, -0.7]).lace(z);  // square
e.data = Array.fill(z, 0);  // clear

e.data = Array.fill(z, 0).put(z div: 2, 0.707);  // positive pulse
e.data = Array.fill(z, 0).put(z div: 2, -0.707);  // negative: watch phases!

e.data = Array.fill(z, { 0.5.rand2 });  // noise

// randomize phases
e.fft = Polar(e.fft.rho, Array.fill(z div: 2 + 1, { rrand(-pi, pi) }).foldExtend(z) * Array.fill(z div: 2, [1, -1]).lace(z));

// H. James Harkins, 8/2019, CC-NC-BY-SA
raw 6906 chars (focus & ctrl+a+c to copy)
reception
comments