Debian Codegraph @

skrf/frequency.py

raw symbols SCIP
1 """
2 .. currentmodule:: skrf.frequency
3
4 ========================================
5 frequency (:mod:`skrf.frequency`)
6 ========================================
7
8 Provides a frequency object and related functions.
9
10 Most of the functionality is provided as methods and properties of the
11 :class:`Frequency` Class.
12
13
14 Frequency Class
15 ===============
16 .. autosummary::
17 :toctree: generated/
18
19 Frequency
20
21 Functions
22 =========
23
24 .. autosummary::
25 :toctree: generated/
26
27 overlap_freq
28
29 Misc
30 ====
31
32 .. autosummary::
33 :toctree: generated/
34
35 InvalidFrequencyWarning
36
37 """
38
39 from __future__ import annotations
40
41 import re
42 import warnings
43 from numbers import Number
44
45 import numpy as np
46 from numpy import (
47 geomspace,
48 gradient, # used to center attribute `t` at 0
49 linspace,
50 pi,
51 )
52
53 from .constants import FREQ_UNITS, ZERO, FrequencyUnitT, NumberLike, SweepTypeT
54 from .util import Axes, axes_kwarg, find_nearest_index, slice_domain
55
56
57 class InvalidFrequencyWarning(UserWarning):
58 """Thrown if frequency values aren't monotonously increasing
59 """
60 pass
61
62
63 class Frequency:
64 """
65 A frequency band.
66
67 The frequency object provides a convenient way to work with and
68 access a frequency band. It contains a frequency vector as well as
69 a frequency unit. This allows a frequency vector in a given unit
70 to be available (:attr:`f_scaled`), as well as an absolute frequency
71 axis in 'Hz' (:attr:`f`).
72
73 A Frequency object can be created from either (start, stop, npoints)
74 using the default constructor, :func:`__init__`. Or, it can be
75 created from an arbitrary frequency vector by using the class
76 method :func:`from_f`.
77
78 Internally, the frequency information is stored in the `f` property
79 combined with the `unit` property. All other properties, `start`
80 `stop`, etc are generated from these.
81 """
82 unit_dict = {k.lower(): k for k in FREQ_UNITS}
83
84 """
85 Dictionary to convert unit string with correct capitalization for display.
86 """
87
88 multiplier_dict={k.lower(): v for k,v in FREQ_UNITS.items()}
89 """
90 Frequency unit multipliers.
91 """
92
93
94 def __init__(self, start: float = 0, stop: float = 0, npoints: int = 0,
95 unit: FrequencyUnitT | None = None, sweep_type: SweepTypeT = 'lin') -> None:
96 """
97 Frequency initializer.
98
99 Creates a Frequency object from start/stop/npoints and a unit.
100 Alternatively, the class method :func:`from_f` can be used to
101 create a Frequency object from a frequency vector instead.
102
103 Parameters
104 ----------
105 start : number, optional
106 start frequency in units of `unit`. Default is 0.
107 stop : number, optional
108 stop frequency in units of `unit`. Default is 0.
109 npoints : int, optional
110 number of points in the band. Default is 0.
111 unit : string, optional
112 Frequency unit of the band: 'Hz', 'kHz', 'MHz', 'GHz', 'THz'.
113 This is used to create the attribute :attr:`f_scaled`.
114 It is also used by the :class:`~skrf.network.Network` class
115 for plots vs. frequency. Default is 'Hz'.
116 sweep_type : string, optional
117 Type of the sweep: 'lin' or 'log'.
118 'lin' for linear and 'log' for logarithmic. Default is 'lin'.
119
120 Note
121 ----
122 The attribute `unit` sets the frequency multiplier, which is used
123 to scale the frequency when `f_scaled` is referenced.
124
125 Note
126 ----
127 The attribute `unit` is not case sensitive.
128 Hence, for example, 'GHz' or 'ghz' is the same.
129
130 See Also
131 --------
132 from_f : constructs a Frequency object from a frequency
133 vector instead of start/stop/npoints.
134 :attr:`unit` : frequency unit of the band
135
136 Examples
137 --------
138 >>> wr1p5band = Frequency(start=500, stop=750, npoints=401, unit='ghz')
139 >>> logband = Frequency(1, 1e9, 301, sweep_type='log')
140
141 """
142 if unit is None:
143 warnings.warn('''
144 Frequency unit not passed: uses 'Hz' per default.
145 ''',
146 DeprecationWarning, stacklevel=2)
147 unit = 'Hz'
148 self._unit = unit.lower()
149
150 start = self.multiplier * start
151 stop = self.multiplier * stop
152
153 if npoints == 0:
154 self._f = np.array([])
155 elif sweep_type.lower() == 'lin':
156 self._f = linspace(start, stop, npoints)
157 elif sweep_type.lower() == 'log' and start > 0:
158 self._f = geomspace(start, stop, npoints)
159 else:
160 raise ValueError('Sweep Type not recognized')
161
162 def __str__(self) -> str:
163 """
164 """
165 try:
166 output = \
167 '%s-%s %s, %i pts' % \
168 (self.f_scaled[0], self.f_scaled[-1], self.unit, self.npoints)
169 except (IndexError):
170 output = "[no freqs]"
171
172 return output
173
174 def __repr__(self) -> str:
175 """
176 """
177 return self.__str__()
178
179 def __getitem__(self, key: str | int | slice) -> Frequency:
180 """
181 Slices a Frequency object based on an index, or human readable string.
182
183 Parameters
184 ----------
185 key : str, int, or slice
186 if int, then it is interpreted as the index of the frequency
187 if str, then should be like '50.1-75.5ghz', or just '50'.
188 If the frequency unit is omitted then :attr:`unit` is
189 used.
190
191 Examples
192 --------
193 >>> b = rf.Frequency(50, 100, 101, 'ghz')
194 >>> a = b['80-90ghz']
195 >>> a.plot_s_db()
196 """
197
198 output = self.copy()
199
200
201 if isinstance(key, str):
202
203 # they passed a string try and do some interpretation
204 re_hyphen = re.compile(r'\s*-\s*')
205 re_letters = re.compile('[a-zA-Z]+')
206
207 freq_unit = re.findall(re_letters,key)
208
209 if len(freq_unit) == 0:
210 freq_unit = self.unit
211 else:
212 freq_unit = freq_unit[0]
213
214 key_nounit = re.sub(re_letters,'',key)
215 edges = re.split(re_hyphen,key_nounit)
216
217 edges_freq = Frequency.from_f([float(k) for k in edges],
218 unit = freq_unit)
219 if len(edges_freq) ==2:
220 slicer=slice_domain(output.f, edges_freq.f)
221 elif len(edges_freq)==1:
222 key = find_nearest_index(output.f, edges_freq.f[0])
223 slicer = slice(key,key+1,1)
224 else:
225 raise ValueError()
226 try:
227 output._f = np.array(output.f[slicer]).reshape(-1)
228 return output
229 except(IndexError) as err:
230 raise IndexError('slicing frequency is incorrect') from err
231
232
233 if output.f.shape[0] > 0:
234 output._f = np.array(output.f[key]).reshape(-1)
235 else:
236 output._f = np.empty(shape=(0))
237
238 return output
239
240
241 @classmethod
242 def from_f(cls, f: NumberLike, unit: FrequencyUnitT | None = None) -> Frequency:
243 """
244 Construct Frequency object from a frequency vector.
245
246 The unit is set by kwarg 'unit'
247
248 Parameters
249 ----------
250 f : scalar or array-like
251 frequency vector
252
253 *args, **kwargs : arguments, keyword arguments
254 passed on to :func:`__init__`.
255
256 Returns
257 -------
258 myfrequency : :class:`Frequency` object
259 the Frequency object
260
261 Raises
262 ------
263 InvalidFrequencyWarning:
264 If frequency points are not monotonously increasing
265
266 Examples
267 --------
268 >>> f = np.linspace(75,100,101)
269 >>> rf.Frequency.from_f(f, unit='GHz')
270 """
271 if np.isscalar(f):
272 f = [f]
273 temp_freq = cls(0,0,0,unit=unit)
274 temp_freq._f = np.asarray(f) * temp_freq.multiplier
275 temp_freq.check_monotonic_increasing()
276
277 return temp_freq
278
279 def __eq__(self, other: object) -> bool:
280 #return (list(self.f) == list(other.f))
281 # had to do this out of practicality
282 if not isinstance(other, self.__class__):
283 return False
284 if len(self.f) != len(other.f):
285 return False
286 elif len(self.f) == len(other.f) == 0:
287 return True
288 else:
289 return (max(abs(self.f-other.f)) < ZERO)
290
291 def __ne__(self,other: object) -> bool:
292 return (not self.__eq__(other))
293
294 def __len__(self) -> int:
295 """
296 The number of frequency points
297 """
298 return self.npoints
299
300 def __add__(self, other: Frequency | NumberLike) -> Frequency:
301 out = self.copy()
302 out._f = self.f + (other.f if isinstance(other, Frequency) else other)
303 return out
304
305 def __sub__(self, other: Frequency | NumberLike) -> Frequency:
306 out = self.copy()
307 out._f = self.f - (other.f if isinstance(other, Frequency) else other)
308 return out
309
310 def __mul__(self, other: Frequency | NumberLike) -> Frequency:
311 out = self.copy()
312 out._f = self.f * (other.f if isinstance(other, Frequency) else other)
313 return out
314
315 def __rmul__(self, other: Frequency | NumberLike) -> Frequency:
316 out = self.copy()
317 out._f = self.f * (other.f if isinstance(other, Frequency) else other)
318 return out
319
320 def __div__(self, other: Frequency | NumberLike) -> Frequency:
321 out = self.copy()
322 out._f = self.f / (other.f if isinstance(other, Frequency) else other)
323 return out
324
325 def __truediv__(self, other: Frequency | NumberLike) -> Frequency:
326 out = self.copy()
327 out._f = self.f / (other.f if isinstance(other, Frequency) else other)
328 return out
329
330 def __floordiv__(self, other: Frequency | NumberLike) -> Frequency:
331 out = self.copy()
332 out._f = self.f // (other.f if isinstance(other, Frequency) else other)
333 return out
334
335 def __mod__(self, other: Frequency | NumberLike) -> Frequency:
336 out = self.copy()
337 out._f = self.f % (other.f if isinstance(other, Frequency) else other)
338 return out
339
340 def check_monotonic_increasing(self) -> None:
341 """Validate the frequency values
342
343 Raises
344 ------
345 InvalidFrequencyWarning:
346 If frequency points are not monotonously increasing
347 """
348 increase = np.diff(self.f) > 0
349 if not increase.all():
350 warnings.warn("Frequency values are not monotonously increasing!\n"
351 "To get rid of the invalid values call `drop_non_monotonic_increasing`",
352 InvalidFrequencyWarning, stacklevel=2)
353
354 def drop_non_monotonic_increasing(self) -> list[int]:
355 """Drop duplicate and invalid frequency values and return the dropped indices
356
357 Returns:
358 list[int]: The dropped indices
359 """
360 invalid = np.diff(self.f, prepend=self.f[0]-1) <= 0
361 self._f = self._f[~invalid]
362 return list(np.flatnonzero(invalid))
363
364 @property
365 def start(self) -> float:
366 """
367 Starting frequency in Hz.
368 """
369 return self.f[0]
370
371 @property
372 def start_scaled(self) -> float:
373 """
374 Starting frequency in :attr:`unit`'s.
375 """
376 return self.f_scaled[0]
377 @property
378 def stop_scaled(self) -> float:
379 """
380 Stop frequency in :attr:`unit`'s.
381 """
382 return self.f_scaled[-1]
383
384 @property
385 def stop(self) -> float:
386 """
387 Stop frequency in Hz.
388 """
389 return self.f[-1]
390
391 @property
392 def npoints(self) -> int:
393 """
394 Number of points in the frequency.
395 """
396 return len(self.f)
397
398 @property
399 def center(self) -> float:
400 """
401 Center frequency in Hz.
402
403 Returns
404 -------
405 center : number
406 the exact center frequency in units of Hz
407 """
408 return self.start + (self.stop-self.start)/2.
409
410 @property
411 def center_idx(self) -> int:
412 """
413 Closes idx of :attr:`f` to the center frequency.
414 """
415 return self.npoints // 2
416
417 @property
418 def center_scaled(self) -> float:
419 """
420 Center frequency in :attr:`unit`'s.
421
422 Returns
423 -------
424 center : number
425 the exact center frequency in units of :attr:`unit`'s
426 """
427 return self.start_scaled + (self.stop_scaled-self.start_scaled)/2.
428
429 @property
430 def step(self) -> float:
431 """
432 The inter-frequency step size (in Hz) for evenly-spaced
433 frequency sweeps
434
435 See Also
436 --------
437 df : for general case
438 """
439 if self.span == 0:
440 return 0.
441 else:
442 return self.span / (self.npoints - 1.)
443
444 @property
445 def step_scaled(self) -> float:
446 """
447 The inter-frequency step size (in :attr:`unit`) for evenly-spaced
448 frequency sweeps.
449
450 See Also
451 --------
452 df : for general case
453 """
454 if self.span_scaled == 0:
455 return 0.
456 else:
457 return self.span_scaled / (self.npoints - 1.)
458
459 @property
460 def span(self) -> float:
461 """
462 The frequency span.
463 """
464 return abs(self.stop-self.start)
465
466 @property
467 def span_scaled(self) -> float:
468 """
469 The frequency span.
470 """
471 return abs(self.stop_scaled-self.start_scaled)
472
473 @property
474 def f(self) -> np.ndarray:
475 """
476 Frequency vector in Hz.
477
478 Returns
479 ----------
480 f : :class:`numpy.ndarray`
481 The frequency vector in Hz
482
483 See Also
484 ----------
485 f_scaled : frequency vector in units of :attr:`unit`
486 w : angular frequency vector in rad/s
487 """
488
489 return self._f
490
491
492 @property
493 def f_scaled(self) -> np.ndarray:
494 """
495 Frequency vector in units of :attr:`unit`.
496
497 Returns
498 -------
499 f_scaled : numpy.ndarray
500 A frequency vector in units of :attr:`unit`
501
502 See Also
503 --------
504 f : frequency vector in Hz
505 w : frequency vector in rad/s
506 """
507 return self.f/self.multiplier
508
509 @property
510 def w(self) -> np.ndarray:
511 r"""
512 Angular frequency in radians/s.
513
514 Angular frequency is defined as :math:`\omega=2\pi f` [#]_
515
516 Returns
517 -------
518 w : :class:`numpy.ndarray`
519 Angular frequency in rad/s
520
521 References
522 ----------
523 .. [#] https://en.wikipedia.org/wiki/Angular_frequency
524
525 See Also
526 --------
527 f_scaled : frequency vector in units of :attr:`unit`
528 f : frequency vector in Hz
529 """
530 return 2*pi*self.f
531
532 @property
533 def df(self) -> np.ndarray:
534 """
535 The gradient of the frequency vector.
536
537 Note
538 ----
539 The gradient is calculated using::
540
541 `gradient(self.f)`
542
543 """
544 return gradient(self.f)
545
546 @property
547 def df_scaled(self) -> np.ndarray:
548 """
549 The gradient of the frequency vector (in unit of :attr:`unit`).
550
551 Note
552 ----
553 The gradient is calculated using::
554
555 `gradient(self.f_scaled)`
556 """
557 return gradient(self.f_scaled)
558
559 @property
560 def dw(self) -> np.ndarray:
561 """
562 The gradient of the frequency vector (in radians).
563
564 Note
565 ----
566 The gradient is calculated using::
567
568 `gradient(self.w)`
569 """
570 return gradient(self.w)
571
572 @property
573 def unit(self) -> FrequencyUnitT:
574 """
575 Unit of this frequency band.
576
577 Possible strings for this attribute are:
578 'Hz', 'kHz', 'MHz', 'GHz', 'THz'
579
580 Setting this attribute is not case sensitive.
581
582 Returns
583 -------
584 unit : string
585 String representing the frequency unit
586 """
587 return self.unit_dict[self._unit]
588
589 @unit.setter
590 def unit(self, unit: FrequencyUnitT) -> None:
591 self._unit = unit.lower()
592
593 @property
594 def multiplier(self) -> float:
595 """
596 Multiplier for formatting axis.
597
598 This accesses the internal dictionary `multiplier_dict` using
599 the value of :attr:`unit`
600
601 Returns
602 -------
603 multiplier : number
604 multiplier for this Frequencies unit
605 """
606 return self.multiplier_dict[self._unit]
607
608 def copy(self) -> Frequency:
609 """
610 Returns a new copy of this frequency.
611 """
612 freq = Frequency.from_f(self.f, unit='Hz')
613 freq.unit = self.unit
614 return freq
615
616 def _t_padded(self, *, pad: int = 0, n: int | None = None, bandpass: bool | None = None) -> np.ndarray:
617 if bandpass is None:
618 bandpass = self.f[0] != 0
619
620 if n is None:
621 n = self.npoints + pad
622 n = n if bandpass else n * 2 - 1
623
624 if bandpass:
625 dt = 1 / (n * self.step)
626 t_stop = (n - 1) // 2 * dt
627 t_start = -t_stop - dt if n % 2 == 0 else (-n // 2 + 1) * dt
628
629 t = np.linspace(t_start, t_stop, num=n, endpoint=True)
630 else:
631 dt = 1 / (n * self.step)
632 t = np.linspace(-dt * (n // 2), dt * (n // 2), num=n, endpoint=True)
633
634 return t
635
636 @property
637 def t(self) -> np.ndarray:
638 """
639 Time vector in s.
640
641 t_period = 2*(n-1)/f_step
642 """
643 return self._t_padded(bandpass=True)
644
645 @property
646 def t_ns(self) -> np.ndarray:
647 """
648 Time vector in ns.
649
650 t_period = 2*(n-1)/f_step
651 """
652 return self.t*1e9
653
654 def round_to(self, val: FrequencyUnitT | Number = 'Hz') -> None:
655 """
656 Round off frequency values to a specified precision.
657
658 This is useful for dealing with finite precision limitations of
659 VNA's and/or other software
660
661 Parameters
662 ----------
663 val : string or number
664 if val is a string it should be a frequency :attr:`unit`
665 (ie 'Hz', 'MHz',etc). if its a number, then this returns
666 f = f-f%val
667
668 Examples
669 --------
670 >>> f = skrf.Frequency.from_f([.1,1.2,3.5],unit='Hz')
671 >>> f.round_to('Hz')
672
673 """
674 if isinstance(val, str):
675 val = self.multiplier_dict[val.lower()]
676
677 self.f = np.round(self.f/val)*val
678
679 def overlap(self,f2: Frequency) -> Frequency:
680 """
681 Calculates overlapping frequency between self and f2.
682
683 See Also
684 --------
685 overlap_freq
686
687 """
688 return overlap_freq(self, f2)
689
690 @property
691 def sweep_type(self) -> str:
692 """
693 Frequency sweep type.
694
695 Returns
696 -------
697 sweep_type: str
698 'lin' if linearly increasing, 'log' or 'unknown'.
699
700 """
701 if np.allclose(self.f, linspace(self.f[0], self.f[-1], self.npoints), rtol=0.05):
702 sweep_type = 'lin'
703 elif self.f[0] and np.allclose(self.f, geomspace(self.f[0], self.f[-1], self.npoints), rtol=0.05):
704 sweep_type = 'log'
705 else:
706 sweep_type = 'unknown'
707 return sweep_type
708
709 @axes_kwarg
710 def labelXAxis(self, ax: Axes = None):
711 """
712 Label the x-axis of a plot.
713
714 Sets the labels of a plot using :func:`matplotlib.x_label` with
715 string containing the frequency unit.
716
717 Parameters
718 ----------
719 ax : :class:`matplotlib.Axes` or None, optional
720 Axes on which to label the plot.
721 Defaults is None, for the current axe
722 returned by :func:`matplotlib.gca()`
723 """
724
725 ax.set_xlabel(f'Frequency ({self.unit})')
726
727 @axes_kwarg
728 def plot(self, y: NumberLike, *args, ax: Axes=None, **kwargs):
729 """
730 Plot something vs this frequency.
731
732 This plots whatever is given vs. `self.f_scaled` and then
733 calls `labelXAxis`.
734 """
735
736 from .plotting import scale_frequency_ticks
737
738 try:
739 if len(np.shape(y)) > 2:
740 # perhaps the dimensions are empty, try to squeeze it down
741 y = y.squeeze()
742 if len(np.shape(y)) > 2:
743 # the dimensions are full, so lets loop and plot each
744 for m in range(np.shape(y)[1]):
745 for n in range(np.shape(y)[2]):
746 self.plot(y[:, m, n], *args, **kwargs)
747 return
748 if len(y) == len(self):
749 pass
750 else:
751
752 raise IndexError(['thing to plot doesn\'t have same'
753 ' number of points as f'])
754 except(TypeError):
755 y = y * np.ones(len(self))
756
757 # plt.plot(self.f_scaled, y, *args, **kwargs)
758 ax.plot(self.f, y, *args, **kwargs)
759 scale_frequency_ticks(ax, self.unit)
760 ax.autoscale(axis='x', tight=True)
761 self.labelXAxis()
762
763
764 def overlap_freq(f1: Frequency,f2: Frequency) -> Frequency:
765 """
766 Calculates overlapping frequency between f1 and f2.
767
768 Or, put more accurately, this returns a Frequency that is the part
769 of f1 that is overlapped by f2. The resultant start frequency is
770 the smallest f1.f that is greater than f2.f.start, and the stop
771 frequency is the largest f1.f that is smaller than f2.f.stop.
772
773 This way the new frequency overlays onto f1.
774
775
776 Parameters
777 ----------
778 f1 : :class:`Frequency`
779 a frequency object
780 f2 : :class:`Frequency`
781 a frequency object
782
783 Returns
784 -------
785 f3 : :class:`Frequency`
786 part of f1 that is overlapped by f2
787
788 """
789 if f1.start > f2.stop:
790 raise ValueError('Out of bounds. f1.start > f2.stop')
791 elif f2.start > f1.stop:
792 raise ValueError('Out of bounds. f2.start > f1.stop')
793
794
795 start = max(f1.start, f2.start)
796 stop = min(f1.stop, f2.stop)
797 f = f1.f[(f1.f>=start) & (f1.f<=stop)]
798 freq = Frequency.from_f(f, unit = 'Hz')
799 freq.unit = f1.unit
800 return freq