-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththinkdsp.py
1951 lines (1425 loc) · 47.4 KB
/
thinkdsp.py
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This file contains code used in "Think DSP",
by Allen B. Downey, available from greenteapress.com
Copyright 2013 Allen B. Downey
License: MIT License (https://opensource.org/licenses/MIT)
"""
import copy
import math
import numpy as np
import random
import scipy
import scipy.stats
import scipy.fftpack
import subprocess
import warnings
from wave import open as open_wave
from scipy.io import wavfile
import matplotlib.pyplot as plt
try:
from IPython.display import Audio
except ImportError:
warnings.warn(
"Can't import Audio from IPython.display; " "Wave.make_audio() will not work."
)
PI2 = math.pi * 2
def random_seed(x):
"""Initialize the random and np.random generators.
x: int seed
"""
random.seed(x)
np.random.seed(x)
class UnimplementedMethodException(Exception):
"""Exception if someone calls a method that should be overridden."""
class WavFileWriter:
"""Writes wav files."""
def __init__(self, filename="sound.wav", framerate=11025):
"""Opens the file and sets parameters.
filename: string
framerate: samples per second
"""
self.filename = filename
self.framerate = framerate
self.nchannels = 1
self.sampwidth = 2
self.bits = self.sampwidth * 8
self.bound = 2 ** (self.bits - 1) - 1
self.fmt = "h"
self.dtype = np.int16
self.fp = open_wave(self.filename, "w")
self.fp.setnchannels(self.nchannels)
self.fp.setsampwidth(self.sampwidth)
self.fp.setframerate(self.framerate)
def write(self, wave):
"""Writes a wave.
wave: Wave
"""
zs = wave.quantize(self.bound, self.dtype)
self.fp.writeframes(zs.tostring())
def close(self, duration=0):
"""Closes the file.
duration: how many seconds of silence to append
"""
if duration:
self.write(rest(duration))
self.fp.close()
def read_wave(filename="sound.wav"):
"""Reads a wave file.
filename: string
returns: Wave
"""
fp = open_wave(filename, "r")
nchannels = fp.getnchannels()
nframes = fp.getnframes()
sampwidth = fp.getsampwidth()
framerate = fp.getframerate()
z_str = fp.readframes(nframes)
fp.close()
dtype_map = {1: np.int8, 2: np.int16, 3: "special", 4: np.int32}
if sampwidth not in dtype_map:
raise ValueError("sampwidth %d unknown" % sampwidth)
if sampwidth == 3:
xs = np.fromstring(z_str, dtype=np.int8).astype(np.int32)
ys = (xs[2::3] * 256 + xs[1::3]) * 256 + xs[0::3]
else:
ys = np.fromstring(z_str, dtype=dtype_map[sampwidth])
# if it's in stereo, just pull out the first channel
if nchannels == 2:
ys = ys[::2]
# ts = np.arange(len(ys)) / framerate
wave = Wave(ys, framerate=framerate)
wave.normalize()
return wave
def read_wave_with_scipy(filename):
"""Reads a wave file.
filename: string
returns: Wave
"""
# TODO: Check back later and see if this works on 24-bit data,
# and runs without throwing warnings.
framerate, ys = wavfile.read(filename)
# if it's in stereo, just pull out the first channel
if ys.ndim == 2:
ys = ys[:, 0]
# ts = np.arange(len(ys)) / framerate
wave = Wave(ys, framerate=framerate)
wave.normalize()
return wave
def play_wave(filename="sound.wav", player="aplay"):
"""Plays a wave file.
filename: string
player: string name of executable that plays wav files
"""
cmd = "%s %s" % (player, filename)
popen = subprocess.Popen(cmd, shell=True)
popen.communicate()
def find_index(x, xs):
"""Find the index corresponding to a given value in an array."""
n = len(xs)
start = xs[0]
end = xs[-1]
i = round((n - 1) * (x - start) / (end - start))
return int(i)
class _SpectrumParent:
"""Contains code common to Spectrum and DCT."""
def __init__(self, hs, fs, framerate, full=False):
"""Initializes a spectrum.
hs: array of amplitudes (real or complex)
fs: array of frequencies
framerate: frames per second
full: boolean to indicate full or real FFT
"""
self.hs = np.asanyarray(hs)
self.fs = np.asanyarray(fs)
self.framerate = framerate
self.full = full
@property
def max_freq(self):
"""Returns the Nyquist frequency for this spectrum."""
return self.framerate / 2
@property
def amps(self):
"""Returns a sequence of amplitudes (read-only property)."""
return np.absolute(self.hs)
@property
def power(self):
"""Returns a sequence of powers (read-only property)."""
return self.amps**2
def copy(self):
"""Makes a copy.
Returns: new Spectrum
"""
return copy.deepcopy(self)
def max_diff(self, other):
"""Computes the maximum absolute difference between spectra.
other: Spectrum
returns: float
"""
assert self.framerate == other.framerate
assert len(self) == len(other)
hs = self.hs - other.hs
return np.max(np.abs(hs))
def ratio(self, denom, thresh=1, val=0):
"""The ratio of two spectrums.
denom: Spectrum
thresh: values smaller than this are replaced
val: with this value
returns: new Wave
"""
ratio_spectrum = self.copy()
ratio_spectrum.hs /= denom.hs
ratio_spectrum.hs[denom.amps < thresh] = val
return ratio_spectrum
def invert(self):
"""Inverts this spectrum/filter.
returns: new Wave
"""
inverse = self.copy()
inverse.hs = 1 / inverse.hs
return inverse
@property
def freq_res(self):
return self.framerate / 2 / (len(self.fs) - 1)
def render_full(self, high=None):
"""Extracts amps and fs from a full spectrum.
high: cutoff frequency
returns: fs, amps
"""
hs = np.fft.fftshift(self.hs)
amps = np.abs(hs)
fs = np.fft.fftshift(self.fs)
i = 0 if high is None else find_index(-high, fs)
j = None if high is None else find_index(high, fs) + 1
return fs[i:j], amps[i:j]
def plot(self, high=None, **options):
"""Plots amplitude vs frequency.
Note: if this is a full spectrum, it ignores low and high
high: frequency to cut off at
"""
if self.full:
fs, amps = self.render_full(high)
plt.plot(fs, amps, **options)
else:
i = None if high is None else find_index(high, self.fs)
plt.plot(self.fs[:i], self.amps[:i], **options)
def plot_power(self, high=None, **options):
"""Plots power vs frequency.
high: frequency to cut off at
"""
if self.full:
fs, amps = self.render_full(high)
plt.plot(fs, amps**2, **options)
else:
i = None if high is None else find_index(high, self.fs)
plt.plot(self.fs[:i], self.power[:i], **options)
def estimate_slope(self):
"""Runs linear regression on log power vs log frequency.
returns: slope, inter, r2, p, stderr
"""
x = np.log(self.fs[1:])
y = np.log(self.power[1:])
t = scipy.stats.linregress(x, y)
return t
def peaks(self):
"""Finds the highest peaks and their frequencies.
returns: sorted list of (amplitude, frequency) pairs
"""
t = list(zip(self.amps, self.fs))
t.sort(reverse=True)
return t
class Spectrum(_SpectrumParent):
"""Represents the spectrum of a signal."""
def __len__(self):
"""Length of the spectrum."""
return len(self.hs)
def __add__(self, other):
"""Adds two spectrums elementwise.
other: Spectrum
returns: new Spectrum
"""
if other == 0:
return self.copy()
assert all(self.fs == other.fs)
hs = self.hs + other.hs
return Spectrum(hs, self.fs, self.framerate, self.full)
__radd__ = __add__
def __mul__(self, other):
"""Multiplies two spectrums elementwise.
other: Spectrum
returns: new Spectrum
"""
assert all(self.fs == other.fs)
hs = self.hs * other.hs
return Spectrum(hs, self.fs, self.framerate, self.full)
def convolve(self, other):
"""Convolves two Spectrums.
other: Spectrum
returns: Spectrum
"""
assert all(self.fs == other.fs)
if self.full:
hs1 = np.fft.fftshift(self.hs)
hs2 = np.fft.fftshift(other.hs)
hs = np.convolve(hs1, hs2, mode="same")
hs = np.fft.ifftshift(hs)
else:
# not sure this branch would mean very much
hs = np.convolve(self.hs, other.hs, mode="same")
return Spectrum(hs, self.fs, self.framerate, self.full)
@property
def real(self):
"""Returns the real part of the hs (read-only property)."""
return np.real(self.hs)
@property
def imag(self):
"""Returns the imaginary part of the hs (read-only property)."""
return np.imag(self.hs)
@property
def angles(self):
"""Returns a sequence of angles (read-only property)."""
return np.angle(self.hs)
def scale(self, factor):
"""Multiplies all elements by the given factor.
factor: what to multiply the magnitude by (could be complex)
"""
self.hs *= factor
def low_pass(self, cutoff, factor=0):
"""Attenuate frequencies above the cutoff.
cutoff: frequency in Hz
factor: what to multiply the magnitude by
"""
self.hs[abs(self.fs) > cutoff] *= factor
def high_pass(self, cutoff, factor=0):
"""Attenuate frequencies below the cutoff.
cutoff: frequency in Hz
factor: what to multiply the magnitude by
"""
self.hs[abs(self.fs) < cutoff] *= factor
def band_stop(self, low_cutoff, high_cutoff, factor=0):
"""Attenuate frequencies between the cutoffs.
low_cutoff: frequency in Hz
high_cutoff: frequency in Hz
factor: what to multiply the magnitude by
"""
# TODO: test this function
fs = abs(self.fs)
indices = (low_cutoff < fs) & (fs < high_cutoff)
self.hs[indices] *= factor
def pink_filter(self, beta=1):
"""Apply a filter that would make white noise pink.
beta: exponent of the pink noise
"""
denom = self.fs ** (beta / 2.0)
denom[0] = 1
self.hs /= denom
def differentiate(self):
"""Apply the differentiation filter.
returns: new Spectrum
"""
new = self.copy()
new.hs *= PI2 * 1j * new.fs
return new
def integrate(self):
"""Apply the integration filter.
returns: new Spectrum
"""
new = self.copy()
zero = new.fs == 0
new.hs[~zero] /= PI2 * 1j * new.fs[~zero]
new.hs[zero] = np.inf
return new
def make_integrated_spectrum(self):
"""Makes an integrated spectrum."""
cs = np.cumsum(self.power)
cs /= cs[-1]
return IntegratedSpectrum(cs, self.fs)
def make_wave(self):
"""Transforms to the time domain.
returns: Wave
"""
if self.full:
ys = np.fft.ifft(self.hs)
else:
ys = np.fft.irfft(self.hs)
# NOTE: whatever the start time was, we lose it when
# we transform back; we could fix that by saving start
# time in the Spectrum
# ts = self.start + np.arange(len(ys)) / self.framerate
return Wave(ys, framerate=self.framerate)
class IntegratedSpectrum:
"""Represents the integral of a spectrum."""
def __init__(self, cs, fs):
"""Initializes an integrated spectrum:
cs: sequence of cumulative amplitudes
fs: sequence of frequencies
"""
self.cs = np.asanyarray(cs)
self.fs = np.asanyarray(fs)
def plot_power(self, low=0, high=None, expo=False, **options):
"""Plots the integrated spectrum.
low: int index to start at
high: int index to end at
"""
cs = self.cs[low:high]
fs = self.fs[low:high]
if expo:
cs = np.exp(cs)
plt.plot(fs, cs, **options)
def estimate_slope(self, low=1, high=-12000):
"""Runs linear regression on log cumulative power vs log frequency.
returns: slope, inter, r2, p, stderr
"""
# print self.fs[low:high]
# print self.cs[low:high]
x = np.log(self.fs[low:high])
y = np.log(self.cs[low:high])
t = scipy.stats.linregress(x, y)
return t
class Dct(_SpectrumParent):
"""Represents the spectrum of a signal using discrete cosine transform."""
@property
def amps(self):
"""Returns a sequence of amplitudes (read-only property).
Note: for DCTs, amps are positive or negative real.
"""
return self.hs
def __add__(self, other):
"""Adds two DCTs elementwise.
other: DCT
returns: new DCT
"""
if other == 0:
return self
assert self.framerate == other.framerate
hs = self.hs + other.hs
return Dct(hs, self.fs, self.framerate)
__radd__ = __add__
def make_wave(self):
"""Transforms to the time domain.
returns: Wave
"""
N = len(self.hs)
ys = scipy.fftpack.idct(self.hs, type=2) / 2 / N
# NOTE: whatever the start time was, we lose it when
# we transform back
# ts = self.start + np.arange(len(ys)) / self.framerate
return Wave(ys, framerate=self.framerate)
class Spectrogram:
"""Represents the spectrum of a signal."""
def __init__(self, spec_map, seg_length):
"""Initialize the spectrogram.
spec_map: map from float time to Spectrum
seg_length: number of samples in each segment
"""
self.spec_map = spec_map
self.seg_length = seg_length
def any_spectrum(self):
"""Returns an arbitrary spectrum from the spectrogram."""
index = next(iter(self.spec_map))
return self.spec_map[index]
@property
def time_res(self):
"""Time resolution in seconds."""
spectrum = self.any_spectrum()
return float(self.seg_length) / spectrum.framerate
@property
def freq_res(self):
"""Frequency resolution in Hz."""
return self.any_spectrum().freq_res
def times(self):
"""Sorted sequence of times.
returns: sequence of float times in seconds
"""
ts = sorted(iter(self.spec_map))
return ts
def frequencies(self):
"""Sequence of frequencies.
returns: sequence of float freqencies in Hz.
"""
fs = self.any_spectrum().fs
return fs
def plot(self, high=None, **options):
"""Make a pseudocolor plot.
high: highest frequency component to plot
"""
fs = self.frequencies()
i = None if high is None else find_index(high, fs)
fs = fs[:i]
ts = self.times()
# make the array
size = len(fs), len(ts)
array = np.zeros(size, dtype=float)
# copy amplitude from each spectrum into a column of the array
for j, t in enumerate(ts):
spectrum = self.spec_map[t]
array[:, j] = spectrum.amps[:i]
underride(options, cmap="inferno_r", shading="auto")
plt.pcolormesh(ts, fs, array, **options)
def get_data(self, high=None, **options):
"""Returns spectogram as 2D numpy array
high: highest frequency component to return
"""
fs = self.frequencies()
i = None if high is None else find_index(high, fs)
fs = fs[:i]
ts = self.times()
# make the array
size = len(fs), len(ts)
array = np.zeros(size, dtype=float)
# copy amplitude from each spectrum into a column of the array
for j, t in enumerate(ts):
spectrum = self.spec_map[t]
array[:, j] = spectrum.amps[:i]
return array
def make_wave(self):
"""Inverts the spectrogram and returns a Wave.
returns: Wave
"""
res = []
for t, spectrum in sorted(self.spec_map.items()):
wave = spectrum.make_wave()
n = len(wave)
window = 1 / np.hamming(n)
wave.window(window)
i = wave.find_index(t)
start = i - n // 2
end = start + n
res.append((start, end, wave))
starts, ends, waves = zip(*res)
low = min(starts)
high = max(ends)
ys = np.zeros(high - low, dtype=float)
for start, end, wave in res:
ys[start:end] = wave.ys
# ts = np.arange(len(ys)) / self.framerate
return Wave(ys, framerate=wave.framerate)
class Wave:
"""Represents a discrete-time waveform."""
def __init__(self, ys, ts=None, framerate=None):
"""Initializes the wave.
ys: wave array
ts: array of times
framerate: samples per second
"""
self.ys = np.asanyarray(ys)
self.framerate = framerate if framerate is not None else 11025
if ts is None:
self.ts = np.arange(len(ys)) / self.framerate
else:
self.ts = np.asanyarray(ts)
def copy(self):
"""Makes a copy.
Returns: new Wave
"""
return copy.deepcopy(self)
def __len__(self):
return len(self.ys)
@property
def start(self):
return self.ts[0]
@property
def end(self):
return self.ts[-1]
@property
def duration(self):
"""Duration (property).
returns: float duration in seconds
"""
return len(self.ys) / self.framerate
def __add__(self, other):
"""Adds two waves elementwise.
other: Wave
returns: new Wave
"""
if other == 0:
return self
assert self.framerate == other.framerate
# make an array of times that covers both waves
start = min(self.start, other.start)
end = max(self.end, other.end)
n = int(round((end - start) * self.framerate)) + 1
ys = np.zeros(n)
ts = start + np.arange(n) / self.framerate
def add_ys(wave):
i = find_index(wave.start, ts)
# make sure the arrays line up reasonably well
diff = ts[i] - wave.start
dt = 1 / wave.framerate
if (diff / dt) > 0.1:
warnings.warn(
"Can't add these waveforms; their " "time arrays don't line up."
)
j = i + len(wave)
ys[i:j] += wave.ys
add_ys(self)
add_ys(other)
return Wave(ys, ts, self.framerate)
__radd__ = __add__
def __or__(self, other):
"""Concatenates two waves.
other: Wave
returns: new Wave
"""
if self.framerate != other.framerate:
raise ValueError("Wave.__or__: framerates do not agree")
ys = np.concatenate((self.ys, other.ys))
# ts = np.arange(len(ys)) / self.framerate
return Wave(ys, framerate=self.framerate)
def __mul__(self, other):
"""Multiplies two waves elementwise.
Note: this operation ignores the timestamps; the result
has the timestamps of self.
other: Wave
returns: new Wave
"""
# the spectrums have to have the same framerate and duration
assert self.framerate == other.framerate
assert len(self) == len(other)
ys = self.ys * other.ys
return Wave(ys, self.ts, self.framerate)
def max_diff(self, other):
"""Computes the maximum absolute difference between waves.
other: Wave
returns: float
"""
assert self.framerate == other.framerate
assert len(self) == len(other)
ys = self.ys - other.ys
return np.max(np.abs(ys))
def convolve(self, other):
"""Convolves two waves.
Note: this operation ignores the timestamps; the result
has the timestamps of self.
other: Wave or NumPy array
returns: Wave
"""
if isinstance(other, Wave):
assert self.framerate == other.framerate
window = other.ys
else:
window = other
ys = np.convolve(self.ys, window, mode="full")
# ts = np.arange(len(ys)) / self.framerate
return Wave(ys, framerate=self.framerate)
def diff(self):
"""Computes the difference between successive elements.
returns: new Wave
"""
ys = np.diff(self.ys)
ts = self.ts[1:].copy()
return Wave(ys, ts, self.framerate)
def cumsum(self):
"""Computes the cumulative sum of the elements.
returns: new Wave
"""
ys = np.cumsum(self.ys)
ts = self.ts.copy()
return Wave(ys, ts, self.framerate)
def quantize(self, bound, dtype):
"""Maps the waveform to quanta.
bound: maximum amplitude
dtype: numpy data type or string
returns: quantized signal
"""
return quantize(self.ys, bound, dtype)
def apodize(self, denom=20, duration=0.1):
"""Tapers the amplitude at the beginning and end of the signal.
Tapers either the given duration of time or the given
fraction of the total duration, whichever is less.
denom: float fraction of the segment to taper
duration: float duration of the taper in seconds
"""
self.ys = apodize(self.ys, self.framerate, denom, duration)
def hamming(self):
"""Apply a Hamming window to the wave."""
self.ys *= np.hamming(len(self.ys))
def window(self, window):
"""Apply a window to the wave.
window: sequence of multipliers, same length as self.ys
"""
self.ys *= window
def scale(self, factor):
"""Multplies the wave by a factor.
factor: scale factor
"""
self.ys *= factor
def shift(self, shift):
"""Shifts the wave left or right in time.
shift: float time shift
"""
# TODO: track down other uses of this function and check them
self.ts += shift
def roll(self, roll):
"""Rolls this wave by the given number of locations."""
self.ys = np.roll(self.ys, roll)
def truncate(self, n):
"""Trims this wave to the given length.
n: integer index
"""
self.ys = truncate(self.ys, n)
self.ts = truncate(self.ts, n)
def zero_pad(self, n):
"""Trims this wave to the given length.
n: integer index
"""
self.ys = zero_pad(self.ys, n)
self.ts = self.start + np.arange(n) / self.framerate
def normalize(self, amp=1.0):
"""Normalizes the signal to the given amplitude.
amp: float amplitude
"""
self.ys = normalize(self.ys, amp=amp)
def unbias(self):
"""Unbiases the signal."""
self.ys = unbias(self.ys)
def find_index(self, t):
"""Find the index corresponding to a given time."""
n = len(self)
start = self.start
end = self.end
i = round((n - 1) * (t - start) / (end - start))
return int(i)
def segment(self, start=None, duration=None):
"""Extracts a segment.
start: float start time in seconds
duration: float duration in seconds
returns: Wave
"""
if start is None:
start = self.ts[0]
i = 0
else:
i = self.find_index(start)
j = None if duration is None else self.find_index(start + duration)
return self.slice(i, j)
def slice(self, i, j):
"""Makes a slice from a Wave.
i: first slice index
j: second slice index
"""
ys = self.ys[i:j].copy()
ts = self.ts[i:j].copy()
return Wave(ys, ts, self.framerate)
def make_spectrum(self, full=False):
"""Computes the spectrum using FFT.
full: boolean, whethere to compute a full FFT
(as opposed to a real FFT)
returns: Spectrum
"""
n = len(self.ys)
d = 1 / self.framerate
if full:
hs = np.fft.fft(self.ys)
fs = np.fft.fftfreq(n, d)
else:
hs = np.fft.rfft(self.ys)
fs = np.fft.rfftfreq(n, d)
return Spectrum(hs, fs, self.framerate, full)
def make_dct(self):
"""Computes the DCT of this wave."""
N = len(self.ys)
hs = scipy.fftpack.dct(self.ys, type=2)
fs = (0.5 + np.arange(N)) / 2
return Dct(hs, fs, self.framerate)
def make_spectrogram(self, seg_length, win_flag=True):
"""Computes the spectrogram of the wave.
seg_length: number of samples in each segment
win_flag: boolean, whether to apply hamming window to each segment
returns: Spectrogram
"""
if win_flag:
window = np.hamming(seg_length)
i, j = 0, seg_length
step = int(seg_length // 2)
# map from time to Spectrum
spec_map = {}
while j < len(self.ys):
segment = self.slice(i, j)
if win_flag:
segment.window(window)
# the nominal time for this segment is the midpoint
t = (segment.start + segment.end) / 2
spec_map[t] = segment.make_spectrum()
i += step
j += step
return Spectrogram(spec_map, seg_length)
def get_xfactor(self, options):
try:
xfactor = options["xfactor"]
options.pop("xfactor")
except KeyError:
xfactor = 1
return xfactor