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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
|
"""
mathFunctions (:mod:`skrf.mathFunctions`)
=============================================
Provides commonly used mathematical functions.
Mathematical Constants
----------------------
Some convenient constants are defined in the :mod:`skrf.constants` module.
Complex Component Conversion
----------------------------
.. autosummary::
:toctree: generated/
complex_2_reim
complex_2_magnitude
complex_2_db
complex_2_db10
complex_2_radian
complex_2_degree
complex_2_magnitude
complex_2_quadrature
complex_components
Magnitude and decibel
---------------------
.. autosummary::
:toctree: generated/
magnitude_2_db
mag_2_db
mag_2_db10
db_2_magnitude
db_2_mag
db10_2_mag
Phase Unwrapping
----------------
.. autosummary::
:toctree: generated/
unwrap_rad
sqrt_phase_unwrap
Unit Conversion
---------------
.. autosummary::
:toctree: generated/
radian_2_degree
degree_2_radian
np_2_db
db_2_np
feet_2_meter
meter_2_feet
db_per_100feet_2_db_per_100meter
Scalar-Complex Conversion
-------------------------
These conversions are useful for wrapping other functions that don't
support complex numbers.
.. autosummary::
:toctree: generated/
complex2Scalar
scalar2Complex
Special Functions
-----------------
.. autosummary::
:toctree: generated/
dirac_delta
neuman
null
cross_ratio
Random Number Generation
------------------------
.. autosummary::
:toctree: generated/
set_rand_rng
rand_rng
rand_c
Various Utility Functions
--------------------------
.. autosummary::
:toctree: generated/
psd2TimeDomain
rational_interp
ifft
irfft
is_square
is_symmetric
is_Hermitian
is_positive_definite
is_positive_semidefinite
get_Hermitian_transpose
sqrt_known_sign
find_correct_sign
find_closest
inf_to_num
rsolve
nudge_eig
"""
from __future__ import annotations
from collections.abc import Callable
import numpy as np
from numpy import imag, pi, real, unwrap
from scipy import signal
from .constants import ALMOST_ZERO, EIG_COND, EIG_MIN, INF, LOG_OF_NEG, NumberLike
# simple conversions
def complex_2_magnitude(z: NumberLike):
"""
Return the magnitude of the complex argument.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
mag : ndarray or scalar
"""
return np.abs(z)
def complex_2_db(z: NumberLike):
r"""
Return the magnitude in dB of a complex number (as :math:`20\log_{10}(|z|)`)..
The magnitude in dB is defined as :math:`20\log_{10}(|z|)`
where :math:`z` is a complex number.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
mag20dB : ndarray or scalar
"""
return magnitude_2_db(np.abs(z))
def complex_2_db10(z: NumberLike):
r"""
Return the magnitude in dB of a complex number (as :math:`10\log_{10}(|z|)`).
The magnitude in dB is defined as :math:`10\log_{10}(|z|)`
where :math:`z` is a complex number.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
mag10dB : ndarray or scalar
"""
return mag_2_db10(np.abs(z))
def complex_2_radian(z: NumberLike):
"""
Return the angle complex argument in radian.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
ang_rad : ndarray or scalar
The counterclockwise angle from the positive real axis on the complex
plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
"""
return np.angle(z)
def complex_2_degree(z: NumberLike):
"""
Returns the angle complex argument in degree.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
ang_deg : ndarray or scalar
"""
return np.angle(z, deg=True)
def complex_2_quadrature(z: NumberLike):
r"""
Take a complex number and returns quadrature, which is (length, arc-length from real axis)
Arc-length is calculated as :math:`|z| \arg(z)`.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
mag : array like or scalar
magnitude (length)
arc_length : array like or scalar
arc-length from real axis: angle*magnitude
"""
return (np.abs(z), np.angle(z)*np.abs(z))
def complex_2_reim(z: NumberLike):
"""
Return real and imaginary parts of a complex number.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
real : array like or scalar
real part of input
imag : array like or scalar
imaginary part of input
"""
return (np.real(z), np.imag(z))
def complex_components(z: NumberLike):
"""
Break up a complex array into all possible scalar components.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
c_real : array like or scalar
real part
c_imag : array like or scalar
imaginary part
c_angle : array like or scalar
angle in degrees
c_mag : array like or scalar
magnitude
c_arc : array like or scalar
arclength from real axis, angle*magnitude
"""
return (*complex_2_reim(z), np.angle(z,deg=True), *complex_2_quadrature(z))
def magnitude_2_db(z: NumberLike, zero_nan: bool = True):
"""
Convert linear magnitude to dB.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
zero_nan : bool, optional
Replace NaN with zero. The default is True.
Returns
-------
z : number or array_like
Magnitude in dB given by 20*log10(|z|)
"""
out = 20 * np.log10(z)
if zero_nan:
return np.nan_to_num(out, nan=LOG_OF_NEG, neginf=-np.inf)
return out
mag_2_db = magnitude_2_db
def mag_2_db10(z: NumberLike, zero_nan:bool = True):
"""
Convert linear magnitude to dB.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers
zero_nan : bool, optional
Replace NaN with zero. The default is True.
Returns
-------
z : array_like
Magnitude in dB given by 10*log10(|z|)
"""
out = 10 * np.log10(z)
if zero_nan:
return np.nan_to_num(out, nan=LOG_OF_NEG, neginf=-np.inf)
return out
def db_2_magnitude(z: NumberLike):
"""
Convert dB to linear magnitude.
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
z : number or array_like
10**((z)/20) where z is a complex number
"""
return 10**((z)/20.)
db_2_mag = db_2_magnitude
def db10_2_mag(z: NumberLike):
"""
Convert dB to linear magnitude.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers
Returns
-------
z : array_like
10**((z)/10) where z is a complex number
"""
return 10**((z)/10.)
def magdeg_2_reim(mag: NumberLike, deg: NumberLike):
"""
Convert linear magnitude and phase (in deg) arrays into a complex array.
Parameters
----------
mag : number or array_like
A complex number or sequence of real numbers
deg : number or array_like
A complex number or sequence of real numbers
Returns
-------
z : array_like
A complex number or sequence of complex numbers
"""
return mag*np.exp(1j*deg*pi/180.)
def dbdeg_2_reim(db: NumberLike, deg: NumberLike):
"""
Converts dB magnitude and phase (in deg) arrays into a complex array.
Parameters
----------
db : number or array_like
A realnumber or sequence of real numbers
deg : number or array_like
A real number or sequence of real numbers
Returns
-------
z : array_like
A complex number or sequence of complex numbers
"""
return magdeg_2_reim(db_2_magnitude(db), deg)
def db_2_np(db: NumberLike):
"""
Converts a value in decibel (dB) to neper (Np).
Parameters
----------
db : number or array_like
A real number or sequence of real numbers
Returns
-------
np : number or array_like
A real number of sequence of real numbers
"""
return (np.log(10)/20) * db
def np_2_db(x: NumberLike):
"""
Converts a value in Nepers (Np) to decibel (dB).
Parameters
----------
np : number or array_like
A real number or sequence of real numbers
Returns
-------
db : number or array_like
A real number of sequence of real numbers
"""
return 20/np.log(10) * x
def radian_2_degree(rad: NumberLike):
"""
Convert angles from radians to degrees.
Parameters
----------
rad : number or array_like
Angle in radian
Returns
-------
deg : number or array_like
Angle in degree
"""
return (rad)*180/pi
def degree_2_radian(deg: NumberLike):
"""
Convert angles from degrees to radians.
Parameters
----------
deg : number or array_like
Angle in radian
Returns
-------
rad : number or array_like
Angle in degree
"""
return (deg)*pi/180.
def feet_2_meter(feet: NumberLike = 1):
"""
Convert length in feet to meter.
1 foot is equal to 0.3048 meters.
Parameters
----------
feet : number or array-like, optional
length in feet. Default is 1.
Returns
-------
meter: number or array-like
length in meter
See Also
--------
meter_2_feet
"""
return 0.3048*feet
def meter_2_feet(meter: NumberLike = 1):
"""
Convert length in meter to feet.
1 meter is equal to 0.3.28084 feet.
Parameters
----------
meter : number or array-like, optional
length in meter. Default is 1.
Returns
-------
feet : number or array-like
length in feet
See Also
--------
feet_2_meter
"""
return 3.28084*meter
def db_per_100feet_2_db_per_100meter(db_per_100feet: NumberLike = 1):
"""
Convert attenuation values given in dB/100ft to dB/100m.
db_per_100meter = db_per_100feet * rf.meter_2_feet()
Parameters
----------
db_per_100feet : number or array-like, optional
Attenuation in dB/ 100 ft. Default is 1.
Returns
-------
db_per_100meter : number or array-like
Attenuation in dB/ 100 m
See Also
--------
meter_2_feet
feet_2_meter
np_2_db
db_2_np
"""
return db_per_100feet * 100 / feet_2_meter(100)
def unwrap_rad(phi: NumberLike):
"""
Unwraps a phase given in radians.
Parameters
----------
phi : number or array_like
phase in radians
Returns
-------
phi : number of array_like
unwrapped phase in radians
"""
return unwrap(phi, axis=0)
def sqrt_known_sign(z_squared: NumberLike, z_approx: NumberLike):
"""
Return the square root of a complex number, with sign chosen to match `z_approx`.
Parameters
----------
z_squared : number or array-like
the complex to be square-rooted
z_approx : number or array-like
the approximate value of z. sign of z is chosen to match that of
z_approx
Returns
-------
z : number, array-like (same type as z_squared)
square root of z_squared.
"""
z = np.sqrt(z_squared)
return np.where(
np.sign(np.angle(z)) == np.sign(np.angle(z_approx)),
z, z.conj())
def find_correct_sign(z1: NumberLike, z2: NumberLike, z_approx: NumberLike):
r"""
Create new vector from z1, z2 choosing elements with sign matching z_approx.
This is used when you have to make a root choice on a complex number.
and you know the approximate value of the root.
.. math::
z1,z2 = \pm \sqrt(z^2)
Parameters
----------
z1 : array-like
root 1
z2 : array-like
root 2
z_approx : array-like
approximate answer of z
Returns
-------
z3 : np.array
array built from z1 and z2 by
z1 where sign(z1) == sign(z_approx), z2 else
"""
return np.where(
np.sign(np.angle(z1)) == np.sign(np.angle(z_approx)),z1, z2)
def find_closest(z1: NumberLike, z2: NumberLike, z_approx: NumberLike):
"""
Return z1 or z2 depending on which is closer to z_approx.
Parameters
----------
z1 : array-like
root 1
z2 : array-like
root 2
z_approx : array-like
approximate answer of z
Returns
-------
z3 : np.array
array built from z1 and z2
"""
z1_dist = abs(z1-z_approx)
z2_dist = abs(z2-z_approx)
return np.where(z1_dist<z2_dist,z1, z2)
def sqrt_phase_unwrap(z: NumberLike):
r"""
Take the square root of a complex number with unwrapped phase.
This idea came from Lihan Chen.
.. math::
\sqrt{|z|} \exp( \arg_{unwrap}(z) / 2 )
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
z : number of array_like
A complex number or sequence of complex numbers
"""
return np.sqrt(abs(z))*\
np.exp(0.5*1j*unwrap_rad(complex_2_radian(z)))
# mathematical functions
def dirac_delta(x: NumberLike):
r"""
Calculate Dirac function.
Dirac function :math:`\delta(x)` defined as :math:`\delta(x)=1` if x=0,
0 otherwise.
Parameters
----------
x : number of array_like
A real number or sequence of real numbers
Returns
-------
delta : number of array_like
1 or 0
References
----------
https://en.wikipedia.org/wiki/Dirac_delta_function
"""
return (x==0)*1. + (x!=0)*0.
def neuman(x: NumberLike):
r"""
Calculate Neumans number.
It is defined as:
.. math::
2 - \delta(x)
where :math:`\delta` is the Dirac function.
Parameters
----------
x : number or array_like
A real number or sequence of real numbers
Returns
-------
y : number or array_like
A real number or sequence of real numbers
See Also
--------
dirac_delta
"""
return 2. - dirac_delta(x)
def null(A: np.ndarray, eps: float = 1e-15):
"""
Calculate the null space of matrix A.
Parameters
----------
A : array_like
eps : float
Returns
-------
null_space : array_like
References
----------
https://scipy-cookbook.readthedocs.io/items/RankNullspace.html
https://stackoverflow.com/questions/5889142/python-numpy-scipy-finding-the-null-space-of-a-matrix
"""
u, s, vh = np.linalg.svd(A)
null_space = np.compress(s <= eps, vh, axis=0)
return null_space.T
def inf_to_num(x: NumberLike):
"""
Convert inf and -inf's to large numbers.
Parameters
------------
x : array-like or number
the input array or number
Returns
-------
x : Number of array_like
Input without with +/- inf replaced by large numbers
"""
x = np.nan_to_num(x, nan=np.nan, posinf=INF, neginf=-1*INF)
return x
def cross_ratio(a: NumberLike, b: NumberLike, c: NumberLike, d:NumberLike):
r"""
Calculate the cross ratio of a quadruple of distinct points on the real line.
The cross ratio is defined as:
.. math::
r = \frac{ (a-b)(c-d) }{ (a-d)(c-b) }
Parameters
----------
a,b,c,d : array-like or number
Returns
-------
r : array-like or number
References
----------
https://en.wikipedia.org/wiki/Cross-ratio
"""
return ((a-b)*(c-d))/((a-d)*(c-b))
def complexify(f: Callable, name: str = None):
"""
Make a function f(scalar) into f(complex).
If `f(x)` then it returns `f_c(z) = f(real(z)) + 1j*f(imag(z))`
If the real/imag arguments are not first, then you may specify the
name given to them as kwargs.
Parameters
----------
f : Callable
function of real variable
name : string, optional
name of the real/imag argument names if they are not first
Returns
-------
f_c : Callable
function of a complex variable
Examples
--------
>>> def f(x): return x
>>> f_c = rf.complexify(f)
>>> z = 0.2 -1j*0.3
>>> f_c(z)
"""
def f_c(z, *args, **kw):
if name is not None:
kw_re = {name: real(z)}
kw_im = {name: imag(z)}
kw_re.update(kw)
kw_im.update(kw)
return f(*args, **kw_re) + 1j*f(*args, **kw_im)
else:
return f(real(z), *args,**kw) + 1j*f(imag(z), *args, **kw)
return f_c
# old functions just for reference
def complex2Scalar(z: NumberLike):
"""
Serialize a list/array of complex numbers
Parameters
----------
z : number or array_like
A complex number or sequence of complex numbers
Returns
-------
re_im : array_like
produce the following array for an input z:
z[0].real, z[0].imag, z[1].real, z[1].imag, etc.
See Also
--------
scalar2Complex
"""
z = np.array(z)
re_im = []
for k in z:
re_im.append(np.real(k))
re_im.append(np.imag(k))
return np.array(re_im).flatten()
def scalar2Complex(s: NumberLike):
"""
Unserialize a list/array of real and imag numbers into a complex array.
Inverse of :func:`complex2Scalar`.
Parameters
----------
s : array_like
an array with real and imaginary parts ordered as:
z[0].real, z[0].imag, z[1].real, z[1].imag, etc.
Returns
-------
z : Number or array_like
A complex number or sequence of complex number
See Also
--------
complex2Scalar
"""
s = np.array(s)
z = []
for k in range(0,len(s),2):
z.append(s[k] + 1j*s[k+1])
return np.array(z).flatten()
def flatten_c_mat(s: NumberLike, order: str = 'F'):
"""
Take a 2D (mxn) complex matrix and serialize and flatten it.
by default (using order='F') this generates the following
from a 2x2
[s11,s12;s21,s22]->[s11re,s11im,s21re,s12im, ...]
Parameters
------------
s : ndarray
input 2D array
order : string, optional
either 'F' or 'C', for the order of flattening
"""
return complex2Scalar(s.flatten(order='F'))
_global_rng = np.random.default_rng()
def set_rand_rng(rng: np.random.Generator) -> None:
"""
Set the global :mod:`numpy` random number generator instance
for generating random numbers in scikit-rf. This is useful for
fixing a random seed for reproducible Monte Carlo analysis.
This function is expected to be called before using any scikit-rf
features, since it's a global variable and thread-unsafe. To temporarily
change the random number generator of a particular method (e.g.
:meth:`skrf.media.Media.random`), use the ``rng`` argument instead.
Parameters
-----------
rng : :class:`numpy.random.Generator`
Any random number generator accepted by :mod:`numpy`.
Examples
---------
>>> set_rand_rng(np.random.default_rng(seed=42))
"""
global _global_rng
_global_rng = rng
def rand_rng() -> np.random.Generator:
"""
Obtain the global :mod:`numpy` random number generator instance.
By default, it is :func:`numpy.random.default_rng`.
"""
return _global_rng
def rand_c(*size, rng=None) -> np.ndarray:
"""
Creates a complex random array of shape s.
The bounds on real and imaginary values are (-1,1)
Parameters
-----------
s : list-like
shape of array
rng : :class:`numpy.random.Generator` or None
Any random number generator accepted by :mod:`numpy`.
Examples
---------
>>> x1 = rf.rand_c(2, 2)
>>> x2 = rf.rand_c(2, 2, np.random.default_rng(seed=42))
"""
if rng is None:
rng = _global_rng
return 1-2*rng.random(size) + \
1j-2j*rng.random(size)
def psd2TimeDomain(f: np.ndarray, y: np.ndarray, windowType: str = 'hamming'):
"""
Convert a one sided complex spectrum into a real time-signal.
Parameters
----------
f : list or np.ndarray
frequency array
y : list of np.ndarray
complex PSD array
windowType: string
windowing function, defaults to 'hamming''
Returns
-------
timeVector : array_like
inverse units of the input variable f,
signalVector : array_like
Note
----
If spectrum is not baseband then, `timeSignal` is modulated by `exp(t*2*pi*f[0])`.
So keep in mind units. Also, due to this, `f` must be increasing left to right.
"""
# apply window function
# make sure windowType exists in scipy.signal
if callable(getattr(signal, windowType)) and (windowType != 'rect' ):
window = getattr(signal, windowType)(len(f))
y = y * window
#create other half of spectrum
spectrum = (np.hstack([np.real(y[:0:-1]),np.real(y)])) + \
1j*(np.hstack([-np.imag(y[:0:-1]),np.imag(y)]))
# do the transform
df = abs(f[1]-f[0])
T = 1./df
timeVector = np.linspace(-T/2.,T/2,2*len(f)-1)
signalVector = np.fft.ifftshift(np.fft.ifft(np.fft.ifftshift(spectrum)))
#the imaginary part of this signal should be from fft errors only,
signalVector= np.real(signalVector)
# the response of frequency shifting is
# exp(1j*2*pi*timeVector*f[0])
# but I would have to manually undo this for the inverse, which is just
# another variable to require. The reason you need this is because
# you can't transform to a bandpass signal, only a lowpass.
#
return timeVector, signalVector
def rational_interp(
x: np.ndarray,
y: np.ndarray,
d: int = 4,
epsilon: float = 1e-9,
axis: int = 0,
assume_sorted: bool = False) -> Callable:
"""
Interpolates function using rational polynomials of degree `d`.
Interpolating function is singular when xi is exactly one of the
original x points. If xi is closer than epsilon to one of the original points,
then the value at that points is returned instead.
Implementation is based on [#]_.
Parameters
----------
x : np.ndarray
y : np.ndarray
d : int, optional
order of the polynomial, by default 4
epsilon : float, optional
numerical tolerance, by default 1e-9
axis : int, optional
axis to operate on, by default 0
assume_sorted : bool, optional
If False, values of x can be in any order and they are sorted first.
If True, x has to be an array of monotonically increasing values.
Returns
-------
fx : Callable
Interpolate function
Raises
------
NotImplementedError
if axis != 0.
References
------------
.. [#] M. S. Floater and K. Hormann, "Barycentric rational interpolation with no poles and high rates of
approximation," Numer. Math., vol. 107, no. 2, pp. 315-331, Aug. 2007
"""
if axis != 0:
raise NotImplementedError("Axis other than 0 is not implemented")
if not assume_sorted:
sort_indices = np.argsort(x, axis=axis)
x = x[sort_indices]
y = y[sort_indices]
n = len(x)
if n <= d:
raise ValueError('Not enough x-axis points')
w = np.zeros(n)
# Scaling to give close to 1 weights
hd = (x[n//2] - x[n//2-1])**d
for k in range(n):
for i in range(max(0,k-d), min(k+1, n-d)):
p, xk = hd, x[k]
for j in range(i,min(n,i+d+1)):
if j == k:
continue
p /= (xk - x[j])
if i % 2 == 1:
w[k] -= p
else:
w[k] += p
# Add dimensions to match y shape
w_shape = [1]*len(y.shape)
w_shape[0] = -1
w = w.reshape(w_shape)
def fx(xi):
# The method will divide by zero if new x value is exactly existing x value.
# To avoid this we need to check for too close values and replace them with
# y value at that position.
idx = np.searchsorted(x, xi)
idx[idx == len(x)] = len(x) - 1
nearest_idx = np.where(np.abs(x[idx] - xi) < epsilon)[0]
nearest_value = y[idx[nearest_idx]]
xi = xi.reshape(*w_shape)
with np.errstate(divide='ignore', invalid='ignore'):
assert axis == 0
tmp = [w[i] / (xi - x[i]) for i in range(n)]
v = sum(y[i] * tmp[i] for i in range(n)) / sum(tmp)
# Fix divide by zero errors
for e, i in enumerate(nearest_idx):
v[i] = nearest_value[e]
return v
return fx
def ifft(x: np.ndarray) -> np.ndarray:
"""
Transforms S-parameters to time-domain bandpass.
Parameters
----------
x : array_like
S-parameters vs frequency array.
Returns
-------
X : array_like
Fourier transformed array
See Also
--------
irfft
"""
return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(x, axes=0), axis=0), axes=0)
def irfft(x: np.ndarray, n:int = None) -> np.ndarray:
"""
Transforms S-parameters to time-domain, assuming complex conjugates for
values corresponding to negative frequencies.
Parameters
----------
x : array_like
S-parameters vs frequency array.
n : int, optional
n parameter passed to :func:`numpy.fft.irfft`. Defaults to None.
Returns
-------
X : array_like
Fourier transformed array
See Also
--------
ifft
"""
return np.fft.fftshift(np.fft.irfft(x, axis=0, n=n), axes=0)
def is_square(mat: np.ndarray) -> bool:
"""
Tests whether mat is a square matrix.
Parameters
----------
mat : np.ndarray
Matrix to test for being square
Returns
-------
res : boolean
See Also
--------
is_unitary
is_symmetric
"""
return mat.shape[0] == mat.shape[1]
def is_unitary(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
"""
Tests mat for unitariness.
Parameters
----------
mat : np.ndarray
Matrix to test for unitariness
tol : float
Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
Returns
-------
res : boolean or array of boolean
See Also
--------
is_square
is_symmetric
"""
if not is_square(mat):
return False
return np.allclose(get_Hermitian_transpose(mat) @ mat,
np.identity(mat.shape[0]), atol=tol)
def is_symmetric(mat: np.ndarray, tol: int = ALMOST_ZERO) -> bool:
"""
Tests mat for symmetry.
Parameters
----------
mat : np.ndarray
Matrix to test for symmetry
tol : float, optional
Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
Returns
-------
res : boolean or array of boolean
See Also
--------
is_square
is_unitary
"""
if not is_square(mat):
return False
return np.allclose(mat, mat.transpose(), atol=tol)
def get_Hermitian_transpose(mat: np.ndarray) -> np.ndarray:
"""
Returns the conjugate transpose of mat.
Parameters
----------
mat : np.ndarray
Matrix to compute the conjugate transpose of
Returns
-------
mat : np.ndarray
"""
return mat.transpose().conjugate()
def is_Hermitian(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
"""
Tests whether mat is Hermitian.
Parameters
----------
mat : np.ndarray
Matrix to test for being Hermitian
tol : float
Absolute tolerance
Returns
-------
res : boolean
See Also
--------
is_positive_definite
is_positive_semidefinite
"""
if not is_square(mat):
return False
return np.allclose(mat, get_Hermitian_transpose(mat), atol=tol)
def is_positive_definite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
"""
Tests mat for positive definiteness.
Verifying that
(1) mat is symmetric
(2) it's possible to compute the Cholesky decomposition of mat.
Parameters
----------
mat : np.ndarray
Matrix to test for positive definiteness
tol : float, optional
Absolute tolerance. Defaults to :data:`ALMOST_ZERO`
Returns
-------
res : bool or array of bool
See Also
--------
is_Hermitian
is_positive_semidefinite
"""
if not is_Hermitian(mat, tol=tol):
return False
try:
np.linalg.cholesky(mat)
return True
except np.linalg.LinAlgError:
return False
def is_positive_semidefinite(mat: np.ndarray, tol: float = ALMOST_ZERO) -> bool:
"""
Tests mat for positive semidefiniteness.
Checking whether all eigenvalues of mat are nonnegative within a certain tolerance
Parameters
----------
mat : np.ndarray
Matrix to test for positive semidefiniteness
tol : float, optional
Absolute tolerance in determining nonnegativity due to loss of precision
when computing the eigenvalues of mat. Defaults to :data:`ALMOST_ZERO`
Returns
-------
res : bool or array of bool
See Also
--------
is_Hermitian
is_positive_definite
"""
if not is_Hermitian(mat):
return False
try:
v = np.linalg.eigvalsh(mat)
except np.linalg.LinAlgError:
return False
return np.all(v > -tol)
def rsolve(A: np.ndarray, B: np.ndarray) -> np.ndarray:
r"""Solves x @ A = B.
Calls numpy.linalg.solve with transposed matrices.
Same as B @ np.linalg.inv(A) but avoids calculating the inverse and
should be numerically slightly more accurate.
Input should have dimension of similar to (nfreqs, nports, nports).
Parameters
----------
A : np.ndarray
B : np.ndarray
Returns
-------
x : np.ndarray
"""
return np.transpose(np.linalg.solve(np.transpose(A, (0, 2, 1)).conj(),
np.transpose(B, (0, 2, 1)).conj()), (0, 2, 1)).conj()
def nudge_eig(mat: np.ndarray,
cond: float | None = None,
min_eig: float | None = None) -> np.ndarray:
r"""Nudge eigenvalues with absolute value smaller than
max(cond * max(eigenvalue), min_eig) to that value.
Can be used to avoid singularities in solving matrix equations.
Input should have dimension of similar to (nfreqs, nports, nports).
Parameters
----------
mat : np.ndarray
Matrices to nudge
cond : float, optional
Minimum eigenvalue ratio compared to the maximum eigenvalue.
Default value is set by `skrf.constants.EIG_COND`.
min_eig : float, optional
Minimum eigenvalue.
Default value is set by `skrf.constants.EIG_MIN`.
Returns
-------
res : np.ndarray
Nudged matrices
"""
# use current constants
if not cond:
cond = EIG_COND
if not min_eig:
min_eig = EIG_MIN
# Eigenvalues and vectors
eigw, eigv = np.linalg.eig(mat)
# Max eigenvalue for each frequency
max_eig = np.amax(np.abs(eigw), axis=1)
# Calculate mask for positions where problematic eigenvalues are
mask = np.logical_or(np.abs(eigw) < cond * max_eig[:, None], np.abs(eigw) < min_eig)
if not mask.any():
# Nothing to do. Return the original array.
return mat
mask_cond = cond * np.repeat(max_eig[:, None], mat.shape[-1], axis=-1)[mask]
mask_min = min_eig * np.ones(mask_cond.shape)
# Correct the eigenvalues
eigw[mask] = np.maximum(mask_cond, mask_min)
# Now assemble the eigendecomposited matrices back
e = np.zeros_like(mat)
np.einsum('ijj->ij', e)[...] = eigw
return rsolve(eigv, eigv @ e)
|