Debian Codegraph @

skrf/mathFunctions.py

raw symbols SCIP
1 """
2 mathFunctions (:mod:`skrf.mathFunctions`)
3 =============================================
4
5
6 Provides commonly used mathematical functions.
7
8 Mathematical Constants
9 ----------------------
10 Some convenient constants are defined in the :mod:`skrf.constants` module.
11
12 Complex Component Conversion
13 ----------------------------
14
15 .. autosummary::
16 :toctree: generated/
17
18 complex_2_reim
19 complex_2_magnitude
20 complex_2_db
21 complex_2_db10
22 complex_2_radian
23 complex_2_degree
24 complex_2_magnitude
25 complex_2_quadrature
26 complex_components
27
28 Magnitude and decibel
29 ---------------------
30
31 .. autosummary::
32 :toctree: generated/
33
34 magnitude_2_db
35 mag_2_db
36 mag_2_db10
37 db_2_magnitude
38 db_2_mag
39 db10_2_mag
40
41 Phase Unwrapping
42 ----------------
43
44 .. autosummary::
45 :toctree: generated/
46
47 unwrap_rad
48 sqrt_phase_unwrap
49
50 Unit Conversion
51 ---------------
52
53 .. autosummary::
54 :toctree: generated/
55
56 radian_2_degree
57 degree_2_radian
58 np_2_db
59 db_2_np
60 feet_2_meter
61 meter_2_feet
62 db_per_100feet_2_db_per_100meter
63
64 Scalar-Complex Conversion
65 -------------------------
66
67 These conversions are useful for wrapping other functions that don't
68 support complex numbers.
69
70 .. autosummary::
71 :toctree: generated/
72
73 complex2Scalar
74 scalar2Complex
75
76 Special Functions
77 -----------------
78
79 .. autosummary::
80 :toctree: generated/
81
82 dirac_delta
83 neuman
84 null
85 cross_ratio
86
87 Random Number Generation
88 ------------------------
89
90 .. autosummary::
91 :toctree: generated/
92
93 set_rand_rng
94 rand_rng
95 rand_c
96
97 Various Utility Functions
98 --------------------------
99 .. autosummary::
100 :toctree: generated/
101
102 psd2TimeDomain
103 rational_interp
104 ifft
105 irfft
106 is_square
107 is_symmetric
108 is_Hermitian
109 is_positive_definite
110 is_positive_semidefinite
111 get_Hermitian_transpose
112 sqrt_known_sign
113 find_correct_sign
114 find_closest
115 inf_to_num
116 rsolve
117 nudge_eig
118
119
120 """
121 from __future__ import annotations
122
123 from collections.abc import Callable
124
125 import numpy as np
126 from numpy import imag, pi, real, unwrap
127 from scipy import signal
128
129 from .constants import ALMOST_ZERO, EIG_COND, EIG_MIN, INF, LOG_OF_NEG, NumberLike
130
131
132 # simple conversions
133 def complex_2_magnitude(z: NumberLike):
134 """
135 Return the magnitude of the complex argument.
136
137 Parameters
138 ----------
139 z : number or array_like
140 A complex number or sequence of complex numbers
141
142 Returns
143 -------
144 mag : ndarray or scalar
145
146 """
147 return np.abs(z)
148
149
150 def complex_2_db(z: NumberLike):
151 r"""
152 Return the magnitude in dB of a complex number (as :math:`20\log_{10}(|z|)`)..
153
154 The magnitude in dB is defined as :math:`20\log_{10}(|z|)`
155 where :math:`z` is a complex number.
156
157 Parameters
158 ----------
159 z : number or array_like
160 A complex number or sequence of complex numbers
161
162 Returns
163 -------
164 mag20dB : ndarray or scalar
165 """
166 return magnitude_2_db(np.abs(z))
167
168
169 def complex_2_db10(z: NumberLike):
170 r"""
171 Return the magnitude in dB of a complex number (as :math:`10\log_{10}(|z|)`).
172
173 The magnitude in dB is defined as :math:`10\log_{10}(|z|)`
174 where :math:`z` is a complex number.
175
176 Parameters
177 ----------
178 z : number or array_like
179 A complex number or sequence of complex numbers
180
181 Returns
182 -------
183 mag10dB : ndarray or scalar
184 """
185 return mag_2_db10(np.abs(z))
186
187
188 def complex_2_radian(z: NumberLike):
189 """
190 Return the angle complex argument in radian.
191
192 Parameters
193 ----------
194 z : number or array_like
195 A complex number or sequence of complex numbers
196
197 Returns
198 -------
199 ang_rad : ndarray or scalar
200 The counterclockwise angle from the positive real axis on the complex
201 plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
202 """
203 return np.angle(z)
204
205
206 def complex_2_degree(z: NumberLike):
207 """
208 Returns the angle complex argument in degree.
209
210 Parameters
211 ----------
212 z : number or array_like
213 A complex number or sequence of complex numbers
214
215 Returns
216 -------
217 ang_deg : ndarray or scalar
218 """
219 return np.angle(z, deg=True)
220
221
222 def complex_2_quadrature(z: NumberLike):
223 r"""
224 Take a complex number and returns quadrature, which is (length, arc-length from real axis)
225
226 Arc-length is calculated as :math:`|z| \arg(z)`.
227
228 Parameters
229 ----------
230 z : number or array_like
231 A complex number or sequence of complex numbers
232
233 Returns
234 -------
235 mag : array like or scalar
236 magnitude (length)
237 arc_length : array like or scalar
238 arc-length from real axis: angle*magnitude
239 """
240 return (np.abs(z), np.angle(z)*np.abs(z))
241
242
243 def complex_2_reim(z: NumberLike):
244 """
245 Return real and imaginary parts of a complex number.
246
247 Parameters
248 ----------
249 z : number or array_like
250 A complex number or sequence of complex numbers
251
252 Returns
253 -------
254 real : array like or scalar
255 real part of input
256 imag : array like or scalar
257 imaginary part of input
258 """
259 return (np.real(z), np.imag(z))
260
261
262 def complex_components(z: NumberLike):
263 """
264 Break up a complex array into all possible scalar components.
265
266 Parameters
267 ----------
268 z : number or array_like
269 A complex number or sequence of complex numbers
270
271 Returns
272 -------
273 c_real : array like or scalar
274 real part
275 c_imag : array like or scalar
276 imaginary part
277 c_angle : array like or scalar
278 angle in degrees
279 c_mag : array like or scalar
280 magnitude
281 c_arc : array like or scalar
282 arclength from real axis, angle*magnitude
283 """
284 return (*complex_2_reim(z), np.angle(z,deg=True), *complex_2_quadrature(z))
285
286
287 def magnitude_2_db(z: NumberLike, zero_nan: bool = True):
288 """
289 Convert linear magnitude to dB.
290
291 Parameters
292 ----------
293 z : number or array_like
294 A complex number or sequence of complex numbers
295 zero_nan : bool, optional
296 Replace NaN with zero. The default is True.
297
298 Returns
299 -------
300 z : number or array_like
301 Magnitude in dB given by 20*log10(|z|)
302 """
303 out = 20 * np.log10(z)
304 if zero_nan:
305 return np.nan_to_num(out, nan=LOG_OF_NEG, neginf=-np.inf)
306 return out
307
308 mag_2_db = magnitude_2_db
309
310
311 def mag_2_db10(z: NumberLike, zero_nan:bool = True):
312 """
313 Convert linear magnitude to dB.
314
315 Parameters
316 ----------
317 z : array_like
318 A complex number or sequence of complex numbers
319 zero_nan : bool, optional
320 Replace NaN with zero. The default is True.
321
322 Returns
323 -------
324 z : array_like
325 Magnitude in dB given by 10*log10(|z|)
326 """
327 out = 10 * np.log10(z)
328 if zero_nan:
329 return np.nan_to_num(out, nan=LOG_OF_NEG, neginf=-np.inf)
330 return out
331
332
333 def db_2_magnitude(z: NumberLike):
334 """
335 Convert dB to linear magnitude.
336
337 Parameters
338 ----------
339 z : number or array_like
340 A complex number or sequence of complex numbers
341
342 Returns
343 -------
344 z : number or array_like
345 10**((z)/20) where z is a complex number
346 """
347 return 10**((z)/20.)
348
349 db_2_mag = db_2_magnitude
350
351
352 def db10_2_mag(z: NumberLike):
353 """
354 Convert dB to linear magnitude.
355
356 Parameters
357 ----------
358 z : array_like
359 A complex number or sequence of complex numbers
360
361 Returns
362 -------
363 z : array_like
364 10**((z)/10) where z is a complex number
365 """
366 return 10**((z)/10.)
367
368
369 def magdeg_2_reim(mag: NumberLike, deg: NumberLike):
370 """
371 Convert linear magnitude and phase (in deg) arrays into a complex array.
372
373 Parameters
374 ----------
375 mag : number or array_like
376 A complex number or sequence of real numbers
377 deg : number or array_like
378 A complex number or sequence of real numbers
379
380 Returns
381 -------
382 z : array_like
383 A complex number or sequence of complex numbers
384
385 """
386 return mag*np.exp(1j*deg*pi/180.)
387
388 def dbdeg_2_reim(db: NumberLike, deg: NumberLike):
389 """
390 Converts dB magnitude and phase (in deg) arrays into a complex array.
391
392 Parameters
393 ----------
394 db : number or array_like
395 A realnumber or sequence of real numbers
396 deg : number or array_like
397 A real number or sequence of real numbers
398
399 Returns
400 -------
401 z : array_like
402 A complex number or sequence of complex numbers
403 """
404 return magdeg_2_reim(db_2_magnitude(db), deg)
405
406
407 def db_2_np(db: NumberLike):
408 """
409 Converts a value in decibel (dB) to neper (Np).
410
411 Parameters
412 ----------
413 db : number or array_like
414 A real number or sequence of real numbers
415
416 Returns
417 -------
418 np : number or array_like
419 A real number of sequence of real numbers
420 """
421 return (np.log(10)/20) * db
422
423
424 def np_2_db(x: NumberLike):
425 """
426 Converts a value in Nepers (Np) to decibel (dB).
427
428 Parameters
429 ----------
430 np : number or array_like
431 A real number or sequence of real numbers
432
433 Returns
434 -------
435 db : number or array_like
436 A real number of sequence of real numbers
437 """
438 return 20/np.log(10) * x
439
440
441 def radian_2_degree(rad: NumberLike):
442 """
443 Convert angles from radians to degrees.
444
445 Parameters
446 ----------
447 rad : number or array_like
448 Angle in radian
449
450 Returns
451 -------
452 deg : number or array_like
453 Angle in degree
454 """
455 return (rad)*180/pi
456
457
458 def degree_2_radian(deg: NumberLike):
459 """
460 Convert angles from degrees to radians.
461
462 Parameters
463 ----------
464 deg : number or array_like
465 Angle in radian
466
467 Returns
468 -------
469 rad : number or array_like
470 Angle in degree
471 """
472 return (deg)*pi/180.
473
474
475 def feet_2_meter(feet: NumberLike = 1):
476 """
477 Convert length in feet to meter.
478
479 1 foot is equal to 0.3048 meters.
480
481 Parameters
482 ----------
483 feet : number or array-like, optional
484 length in feet. Default is 1.
485
486 Returns
487 -------
488 meter: number or array-like
489 length in meter
490
491 See Also
492 --------
493 meter_2_feet
494 """
495 return 0.3048*feet
496
497 def meter_2_feet(meter: NumberLike = 1):
498 """
499 Convert length in meter to feet.
500
501 1 meter is equal to 0.3.28084 feet.
502
503 Parameters
504 ----------
505 meter : number or array-like, optional
506 length in meter. Default is 1.
507
508 Returns
509 -------
510 feet : number or array-like
511 length in feet
512
513 See Also
514 --------
515 feet_2_meter
516 """
517 return 3.28084*meter
518
519
520 def db_per_100feet_2_db_per_100meter(db_per_100feet: NumberLike = 1):
521 """
522 Convert attenuation values given in dB/100ft to dB/100m.
523
524 db_per_100meter = db_per_100feet * rf.meter_2_feet()
525
526 Parameters
527 ----------
528 db_per_100feet : number or array-like, optional
529 Attenuation in dB/ 100 ft. Default is 1.
530
531 Returns
532 -------
533 db_per_100meter : number or array-like
534 Attenuation in dB/ 100 m
535
536 See Also
537 --------
538 meter_2_feet
539 feet_2_meter
540 np_2_db
541 db_2_np
542 """
543 return db_per_100feet * 100 / feet_2_meter(100)
544
545
546 def unwrap_rad(phi: NumberLike):
547 """
548 Unwraps a phase given in radians.
549
550 Parameters
551 ----------
552 phi : number or array_like
553 phase in radians
554
555 Returns
556 -------
557 phi : number of array_like
558 unwrapped phase in radians
559 """
560 return unwrap(phi, axis=0)
561
562
563 def sqrt_known_sign(z_squared: NumberLike, z_approx: NumberLike):
564 """
565 Return the square root of a complex number, with sign chosen to match `z_approx`.
566
567 Parameters
568 ----------
569 z_squared : number or array-like
570 the complex to be square-rooted
571 z_approx : number or array-like
572 the approximate value of z. sign of z is chosen to match that of
573 z_approx
574
575 Returns
576 -------
577 z : number, array-like (same type as z_squared)
578 square root of z_squared.
579 """
580 z = np.sqrt(z_squared)
581 return np.where(
582 np.sign(np.angle(z)) == np.sign(np.angle(z_approx)),
583 z, z.conj())
584
585
586 def find_correct_sign(z1: NumberLike, z2: NumberLike, z_approx: NumberLike):
587 r"""
588 Create new vector from z1, z2 choosing elements with sign matching z_approx.
589
590 This is used when you have to make a root choice on a complex number.
591 and you know the approximate value of the root.
592
593 .. math::
594
595 z1,z2 = \pm \sqrt(z^2)
596
597
598 Parameters
599 ----------
600 z1 : array-like
601 root 1
602 z2 : array-like
603 root 2
604 z_approx : array-like
605 approximate answer of z
606
607 Returns
608 -------
609 z3 : np.array
610 array built from z1 and z2 by
611 z1 where sign(z1) == sign(z_approx), z2 else
612
613 """
614 return np.where(
615 np.sign(np.angle(z1)) == np.sign(np.angle(z_approx)),z1, z2)
616
617
618 def find_closest(z1: NumberLike, z2: NumberLike, z_approx: NumberLike):
619 """
620 Return z1 or z2 depending on which is closer to z_approx.
621
622 Parameters
623 ----------
624 z1 : array-like
625 root 1
626 z2 : array-like
627 root 2
628 z_approx : array-like
629 approximate answer of z
630
631 Returns
632 -------
633 z3 : np.array
634 array built from z1 and z2
635
636 """
637 z1_dist = abs(z1-z_approx)
638 z2_dist = abs(z2-z_approx)
639
640 return np.where(z1_dist<z2_dist,z1, z2)
641
642 def sqrt_phase_unwrap(z: NumberLike):
643 r"""
644 Take the square root of a complex number with unwrapped phase.
645
646 This idea came from Lihan Chen.
647
648 .. math::
649
650 \sqrt{|z|} \exp( \arg_{unwrap}(z) / 2 )
651
652
653 Parameters
654 ----------
655 z : number or array_like
656 A complex number or sequence of complex numbers
657
658 Returns
659 -------
660 z : number of array_like
661 A complex number or sequence of complex numbers
662 """
663 return np.sqrt(abs(z))*\
664 np.exp(0.5*1j*unwrap_rad(complex_2_radian(z)))
665
666
667 # mathematical functions
668 def dirac_delta(x: NumberLike):
669 r"""
670 Calculate Dirac function.
671
672 Dirac function :math:`\delta(x)` defined as :math:`\delta(x)=1` if x=0,
673 0 otherwise.
674
675 Parameters
676 ----------
677 x : number of array_like
678 A real number or sequence of real numbers
679
680 Returns
681 -------
682 delta : number of array_like
683 1 or 0
684
685 References
686 ----------
687 https://en.wikipedia.org/wiki/Dirac_delta_function
688
689 """
690 return (x==0)*1. + (x!=0)*0.
691
692
693 def neuman(x: NumberLike):
694 r"""
695 Calculate Neumans number.
696
697 It is defined as:
698
699 .. math::
700
701 2 - \delta(x)
702
703 where :math:`\delta` is the Dirac function.
704
705 Parameters
706 ----------
707 x : number or array_like
708 A real number or sequence of real numbers
709
710 Returns
711 -------
712 y : number or array_like
713 A real number or sequence of real numbers
714
715 See Also
716 --------
717 dirac_delta
718 """
719 return 2. - dirac_delta(x)
720
721
722 def null(A: np.ndarray, eps: float = 1e-15):
723 """
724 Calculate the null space of matrix A.
725
726 Parameters
727 ----------
728 A : array_like
729 eps : float
730
731 Returns
732 -------
733 null_space : array_like
734
735 References
736 ----------
737 https://scipy-cookbook.readthedocs.io/items/RankNullspace.html
738 https://stackoverflow.com/questions/5889142/python-numpy-scipy-finding-the-null-space-of-a-matrix
739 """
740 u, s, vh = np.linalg.svd(A)
741 null_space = np.compress(s <= eps, vh, axis=0)
742 return null_space.T
743
744
745 def inf_to_num(x: NumberLike):
746 """
747 Convert inf and -inf's to large numbers.
748
749 Parameters
750 ------------
751 x : array-like or number
752 the input array or number
753
754 Returns
755 -------
756 x : Number of array_like
757 Input without with +/- inf replaced by large numbers
758 """
759 x = np.nan_to_num(x, nan=np.nan, posinf=INF, neginf=-1*INF)
760 return x
761
762
763 def cross_ratio(a: NumberLike, b: NumberLike, c: NumberLike, d:NumberLike):
764 r"""
765 Calculate the cross ratio of a quadruple of distinct points on the real line.
766
767
768 The cross ratio is defined as:
769
770
771 .. math::
772
773 r = \frac{ (a-b)(c-d) }{ (a-d)(c-b) }
774
775
776
777 Parameters
778 ----------
779 a,b,c,d : array-like or number
780
781 Returns
782 -------
783 r : array-like or number
784
785 References
786 ----------
787 https://en.wikipedia.org/wiki/Cross-ratio
788
789 """
790 return ((a-b)*(c-d))/((a-d)*(c-b))
791
792
793 def complexify(f: Callable, name: str = None):
794 """
795 Make a function f(scalar) into f(complex).
796
797 If `f(x)` then it returns `f_c(z) = f(real(z)) + 1j*f(imag(z))`
798
799 If the real/imag arguments are not first, then you may specify the
800 name given to them as kwargs.
801
802 Parameters
803 ----------
804 f : Callable
805 function of real variable
806 name : string, optional
807 name of the real/imag argument names if they are not first
808
809 Returns
810 -------
811 f_c : Callable
812 function of a complex variable
813
814 Examples
815 --------
816 >>> def f(x): return x
817 >>> f_c = rf.complexify(f)
818 >>> z = 0.2 -1j*0.3
819 >>> f_c(z)
820
821 """
822 def f_c(z, *args, **kw):
823 if name is not None:
824 kw_re = {name: real(z)}
825 kw_im = {name: imag(z)}
826 kw_re.update(kw)
827 kw_im.update(kw)
828 return f(*args, **kw_re) + 1j*f(*args, **kw_im)
829 else:
830 return f(real(z), *args,**kw) + 1j*f(imag(z), *args, **kw)
831 return f_c
832
833
834
835 # old functions just for reference
836 def complex2Scalar(z: NumberLike):
837 """
838 Serialize a list/array of complex numbers
839
840 Parameters
841 ----------
842 z : number or array_like
843 A complex number or sequence of complex numbers
844
845 Returns
846 -------
847 re_im : array_like
848 produce the following array for an input z:
849 z[0].real, z[0].imag, z[1].real, z[1].imag, etc.
850
851 See Also
852 --------
853 scalar2Complex
854 """
855 z = np.array(z)
856 re_im = []
857 for k in z:
858 re_im.append(np.real(k))
859 re_im.append(np.imag(k))
860 return np.array(re_im).flatten()
861
862 def scalar2Complex(s: NumberLike):
863 """
864 Unserialize a list/array of real and imag numbers into a complex array.
865
866 Inverse of :func:`complex2Scalar`.
867
868 Parameters
869 ----------
870 s : array_like
871 an array with real and imaginary parts ordered as:
872 z[0].real, z[0].imag, z[1].real, z[1].imag, etc.
873
874 Returns
875 -------
876 z : Number or array_like
877 A complex number or sequence of complex number
878
879 See Also
880 --------
881 complex2Scalar
882 """
883 s = np.array(s)
884 z = []
885
886 for k in range(0,len(s),2):
887 z.append(s[k] + 1j*s[k+1])
888 return np.array(z).flatten()
889
890
891 def flatten_c_mat(s: NumberLike, order: str = 'F'):
892 """
893 Take a 2D (mxn) complex matrix and serialize and flatten it.
894
895 by default (using order='F') this generates the following
896 from a 2x2
897
898 [s11,s12;s21,s22]->[s11re,s11im,s21re,s12im, ...]
899
900 Parameters
901 ------------
902 s : ndarray
903 input 2D array
904 order : string, optional
905 either 'F' or 'C', for the order of flattening
906 """
907 return complex2Scalar(s.flatten(order='F'))
908
909
910 _global_rng = np.random.default_rng()
911
912
913 def set_rand_rng(rng: np.random.Generator) -> None:
914 """
915 Set the global :mod:`numpy` random number generator instance
916 for generating random numbers in scikit-rf. This is useful for
917 fixing a random seed for reproducible Monte Carlo analysis.
918
919 This function is expected to be called before using any scikit-rf
920 features, since it's a global variable and thread-unsafe. To temporarily
921 change the random number generator of a particular method (e.g.
922 :meth:`skrf.media.Media.random`), use the ``rng`` argument instead.
923
924 Parameters
925 -----------
926 rng : :class:`numpy.random.Generator`
927 Any random number generator accepted by :mod:`numpy`.
928
929 Examples
930 ---------
931 >>> set_rand_rng(np.random.default_rng(seed=42))
932 """
933 global _global_rng
934 _global_rng = rng
935
936
937 def rand_rng() -> np.random.Generator:
938 """
939 Obtain the global :mod:`numpy` random number generator instance.
940 By default, it is :func:`numpy.random.default_rng`.
941 """
942 return _global_rng
943
944
945 def rand_c(*size, rng=None) -> np.ndarray:
946 """
947 Creates a complex random array of shape s.
948
949 The bounds on real and imaginary values are (-1,1)
950
951 Parameters
952 -----------
953 s : list-like
954 shape of array
955
956 rng : :class:`numpy.random.Generator` or None
957 Any random number generator accepted by :mod:`numpy`.
958
959 Examples
960 ---------
961 >>> x1 = rf.rand_c(2, 2)
962 >>> x2 = rf.rand_c(2, 2, np.random.default_rng(seed=42))
963 """
964 if rng is None:
965 rng = _global_rng
966 return 1-2*rng.random(size) + \
967 1j-2j*rng.random(size)
968
969
970 def psd2TimeDomain(f: np.ndarray, y: np.ndarray, windowType: str = 'hamming'):
971 """
972 Convert a one sided complex spectrum into a real time-signal.
973
974 Parameters
975 ----------
976 f : list or np.ndarray
977 frequency array
978 y : list of np.ndarray
979 complex PSD array
980 windowType: string
981 windowing function, defaults to 'hamming''
982
983 Returns
984 -------
985 timeVector : array_like
986 inverse units of the input variable f,
987 signalVector : array_like
988
989 Note
990 ----
991 If spectrum is not baseband then, `timeSignal` is modulated by `exp(t*2*pi*f[0])`.
992 So keep in mind units. Also, due to this, `f` must be increasing left to right.
993 """
994
995
996 # apply window function
997 # make sure windowType exists in scipy.signal
998 if callable(getattr(signal, windowType)) and (windowType != 'rect' ):
999 window = getattr(signal, windowType)(len(f))
1000 y = y * window
1001
1002 #create other half of spectrum
1003 spectrum = (np.hstack([np.real(y[:0:-1]),np.real(y)])) + \
1004 1j*(np.hstack([-np.imag(y[:0:-1]),np.imag(y)]))
1005
1006 # do the transform
1007 df = abs(f[1]-f[0])
1008 T = 1./df
1009 timeVector = np.linspace(-T/2.,T/2,2*len(f)-1)
1010 signalVector = np.fft.ifftshift(np.fft.ifft(np.fft.ifftshift(spectrum)))
1011
1012 #the imaginary part of this signal should be from fft errors only,
1013 signalVector= np.real(signalVector)
1014 # the response of frequency shifting is
1015 # exp(1j*2*pi*timeVector*f[0])
1016 # but I would have to manually undo this for the inverse, which is just
1017 # another variable to require. The reason you need this is because
1018 # you can't transform to a bandpass signal, only a lowpass.
1019 #
1020 return timeVector, signalVector
1021
1022
1023 def rational_interp(
1024 x: np.ndarray,
1025 y: np.ndarray,
1026 d: int = 4,
1027 epsilon: float = 1e-9,
1028 axis: int = 0,
1029 assume_sorted: bool = False) -> Callable:
1030 """
1031 Interpolates function using rational polynomials of degree `d`.
1032
1033 Interpolating function is singular when xi is exactly one of the
1034 original x points. If xi is closer than epsilon to one of the original points,
1035 then the value at that points is returned instead.
1036
1037 Implementation is based on [#]_.
1038
1039 Parameters
1040 ----------
1041 x : np.ndarray
1042 y : np.ndarray
1043 d : int, optional
1044 order of the polynomial, by default 4
1045 epsilon : float, optional
1046 numerical tolerance, by default 1e-9
1047 axis : int, optional
1048 axis to operate on, by default 0
1049 assume_sorted : bool, optional
1050 If False, values of x can be in any order and they are sorted first.
1051 If True, x has to be an array of monotonically increasing values.
1052
1053 Returns
1054 -------
1055 fx : Callable
1056 Interpolate function
1057
1058 Raises
1059 ------
1060 NotImplementedError
1061 if axis != 0.
1062
1063 References
1064 ------------
1065 .. [#] M. S. Floater and K. Hormann, "Barycentric rational interpolation with no poles and high rates of
1066 approximation," Numer. Math., vol. 107, no. 2, pp. 315-331, Aug. 2007
1067 """
1068 if axis != 0:
1069 raise NotImplementedError("Axis other than 0 is not implemented")
1070
1071 if not assume_sorted:
1072 sort_indices = np.argsort(x, axis=axis)
1073 x = x[sort_indices]
1074 y = y[sort_indices]
1075
1076 n = len(x)
1077 if n <= d:
1078 raise ValueError('Not enough x-axis points')
1079
1080 w = np.zeros(n)
1081 # Scaling to give close to 1 weights
1082 hd = (x[n//2] - x[n//2-1])**d
1083 for k in range(n):
1084 for i in range(max(0,k-d), min(k+1, n-d)):
1085 p, xk = hd, x[k]
1086 for j in range(i,min(n,i+d+1)):
1087 if j == k:
1088 continue
1089 p /= (xk - x[j])
1090 if i % 2 == 1:
1091 w[k] -= p
1092 else:
1093 w[k] += p
1094
1095 # Add dimensions to match y shape
1096 w_shape = [1]*len(y.shape)
1097 w_shape[0] = -1
1098 w = w.reshape(w_shape)
1099
1100 def fx(xi):
1101 # The method will divide by zero if new x value is exactly existing x value.
1102 # To avoid this we need to check for too close values and replace them with
1103 # y value at that position.
1104 idx = np.searchsorted(x, xi)
1105 idx[idx == len(x)] = len(x) - 1
1106 nearest_idx = np.where(np.abs(x[idx] - xi) < epsilon)[0]
1107 nearest_value = y[idx[nearest_idx]]
1108
1109 xi = xi.reshape(*w_shape)
1110 with np.errstate(divide='ignore', invalid='ignore'):
1111 assert axis == 0
1112 tmp = [w[i] / (xi - x[i]) for i in range(n)]
1113 v = sum(y[i] * tmp[i] for i in range(n)) / sum(tmp)
1114
1115 # Fix divide by zero errors
1116 for e, i in enumerate(nearest_idx):
1117 v[i] = nearest_value[e]
1118
1119 return v
1120
1121 return fx
1122
1123 def ifft(x: np.ndarray) -> np.ndarray:
1124 """
1125 Transforms S-parameters to time-domain bandpass.
1126
1127 Parameters
1128 ----------
1129 x : array_like
1130 S-parameters vs frequency array.
1131
1132 Returns
1133 -------
1134 X : array_like
1135 Fourier transformed array
1136
1137 See Also
1138 --------
1139 irfft
1140 """
1141 return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(x, axes=0), axis=0), axes=0)
1142
1143
1144 def irfft(x: np.ndarray, n:int = None) -> np.ndarray:
1145 """
1146 Transforms S-parameters to time-domain, assuming complex conjugates for
1147 values corresponding to negative frequencies.
1148
1149 Parameters
1150 ----------
1151 x : array_like
1152 S-parameters vs frequency array.
1153 n : int, optional
1154 n parameter passed to :func:`numpy.fft.irfft`. Defaults to None.
1155
1156 Returns
1157 -------
1158 X : array_like
1159 Fourier transformed array
1160
1161 See Also
1162 --------
1163 ifft
1164 """
1165 return np.fft.fftshift(np.fft.irfft(x, axis=0, n=n), axes=0)
1166
1167
1168 def is_square(mat: np.ndarray) -> bool:
1169 """
1170 Tests whether mat is a square matrix.
1171
1172 Parameters
1173 ----------
1174 mat : np.ndarray
1175 Matrix to test for being square
1176
1177 Returns
1178 -------
1179 res : boolean
1180
1181 See Also
1182 --------
1183 is_unitary
1184 is_symmetric
1185 """
1186 return mat.shape[0] == mat.shape[1]
1187
1188
1189 def is_unitary(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
1190 """
1191 Tests mat for unitariness.
1192
1193 Parameters
1194 ----------
1195 mat : np.ndarray
1196 Matrix to test for unitariness
1197 tol : float
1198 Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
1199
1200 Returns
1201 -------
1202 res : boolean or array of boolean
1203
1204 See Also
1205 --------
1206 is_square
1207 is_symmetric
1208
1209 """
1210 if not is_square(mat):
1211 return False
1212 return np.allclose(get_Hermitian_transpose(mat) @ mat,
1213 np.identity(mat.shape[0]), atol=tol)
1214
1215
1216 def is_symmetric(mat: np.ndarray, tol: int = ALMOST_ZERO) -> bool:
1217 """
1218 Tests mat for symmetry.
1219
1220 Parameters
1221 ----------
1222 mat : np.ndarray
1223 Matrix to test for symmetry
1224 tol : float, optional
1225 Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
1226
1227 Returns
1228 -------
1229 res : boolean or array of boolean
1230
1231 See Also
1232 --------
1233 is_square
1234 is_unitary
1235 """
1236 if not is_square(mat):
1237 return False
1238 return np.allclose(mat, mat.transpose(), atol=tol)
1239
1240
1241 def get_Hermitian_transpose(mat: np.ndarray) -> np.ndarray:
1242 """
1243 Returns the conjugate transpose of mat.
1244
1245 Parameters
1246 ----------
1247 mat : np.ndarray
1248 Matrix to compute the conjugate transpose of
1249
1250 Returns
1251 -------
1252 mat : np.ndarray
1253
1254 """
1255 return mat.transpose().conjugate()
1256
1257
1258 def is_Hermitian(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
1259 """
1260 Tests whether mat is Hermitian.
1261
1262 Parameters
1263 ----------
1264 mat : np.ndarray
1265 Matrix to test for being Hermitian
1266 tol : float
1267 Absolute tolerance
1268
1269 Returns
1270 -------
1271 res : boolean
1272
1273 See Also
1274 --------
1275 is_positive_definite
1276 is_positive_semidefinite
1277 """
1278 if not is_square(mat):
1279 return False
1280 return np.allclose(mat, get_Hermitian_transpose(mat), atol=tol)
1281
1282
1283 def is_positive_definite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
1284 """
1285 Tests mat for positive definiteness.
1286
1287 Verifying that
1288 (1) mat is symmetric
1289 (2) it's possible to compute the Cholesky decomposition of mat.
1290
1291 Parameters
1292 ----------
1293 mat : np.ndarray
1294 Matrix to test for positive definiteness
1295 tol : float, optional
1296 Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
1297
1298 Returns
1299 -------
1300 res : bool or array of bool
1301
1302 See Also
1303 --------
1304 is_Hermitian
1305 is_positive_semidefinite
1306 """
1307 if not is_Hermitian(mat, tol=tol):
1308 return False
1309 try:
1310 np.linalg.cholesky(mat)
1311 return True
1312 except np.linalg.LinAlgError:
1313 return False
1314
1315
1316 def is_positive_semidefinite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
1317 """
1318 Tests mat for positive semidefiniteness.
1319
1320 Checking whether all eigenvalues of mat are nonnegative within a certain tolerance
1321
1322 Parameters
1323 ----------
1324 mat : np.ndarray
1325 Matrix to test for positive semidefiniteness
1326 tol : float, optional
1327 Absolute tolerance in determining nonnegativity due to loss of precision
1328 when computing the eigenvalues of mat. Defaults to :data:`ALMOST_ZERO`
1329
1330 Returns
1331 -------
1332 res : bool or array of bool
1333
1334 See Also
1335 --------
1336 is_Hermitian
1337 is_positive_definite
1338 """
1339 if not is_Hermitian(mat):
1340 return False
1341 try:
1342 v = np.linalg.eigvalsh(mat)
1343 except np.linalg.LinAlgError:
1344 return False
1345 return np.all(v > -tol)
1346
1347 def rsolve(A: np.ndarray, B: np.ndarray) -> np.ndarray:
1348 r"""Solves x @ A = B.
1349
1350 Calls numpy.linalg.solve with transposed matrices.
1351
1352 Same as B @ np.linalg.inv(A) but avoids calculating the inverse and
1353 should be numerically slightly more accurate.
1354
1355 Input should have dimension of similar to (nfreqs, nports, nports).
1356
1357 Parameters
1358 ----------
1359 A : np.ndarray
1360 B : np.ndarray
1361
1362 Returns
1363 -------
1364 x : np.ndarray
1365 """
1366 return np.transpose(np.linalg.solve(np.transpose(A, (0, 2, 1)).conj(),
1367 np.transpose(B, (0, 2, 1)).conj()), (0, 2, 1)).conj()
1368
1369 def nudge_eig(mat: np.ndarray,
1370 cond: float | None = None,
1371 min_eig: float | None = None) -> np.ndarray:
1372 r"""Nudge eigenvalues with absolute value smaller than
1373 max(cond * max(eigenvalue), min_eig) to that value.
1374 Can be used to avoid singularities in solving matrix equations.
1375
1376 Input should have dimension of similar to (nfreqs, nports, nports).
1377
1378 Parameters
1379 ----------
1380 mat : np.ndarray
1381 Matrices to nudge
1382 cond : float, optional
1383 Minimum eigenvalue ratio compared to the maximum eigenvalue.
1384 Default value is set by `skrf.constants.EIG_COND`.
1385 min_eig : float, optional
1386 Minimum eigenvalue.
1387 Default value is set by `skrf.constants.EIG_MIN`.
1388 Returns
1389 -------
1390 res : np.ndarray
1391 Nudged matrices
1392 """
1393 # use current constants
1394 if not cond:
1395 cond = EIG_COND
1396 if not min_eig:
1397 min_eig = EIG_MIN
1398
1399 # Eigenvalues and vectors
1400 eigw, eigv = np.linalg.eig(mat)
1401 # Max eigenvalue for each frequency
1402 max_eig = np.amax(np.abs(eigw), axis=1)
1403 # Calculate mask for positions where problematic eigenvalues are
1404 mask = np.logical_or(np.abs(eigw) < cond * max_eig[:, None], np.abs(eigw) < min_eig)
1405 if not mask.any():
1406 # Nothing to do. Return the original array.
1407 return mat
1408
1409 mask_cond = cond * np.repeat(max_eig[:, None], mat.shape[-1], axis=-1)[mask]
1410 mask_min = min_eig * np.ones(mask_cond.shape)
1411 # Correct the eigenvalues
1412 eigw[mask] = np.maximum(mask_cond, mask_min)
1413
1414 # Now assemble the eigendecomposited matrices back
1415 e = np.zeros_like(mat)
1416 np.einsum('ijj->ij', e)[...] = eigw
1417 return rsolve(eigv, eigv @ e)