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 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
|
"""
.. module:: skrf.networkSet
========================================
networkSet (:mod:`skrf.networkSet`)
========================================
Provides a class representing an un-ordered set of n-port microwave networks.
Frequently one needs to make calculations, such as mean or standard
deviation, on an entire set of n-port networks. To facilitate these
calculations the :class:`NetworkSet` class provides convenient
ways to make such calculations.
Another usage is to interpolate a set of Networks which depend of
an parameter (like a knob, or a geometrical parameter).
The results are returned in :class:`~skrf.network.Network` objects,
so they can be plotted and saved in the same way one would do with a
:class:`~skrf.network.Network`.
The functionality in this module is provided as methods and
properties of the :class:`NetworkSet` Class.
NetworkSet Class
================
.. autosummary::
:toctree: generated/
NetworkSet
NetworkSet Utilities
====================
.. autosummary::
:toctree: generated/
func_on_networks
getset
"""
from __future__ import annotations
import zipfile
from collections.abc import Mapping
from io import BytesIO
from numbers import Number
from pathlib import Path
from typing import Any, TextIO
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
from . import mathFunctions as mf
from .constants import NumberLike, PrimaryPropertiesT
from .network import COMPONENT_FUNC_DICT, PRIMARY_PROPERTIES, Frequency, Network
from .util import copy_doc, now_string_2_dt
try:
from numpy.typing import ArrayLike
except ImportError:
ArrayLike = Any
from . import plotting as skrf_plt
class NetworkSet:
"""
A set of Networks.
This class allows functions on sets of Networks, such as mean or
standard deviation, to be calculated conveniently. The results are
returned in :class:`~skrf.network.Network` objects, so that they may be
plotted and saved in like :class:`~skrf.network.Network` objects.
This class also provides methods which can be used to plot uncertainty
bounds for a set of :class:`~skrf.network.Network`.
The names of the :class:`NetworkSet` properties are generated
dynamically upon initialization, and thus documentation for
individual properties and methods is not available. However, the
properties do follow the convention::
>>> my_network_set.function_name_network_property_name
For example, the complex average (mean)
:class:`~skrf.network.Network` for a
:class:`NetworkSet` is::
>>> my_network_set.mean_s
This accesses the property 's', for each element in the
set, and **then** calculates the 'mean' of the resultant set. The
order of operations is important.
Results are returned as :class:`~skrf.network.Network` objects,
so they may be plotted or saved in the same way as for
:class:`~skrf.network.Network` objects::
>>> my_network_set.mean_s.plot_s_mag()
>>> my_network_set.mean_s.write_touchstone('mean_response')
If you are calculating functions that return scalar variables, then
the result is accessible through the Network property .s_re. For
example::
>>> std_s_deg = my_network_set.std_s_deg
This result would be plotted by::
>>> std_s_deg.plot_s_re()
The operators, properties, and methods of NetworkSet object are
dynamically generated by private methods
* :func:`~NetworkSet.__add_a_operator`
* :func:`~NetworkSet.__add_a_func_on_property`
* :func:`~NetworkSet.__add_a_element_wise_method`
* :func:`~NetworkSet.__add_a_plot_uncertainty`
thus, documentation on the individual methods and properties are
not available.
"""
def __init__(self, ntwk_set: list | dict = None, name: str = None):
"""
Initialize for NetworkSet.
Parameters
----------
ntwk_set : list of :class:`~skrf.network.Network` objects
the set of :class:`~skrf.network.Network` objects
name : string
the name of the NetworkSet, given to the Networks returned
from properties of this class.
"""
if ntwk_set is None:
ntwk_set = []
if not isinstance(ntwk_set, (list, dict)):
raise ValueError('NetworkSet requires a list as argument')
# dict is authorized for convenience
# but if a dict is passed instead of a list -> list
if isinstance(ntwk_set, dict):
ntwk_set = list(ntwk_set.values())
# did they pass a list of Networks?
if not all([isinstance(ntwk, Network) for ntwk in ntwk_set]):
raise(TypeError('input must be list of Network types'))
# do all Networks have the same # ports?
if len (set([ntwk.number_of_ports for ntwk in ntwk_set])) > 1:
raise(ValueError('All elements in list of Networks must have same number of ports'))
# is all frequency information the same?
if not np.all([(ntwk_set[0].frequency == ntwk.frequency) for ntwk in ntwk_set]):
raise(ValueError('All elements in list of Networks must have same frequency information'))
## initialization
# we are good to go
self.ntwk_set: list[Network] = ntwk_set
self.name = name
# extract the dimensions of the set
try:
self.dims = self.ntwk_set[0].params.keys()
except (AttributeError, IndexError): # .params is None
self.dims = dict()
# extract the coordinates of the set
try:
self.coords = {p: [] for p in self.dims}
for k in self.ntwk_set:
for p in self.dims:
self.coords[p].append(k.params[p])
# keep only unique terms
for p in self.coords.keys():
self.coords[p] = list(set(self.coords[p]))
except TypeError: # .params is None
self.coords = None
# create list of network properties, which we use to dynamically
# create a statistical properties of this set
network_property_list = [k+'_'+l \
for k in PRIMARY_PROPERTIES \
for l in COMPONENT_FUNC_DICT.keys()] + \
['passivity','s']
# dynamically generate properties. this is slick.
max, min = np.max, np.min
max.__name__ = 'max'
min.__name__ = 'min'
for network_property_name in network_property_list:
for func in [np.mean, np.std, max, min]:
self.__add_a_func_on_property(func, network_property_name)
if 'db' not in network_property_name:# != 's_db' and network_property_name != 's':
# db uncertainty requires a special function call see
# plot_uncertainty_bounds_s_db
self.__add_a_plot_uncertainty(network_property_name)
self.__add_a_plot_minmax(network_property_name)
self.__add_a_element_wise_method('plot_'+network_property_name)
self.__add_a_element_wise_method('plot_s_db')
self.__add_a_element_wise_method('plot_s_db_time')
for network_method_name in \
['write_touchstone','interpolate','plot_s_smith']:
self.__add_a_element_wise_method(network_method_name)
for operator_name in \
['__pow__','__floordiv__','__mul__','__truediv__','__add__','__sub__']:
self.__add_a_operator(operator_name)
@classmethod
def from_zip(cls, zip_file_name: str | Path, sort_filenames: bool = True, *args, **kwargs):
r"""
Create a NetworkSet from a zipfile of touchstones.
Parameters
----------
zip_file_name : string or Path
name of zipfile
sort_filenames: Boolean
sort the filenames in the zip file before constructing the
NetworkSet
\*args, \*\*kwargs : arguments
passed to NetworkSet constructor
Examples
--------
>>> import skrf as rf
>>> my_set = rf.NetworkSet.from_zip('myzip.zip')
"""
z = zipfile.ZipFile(zip_file_name)
filename_list = z.namelist()
ntwk_list = []
if sort_filenames:
filename_list.sort()
for filename in filename_list:
# try/except block in case not all files are touchstones
try: # Ascii files (Touchstone, etc)
n = Network.zipped_touchstone(filename, z)
ntwk_list.append(n)
continue
except Exception:
pass
try: # Binary files (pickled Network)
fileobj = BytesIO(z.open(filename).read())
fileobj.name = filename
n = Network(fileobj)
ntwk_list.append(n)
continue
except Exception:
pass
return cls(ntwk_list)
@classmethod
def from_dir(cls, dir: str | Path = '.', *args, **kwargs):
r"""
Create a NetworkSet from a directory containing Networks.
This just calls ::
rf.NetworkSet(rf.read_all_networks(dir), *args, **kwargs)
Parameters
----------
dir : str or Path
directory containing Network files.
\*args, \*\*kwargs :
passed to NetworkSet constructor
Examples
--------
>>> my_set = rf.NetworkSet.from_dir('./data/')
"""
from .io.general import read_all_networks
return cls(read_all_networks(dir), *args, **kwargs)
@classmethod
def from_s_dict(cls, d: dict, frequency: Frequency, *args, **kwargs):
r"""
Create a NetworkSet from a dictionary of s-parameters
The resultant elements of the NetworkSet are named by the keys of
the dictionary.
Parameters
-------------
d : dict
dictionary of s-parameters data. values of this should be
:class:`numpy.ndarray` assignable to :attr:`skrf.network.Network.s`
frequency: :class:`~skrf.frequency.Frequency` object
frequency assigned to each network
\*args, \*\*kwargs :
passed to Network.__init__ for each key/value pair of d
Returns
----------
ns : NetworkSet
See Also
----------
NetworkSet.to_s_dict
"""
return cls([Network(s=d[k], frequency=frequency, name=k,
**kwargs) for k in d])
@classmethod
def from_mdif(cls, file: str | Path | TextIO) -> NetworkSet:
"""
Create a NetworkSet from a MDIF file.
Parameters
----------
file : str, Path, file-object
MDIF file to load
Returns
-------
ns : :class: `~skrf.networkSet.NetworkSet`
See Also
--------
Mdif : MDIF Object
write_mdif : Convert a NetworkSet to a Generalized MDIF file.
"""
from .io import Mdif
return Mdif(file).to_networkset()
@classmethod
def from_citi(cls, file: str | Path | TextIO) -> NetworkSet:
"""
Create a NetworkSet from a CITI file.
Parameters
----------
file : str, Path, or file-object
CITI file to load
Returns
-------
ns : :class: `~skrf.networkSet.NetworkSet`
See Also
--------
Citi
"""
from .io import Citi
return Citi(file).to_networkset()
def __add_a_operator(self, operator_name):
"""
Add an operator method to the NetworkSet.
this is made to
take either a Network or a NetworkSet. if a Network is passed
to the operator, each element of the set will operate on the
Network. If a NetworkSet is passed to the operator, and is the
same length as self. then it will operate element-to-element
like a dot-product.
"""
def operator_func(self, other):
if isinstance(other, NetworkSet):
if len(other) != len(self):
raise(ValueError('Network sets must be of same length to be cascaded'))
return NetworkSet([
getattr(self.ntwk_set[k], operator_name)(other.ntwk_set[k]) for k in range(len(self))
])
elif isinstance(other, Network):
return NetworkSet([getattr(ntwk, operator_name)(other) for ntwk in self.ntwk_set])
else:
raise(TypeError('NetworkSet operators operate on either Network, or NetworkSet types'))
setattr(self.__class__,operator_name,operator_func)
def __str__(self):
"""
"""
return f'{len(self.ntwk_set)}-Networks NetworkSet: '+self.ntwk_set.__str__()
def __repr__(self):
return self.__str__()
def __getitem__(self, key):
"""
Return an element of the network set.
"""
if isinstance(key, str):
# if they pass a string then slice each network in this set
return NetworkSet([k[key] for k in self.ntwk_set],
name = self.name)
else:
return self.ntwk_set[key]
def __len__(self) -> int:
"""
Return the number of Networks in a NetworkSet.
Return
------
len: int
Number of Networks in a NetworkSet
"""
return len(self.ntwk_set)
def __eq__(self, other: NetworkSet) -> bool:
"""
Compare the NetworkSet with another NetworkSet.
Two NetworkSets are considered equal of their Networks are all equals
(in the same order)
Returns
-------
is_equal: bool
"""
# of course they should have equal lengths
if len(self) != len(other):
return False
# compare all networks in the order of the list
# return False as soon as 2 networks are different
for (ntwk, ntwk_other) in zip(self.ntwk_set, other):
if ntwk != ntwk_other:
return False
return True
def __add_a_element_wise_method(self, network_method_name: str):
def func(self, *args, **kwargs):
return self.element_wise_method(network_method_name, *args, **kwargs)
setattr(self.__class__,network_method_name,func)
def __add_a_func_on_property(self, func, network_property_name: str):
"""
Dynamically add a property to this class (NetworkSet).
this is mostly used internally to generate all of the classes
properties.
Parameters
----------
func: a function to be applied to the network_property
across the first axis of the property's output
network_property_name: str
a property of the Network class,
which must have a matrix output of shape (f, n, n)
example
-------
>>> my_ntwk_set.add_a_func_on_property(mean, 's')
"""
def fget(self):
return fon(self.ntwk_set, func, network_property_name, name=self.name)
setattr(self.__class__,func.__name__+'_'+network_property_name,\
property(fget))
def __add_a_plot_uncertainty(self, network_property_name: str):
"""
Add a plot uncertainty to a Network property.
Parameter
---------
network_property_name: str
A property of the Network class,
which must have a matrix output of shape (f, n, n)
Parameter
---------
>>> my_ntwk_set.__add_a_plot_uncertainty('s')
"""
def plot_func(self,*args, **kwargs):
self.plot_uncertainty_bounds_component(network_property_name, *args,**kwargs)
setattr(self.__class__,'plot_uncertainty_bounds_'+\
network_property_name,plot_func)
setattr(self.__class__,'plot_ub_'+\
network_property_name,plot_func)
def __add_a_plot_minmax(self, network_property_name: str):
"""
Parameter
---------
network_property_name: str
A property of the Network class,
which must have a matrix output of shape (f, n, n)
Example
-------
>>> my_ntwk_set.__add_a_plot_minmax('s')
"""
def plot_func(self,*args, **kwargs):
self.plot_minmax_bounds_component(network_property_name, *args,**kwargs)
setattr(self.__class__,'plot_minmax_bounds_'+\
network_property_name,plot_func)
setattr(self.__class__,'plot_mm_'+\
network_property_name,plot_func)
def to_dict(self) -> dict:
"""
Return a dictionary representation of the NetworkSet.
Return
------
d : dict
The returned dictionary has the Network names for keys,
and the Networks as values.
"""
return {k.name: k for k in self.ntwk_set}
def to_s_dict(self):
"""
Converts a NetworkSet to a dictionary of s-parameters.
The resultant keys of the dictionary are the names of the Networks
in NetworkSet
Returns
-------
s_dict : dictionary
contains s-parameters in the form of complex numpy arrays
See Also
--------
NetworkSet.from_s_dict
"""
d = self.to_dict()
for k in d:
d[k] = d[k].s
return d
def element_wise_method(self, network_method_name: str, *args, **kwargs) -> NetworkSet:
"""
Call a given method of each element and returns the result as
a new NetworkSet if the output is a Network.
Parameter
---------
network_property_name: str
A property of the Network class,
which must have a matrix output of shape (f, n, n)
Return
------
ns: :class: `~skrf.networkSet.NetworkSet`
"""
output = [getattr(ntwk, network_method_name)(*args, **kwargs) for ntwk in self.ntwk_set]
if isinstance(output[0],Network):
return NetworkSet(output)
else:
return output
def copy(self) -> NetworkSet:
"""
Copy each network of the network set.
Return
------
ns: :class: `~skrf.networkSet.NetworkSet`
"""
return NetworkSet([k.copy() for k in self.ntwk_set])
def sort(self, key=lambda x: x.name, inplace: bool = True, **kwargs) -> None | NetworkSet:
r"""
Sort this network set.
Parameters
----------
key:
inplace: bool
Sort the NetworkSet object directly if True,
return the sorted NetworkSet if False. Default is True.
\*\*kwargs : dict
keyword args passed to builtin sorted acting on self.ntwk_set
Return
------
ns: None if inplace=True, NetworkSet if False
Examples
--------
>>> ns = rf.NetworkSet.from_dir('mydir')
>>> ns.sort()
Sort by other property:
>>> ns.sort(key= lambda x: x.voltage)
Returns a new NetworkSet:
>>> sorted_ns = ns.sort(inplace=False)
"""
sorted_ns = sorted(self.ntwk_set, key = key, **kwargs)
if inplace:
self.ntwk_set = sorted_ns
else:
return sorted_ns
def rand(self, n: int = 1, rng: None | np.random.Generator = None):
"""
Return `n` random samples from this NetworkSet.
Parameters
----------
n : int
number of samples to return (default is 1)
rng : :class:`numpy.random.Generator` or None
override the global :mod:`numpy` random number generator,
useful for multi-threaded programs since
:func:`skrf.mathFunctions.set_rand_rng` is not thread-safe.
"""
if rng is None:
rng = mf.rand_rng()
idx = rng.randint(0,len(self), n)
out = [self.ntwk_set[k] for k in idx]
if n ==1:
return out[0]
else:
return out
def filter(self, s: str) -> NetworkSet:
"""
Filter NetworkSet based on a string in `Network.name`.
Notes
-----
This is just
`NetworkSet([k for k in self if s in k.name])`
Parameters
----------
s: str
string contained in network elements to be filtered
Returns
--------
ns : :class: `skrf.NetworkSet`
Examples
-----------
>>> ns.filter('monday')
"""
return NetworkSet([k for k in self if s in k.name])
def scalar_mat(self, param: str = 's') -> np.ndarray:
"""
Return a scalar ndarray representing `param` data vs freq and element idx.
Output is a 3d array with axes (freq, ns_index, port/ri).
ports is a flattened re/im components of port index (`len = 2*nports**2`).
Parameter
---------
param : str
name of the parameter to export. Default is 's'.
Return
------
x : :class: np.ndarray
"""
ntwk = self[0]
nfreq = len(ntwk)
# x will have the axes (frequency, observations, ports)
x = np.array([[mf.flatten_c_mat(getattr(k, param)[f]) \
for k in self] for f in range(nfreq)])
return x
def cov(self, **kw) -> np.ndarray:
"""
Covariance matrix.
shape of output will be (nfreq, 2*nports**2, 2*nports**2)
"""
smat=self.scalar_mat(**kw)
return np.array([np.cov(k.T) for k in smat])
@property
def mean_s_db(self) -> Network:
"""
Return Network of mean magnitude in dB.
Return
------
ntwk : :class: `~skrf.network.Network`
Network of the mean magnitude in dB
Note
----
The mean is taken on the magnitude before converted to db, so
`magnitude_2_db(mean(s_mag))`
which is NOT the same as
`mean(s_db)`
"""
ntwk = self.mean_s_mag
ntwk.s = ntwk.s_db
return ntwk
@property
def std_s_db(self) -> Network:
"""
Return the Network of the standard deviation magnitude in dB.
Return
------
ntwk : :class: `~skrf.network.Network`
Network of the mean magnitude in dB
Note
----
The standard deviation is taken on the magnitude before converted to db, so
`magnitude_2_db(std(s_mag))`
which is NOT the same as
`std(s_db)`
"""
ntwk= self.std_s_mag
ntwk.s = ntwk.s_db
return ntwk
@property
def inv(self) -> NetworkSet:
"""
Return the NetworkSet of inverted Networks (Network.inv()).
Returns
-------
ntwkSet : :class: `~skrf.networkSet.NetworkSet`
NetworkSet of inverted Networks
"""
return NetworkSet( [ntwk.inv for ntwk in self.ntwk_set])
def add_polar_noise(self, ntwk: Network) -> Network:
"""
Parameters
----------
ntwk : :class: `~skrf.network.Network`
Returns
-------
ntwk : :class: `~skrf.network.Network`
"""
from numpy import frompyfunc
from scipy import stats
def gimme_norm(x):
return stats.norm(loc=0, scale=x).rvs(1)[0]
ugimme_norm = frompyfunc(gimme_norm,1,1)
s_deg_rv = np.array(map(ugimme_norm, self.std_s_deg.s_re), dtype=float)
s_mag_rv = np.array(map(ugimme_norm, self.std_s_mag.s_re), dtype=float)
mag = ntwk.s_mag + s_mag_rv
deg = ntwk.s_deg + s_deg_rv
ntwk.s = mag * np.exp(1j*np.pi/180*deg)
return ntwk
def set_wise_function(self, func, a_property: str, *args, **kwargs):
"""
Calls a function on a specific property of the Networks in this NetworkSet.
Parameters
----------
func : callable
a_property : str
Example
-------
>>> my_ntwk_set.set_wise_func(mean,'s')
"""
return fon(self.ntwk_set, func, a_property, *args, **kwargs)
def uncertainty_ntwk_triplet(self, attribute: PrimaryPropertiesT, n_deviations: int = 3) -> tuple(
Network, Network, Network
):
"""
Return a 3-tuple of Network objects which contain the
mean, upper_bound, and lower_bound for the given Network
attribute.
Used to save and plot uncertainty information data.
Note that providing 's' and 's_mag' as attributes will provide different results.
For those who want to directly find uncertainty on dB performance, use 's_mag'.
Parameters
----------
attribute : str
Attribute to operate on.
n_deviations : int, optional
Number of standard deviation. The default is 3.
Returns
-------
ntwk_mean : :class: `~skrf.network.Network`
Network of the averaged attribute
lower_bound : :class: `~skrf.network.Network`
Network of the lower bound of N*sigma deviation.
upper_bound : :class: `~skrf.network.Network`
Network of the upper bound of N*sigma deviation.
Example
-------
>>> (ntwk_mean, ntwk_lb, ntwk_ub) = my_ntwk_set.uncertainty_ntwk_triplet('s')
>>> (ntwk_mean, ntwk_lb, ntwk_ub) = my_ntwk_set.uncertainty_ntwk_triplet('s_mag')
"""
ntwk_mean = getattr(self, 'mean_'+attribute)
ntwk_std = getattr(self, 'std_'+attribute)
ntwk_std.s = n_deviations * ntwk_std.s
upper_bound = (ntwk_mean + ntwk_std)
lower_bound = (ntwk_mean - ntwk_std)
return (ntwk_mean, lower_bound, upper_bound)
def datetime_index(self) -> list:
"""
Create a datetime index from networks names.
this is just:
`[rf.now_string_2_dt(k.name ) for k in self]`
"""
return [now_string_2_dt(k.name ) for k in self]
# io
def write(self, file=None, *args, **kwargs):
r"""
Write the NetworkSet to disk using :func:`~skrf.io.general.write`
Parameters
----------
file : str or file-object
filename or a file-object. If left as None then the
filename will be set to Calibration.name, if its not None.
If both are None, ValueError is raised.
\*args, \*\*kwargs : arguments and keyword arguments
passed through to :func:`~skrf.io.general.write`
Notes
-----
If the self.name is not None and file is can left as None
and the resultant file will have the `.ns` extension appended
to the filename.
Examples
---------
>>> ns.name = 'my_ns'
>>> ns.write()
See Also
---------
skrf.io.general.write
skrf.io.general.read
"""
# this import is delayed until here because of a circular dependency
from .io.general import write
if file is None:
if self.name is None:
raise (ValueError('No filename given. You must provide a filename, or set the name attribute'))
file = self.name
write(file, self, *args, **kwargs)
def write_spreadsheet(self, *args, **kwargs):
"""
Write contents of network to a spreadsheet, for your boss to use.
Example
-------
>>> ns.write_spreadsheet() # the ns.name attribute must exist
>>> ns.write_spreadsheet(file_name='testing.xlsx')
See Also
---------
skrf.io.general.network_2_spreadsheet
"""
from .io.general import networkset_2_spreadsheet
networkset_2_spreadsheet(self, *args, **kwargs)
def write_mdif(self,
filename: str,
values: dict | None = None,
data_types: dict | None = None,
comments: list[str] | None = None,
**kwargs):
"""Convert a scikit-rf NetworkSet object to a Generalized MDIF file.
Parameters
----------
filename : string
Output MDIF file name.
values : dictionary or None. Default is None.
The keys of the dictionary are MDIF variables and its values are
a list of the parameter values.
If None, then the values will be set to the NetworkSet names
and the datatypes will be set to "string".
data_types: dictionary or None. Default is None.
The keys are MDIF variables and the value are datatypes
specified by the following strings: "int", "double", and "string"
comments: list of strings
Comments to add to output_file.
Each list items is a separate comment line
**kwargs: dictionary with extra arguments to pass through to the
underlying Mdif.write and Network.write_touchstone methods
See Also
--------
from_mdif : Create a NetworkSet from a MDIF file.
params_values : parameters values
params_types : parameters types
"""
from .io import Mdif
if comments is None:
comments = []
Mdif.write(ns=self, filename=filename, values=values,
data_types=data_types, comments=comments, **kwargs)
def ntwk_attr_2_df(self, attr='s_db', m=0, n=0, *args, **kwargs):
"""
Converts an attributes of the Networks within a NetworkSet to a Pandas DataFrame.
Examples
--------
>>> df = ns.ntwk_attr_2_df('s_db', m=1, n=0)
>>> df.to_excel('output.xls') # see Pandas docs for more info
"""
from pandas import DataFrame, Index, Series
index = Index(
self[0].frequency.f_scaled,
name=f'Freq({self[0].frequency.unit})'
)
df = DataFrame(
{f'{k.name}':
Series(getattr(k, attr)[:,m,n],index=index)
for k in self},
index = index,
)
return df
def interpolate_from_network(self, ntw_param: ArrayLike, x: float, interp_kind: str = 'linear'):
"""
Interpolate a Network from a NetworkSet, as a multi-file N-port network.
Assumes that the NetworkSet contains N-port networks
with same number of ports N and same number of frequency points.
These networks differ from an given array parameter `interp_param`,
which is used to interpolate the returned Network. Length of `interp_param`
should be equal to the length of the NetworkSet.
Parameters
----------
ntw_param : (N,) array_like
A 1-D array of real values. The length of ntw_param must be equal
to the length of the NetworkSet
x : real
Point to evaluate the interpolated network at
interp_kind: str
Specifies the kind of interpolation as a string: 'linear', 'nearest', 'zero', 'slinear', 'quadratic',
'cubic'. See :class:`scipy.interpolate.interp1d` for detailed description.
Default is 'linear'.
Returns
-------
ntw : class:`~skrf.network.Network`
Network interpolated at x
Example
-------
Assuming that `ns` is a NetworkSet containing 3 Networks (length=3) :
>>> param_x = [1, 2, 3] # a parameter associated to each Network
>>> x0 = 1.5 # parameter value to interpolate for
>>> interp_ntwk = ns.interpolate_from_network(param_x, x0)
"""
ntw = self[0].copy()
# Interpolating the scattering parameters
s = np.array([self[idx].s for idx in range(len(self))])
f = interp1d(ntw_param, s, axis=0, kind=interp_kind)
ntw.s = f(x)
return ntw
def interpolate_frequency(self, freq_or_n: Frequency | NumberLike, basis: str = 's',
coords: str = 'cart', f_kwargs: dict = None, **kwargs) -> NetworkSet:
"""Interpolates each network in the set by frequency by calling :meth:`Network.interpolate`.
Parameters
----------
freq_or_n : :class:`~skrf.frequency.Frequency` or int or list-like
The new frequency over which to interpolate. this arg may be
one of the following:
* a new :class:`~skrf.frequency.Frequency` object
* an int: the current frequency span is resampled linearly.
* a list-like: create a new frequency using :meth:`~skrf.frequency.Frequency.from_f`
basis : ['s','z','y','a'], etc
The network parameter to interpolate
coords : string
Coordinate system to use for interpolation: 'cart' or 'polar':
'cart' is cartesian is Re/Im. 'polar' is unwrapped phase/mag
f_kwargs : dict
Key word arguments that are passed to the new :class:`Frequency` object
**kwargs : keyword arguments
passed to :func:`scipy.interpolate.interp1d` initializer.
`kind` controls interpolation type.
`kind` = `rational` uses interpolation by rational polynomials.
`d` kwarg controls the degree of rational polynomials
when `kind`=`rational`. Defaults to 4.
Returns
-------
NetworkSet : :class:`NetworkSet`
New NetworkSet with interpolated frequencies
"""
return NetworkSet([ntwk.interpolate(freq_or_n, basis, coords, f_kwargs, **kwargs) for ntwk in self.ntwk_set])
def has_params(self) -> bool:
"""
Check is all Networks in the NetworkSet have a similar params dictionary.
Returns
-------
bool
True is all Networks have a .params dictionary (of same size),
False otherwise
"""
# does all networks have a params property?
if not all(hasattr(ntwk, 'params') for ntwk in self.ntwk_set):
return False
# are all params property been set?
if any(ntwk.params is None for ntwk in self.ntwk_set):
return False
# are they all of the same size?
params_len = len(self.ntwk_set[0].params)
if not all(len(ntwk.params) == params_len for ntwk in self.ntwk_set):
return False
# are all the dict keys the same?
params_keys = self.ntwk_set[0].params.keys()
if not all(ntwk.params.keys() == params_keys for ntwk in self.ntwk_set):
return False
# then we are all good
return True
@property
def params(self) -> list:
"""
Return the list of parameter names stored in the Network of the NetworkSet.
Similar to the `dims` property, except it returns a list instead of a view.
Returns
-------
list: list
list of the parameter names if any. Empty list if no parameter found.
"""
return list(self.dims)
@property
def params_values(self) -> dict | None:
"""
Return a dictionary containing all parameters and their values.
Returns
-------
values : dict or None.
Dictionary of all parameters names and their values (into a list).
Return None if no parameters are defined in the NetworkSet.
"""
if self.has_params():
# creating a dict of empty lists for each of the param keys
values = {key: [] for key in self.dims}
for ntwk in self.ntwk_set:
for key, value in ntwk.params.items():
values[key].append(value)
return values
else:
return None
@property
def params_types(self) -> dict | None:
"""
Return a dictionary describing the data type of each parameters.
Returns
-------
data_types : dict or None.
Dictionary of the (guessed) type of each parameters.
Return None if no parameters are defined in the NetworkSet.
"""
# for each parameter, scan all the value and try to guess the type
# If is not a int, and not a float (double), then it's a string
if self.has_params():
data_types = {}
values = self.params_values
for key in values:
try:
_ = [int(v) for v in values[key]]
data_types[key] = 'int'
except ValueError: # not an int
try:
_ = [float(v) for v in values[key]]
data_types[key] = 'double'
except ValueError: # not a float -> then a string
data_types[key] = 'string'
return data_types
else:
return None
def to_dataframe(self, attrs: list[str] = None, ports: list[tuple[int, int]] = None, port_sep: str | None = None):
"""
Convert attributes of a NetworkSet to a pandas DataFrame.
Use the same parameters than :func:`skrf.io.general.network_2_dataframe`
Parameters
----------
attrs : list of string
Network attributes to convert, like ['s_db','s_deg']
ports : list of tuples
list of port pairs to write. defaults to ntwk.port_tuples
(like [[0,0]])
port_sep : string
defaults to None, which means a empty string "" is used for
networks with lower than 10 ports. (s_db 11, s_db 21)
For more than ten ports a "_" is used to avoid ambiguity.
(s_db 1_1, s_db 2_1)
For consistent behaviour it's recommended to specify "_" or
"," explicitly.
Returns
-------
df : `pandas.DataFrame`
Raises
------
ValueError : if the networkset doesn't have parameters
See Also
---------
skrf.io.general.network_2_dataframe
"""
if not self.params:
raise ValueError(
"The NetworkSet must have parameters to be combined into a dataframe. "
"Try using `ntwk_attr_2_df` instead."
)
dfs = []
for ntwk in self.ntwk_set:
# Create a dataframe for each network
df = ntwk.to_dataframe(attrs=attrs, ports=ports, port_sep=port_sep)
# Insert the parameters and values for each network
df[list(ntwk.params.keys())] = list(ntwk.params.values())
# Get the columns by type
data_cols = df.columns[:-1 * len(ntwk.params)].tolist()
param_cols = df.columns[-1 * len(ntwk.params):].tolist()
# Append to the list of dataframes with the parameter columns first
dfs.append(df[param_cols + data_cols])
# Return a concatenated dataframe
return pd.concat(dfs)
def sel(self, indexers: Mapping[Any, Any] = None) -> NetworkSet:
"""
Select Network(s) in the NetworkSet from a given value of a parameter.
Parameters
----------
indexers : dict, optional
A dict with keys matching dimensions and values given by scalars,
or arrays of parameters.
Default is None, which returns the entire NetworkSet
Returns
-------
ns : NetworkSet
NetworkSet containing the selected Networks or
an empty NetworkSet if no match is found
Example
-------
Creating a dummy example:
>>> params = [
{'a':0, 'X':10, 'c':'A'},
{'a':1, 'X':10, 'c':'A'},
{'a':2, 'X':10, 'c':'A'},
{'a':1, 'X':20, 'c':'A'},
{'a':0, 'X':20, 'c':'A'},
]
>>> freq1 = rf.Frequency(75, 110, 101, 'ghz')
>>> ntwks_params = [rf.Network(frequency=freq1,
s=np.random.rand(len(freq1),2,2),
name=f'ntwk_{m}',
comment=f'ntwk_{m}',
params=params) \
for (m, params) in enumerate(params) ]
>>> ns = rf.NetworkSet(ntwks_params)
Selecting the sub-NetworkSet matching scalar parameters:
>>> ns.sel({'a': 1}) # len == 2
>>> ns.sel({'a': 0, 'X': 10}) # len == 1
Selectong the sub-NetworkSet matching a range of parameters:
>>> ns.sel({'a': 0, 'X': [10,20]}) # len == 2
>>> ns.sel({'a': [0,1], 'X': [10,20]}) # len == 4
If using a parameter name of value that does not exist, returns empty NetworkSet:
>>> ns.sel({'a': -1}) # len == 0
>>> ns.sel({'duh': 0}) # len == 0
"""
from collections.abc import Iterable
if not indexers: # None or {}
return self.copy()
if not self.has_params():
return NetworkSet()
if not isinstance(indexers, dict):
raise TypeError('indexers should be a dictionary.')
for p in indexers.keys():
if p not in self.dims:
return NetworkSet()
ntwk_list = []
for k in self.ntwk_set:
match_list = [k.params[p] in (v if isinstance(v, Iterable) else [v])
for (p, v) in indexers.items()]
if all(match_list):
ntwk_list.append(k)
if ntwk_list:
return NetworkSet(ntwk_list)
else: # no match found
return NetworkSet()
def interpolate_from_params(self, param: str, x: float,
sub_params: dict=None, interp_kind: str = 'linear'):
"""
Interpolate a Network from given parameters of NetworkSet's Networks.
Parameters
----------
param : string
Name of the parameter to interpolate the NetworkSet with
x : float
Point to evaluate the interpolated network at
sub_params : dict, optional
Dictionary of parameter/values to filter the NetworkSet,
if necessary to avoid an ambiguity.
Default is empty dict.
interp_kind: str
Specifies the kind of interpolation as a string: 'linear', 'nearest',
'zero', 'slinear', 'quadratic', 'cubic'.
Cf :class:`scipy.interpolate.interp1d` for detailed description.
Default is 'linear'.
Returns
-------
ntw : class:`~skrf.network.Network`
Network interpolated at x
Raises
------
ValueError : if the interpolating param/value are incorrect or ambiguous
Example
-------
Creating a dummy example:
>>> params = [
{'a':0, 'X':10, 'c':'A'},
{'a':1, 'X':10, 'c':'A'},
{'a':2, 'X':10, 'c':'A'},
{'a':1, 'X':20, 'c':'A'},
{'a':0, 'X':20, 'c':'A'},
]
>>> freq1 = rf.Frequency(75, 110, 101, 'ghz')
>>> ntwks_params = [rf.Network(frequency=freq1,
s=np.random.rand(len(freq1),2,2),
name=f'ntwk_{m}',
comment=f'ntwk_{m}',
params=params) \
for (m, params) in enumerate(params) ]
>>> ns = rf.NetworkSet(ntwks_params)
Interpolated Network for a=1.2 within X=10 Networks:
>>> ns.interpolate_from_params('a', 1.2, {'X': 10})
"""
# checking interpolating param and values
if sub_params is None:
sub_params = {}
if param not in self.params:
raise ValueError(f'Parameter {param} is not found in the NetworkSet params.')
if isinstance(x, Number):
if not (min(self.coords[param]) < x < max(self.coords[param])):
raise ValueError(f'Out of bound values: {x} is not inside {self.coords[param]}. Cannot interpolate.')
else:
raise ValueError('Cannot interpolate between string-based parameters.')
# checking sub-parameters
if sub_params:
for (p, v) in sub_params.items():
# of course it should exist
if p not in self.dims:
raise ValueError(f'Parameter {p} is not found in the NetworkSet params.')
# check if each sub-param exist in the parameters
if v not in self.coords[p]: # also deals with string case
raise ValueError(f'Parameter {p} value {v} is not found in the NetworkSet params.')
# interpolating the sub-NetworkSet matching the passed sub-parameters
sub_ns = self.sel(sub_params)
interp_ntwk = sub_ns.interpolate_from_network(sub_ns.coords[param],
x, interp_kind)
return interp_ntwk
@copy_doc(skrf_plt.animate)
def animate(self, *args, **kwargs):
skrf_plt.animate(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_uncertainty_bounds_component)
def plot_uncertainty_bounds_component(self, *args, **kwargs):
skrf_plt.plot_uncertainty_bounds_component(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_minmax_bounds_component)
def plot_minmax_bounds_component(self, *args, **kwargs):
skrf_plt.plot_minmax_bounds_component(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_uncertainty_bounds_s_db)
def plot_uncertainty_bounds_s_db(self, *args, **kwargs):
skrf_plt.plot_uncertainty_bounds_s_db(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_minmax_bounds_s_db)
def plot_minmax_bounds_s_db(self, *args, **kwargs):
skrf_plt.plot_minmax_bounds_s_db(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_minmax_bounds_s_db10)
def plot_minmax_bounds_s_db10(self, *args, **kwargs):
skrf_plt.plot_minmax_bounds_s_db10(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_uncertainty_bounds_s_time_db)
def plot_uncertainty_bounds_s_time_db(self, *args, **kwargs):
skrf_plt.plot_uncertainty_bounds_s_time_db(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_minmax_bounds_s_time_db)
def plot_minmax_bounds_s_time_db(self, *args, **kwargs):
skrf_plt.plot_minmax_bounds_s_time_db(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_uncertainty_decomposition)
def plot_uncertainty_decomposition(self, *args, **kwargs):
skrf_plt.plot_uncertainty_decomposition(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_logsigma)
def plot_logsigma(self, *args, **kwargs):
skrf_plt.plot_logsigma(self, *args, **kwargs)
@copy_doc(skrf_plt.signature)
def signature(self, *args, **kwargs):
skrf_plt.signature(self, *args, **kwargs)
@copy_doc(skrf_plt.plot_violin)
def plot_violin(self, attribute, *args, **kwargs):
if "time" not in attribute:
skrf_plt.plot_violin(self, attribute, *args,**kwargs)
else:
raise NotImplementedError("Violin plots are not implemented for time based parameters")
def func_on_networks(ntwk_list, func, attribute='s',name=None, *args,\
**kwargs):
r"""
Applies a function to some attribute of a list of networks.
Returns the result in the form of a Network. This means information
that may not be s-parameters is stored in the s-matrix of the
returned Network.
Parameters
-------------
ntwk_list : list of :class:`~skrf.network.Network` objects
list of Networks on which to apply `func` to
func : function
function to operate on `ntwk_list` s-matrices
attribute : string
attribute of Network's in ntwk_list for func to act on
\*args,\*\*kwargs : arguments and keyword arguments
passed to func
Returns
---------
ntwk : :class:`~skrf.network.Network`
Network with s-matrix the result of func, operating on
ntwk_list's s-matrices
Examples
----------
averaging can be implemented with func_on_networks by
>>> func_on_networks(ntwk_list, mean)
"""
data_matrix = np.array([getattr(ntwk, attribute) for ntwk in ntwk_list])
new_ntwk = ntwk_list[0].copy()
new_ntwk.s = func(data_matrix,axis=0,**kwargs)
if name is not None:
new_ntwk.name = name
return new_ntwk
# short hand name for convenience
fon = func_on_networks
def getset(ntwk_dict, s, *args, **kwargs):
r"""
Creates a :class:`NetworkSet`, of all :class:`~skrf.network.Network`s
objects in a dictionary that contain `s` in its key. This is useful
for dealing with the output of
:func:`~skrf.io.general.load_all_touchstones`, which contains
Networks grouped by some kind of naming convention.
Parameters
------------
ntwk_dict : dictionary of Network objects
network dictionary that contains a set of keys `s`
s : string
string contained in the keys of ntwk_dict that are to be in the
NetworkSet that is returned
\*args,\*\*kwargs : passed to NetworkSet()
Returns
--------
ntwk_set : NetworkSet object
A NetworkSet that made from values of ntwk_dict with `s` in
their key
Examples
---------
>>>ntwk_dict = rf.load_all_touchstone('my_dir')
>>>set5v = getset(ntwk_dict,'5v')
>>>set10v = getset(ntwk_dict,'10v')
"""
ntwk_list = [ntwk_dict[k] for k in ntwk_dict if s in k]
if len(ntwk_list) > 0:
return NetworkSet( ntwk_list,*args, **kwargs)
else:
print(f'Warning: No keys in ntwk_dict contain \'{s}\'')
return None
def tuner_constellation(name='tuner', singlefreq=76, Z0=50, r_lin = 9, phi_lin=21, TNWformat=True):
r = np.linspace(0.1,0.9,r_lin)
a = np.linspace(0,2*np.pi,phi_lin)
r_, a_ = np.meshgrid(r,a)
c_ = r_ *np.exp(1j * a_)
g= c_.flatten()
x = np.real(g)
y = np.imag(g)
if TNWformat :
TNL = dict()
# for ii, gi in enumerate(g) :
for ii, gi in enumerate(g) :
TNL['pos'+str(ii)] = Network(f = [singlefreq ], s=[[[gi]]], z0=[[Z0]], name=name +'_' + str(ii))
TNW = NetworkSet(TNL, name=name)
return TNW, x,y,g
else :
return x,y,g
|