-
Notifications
You must be signed in to change notification settings - Fork 4
/
response.py
1721 lines (1382 loc) · 47.7 KB
/
response.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
"""Your handy frequency and impulse response processing object.
[![](https://img.shields.io/pypi/l/response.svg?style=flat)](https://pypi.org/project/response/)
[![](https://img.shields.io/pypi/v/response.svg?style=flat)](https://pypi.org/project/response/)
[![travis-ci](https://travis-ci.org/fhchl/Response.svg?branch=master)](https://travis-ci.org/fhchl/Response)
[![codecov](https://codecov.io/gh/fhchl/Response/branch/master/graph/badge.svg)](https://codecov.io/gh/fhchl/Response)
This module supplies the `Response` class: an abstraction of frequency and
impulse responses and a set of handy methods for their processing. It implements a
[fluent interface][1] for chaining the processing commands.
Find the documentation [here][2] and the source code on [GitHub][3].
```python
import numpy as np
from response import Response
fs = 48000 # sampling rate
T = 0.5 # length of signal
# a sine at 100 Hz
t = np.arange(int(T * fs)) / fs
x = np.sin(2 * np.pi * 100 * t)
# Do chain of processing
r = (
Response.from_time(fs, x)
# time window at the end and beginning
.time_window((0, 0.1), (-0.1, None), window="hann") # equivalent to Tukey window
# zeropad to one second length
.zeropad_to_length(fs * 1)
# circular shift to center
.circdelay(T / 2)
# resample with polyphase filter, keep gain of filter
.resample_poly(500, window=("kaiser", 0.5), normalize="same_amplitude")
# cut 0.2s at beginning and end
.timecrop(0.2, -0.2)
# apply frequency domain window
.freq_window((0, 90), (110, 500))
)
# plot magnitude, phase and time response
r.plot(show=True)
# real impulse response
r.in_time
# complex frequency response
r.in_freq
# and much more ...
```
[1]: https://en.wikipedia.org/wiki/Fluent_interface
[2]: https://fhchl.github.io/Response/
[3]: https://github.com/fhchl/Response
"""
import warnings
from fractions import Fraction
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from scipy.signal import get_window, lfilter, resample, resample_poly, tukey, welch
class Response(object):
"""Representation of a linear response in time and frequency domain."""
def __init__(self, fs, fdata=None, tdata=None, isEvenSampled=True):
"""Create Response from time or frequency data.
Use `from_time` or `from_freq methods` to create objects of this class!
Parameters
----------
fs : int
Sampling frequency in Hertz
fdata : (..., nt) complex ndarray, optional
Single sided frequency spectra with nt from ns to nr points.
tdata : (..., nf) real ndarray, optional
Time responses with nt from ns to nr points.
isEvenSampled : bool or None, optional
If fdata is given, this tells us if the last entry of fdata is the
Nyquist frequency or not. Must be `None` if tdata is given.
Raises
------
ValueError
if neither fdata or tdata are given.
"""
assert float(fs).is_integer()
if fdata is not None and tdata is None:
fdata = np.atleast_1d(fdata)
self._nf = fdata.shape[-1]
if isEvenSampled:
self._nt = 2 * (self._nf - 1)
else:
self._nt = 2 * self._nf - 1
self._isEvenSampled = isEvenSampled
self.__set_frequency_data(fdata)
elif tdata is not None and fdata is None:
assert np.all(np.imag(tdata) == 0), "Time data must be real."
tdata = np.atleast_1d(tdata)
self._nt = tdata.shape[-1]
self._nf = self._nt // 2 + 1
self._isEvenSampled = self._nt % 2 == 0
self.__set_time_data(tdata)
else:
raise ValueError("One and only one of fdata and tdata must be given.")
self._fs = int(fs)
self._freqs = freq_vector(self._nt, fs)
self._times = time_vector(self._nt, fs)
self._time_length = self._nt * 1 / fs
self.df = self._freqs[1] # frequency resolution
self.dt = self._times[1] # time resolution
@classmethod
def from_time(cls, fs, tdata, **kwargs):
"""Generate Response obj from time response data."""
tf = cls(fs, tdata=tdata, **kwargs)
return tf
@classmethod
def from_freq(cls, fs, fdata, **kwargs):
"""Generate Response obj from frequency response data."""
tf = cls(fs, fdata=fdata, **kwargs)
return tf
@classmethod
def from_wav(cls, fps):
"""Import responses from wav files.
Parameters
----------
fps : list
File paths of all wav files.
Returns
-------
Response
New Response object with imported time responses.
"""
fpi = iter(fps)
fs, data = wavfile.read(next(fpi))
hlist = [data] + [wavfile.read(fp)[1] for fp in fpi]
h = np.array(hlist)
if data.dtype in [np.uint8, np.int16, np.int32]:
lim_orig = (np.iinfo(data.dtype).min, np.iinfo(data.dtype).max)
lim_new = (-1.0, 1.0)
h = _rescale(h, lim_orig, lim_new).astype(np.double)
return cls.from_time(fs, h)
@classmethod
def new_dirac(cls, fs, T=None, n=None, nch=(1,)):
"""Generate new allpass / dirac response."""
nch = np.atleast_1d(nch)
if T is not None:
nt = round(fs * T)
else:
nt = n
h = np.zeros((*nch, nt))
h[..., 0] = 1
return cls.from_time(fs, h)
@classmethod
def join(cls, tfs, axis=0, newaxis=True):
"""Concat or stack a set of Responses along a given axis.
Parameters
----------
tfs : array_like
List of Responses
axis : int, optional
Indice of axis along wich to concatenate / stack TFs.
newaxis : bool, optional
If True, do not concatenate but stack arrays along a new axis.
Returns
-------
Response
Note
----
Transfer functions need to have same sampling rate, length etc.
"""
joinfunc = np.stack if newaxis else np.concatenate
tdata = joinfunc([tf.in_time for tf in tfs], axis=axis)
return cls.from_time(tfs[0].fs, tdata)
@property
def time_length(self):
"""Length of time response in seconds."""
return self._time_length
@property
def nf(self): # noqa: D401
"""Number of frequencies in frequency representation."""
return len(self._freqs)
@property
def nt(self): # noqa: D401
"""Number of taps."""
return len(self._times)
@property
def fs(self): # noqa: D401
"""Sampling frequency."""
return self._fs
@property
def freqs(self): # noqa: D401
"""Frequencies."""
return self._freqs
@property
def times(self): # noqa: D401
"""Times."""
return self._times
@property
def in_time(self):
"""Time domain response.
Returns
-------
(... , n) ndarray
Real FIR filters.
"""
if self._in_time is None:
self._in_time = np.fft.irfft(self._in_freq, n=self._times.size)
return self._in_time
@property
def in_freq(self):
"""Single sided frequency spectrum.
Returns
-------
(... , n) ndarray
Complex frequency response.
"""
if self._in_freq is None:
self._in_freq = np.fft.rfft(self._in_time)
return self._in_freq
@property
def amplitude_spectrum(self):
"""Amplitude spectrum."""
X = self.in_freq / self.nt
if self.nt % 2 == 0:
# zero and nyquist element only appear once in complex spectrum
X[..., 1:-1] *= 2
else:
# there is no nyquist element
X[..., 1:] *= 2
return X
def __set_time_data(self, tdata):
"""Set time data without creating new object."""
assert tdata.shape[-1] == self._nt
self._in_time = tdata
self._in_freq = None
def __set_frequency_data(self, fdata):
"""Set frequency data without creating new object."""
assert fdata.shape[-1] == self._nf
self._in_freq = fdata
self._in_time = None
def plot(
self,
group_delay=False,
slce=None,
flim=None,
dblim=None,
tlim=None,
grpdlim=None,
dbref=1,
show=False,
use_fig=None,
label=None,
unwrap_phase=False,
logf=True,
third_oct_f=True,
plot_kw={},
**fig_kw,
):
"""Plot the response in both domains.
Parameters
----------
group_delay : bool, optional
Display group delay instead of phase.
slce : numpy.lib.index_tricks.IndexExpression
only plot subset of responses defined by a slice. Last
dimension (frequency or time) is always completely taken.
flim : tuple or None, optional
Frequency axis limits as tuple `(lower, upper)`
dblim : tuple or None, optional
Magnitude axis limits as tuple `(lower, upper)`
tlim : tuple or None, optional
Time axis limits as tuple `(lower, upper)`
grpdlim: tuple or None, optional
Group delay axis limit as tuple `(lower, upper)`
dbref : float
dB reference in magnitude plot
show : bool, optional
Run `matplotlib.pyplot.show()`
use_fig : matplotlib.pyplot.Figure
Reuse an existing figure.
label : None, optional
Description
unwrap_phase : bool, optional
unwrap phase in phase plot
logf : bool, optional
If `True`, use logarithmic frequency axis.
third_oct_f: bool, optional
Label frequency axis with third octave bands.
plot_kw : dictionary, optional
Keyword arguments passed to the `plt.plot` commands.
**fig_kw
Additional options passe to figure creation.
"""
if use_fig is None:
fig_kw = {**{"figsize": (10, 10)}, **fig_kw}
fig, axes = plt.subplots(nrows=3, constrained_layout=True, **fig_kw)
else:
fig = use_fig
axes = fig.axes
self.plot_magnitude(
use_ax=axes[0],
slce=slce,
dblim=dblim,
flim=flim,
dbref=dbref,
label=label,
plot_kw=plot_kw,
logf=logf,
third_oct_f=third_oct_f,
)
if group_delay:
self.plot_group_delay(
use_ax=axes[1],
slce=slce,
flim=flim,
ylim=grpdlim,
plot_kw=plot_kw,
logf=logf,
third_oct_f=third_oct_f,
)
else:
self.plot_phase(
use_ax=axes[1],
slce=slce,
flim=flim,
plot_kw=plot_kw,
unwrap=unwrap_phase,
logf=logf,
third_oct_f=third_oct_f,
)
self.plot_time(
use_ax=axes[2], tlim=tlim, slce=slce, plot_kw=plot_kw
)
if show:
plt.show()
return fig
def plot_magnitude(
self,
use_ax=None,
slce=None,
dblim=None,
flim=None,
dbref=1,
label=None,
plot_kw={},
logf=True,
third_oct_f=True,
**fig_kw,
):
"""Plot magnitude response."""
# TODO: compute db limits similar to librosa.amplitude_to_db / power_to_db
if use_ax is None:
fig_kw = {**{"figsize": (10, 5)}, **fig_kw}
fig, ax = plt.subplots(nrows=1, constrained_layout=True, **fig_kw)
else:
ax = use_ax
fig = ax.get_figure()
# append frequency/time dimension to slice
if slce is None:
slce = [np.s_[:] for n in range(len(self.in_time.shape))]
elif isinstance(slce, tuple):
slce = slce + (np.s_[:],)
else:
slce = (slce, np.s_[:])
# move time / frequency axis to first dimension
freq_plotready = np.rollaxis(self.in_freq[tuple(slce)], -1).reshape(
(self.nf, -1)
)
plotf = ax.semilogx if logf else ax.plot
plotf(
self.freqs,
20 * np.log10(np.abs(freq_plotready / dbref)),
label=label,
**plot_kw,
)
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Magnitude [dB]")
ax.set_title("Frequency response")
ax.grid(True)
if flim is None:
lowlim = min(10, self.fs / 2 / 100)
flim = (lowlim, self.fs / 2)
ax.set_xlim(flim)
if dblim is not None:
ax.set_ylim(dblim)
if label is not None:
ax.legend()
if third_oct_f:
_add_octave_band_xticks(ax)
return fig
def plot_phase(
self,
use_ax=None,
slce=None,
flim=None,
label=None,
unwrap=False,
ylim=None,
plot_kw={},
logf=True,
third_oct_f=True,
**fig_kw,
):
"""Plot phase response."""
if use_ax is None:
fig_kw = {**{"figsize": (10, 5)}, **fig_kw}
fig, ax = plt.subplots(nrows=1, constrained_layout=True, **fig_kw)
else:
ax = use_ax
fig = ax.get_figure()
# append frequency/time dimension to slice
if slce is None:
slce = [np.s_[:] for n in range(len(self.in_time.shape))]
elif isinstance(slce, tuple):
slce = slce + (np.s_[:],)
else:
slce = (slce, np.s_[:])
# move time / frequency axis to first dimension
freq_plotready = np.rollaxis(self.in_freq[tuple(slce)], -1).reshape(
(self.nf, -1)
)
phase = (
np.unwrap(np.angle(freq_plotready)) if unwrap else np.angle(freq_plotready)
)
plotf = ax.semilogx if logf else ax.plot
plotf(self.freqs, phase, label=label, **plot_kw)
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Phase [rad]")
ax.set_title("Phase response")
ax.grid(True)
if flim is None:
lowlim = min(10, self.fs / 2 / 100)
flim = (lowlim, self.fs / 2)
ax.set_xlim(flim)
if ylim:
ax.set_ylim(ylim)
if label is not None:
ax.legend()
if third_oct_f:
_add_octave_band_xticks(ax)
return fig
def plot_time(
self,
use_ax=None,
slce=None,
tlim=None,
ylim=None,
label=None,
plot_kw={},
**fig_kw,
):
"""Plot time response."""
if use_ax is None:
fig_kw = {**{"figsize": (10, 5)}, **fig_kw}
fig, ax = plt.subplots(nrows=1, constrained_layout=True, **fig_kw)
else:
ax = use_ax
fig = ax.get_figure()
# append frequency/time dimension to slice
if slce is None:
slce = [np.s_[:] for n in range(len(self.in_time.shape))]
elif isinstance(slce, tuple):
slce = slce + (np.s_[:],)
else:
slce = (slce, np.s_[:])
time_plotready = np.rollaxis(self.in_time[tuple(slce)], -1).reshape(
(self.nt, -1)
)
ax.plot(self.times, time_plotready, label=label, **plot_kw)
ax.set_xlabel("Time [s]")
ax.set_ylabel("")
ax.set_title("Time response")
ax.grid(True)
if tlim:
ax.set_xlim(tlim)
if ylim:
ax.set_ylim(ylim)
if label is not None:
ax.legend()
return fig
def plot_group_delay(
self,
use_ax=None,
slce=None,
flim=None,
label=None,
ylim=None,
plot_kw={},
logf=True,
third_oct_f=True,
**fig_kw,
):
"""Plot group delay."""
if use_ax is None:
fig_kw = {**{"figsize": (10, 5)}, **fig_kw}
fig, ax = plt.subplots(nrows=1, constrained_layout=True, **fig_kw)
else:
ax = use_ax
fig = ax.get_figure()
# append frequency/time dimension to slice
if slce is None:
slce = [np.s_[:] for n in range(len(self.in_time.shape))]
elif isinstance(slce, tuple):
slce = slce + (np.s_[:],)
else:
slce = (slce, np.s_[:])
# move time / frequency axis to first dimension
freq_plotready = np.rollaxis(self.in_freq[tuple(slce)], -1).reshape(
(self.nf, -1)
)
df = self.freqs[1] - self.freqs[0]
# TODO: use scipy.signal.group_delay here as below has problem at larger delays
grpd = -np.gradient(np.unwrap(np.angle(freq_plotready)), df, axis=0)
plotf = ax.semilogx if logf else ax.plot
plotf(self.freqs, grpd, label=label, **plot_kw)
ax.set_xlabel("Frequency [Hz]")
ax.set_ylabel("Delay [s]")
ax.set_title("Group Delay")
ax.grid(True)
if flim is None:
lowlim = min(10, self.fs / 2 / 100)
flim = (lowlim, self.fs / 2)
ax.set_xlim(flim)
if ylim:
ax.set_ylim(ylim)
if label is not None:
ax.legend()
if third_oct_f:
_add_octave_band_xticks(ax)
return fig
def plot_power_in_bands(
self, bands=None, use_ax=None, barkwargs={}, avgaxis=None, dbref=1, **figkwargs
):
"""Plot signal's power in bands.
Parameters
----------
bands : list or None, optional
List of tuples (f_center, f_lower, f_upper). If `None`, use third octave
bands.
use_ax : matplotlib.axis.Axis or None, optional
Plot into this axis.
barkwargs : dict
Keyword arguments to `axis.bar`
avgaxis : int, tuple or None
Average power over these axes.
dbref : float
dB reference.
**figkwargs
Keyword arguments passed to plt.subplots
Returns
-------
P : ndarray
Power in bands
fc : ndarray
Band frequencies
fig : matplotlib.figure.Figure
Figure
"""
P, fc = self.power_in_bands(bands=bands, avgaxis=avgaxis)
nbands = P.shape[-1]
P = np.atleast_2d(P).reshape((-1, nbands))
if use_ax is None:
fig, ax = plt.subplots(**figkwargs)
else:
ax = use_ax
fig = ax.get_figure()
xticks = range(1, nbands + 1)
for i in range(P.shape[0]):
ax.bar(xticks, 10 * np.log10(P[i] / dbref ** 2), **barkwargs)
ax.set_xticks(xticks)
ax.set_xticklabels(["{:.0f}".format(f) for f in fc], rotation="vertical")
ax.grid(True)
ax.set_xlabel("Band's center frequencies [Hz]")
ax.set_ylabel("Power [dB]")
return (P, fc, fig)
def time_window(self, startwindow, stopwindow, window="hann"):
"""Apply time domain windows.
Parameters
----------
startwindow : None or tuple
Tuple (t1, t2) with beginning and end times of window opening.
stopwindow : None or tuple
Tuple (t1, t2) with beginning and end times of window closing.
window : string or tuple of string and parameter values, optional
Desired window to use. See scipy.signal.get_window for a list of
windows and required parameters.
Returns
-------
Response
Time windowed response object
"""
n = self.times.size
twindow = _time_window(self.fs, n, startwindow, stopwindow, window=window)
new_response = self.from_time(self.fs, self.in_time * twindow)
return new_response
def freq_window(self, startwindow, stopwindow, window="hann"):
"""Apply frequency domain window.
Parameters
----------
startwindow : None or tuple
Tuple (t1, t2) with beginning and end frequencies of window opening.
stopwindow : None or tuple
Tuple (t1, t2) with beginning and end frequencies of window closing.
window : string or tuple of string and parameter values, optional
Desired window to use. See scipy.signal.get_window for a list of
windows and required parameters.
Returns
-------
Response
Frequency windowed response object
"""
n = self.times.size
fwindow = _freq_window(self.fs, n, startwindow, stopwindow, window=window)
new_response = self.from_freq(self.fs, self.in_freq * fwindow)
return new_response
def window_around_peak(self, tleft, tright, alpha, return_window=False):
"""Time window each impulse response around its peak value.
Parameters
----------
tleft, tright : float
Window starts `tleft` seconds before and ends `tright` seconds after maximum
of impulse response.
alpha : float
`alpha` parameter of `scipy.signal.tukey` window.
return_window : bool, optional
Also return used time window
Returns
-------
Response
Time windowed response object.
ndarray
Time window, if `return_window` is `True`.
"""
window = _construct_window_around_peak(
self.fs, self.in_time, tleft, tright, alpha=alpha
)
if return_window:
return self.from_time(self.fs, self.in_time * window), window
return self.from_time(self.fs, self.in_time * window)
def delay(self, dt, keep_length=True):
"""Delay time response by dt seconds.
Rounds of to closest integer delay.
"""
x = delay(self.fs, self.in_time, dt, keep_length=keep_length)
return self.from_time(self.fs, x)
def circdelay(self, dt):
"""Delay by circular shift.
Rounds of to closest integer delay.
"""
x = self.in_time
n = int(round(dt * self.fs))
shifted = np.roll(x, n, axis=-1)
return self.from_time(self.fs, shifted)
def timecrop(self, start, end):
"""Crop time response.
Parameters
----------
start, end : float
Start and end times in seconds. Does not include sample at t=end. Use
end=None to force inclusion of last sample.
Returns
-------
Response
New Response object with cropped time.
Notes
-----
Creates new Response object.
Examples
--------
>>> import numpy as np
>>> from response import Response
>>> r = Response.from_time(100, np.random.normal(size=100))
>>> split = 0.2
The following holds:
>>> np.all(np.concatenate(
... (
... r.timecrop(0, split).in_time,
... r.timecrop(split, None).in_time,
... ),
... axis=-1,
... ) == r.in_time)
True
"""
if start < 0:
start += self.time_length
if end is not None and end < 0:
end += self.time_length
assert 0 <= start < self.time_length
assert end is None or (0 < end <= self.time_length)
_, i_start = _find_nearest(self.times, start)
if end is None:
i_end = None
else:
_, i_end = _find_nearest(self.times, end)
h = self.in_time[..., i_start:i_end]
new_response = self.from_time(self.fs, h)
return new_response
def non_causal_timecrop(self, length):
"""Cut length of non-causal impulse response.
"FFT shift, cropping on both ends, iFFT shift"
Parameters
----------
length : float
final length in seconds
Returns
-------
Response
New Response object new length.
Note
----
Can introduce delay pre-delay by a sample.
"""
assert length < self.time_length
cut = (self.time_length - length) / 2
_, i_start = _find_nearest(self.times, cut)
_, i_end = _find_nearest(self.times, self.time_length - cut)
h = np.fft.ifftshift(np.fft.fftshift(self.in_time)[..., i_start:i_end])
new_response = self.from_time(self.fs, h)
if new_response.time_length != length:
w = f"Could not precisely shrink to {length}s with fs = {self.fs}"
warnings.warn(w)
return new_response
def non_causal_set_to_length(self, n):
"""Change length of non-causal impulse response.
"FFT shift, cropping / adding on both ends, iFFT shift"
Parameters
----------
n : float
final length in samples
Returns
-------
Response
New Response object with new length n.
"""
if n == self.nt:
# return copy
return self.from_time(self.fs, self.in_time)
elif n < self.nt:
cut = (self.nt - n) / 2
h = np.fft.ifftshift(np.fft.fftshift(self.in_time)[..., int(np.floor(cut)):int(-np.ceil(cut))])
elif n > self.nt:
add = (n - self.nt) / 2
h = np.fft.ifftshift(
Response.from_time(self.fs, np.fft.fftshift(self.in_time))
.zeropad(np.floor(add), np.ceil(add)).in_time
)
new_response = self.from_time(self.fs, h)
assert new_response.nt == n
return new_response
def zeropad(self, before, after):
"""Zeropad time response.
Parameters
----------
before, after : int
Number of zero samples inserted before and after response.
Returns
-------
Response
Zeropadded response
"""
assert before % 1 == 0
assert after % 1 == 0
dims = self.in_time.ndim
pad_width = [(0, 0) for n in range(dims)]
pad_width[-1] = (int(before), int(after))
h = np.pad(self.in_time, pad_width, "constant")
return self.from_time(self.fs, h)
def zeropad_to_power_of_2(self):
"""Pad time response for length of power of 2.
Returns
-------
Response
New response object with larger, power of 2 length.
"""
# https://stackoverflow.com/questions/14267555/find-the-smallest-power-of-2-greater-than-n-in-python
n = 2 ** (self.nt - 1).bit_length()
return self.zeropad(0, n - self.nt)
def zeropad_to_length(self, n):
"""Zeropad time response to specific length.
Returns
-------
Response
New response object with new length n.
"""
oldn = self.nt
assert n >= oldn
return self.zeropad(0, n - oldn)
def resample(self, fs_new, normalize="same_gain", window=None):
"""Resample using Fourier method.
Parameters
----------
fs_new : int
New sample rate
normalize : str, optional
If 'same_gain', normalize such that the gain is the same
as the original signal. If 'same_amplitude', amplitudes will be preserved.
window : None, optional
Passed to scipy.signal.resample.
Returns
-------
Response
New resampled response object.
Raises
------
ValueError
If resulting number of samples would be a non-integer.
"""
if fs_new == self.fs:
return self
nt_new = fs_new * self.time_length
if nt_new % 1 != 0:
raise ValueError(
"New number of samples must be integer, but is {}".format(nt_new)
)
nt_new = int(nt_new)
h_new = resample(self.in_time, nt_new, axis=-1, window=window)
if normalize == "same_gain":
h_new *= self.nt / nt_new
elif normalize == "same_amplitude":
pass
else:
raise ValueError(
"Expected 'same_gain' or 'same_amplitude', got %s" % (normalize,)
)
return self.from_time(fs_new, h_new)
def resample_poly(self, fs_new, normalize="same_gain", window=("kaiser", 5.0)):
"""Resample using polyphase filtering.
Parameters
----------
fs_new : int
New sample rate
normalize : str, optional