Debian Codegraph @

skrf/time.py

raw symbols SCIP
1 """
2 .. module:: skrf.time
3 ========================================
4 time (:mod:`skrf.time`)
5 ========================================
6
7 Time domain functions
8
9
10 .. autosummary::
11 :toctree: generated/
12
13 time_gate
14 detect_span
15 find_n_peaks
16 indexes
17 get_window
18
19 """
20 from __future__ import annotations
21
22 import warnings
23 from collections.abc import Callable
24
25 # imports for type hinting
26 from typing import TYPE_CHECKING
27
28 import numpy as np
29 from numpy.fft import fft, fftshift, ifft, ifftshift, irfft, rfft
30 from scipy import signal
31 from scipy.ndimage import convolve1d
32
33 from .util import find_nearest_index
34
35 if TYPE_CHECKING:
36 from .network import Network
37
38
39 def indexes(y: np.ndarray, thres: float = 0.3, min_dist: int = 1) -> np.ndarray:
40 """
41 Peak detection routine.
42
43 Finds the numeric index of the peaks in *y* by taking its first order difference. By using
44 *thres* and *min_dist* parameters, it is possible to reduce the number of
45 detected peaks. *y* must be signed.
46
47 Parameters
48 ----------
49 y : ndarray (signed)
50 1D amplitude data to search for peaks.
51 thres : float between [0., 1.], optional
52 Normalized threshold. Only the peaks with amplitude higher than the
53 threshold will be detected. Default is 0.3
54 min_dist : int, optional
55 Minimum distance between each detected peak. The peak with the highest
56 amplitude is preferred to satisfy this constraint. Default is 1
57
58 Returns
59 -------
60 ndarray
61 Array containing the numeric indexes of the peaks that were detected
62
63 Notes
64 -----
65 This function was taken from peakutils-1.1.0
66 http://pythonhosted.org/PeakUtils/index.html
67
68 """
69 #This function was taken from peakutils, and is covered
70 # by the MIT license, included below:
71
72 #The MIT License (MIT)
73
74 #Copyright (c) 2014 Lucas Hermann Negri
75
76 #Permission is hereby granted, free of charge, to any person obtaining a copy
77 #of this software and associated documentation files (the "Software"), to deal
78 #in the Software without restriction, including without limitation the rights
79 #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
80 #copies of the Software, and to permit persons to whom the Software is
81 #furnished to do so, subject to the following conditions:
82
83 #The above copyright notice and this permission notice shall be included in
84 #all copies or substantial portions of the Software.
85
86 #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
87 #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
88 #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
89 #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
90 #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
91 #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
92 #THE SOFTWARE.
93
94 if isinstance(y, np.ndarray) and np.issubdtype(y.dtype, np.unsignedinteger):
95 raise ValueError("y must be signed")
96
97 thres = thres * (np.max(y) - np.min(y)) + np.min(y)
98 min_dist = int(min_dist)
99
100 # compute first order difference
101 dy = np.diff(y)
102
103 # propagate left and right values successively to fill all plateau pixels (0-value)
104 zeros, = np.where(dy == 0)
105
106 # check if the singal is totally flat
107 if len(zeros) == len(y) - 1:
108 return np.array([])
109
110 while len(zeros):
111 # add pixels 2 by 2 to propagate left and right value onto the zero-value pixel
112 zerosr = np.hstack([dy[1:], 0.])
113 zerosl = np.hstack([0., dy[:-1]])
114
115 # replace 0 with right value if non zero
116 dy[zeros]=zerosr[zeros]
117 zeros, = np.where(dy == 0)
118
119 # replace 0 with left value if non zero
120 dy[zeros] = zerosl[zeros]
121 zeros, = np.where(dy == 0)
122
123 # find the peaks by using the first order difference
124 peaks = np.where((np.hstack([dy, 0.]) < 0.)
125 & (np.hstack([0., dy]) > 0.)
126 & (y > thres))[0]
127
128 # handle multiple peaks, respecting the minimum distance
129 if peaks.size > 1 and min_dist > 1:
130 highest = peaks[np.argsort(y[peaks])][::-1]
131 rem = np.ones(y.size, dtype=bool)
132 rem[peaks] = False
133
134 for peak in highest:
135 if not rem[peak]:
136 sl = slice(max(0, peak - min_dist), peak + min_dist + 1)
137 rem[sl] = True
138 rem[peak] = False
139
140 peaks = np.arange(y.size)[~rem]
141
142 return peaks
143
144
145 def find_n_peaks(x: np.ndarray, n: int, thres: float = 0.9, **kwargs) -> list[int]:
146 """
147 Find a given number of peaks in a signal.
148
149 Parameters
150 ----------
151 x : np.ndarray
152 signal
153 n : int
154 number of peaks to search for
155 thres : float, optional
156 threshold, default is 0.9
157 **kwargs : optional keyword arguments passed to :func:`indexes`
158
159 Returns
160 -------
161 peak_idxs : list of int
162 List containing the numeric indexes of the peaks that were detected
163
164 Raises
165 ------
166 ValueError
167 If no peaks are found.
168 """
169 for _dummy in range(10):
170
171 idx = indexes(x, **kwargs)
172 if len(idx) < n:
173 thres *= .5
174
175 else:
176 peak_vals = sorted(x[idx], reverse=True)[:n]
177 peak_idxs = [x.tolist().index(k) for k in peak_vals]
178
179 return peak_idxs
180 raise ValueError('Couldnt find %i peaks' % n)
181
182 time_lookup_dict = {
183 "s": 1,
184 "ms": 1e-3,
185 "us": 1e-6,
186 "µs": 1e-6,
187 "ns": 1e-9,
188 "ps": 1e-12
189 }
190
191 def detect_span(ntwk: Network, t_unit: str = "") -> float:
192 """
193 Detect the correct time-span between two largest peaks.
194
195 Parameters
196 ----------
197 ntwk : :class:`~skrf.network.Network`
198 network to get data from
199
200 t_unit : str
201 Time unit for start, stop, center and span arguments, defaults to seconds (s).
202
203 Possible values:
204 * 's': seconds
205 * 'ms': milliseconds
206 * 'µs' or 'us': microseconds
207 * 'ns': nanoseconds (default)
208 * 'ps': picoseconds
209
210
211 Returns
212 -------
213 span : float in unit t_unit
214 """
215
216 if t_unit == "":
217 # Do not raise in autogate mode, where all parameters are None
218 warnings.warn('''
219 Time unit not passed: uses 's' per default.
220 ''',
221 DeprecationWarning, stacklevel=2)
222 t_unit = 's'
223
224 x = ntwk.s_time_db.flatten()
225 p1, p2 = find_n_peaks(x, n=2)
226 # distance to nearest neighbor peak
227 span = abs(ntwk.frequency.t[p1]-ntwk.frequency.t[p2])
228
229 return span / time_lookup_dict[t_unit]
230
231 def get_window(window: str | tuple | Callable, Nx: int, **kwargs) -> np.ndarray:
232 """Calls a custom window function or `scipy.signal.get_window()` depending on the window argument.
233
234 Parameters
235 ----------
236 window : str, tuple or Callable
237 The callable window function or a valid window string
238 for `scipy.signal.get_window()`.
239 Nx : int
240 Number of samples
241
242 Returns
243 -------
244 window : np.ndarray
245 Window samples.
246 """
247
248 if callable(window):
249 return window(Nx, **kwargs)
250 else:
251 return signal.get_window(window, Nx=Nx, **kwargs)
252
253 def time_gate(ntwk: Network, start: float = None, stop: float = None, center: float = None, span: float = None,
254 mode: str = 'bandpass', window=('kaiser', 6),
255 method: str ='fft', fft_window: str='cosine', conv_mode: str='wrap', t_unit: str = "") -> Network:
256 """
257 Time-domain gating of one-port s-parameters with a window function from scipy.signal.windows.
258
259 The gate can be defined with start/stop times, or by center/span. All times are in units of seconds but
260 can be changed using the `t_unit` parameter.
261 Common windows are:
262
263 * ('kaiser', 6)
264 * 6 # integers are interpreted as kaiser beta-values
265 * 'hamming'
266 * 'boxcar' # a straight up rect
267 * Callable function which accepts integer with window size as argument
268
269 If no parameters are passed this will try to auto-gate the largest
270 peak.
271
272 Parameters
273 ----------
274 ntwk : :class:`~skrf.network.Network`
275 network to operate on
276 start : number, or None
277 start of time gate in t_unit.
278 stop : number, or None
279 stop of time gate in t_unit.
280 center : number, or None
281 center of time gate, in t_unit. If None, and span is given,
282 the gate will be centered on the peak.
283 span : number, or None
284 span of time gate, in t_unit. If None span will be half of the
285 distance to the second tallest peak
286 mode : ['bandpass', 'bandstop']
287 mode of gate
288 window : string, float, or tuple
289 passed to `window` arg of `scipy.signal.get_window()` or callable function
290 method : str
291 Gating method. There are 3 option: 'convolution', 'fft', 'rfft'.
292
293 With *'convolution'*, the time-domain gate gets transformed into frequency-domain using inverse FFT and the
294 gating is then achieved by convolution with the frequency-domain data.
295
296 With *'fft'* (default), the data gets transformed into time-domain using inverse FFT and the gating is achieved
297 by multiplication with the time-domain gate. The gated time-domain signal is then transformed back into
298 frequency-domain using FFT. As only positive signal frequencies are considered for the inverse FFT
299 (with or without a dc component), the resulting time-domain signal has the same number of samples as in the
300 frequency-domain, but is complex-valued. This method is also know as *time-domain band-pass mode*.
301
302 With *'rfft'*, the procedure is the same as with *'fft'*, but the inverse FFT uses a complex-conjugate copy of
303 the positive signal frequencies for the negative frequencies (Hermitian frequency response). A dc sample is
304 also required. The resulting time-domain signal is real-valued and has twice the number of samples, which gives
305 an improved time resolution. This method is also known as *time-domain low-pass mode*.
306
307 fft_window : str or tuple or None
308 Frequency-domain window applied before the inverse FFT in case of the (R)FFT method.
309 This parameter takes the same values as the `window` parameter.
310 Example: `window='hann` (default), or `window=('kaiser', 5)`, or `window=None`.
311 The window helps to remove artefacts such as time-domain sidelobes of the pulses, but it is a trade-off with
312 the achievable pulse width. The window is removed when the gated time-domain signals is transformed back into
313 frequency-domain.
314
315 conv_mode : str
316 Extension mode for the convolution (if selected) determining how the frequency-domain gate is extended beyond
317 the boundaries. This has a large effect on the generation of gating artefacts due to boundary effects. The
318 optimal mode depends on the data. See the parameter description of `scipy.ndimage.convolve1d` for the available
319 options.
320
321 t_unit : str
322 Time unit for start, stop, center and span arguments, defaults to seconds (s).
323
324 Possible values:
325 * 's': seconds (default)
326 * 'ms': milliseconds
327 * 'µs' or 'us': microseconds
328 * 'ns': nanoseconds
329 * 'ps': picoseconds
330
331
332 Note
333 ----
334 You can't gate things that are 'behind' strong reflections. This
335 is due to the multiple reflections that occur.
336
337 If you need to time-gate an N-port network, then you should
338 gate each s-parameter independently.
339
340 Returns
341 -------
342 ntwk : Network
343 copy of ntwk with time-gated s-parameters
344
345 .. warning::
346 Depending on sharpness of the gate, the band edges may be
347 inaccurate, due to properties of FFT. We do not re-normalize
348 anything.
349 """
350
351 if ntwk.nports >1:
352 raise ValueError('Time-gating only works on one-ports. Try passing `ntwk.s11` or `ntwk.s21`.')
353
354 if t_unit == "":
355 if not all([e is None for e in [start, stop, center, span]]):
356 # Do not raise in autogate mode, where all parameters are None
357 warnings.warn('''
358 Time unit not passed: uses 's' per default.
359 ''',
360 DeprecationWarning, stacklevel=2)
361 t_unit = 's'
362
363 t_mult = time_lookup_dict[t_unit]
364
365 if start is not None and stop is not None:
366 start *= t_mult
367 stop *= t_mult
368 span = abs(stop-start)
369 center = (stop+start)/2.
370
371 else:
372 if center is None:
373 # they didn't provide center, so find the peak
374 n = ntwk.s_time_mag.argmax()
375 center = ntwk.frequency.t_ns[n]
376
377 if span is None:
378 span = detect_span(ntwk, t_unit='ns')
379
380 center *= t_mult
381 span *= t_mult
382 start = center - span / 2.
383 stop = center + span / 2.
384
385 ntwk_gated = ntwk.copy()
386 method = method.lower()
387 n_fd = ntwk.frequency.npoints
388 df = ntwk.frequency.step
389
390 if method == 'convolution':
391 # frequency-domain gating
392 n_td = n_fd
393 # create dummy-window
394 window_fd = np.ones(n_fd)
395
396 elif method == 'fft':
397 # time-domain band-pass mode
398 n_td = n_fd
399 if fft_window is not None:
400 # create band-pass window (zero on both lower and upper limit, one at center)
401 window_fd = get_window(fft_window, n_fd)
402 else:
403 # create dummy-window
404 window_fd = np.ones(n_fd)
405
406 elif method == 'rfft':
407 # time-domain low-pass mode
408 if ntwk.f[0] > 0.0:
409 # no dc point included
410 warnings.warn('The network data to be gated does not contain the dc point (0 Hz). This is required for the '
411 'selected low-pass gating mode. Please consider to include the dc point if the results are '
412 'inaccurate, either by direct measurement of by extrapolation using '
413 'skrf.Network.extrapolate_to_dc().', UserWarning, stacklevel=2)
414 n_td = 2 * n_fd - 1
415 if fft_window is not None:
416 # create low-pass window (one at lower limit at f=0, zero on upper limit)
417 window_fd = get_window(fft_window, 2 * n_fd)
418 window_fd = window_fd[n_fd:]
419 else:
420 # create dummy-window
421 window_fd = np.ones(n_fd)
422
423 else:
424 raise ValueError(f'Invalid parameter method=`{method}`')
425
426 # apply frequency-domain window
427 ntwk_gated.s[:, 0, 0] = ntwk_gated.s[:, 0, 0] * window_fd
428
429 # create time vector
430 t = np.fft.fftshift(np.fft.fftfreq(n_td, df))
431 # find start/stop gate indices
432 start_idx = find_nearest_index(t, start)
433 stop_idx = find_nearest_index(t, stop)
434
435 # create gating window
436 window_width = abs(stop_idx - start_idx) + 1
437 window = get_window(window, window_width)
438
439 # create the gate by padding the window with zeros
440 gate = np.zeros_like(t)
441 gate[start_idx:stop_idx+1] = window
442
443 if method == 'convolution':
444 # frequency-domain gating
445 kernel = fftshift(fft(ifftshift(gate), norm='forward'))
446 ntwk_gated.s[:, 0, 0] = convolve1d(ntwk_gated.s[:, 0, 0], kernel, mode=conv_mode)
447 elif method == 'fft':
448 # time-domain band-pass mode
449 s_td = fftshift(ifft(ntwk_gated.s[:, 0, 0]))
450 s_td_g = s_td * gate
451 ntwk_gated.s[:, 0, 0] = fft(ifftshift(s_td_g))
452 elif method == 'rfft':
453 # time-domain low-pass mode
454 s_td = fftshift(irfft(ntwk_gated.s[:, 0, 0], n=len(t)))
455 s_td_g = s_td * gate
456 ntwk_gated.s[:, 0, 0] = rfft(ifftshift(s_td_g))
457
458 # remove frequency-domain window
459 ntwk_gated.s[:, 0, 0] = ntwk_gated.s[:, 0, 0] / window_fd
460
461 if mode == 'bandstop':
462 ntwk_gated = ntwk - ntwk_gated
463 elif mode == 'bandpass':
464 pass
465 else:
466 raise ValueError('mode should be \'bandpass\' or \'bandstop\'')
467
468 return ntwk_gated