Debian Codegraph @

skrf/networkSet.py

raw symbols SCIP
1 """
2 .. module:: skrf.networkSet
3
4 ========================================
5 networkSet (:mod:`skrf.networkSet`)
6 ========================================
7
8 Provides a class representing an un-ordered set of n-port microwave networks.
9
10
11 Frequently one needs to make calculations, such as mean or standard
12 deviation, on an entire set of n-port networks. To facilitate these
13 calculations the :class:`NetworkSet` class provides convenient
14 ways to make such calculations.
15
16 Another usage is to interpolate a set of Networks which depend of
17 an parameter (like a knob, or a geometrical parameter).
18
19 The results are returned in :class:`~skrf.network.Network` objects,
20 so they can be plotted and saved in the same way one would do with a
21 :class:`~skrf.network.Network`.
22
23 The functionality in this module is provided as methods and
24 properties of the :class:`NetworkSet` Class.
25
26
27 NetworkSet Class
28 ================
29
30 .. autosummary::
31 :toctree: generated/
32
33 NetworkSet
34
35 NetworkSet Utilities
36 ====================
37
38 .. autosummary::
39 :toctree: generated/
40
41 func_on_networks
42 getset
43
44
45 """
46 from __future__ import annotations
47
48 import zipfile
49 from collections.abc import Mapping
50 from io import BytesIO
51 from numbers import Number
52 from pathlib import Path
53 from typing import Any, TextIO
54
55 import numpy as np
56 import pandas as pd
57 from scipy.interpolate import interp1d
58
59 from . import mathFunctions as mf
60 from .constants import NumberLike, PrimaryPropertiesT
61 from .network import COMPONENT_FUNC_DICT, PRIMARY_PROPERTIES, Frequency, Network
62 from .util import copy_doc, now_string_2_dt
63
64 try:
65 from numpy.typing import ArrayLike
66 except ImportError:
67 ArrayLike = Any
68
69 from . import plotting as skrf_plt
70
71
72 class NetworkSet:
73 """
74 A set of Networks.
75
76 This class allows functions on sets of Networks, such as mean or
77 standard deviation, to be calculated conveniently. The results are
78 returned in :class:`~skrf.network.Network` objects, so that they may be
79 plotted and saved in like :class:`~skrf.network.Network` objects.
80
81 This class also provides methods which can be used to plot uncertainty
82 bounds for a set of :class:`~skrf.network.Network`.
83
84 The names of the :class:`NetworkSet` properties are generated
85 dynamically upon initialization, and thus documentation for
86 individual properties and methods is not available. However, the
87 properties do follow the convention::
88
89 >>> my_network_set.function_name_network_property_name
90
91 For example, the complex average (mean)
92 :class:`~skrf.network.Network` for a
93 :class:`NetworkSet` is::
94
95 >>> my_network_set.mean_s
96
97 This accesses the property 's', for each element in the
98 set, and **then** calculates the 'mean' of the resultant set. The
99 order of operations is important.
100
101 Results are returned as :class:`~skrf.network.Network` objects,
102 so they may be plotted or saved in the same way as for
103 :class:`~skrf.network.Network` objects::
104
105 >>> my_network_set.mean_s.plot_s_mag()
106 >>> my_network_set.mean_s.write_touchstone('mean_response')
107
108 If you are calculating functions that return scalar variables, then
109 the result is accessible through the Network property .s_re. For
110 example::
111
112 >>> std_s_deg = my_network_set.std_s_deg
113
114 This result would be plotted by::
115
116 >>> std_s_deg.plot_s_re()
117
118
119 The operators, properties, and methods of NetworkSet object are
120 dynamically generated by private methods
121
122 * :func:`~NetworkSet.__add_a_operator`
123 * :func:`~NetworkSet.__add_a_func_on_property`
124 * :func:`~NetworkSet.__add_a_element_wise_method`
125 * :func:`~NetworkSet.__add_a_plot_uncertainty`
126
127 thus, documentation on the individual methods and properties are
128 not available.
129
130
131 """
132
133 def __init__(self, ntwk_set: list | dict = None, name: str = None):
134 """
135 Initialize for NetworkSet.
136
137 Parameters
138 ----------
139 ntwk_set : list of :class:`~skrf.network.Network` objects
140 the set of :class:`~skrf.network.Network` objects
141 name : string
142 the name of the NetworkSet, given to the Networks returned
143 from properties of this class.
144 """
145 if ntwk_set is None:
146 ntwk_set = []
147 if not isinstance(ntwk_set, (list, dict)):
148 raise ValueError('NetworkSet requires a list as argument')
149
150 # dict is authorized for convenience
151 # but if a dict is passed instead of a list -> list
152 if isinstance(ntwk_set, dict):
153 ntwk_set = list(ntwk_set.values())
154
155 # did they pass a list of Networks?
156 if not all([isinstance(ntwk, Network) for ntwk in ntwk_set]):
157 raise(TypeError('input must be list of Network types'))
158
159 # do all Networks have the same # ports?
160 if len (set([ntwk.number_of_ports for ntwk in ntwk_set])) > 1:
161 raise(ValueError('All elements in list of Networks must have same number of ports'))
162
163 # is all frequency information the same?
164 if not np.all([(ntwk_set[0].frequency == ntwk.frequency) for ntwk in ntwk_set]):
165 raise(ValueError('All elements in list of Networks must have same frequency information'))
166
167 ## initialization
168 # we are good to go
169 self.ntwk_set: list[Network] = ntwk_set
170 self.name = name
171
172 # extract the dimensions of the set
173 try:
174 self.dims = self.ntwk_set[0].params.keys()
175 except (AttributeError, IndexError): # .params is None
176 self.dims = dict()
177
178 # extract the coordinates of the set
179 try:
180 self.coords = {p: [] for p in self.dims}
181
182 for k in self.ntwk_set:
183 for p in self.dims:
184 self.coords[p].append(k.params[p])
185
186 # keep only unique terms
187 for p in self.coords.keys():
188 self.coords[p] = list(set(self.coords[p]))
189 except TypeError: # .params is None
190 self.coords = None
191
192 # create list of network properties, which we use to dynamically
193 # create a statistical properties of this set
194 network_property_list = [k+'_'+l \
195 for k in PRIMARY_PROPERTIES \
196 for l in COMPONENT_FUNC_DICT.keys()] + \
197 ['passivity','s']
198
199 # dynamically generate properties. this is slick.
200 max, min = np.max, np.min
201 max.__name__ = 'max'
202 min.__name__ = 'min'
203 for network_property_name in network_property_list:
204 for func in [np.mean, np.std, max, min]:
205 self.__add_a_func_on_property(func, network_property_name)
206
207 if 'db' not in network_property_name:# != 's_db' and network_property_name != 's':
208 # db uncertainty requires a special function call see
209 # plot_uncertainty_bounds_s_db
210 self.__add_a_plot_uncertainty(network_property_name)
211 self.__add_a_plot_minmax(network_property_name)
212
213 self.__add_a_element_wise_method('plot_'+network_property_name)
214 self.__add_a_element_wise_method('plot_s_db')
215 self.__add_a_element_wise_method('plot_s_db_time')
216
217 for network_method_name in \
218 ['write_touchstone','interpolate','plot_s_smith']:
219 self.__add_a_element_wise_method(network_method_name)
220
221 for operator_name in \
222 ['__pow__','__floordiv__','__mul__','__truediv__','__add__','__sub__']:
223 self.__add_a_operator(operator_name)
224
225 @classmethod
226 def from_zip(cls, zip_file_name: str | Path, sort_filenames: bool = True, *args, **kwargs):
227 r"""
228 Create a NetworkSet from a zipfile of touchstones.
229
230 Parameters
231 ----------
232 zip_file_name : string or Path
233 name of zipfile
234 sort_filenames: Boolean
235 sort the filenames in the zip file before constructing the
236 NetworkSet
237 \*args, \*\*kwargs : arguments
238 passed to NetworkSet constructor
239
240 Examples
241 --------
242 >>> import skrf as rf
243 >>> my_set = rf.NetworkSet.from_zip('myzip.zip')
244
245 """
246 z = zipfile.ZipFile(zip_file_name)
247 filename_list = z.namelist()
248
249 ntwk_list = []
250
251 if sort_filenames:
252 filename_list.sort()
253
254 for filename in filename_list:
255 # try/except block in case not all files are touchstones
256 try: # Ascii files (Touchstone, etc)
257 n = Network.zipped_touchstone(filename, z)
258 ntwk_list.append(n)
259 continue
260 except Exception:
261 pass
262 try: # Binary files (pickled Network)
263 fileobj = BytesIO(z.open(filename).read())
264 fileobj.name = filename
265 n = Network(fileobj)
266 ntwk_list.append(n)
267 continue
268 except Exception:
269 pass
270
271 return cls(ntwk_list)
272
273 @classmethod
274 def from_dir(cls, dir: str | Path = '.', *args, **kwargs):
275 r"""
276 Create a NetworkSet from a directory containing Networks.
277
278 This just calls ::
279
280 rf.NetworkSet(rf.read_all_networks(dir), *args, **kwargs)
281
282 Parameters
283 ----------
284 dir : str or Path
285 directory containing Network files.
286
287 \*args, \*\*kwargs :
288 passed to NetworkSet constructor
289
290 Examples
291 --------
292 >>> my_set = rf.NetworkSet.from_dir('./data/')
293
294 """
295 from .io.general import read_all_networks
296 return cls(read_all_networks(dir), *args, **kwargs)
297
298 @classmethod
299 def from_s_dict(cls, d: dict, frequency: Frequency, *args, **kwargs):
300 r"""
301 Create a NetworkSet from a dictionary of s-parameters
302
303 The resultant elements of the NetworkSet are named by the keys of
304 the dictionary.
305
306 Parameters
307 -------------
308 d : dict
309 dictionary of s-parameters data. values of this should be
310 :class:`numpy.ndarray` assignable to :attr:`skrf.network.Network.s`
311 frequency: :class:`~skrf.frequency.Frequency` object
312 frequency assigned to each network
313
314 \*args, \*\*kwargs :
315 passed to Network.__init__ for each key/value pair of d
316
317 Returns
318 ----------
319 ns : NetworkSet
320
321 See Also
322 ----------
323 NetworkSet.to_s_dict
324 """
325 return cls([Network(s=d[k], frequency=frequency, name=k,
326 **kwargs) for k in d])
327
328 @classmethod
329 def from_mdif(cls, file: str | Path | TextIO) -> NetworkSet:
330 """
331 Create a NetworkSet from a MDIF file.
332
333 Parameters
334 ----------
335 file : str, Path, file-object
336 MDIF file to load
337
338 Returns
339 -------
340 ns : :class: `~skrf.networkSet.NetworkSet`
341
342 See Also
343 --------
344 Mdif : MDIF Object
345 write_mdif : Convert a NetworkSet to a Generalized MDIF file.
346
347 """
348 from .io import Mdif
349 return Mdif(file).to_networkset()
350
351 @classmethod
352 def from_citi(cls, file: str | Path | TextIO) -> NetworkSet:
353 """
354 Create a NetworkSet from a CITI file.
355
356 Parameters
357 ----------
358 file : str, Path, or file-object
359 CITI file to load
360
361 Returns
362 -------
363 ns : :class: `~skrf.networkSet.NetworkSet`
364
365 See Also
366 --------
367 Citi
368
369 """
370 from .io import Citi
371 return Citi(file).to_networkset()
372
373 def __add_a_operator(self, operator_name):
374 """
375 Add an operator method to the NetworkSet.
376
377 this is made to
378 take either a Network or a NetworkSet. if a Network is passed
379 to the operator, each element of the set will operate on the
380 Network. If a NetworkSet is passed to the operator, and is the
381 same length as self. then it will operate element-to-element
382 like a dot-product.
383 """
384 def operator_func(self, other):
385 if isinstance(other, NetworkSet):
386 if len(other) != len(self):
387 raise(ValueError('Network sets must be of same length to be cascaded'))
388 return NetworkSet([
389 getattr(self.ntwk_set[k], operator_name)(other.ntwk_set[k]) for k in range(len(self))
390 ])
391
392 elif isinstance(other, Network):
393 return NetworkSet([getattr(ntwk, operator_name)(other) for ntwk in self.ntwk_set])
394
395 else:
396 raise(TypeError('NetworkSet operators operate on either Network, or NetworkSet types'))
397 setattr(self.__class__,operator_name,operator_func)
398
399
400 def __str__(self):
401 """
402 """
403 return f'{len(self.ntwk_set)}-Networks NetworkSet: '+self.ntwk_set.__str__()
404
405 def __repr__(self):
406 return self.__str__()
407
408 def __getitem__(self, key):
409 """
410 Return an element of the network set.
411 """
412 if isinstance(key, str):
413 # if they pass a string then slice each network in this set
414 return NetworkSet([k[key] for k in self.ntwk_set],
415 name = self.name)
416 else:
417 return self.ntwk_set[key]
418
419 def __len__(self) -> int:
420 """
421 Return the number of Networks in a NetworkSet.
422
423 Return
424 ------
425 len: int
426 Number of Networks in a NetworkSet
427
428 """
429 return len(self.ntwk_set)
430
431 def __eq__(self, other: NetworkSet) -> bool:
432 """
433 Compare the NetworkSet with another NetworkSet.
434
435 Two NetworkSets are considered equal of their Networks are all equals
436 (in the same order)
437
438 Returns
439 -------
440 is_equal: bool
441
442 """
443 # of course they should have equal lengths
444 if len(self) != len(other):
445 return False
446 # compare all networks in the order of the list
447 # return False as soon as 2 networks are different
448 for (ntwk, ntwk_other) in zip(self.ntwk_set, other):
449 if ntwk != ntwk_other:
450 return False
451
452 return True
453
454
455 def __add_a_element_wise_method(self, network_method_name: str):
456 def func(self, *args, **kwargs):
457 return self.element_wise_method(network_method_name, *args, **kwargs)
458 setattr(self.__class__,network_method_name,func)
459
460
461 def __add_a_func_on_property(self, func, network_property_name: str):
462 """
463 Dynamically add a property to this class (NetworkSet).
464
465 this is mostly used internally to generate all of the classes
466 properties.
467
468 Parameters
469 ----------
470 func: a function to be applied to the network_property
471 across the first axis of the property's output
472 network_property_name: str
473 a property of the Network class,
474 which must have a matrix output of shape (f, n, n)
475
476 example
477 -------
478 >>> my_ntwk_set.add_a_func_on_property(mean, 's')
479
480
481 """
482 def fget(self):
483 return fon(self.ntwk_set, func, network_property_name, name=self.name)
484 setattr(self.__class__,func.__name__+'_'+network_property_name,\
485 property(fget))
486
487 def __add_a_plot_uncertainty(self, network_property_name: str):
488 """
489 Add a plot uncertainty to a Network property.
490
491 Parameter
492 ---------
493 network_property_name: str
494 A property of the Network class,
495 which must have a matrix output of shape (f, n, n)
496
497 Parameter
498 ---------
499 >>> my_ntwk_set.__add_a_plot_uncertainty('s')
500
501
502 """
503 def plot_func(self,*args, **kwargs):
504 self.plot_uncertainty_bounds_component(network_property_name, *args,**kwargs)
505
506 setattr(self.__class__,'plot_uncertainty_bounds_'+\
507 network_property_name,plot_func)
508
509 setattr(self.__class__,'plot_ub_'+\
510 network_property_name,plot_func)
511
512 def __add_a_plot_minmax(self, network_property_name: str):
513 """
514
515 Parameter
516 ---------
517 network_property_name: str
518 A property of the Network class,
519 which must have a matrix output of shape (f, n, n)
520
521 Example
522 -------
523 >>> my_ntwk_set.__add_a_plot_minmax('s')
524
525
526 """
527 def plot_func(self,*args, **kwargs):
528 self.plot_minmax_bounds_component(network_property_name, *args,**kwargs)
529
530 setattr(self.__class__,'plot_minmax_bounds_'+\
531 network_property_name,plot_func)
532
533 setattr(self.__class__,'plot_mm_'+\
534 network_property_name,plot_func)
535
536 def to_dict(self) -> dict:
537 """
538 Return a dictionary representation of the NetworkSet.
539
540 Return
541 ------
542 d : dict
543 The returned dictionary has the Network names for keys,
544 and the Networks as values.
545
546 """
547 return {k.name: k for k in self.ntwk_set}
548
549 def to_s_dict(self):
550 """
551 Converts a NetworkSet to a dictionary of s-parameters.
552
553 The resultant keys of the dictionary are the names of the Networks
554 in NetworkSet
555
556 Returns
557 -------
558 s_dict : dictionary
559 contains s-parameters in the form of complex numpy arrays
560
561 See Also
562 --------
563 NetworkSet.from_s_dict
564
565 """
566 d = self.to_dict()
567 for k in d:
568 d[k] = d[k].s
569 return d
570
571 def element_wise_method(self, network_method_name: str, *args, **kwargs) -> NetworkSet:
572 """
573 Call a given method of each element and returns the result as
574 a new NetworkSet if the output is a Network.
575
576 Parameter
577 ---------
578 network_property_name: str
579 A property of the Network class,
580 which must have a matrix output of shape (f, n, n)
581
582 Return
583 ------
584 ns: :class: `~skrf.networkSet.NetworkSet`
585
586 """
587 output = [getattr(ntwk, network_method_name)(*args, **kwargs) for ntwk in self.ntwk_set]
588 if isinstance(output[0],Network):
589 return NetworkSet(output)
590 else:
591 return output
592
593 def copy(self) -> NetworkSet:
594 """
595 Copy each network of the network set.
596
597 Return
598 ------
599 ns: :class: `~skrf.networkSet.NetworkSet`
600
601 """
602 return NetworkSet([k.copy() for k in self.ntwk_set])
603
604 def sort(self, key=lambda x: x.name, inplace: bool = True, **kwargs) -> None | NetworkSet:
605 r"""
606 Sort this network set.
607
608 Parameters
609 ----------
610 key:
611
612 inplace: bool
613 Sort the NetworkSet object directly if True,
614 return the sorted NetworkSet if False. Default is True.
615
616 \*\*kwargs : dict
617 keyword args passed to builtin sorted acting on self.ntwk_set
618
619 Return
620 ------
621 ns: None if inplace=True, NetworkSet if False
622
623 Examples
624 --------
625 >>> ns = rf.NetworkSet.from_dir('mydir')
626 >>> ns.sort()
627
628 Sort by other property:
629
630 >>> ns.sort(key= lambda x: x.voltage)
631
632 Returns a new NetworkSet:
633
634 >>> sorted_ns = ns.sort(inplace=False)
635
636
637 """
638 sorted_ns = sorted(self.ntwk_set, key = key, **kwargs)
639 if inplace:
640 self.ntwk_set = sorted_ns
641 else:
642 return sorted_ns
643
644 def rand(self, n: int = 1, rng: None | np.random.Generator = None):
645 """
646 Return `n` random samples from this NetworkSet.
647
648 Parameters
649 ----------
650 n : int
651 number of samples to return (default is 1)
652 rng : :class:`numpy.random.Generator` or None
653 override the global :mod:`numpy` random number generator,
654 useful for multi-threaded programs since
655 :func:`skrf.mathFunctions.set_rand_rng` is not thread-safe.
656
657 """
658 if rng is None:
659 rng = mf.rand_rng()
660 idx = rng.randint(0,len(self), n)
661 out = [self.ntwk_set[k] for k in idx]
662
663 if n ==1:
664 return out[0]
665 else:
666 return out
667
668 def filter(self, s: str) -> NetworkSet:
669 """
670 Filter NetworkSet based on a string in `Network.name`.
671
672 Notes
673 -----
674 This is just
675
676 `NetworkSet([k for k in self if s in k.name])`
677
678 Parameters
679 ----------
680 s: str
681 string contained in network elements to be filtered
682
683 Returns
684 --------
685 ns : :class: `skrf.NetworkSet`
686
687
688 Examples
689 -----------
690 >>> ns.filter('monday')
691
692 """
693 return NetworkSet([k for k in self if s in k.name])
694
695 def scalar_mat(self, param: str = 's') -> np.ndarray:
696 """
697 Return a scalar ndarray representing `param` data vs freq and element idx.
698
699 Output is a 3d array with axes (freq, ns_index, port/ri).
700 ports is a flattened re/im components of port index (`len = 2*nports**2`).
701
702 Parameter
703 ---------
704 param : str
705 name of the parameter to export. Default is 's'.
706
707 Return
708 ------
709 x : :class: np.ndarray
710
711 """
712 ntwk = self[0]
713 nfreq = len(ntwk)
714 # x will have the axes (frequency, observations, ports)
715 x = np.array([[mf.flatten_c_mat(getattr(k, param)[f]) \
716 for k in self] for f in range(nfreq)])
717
718 return x
719
720 def cov(self, **kw) -> np.ndarray:
721 """
722 Covariance matrix.
723
724 shape of output will be (nfreq, 2*nports**2, 2*nports**2)
725 """
726 smat=self.scalar_mat(**kw)
727 return np.array([np.cov(k.T) for k in smat])
728
729 @property
730 def mean_s_db(self) -> Network:
731 """
732 Return Network of mean magnitude in dB.
733
734 Return
735 ------
736 ntwk : :class: `~skrf.network.Network`
737 Network of the mean magnitude in dB
738
739 Note
740 ----
741 The mean is taken on the magnitude before converted to db, so
742
743 `magnitude_2_db(mean(s_mag))`
744
745 which is NOT the same as
746
747 `mean(s_db)`
748
749 """
750 ntwk = self.mean_s_mag
751 ntwk.s = ntwk.s_db
752 return ntwk
753
754 @property
755 def std_s_db(self) -> Network:
756 """
757 Return the Network of the standard deviation magnitude in dB.
758
759 Return
760 ------
761 ntwk : :class: `~skrf.network.Network`
762 Network of the mean magnitude in dB
763
764 Note
765 ----
766 The standard deviation is taken on the magnitude before converted to db, so
767
768 `magnitude_2_db(std(s_mag))`
769
770 which is NOT the same as
771
772 `std(s_db)`
773
774 """
775 ntwk= self.std_s_mag
776 ntwk.s = ntwk.s_db
777 return ntwk
778
779 @property
780 def inv(self) -> NetworkSet:
781 """
782 Return the NetworkSet of inverted Networks (Network.inv()).
783
784 Returns
785 -------
786 ntwkSet : :class: `~skrf.networkSet.NetworkSet`
787 NetworkSet of inverted Networks
788
789 """
790 return NetworkSet( [ntwk.inv for ntwk in self.ntwk_set])
791
792 def add_polar_noise(self, ntwk: Network) -> Network:
793 """
794
795 Parameters
796 ----------
797 ntwk : :class: `~skrf.network.Network`
798
799
800 Returns
801 -------
802 ntwk : :class: `~skrf.network.Network`
803
804
805 """
806 from numpy import frompyfunc
807 from scipy import stats
808
809 def gimme_norm(x):
810 return stats.norm(loc=0, scale=x).rvs(1)[0]
811 ugimme_norm = frompyfunc(gimme_norm,1,1)
812
813 s_deg_rv = np.array(map(ugimme_norm, self.std_s_deg.s_re), dtype=float)
814 s_mag_rv = np.array(map(ugimme_norm, self.std_s_mag.s_re), dtype=float)
815
816 mag = ntwk.s_mag + s_mag_rv
817 deg = ntwk.s_deg + s_deg_rv
818 ntwk.s = mag * np.exp(1j*np.pi/180*deg)
819 return ntwk
820
821 def set_wise_function(self, func, a_property: str, *args, **kwargs):
822 """
823 Calls a function on a specific property of the Networks in this NetworkSet.
824
825 Parameters
826 ----------
827 func : callable
828
829 a_property : str
830
831
832 Example
833 -------
834 >>> my_ntwk_set.set_wise_func(mean,'s')
835
836 """
837 return fon(self.ntwk_set, func, a_property, *args, **kwargs)
838
839 def uncertainty_ntwk_triplet(self, attribute: PrimaryPropertiesT, n_deviations: int = 3) -> tuple(
840 Network, Network, Network
841 ):
842 """
843 Return a 3-tuple of Network objects which contain the
844 mean, upper_bound, and lower_bound for the given Network
845 attribute.
846
847 Used to save and plot uncertainty information data.
848
849 Note that providing 's' and 's_mag' as attributes will provide different results.
850 For those who want to directly find uncertainty on dB performance, use 's_mag'.
851
852 Parameters
853 ----------
854 attribute : str
855 Attribute to operate on.
856 n_deviations : int, optional
857 Number of standard deviation. The default is 3.
858
859 Returns
860 -------
861 ntwk_mean : :class: `~skrf.network.Network`
862 Network of the averaged attribute
863 lower_bound : :class: `~skrf.network.Network`
864 Network of the lower bound of N*sigma deviation.
865 upper_bound : :class: `~skrf.network.Network`
866 Network of the upper bound of N*sigma deviation.
867
868 Example
869 -------
870 >>> (ntwk_mean, ntwk_lb, ntwk_ub) = my_ntwk_set.uncertainty_ntwk_triplet('s')
871 >>> (ntwk_mean, ntwk_lb, ntwk_ub) = my_ntwk_set.uncertainty_ntwk_triplet('s_mag')
872
873 """
874 ntwk_mean = getattr(self, 'mean_'+attribute)
875 ntwk_std = getattr(self, 'std_'+attribute)
876 ntwk_std.s = n_deviations * ntwk_std.s
877
878 upper_bound = (ntwk_mean + ntwk_std)
879 lower_bound = (ntwk_mean - ntwk_std)
880
881 return (ntwk_mean, lower_bound, upper_bound)
882
883 def datetime_index(self) -> list:
884 """
885 Create a datetime index from networks names.
886
887 this is just:
888
889 `[rf.now_string_2_dt(k.name ) for k in self]`
890
891
892 """
893 return [now_string_2_dt(k.name ) for k in self]
894
895
896 # io
897 def write(self, file=None, *args, **kwargs):
898 r"""
899 Write the NetworkSet to disk using :func:`~skrf.io.general.write`
900
901
902 Parameters
903 ----------
904 file : str or file-object
905 filename or a file-object. If left as None then the
906 filename will be set to Calibration.name, if its not None.
907 If both are None, ValueError is raised.
908 \*args, \*\*kwargs : arguments and keyword arguments
909 passed through to :func:`~skrf.io.general.write`
910
911 Notes
912 -----
913 If the self.name is not None and file is can left as None
914 and the resultant file will have the `.ns` extension appended
915 to the filename.
916
917 Examples
918 ---------
919 >>> ns.name = 'my_ns'
920 >>> ns.write()
921
922 See Also
923 ---------
924 skrf.io.general.write
925 skrf.io.general.read
926
927 """
928 # this import is delayed until here because of a circular dependency
929 from .io.general import write
930
931 if file is None:
932 if self.name is None:
933 raise (ValueError('No filename given. You must provide a filename, or set the name attribute'))
934 file = self.name
935
936 write(file, self, *args, **kwargs)
937
938
939 def write_spreadsheet(self, *args, **kwargs):
940 """
941 Write contents of network to a spreadsheet, for your boss to use.
942
943 Example
944 -------
945 >>> ns.write_spreadsheet() # the ns.name attribute must exist
946 >>> ns.write_spreadsheet(file_name='testing.xlsx')
947
948 See Also
949 ---------
950 skrf.io.general.network_2_spreadsheet
951
952 """
953 from .io.general import networkset_2_spreadsheet
954 networkset_2_spreadsheet(self, *args, **kwargs)
955
956 def write_mdif(self,
957 filename: str,
958 values: dict | None = None,
959 data_types: dict | None = None,
960 comments: list[str] | None = None,
961 **kwargs):
962 """Convert a scikit-rf NetworkSet object to a Generalized MDIF file.
963
964 Parameters
965 ----------
966 filename : string
967 Output MDIF file name.
968 values : dictionary or None. Default is None.
969 The keys of the dictionary are MDIF variables and its values are
970 a list of the parameter values.
971 If None, then the values will be set to the NetworkSet names
972 and the datatypes will be set to "string".
973 data_types: dictionary or None. Default is None.
974 The keys are MDIF variables and the value are datatypes
975 specified by the following strings: "int", "double", and "string"
976 comments: list of strings
977 Comments to add to output_file.
978 Each list items is a separate comment line
979 **kwargs: dictionary with extra arguments to pass through to the
980 underlying Mdif.write and Network.write_touchstone methods
981
982 See Also
983 --------
984 from_mdif : Create a NetworkSet from a MDIF file.
985 params_values : parameters values
986 params_types : parameters types
987
988 """
989 from .io import Mdif
990 if comments is None:
991 comments = []
992 Mdif.write(ns=self, filename=filename, values=values,
993 data_types=data_types, comments=comments, **kwargs)
994
995 def ntwk_attr_2_df(self, attr='s_db', m=0, n=0, *args, **kwargs):
996 """
997 Converts an attributes of the Networks within a NetworkSet to a Pandas DataFrame.
998
999 Examples
1000 --------
1001 >>> df = ns.ntwk_attr_2_df('s_db', m=1, n=0)
1002 >>> df.to_excel('output.xls') # see Pandas docs for more info
1003
1004 """
1005 from pandas import DataFrame, Index, Series
1006 index = Index(
1007 self[0].frequency.f_scaled,
1008 name=f'Freq({self[0].frequency.unit})'
1009 )
1010 df = DataFrame(
1011 {f'{k.name}':
1012 Series(getattr(k, attr)[:,m,n],index=index)
1013 for k in self},
1014 index = index,
1015 )
1016 return df
1017
1018 def interpolate_from_network(self, ntw_param: ArrayLike, x: float, interp_kind: str = 'linear'):
1019 """
1020 Interpolate a Network from a NetworkSet, as a multi-file N-port network.
1021
1022 Assumes that the NetworkSet contains N-port networks
1023 with same number of ports N and same number of frequency points.
1024
1025 These networks differ from an given array parameter `interp_param`,
1026 which is used to interpolate the returned Network. Length of `interp_param`
1027 should be equal to the length of the NetworkSet.
1028
1029 Parameters
1030 ----------
1031 ntw_param : (N,) array_like
1032 A 1-D array of real values. The length of ntw_param must be equal
1033 to the length of the NetworkSet
1034 x : real
1035 Point to evaluate the interpolated network at
1036 interp_kind: str
1037 Specifies the kind of interpolation as a string: 'linear', 'nearest', 'zero', 'slinear', 'quadratic',
1038 'cubic'. See :class:`scipy.interpolate.interp1d` for detailed description.
1039 Default is 'linear'.
1040
1041 Returns
1042 -------
1043 ntw : class:`~skrf.network.Network`
1044 Network interpolated at x
1045
1046 Example
1047 -------
1048 Assuming that `ns` is a NetworkSet containing 3 Networks (length=3) :
1049
1050 >>> param_x = [1, 2, 3] # a parameter associated to each Network
1051 >>> x0 = 1.5 # parameter value to interpolate for
1052 >>> interp_ntwk = ns.interpolate_from_network(param_x, x0)
1053
1054
1055 """
1056 ntw = self[0].copy()
1057 # Interpolating the scattering parameters
1058 s = np.array([self[idx].s for idx in range(len(self))])
1059 f = interp1d(ntw_param, s, axis=0, kind=interp_kind)
1060 ntw.s = f(x)
1061
1062 return ntw
1063
1064 def interpolate_frequency(self, freq_or_n: Frequency | NumberLike, basis: str = 's',
1065 coords: str = 'cart', f_kwargs: dict = None, **kwargs) -> NetworkSet:
1066 """Interpolates each network in the set by frequency by calling :meth:`Network.interpolate`.
1067
1068 Parameters
1069 ----------
1070 freq_or_n : :class:`~skrf.frequency.Frequency` or int or list-like
1071 The new frequency over which to interpolate. this arg may be
1072 one of the following:
1073
1074 * a new :class:`~skrf.frequency.Frequency` object
1075
1076 * an int: the current frequency span is resampled linearly.
1077
1078 * a list-like: create a new frequency using :meth:`~skrf.frequency.Frequency.from_f`
1079
1080 basis : ['s','z','y','a'], etc
1081 The network parameter to interpolate
1082 coords : string
1083 Coordinate system to use for interpolation: 'cart' or 'polar':
1084 'cart' is cartesian is Re/Im. 'polar' is unwrapped phase/mag
1085 f_kwargs : dict
1086 Key word arguments that are passed to the new :class:`Frequency` object
1087 **kwargs : keyword arguments
1088 passed to :func:`scipy.interpolate.interp1d` initializer.
1089 `kind` controls interpolation type.
1090
1091 `kind` = `rational` uses interpolation by rational polynomials.
1092
1093 `d` kwarg controls the degree of rational polynomials
1094 when `kind`=`rational`. Defaults to 4.
1095
1096 Returns
1097 -------
1098 NetworkSet : :class:`NetworkSet`
1099 New NetworkSet with interpolated frequencies
1100 """
1101
1102 return NetworkSet([ntwk.interpolate(freq_or_n, basis, coords, f_kwargs, **kwargs) for ntwk in self.ntwk_set])
1103
1104 def has_params(self) -> bool:
1105 """
1106 Check is all Networks in the NetworkSet have a similar params dictionary.
1107
1108 Returns
1109 -------
1110 bool
1111 True is all Networks have a .params dictionary (of same size),
1112 False otherwise
1113
1114 """
1115 # does all networks have a params property?
1116 if not all(hasattr(ntwk, 'params') for ntwk in self.ntwk_set):
1117 return False
1118
1119 # are all params property been set?
1120 if any(ntwk.params is None for ntwk in self.ntwk_set):
1121 return False
1122
1123 # are they all of the same size?
1124 params_len = len(self.ntwk_set[0].params)
1125 if not all(len(ntwk.params) == params_len for ntwk in self.ntwk_set):
1126 return False
1127
1128 # are all the dict keys the same?
1129 params_keys = self.ntwk_set[0].params.keys()
1130 if not all(ntwk.params.keys() == params_keys for ntwk in self.ntwk_set):
1131 return False
1132
1133 # then we are all good
1134 return True
1135
1136 @property
1137 def params(self) -> list:
1138 """
1139 Return the list of parameter names stored in the Network of the NetworkSet.
1140
1141 Similar to the `dims` property, except it returns a list instead of a view.
1142
1143 Returns
1144 -------
1145 list: list
1146 list of the parameter names if any. Empty list if no parameter found.
1147
1148 """
1149 return list(self.dims)
1150
1151 @property
1152 def params_values(self) -> dict | None:
1153 """
1154 Return a dictionary containing all parameters and their values.
1155
1156 Returns
1157 -------
1158 values : dict or None.
1159 Dictionary of all parameters names and their values (into a list).
1160 Return None if no parameters are defined in the NetworkSet.
1161
1162 """
1163 if self.has_params():
1164 # creating a dict of empty lists for each of the param keys
1165 values = {key: [] for key in self.dims}
1166 for ntwk in self.ntwk_set:
1167 for key, value in ntwk.params.items():
1168 values[key].append(value)
1169 return values
1170 else:
1171 return None
1172
1173 @property
1174 def params_types(self) -> dict | None:
1175 """
1176 Return a dictionary describing the data type of each parameters.
1177
1178 Returns
1179 -------
1180 data_types : dict or None.
1181 Dictionary of the (guessed) type of each parameters.
1182 Return None if no parameters are defined in the NetworkSet.
1183
1184 """
1185 # for each parameter, scan all the value and try to guess the type
1186 # If is not a int, and not a float (double), then it's a string
1187 if self.has_params():
1188 data_types = {}
1189 values = self.params_values
1190 for key in values:
1191 try:
1192 _ = [int(v) for v in values[key]]
1193 data_types[key] = 'int'
1194 except ValueError: # not an int
1195 try:
1196 _ = [float(v) for v in values[key]]
1197 data_types[key] = 'double'
1198 except ValueError: # not a float -> then a string
1199 data_types[key] = 'string'
1200
1201 return data_types
1202 else:
1203 return None
1204
1205 def to_dataframe(self, attrs: list[str] = None, ports: list[tuple[int, int]] = None, port_sep: str | None = None):
1206 """
1207 Convert attributes of a NetworkSet to a pandas DataFrame.
1208
1209 Use the same parameters than :func:`skrf.io.general.network_2_dataframe`
1210
1211 Parameters
1212 ----------
1213 attrs : list of string
1214 Network attributes to convert, like ['s_db','s_deg']
1215 ports : list of tuples
1216 list of port pairs to write. defaults to ntwk.port_tuples
1217 (like [[0,0]])
1218 port_sep : string
1219 defaults to None, which means a empty string "" is used for
1220 networks with lower than 10 ports. (s_db 11, s_db 21)
1221 For more than ten ports a "_" is used to avoid ambiguity.
1222 (s_db 1_1, s_db 2_1)
1223 For consistent behaviour it's recommended to specify "_" or
1224 "," explicitly.
1225
1226 Returns
1227 -------
1228 df : `pandas.DataFrame`
1229
1230 Raises
1231 ------
1232 ValueError : if the networkset doesn't have parameters
1233
1234
1235 See Also
1236 ---------
1237 skrf.io.general.network_2_dataframe
1238 """
1239
1240 if not self.params:
1241 raise ValueError(
1242 "The NetworkSet must have parameters to be combined into a dataframe. "
1243 "Try using `ntwk_attr_2_df` instead."
1244 )
1245
1246 dfs = []
1247 for ntwk in self.ntwk_set:
1248 # Create a dataframe for each network
1249 df = ntwk.to_dataframe(attrs=attrs, ports=ports, port_sep=port_sep)
1250
1251 # Insert the parameters and values for each network
1252 df[list(ntwk.params.keys())] = list(ntwk.params.values())
1253
1254 # Get the columns by type
1255 data_cols = df.columns[:-1 * len(ntwk.params)].tolist()
1256 param_cols = df.columns[-1 * len(ntwk.params):].tolist()
1257
1258 # Append to the list of dataframes with the parameter columns first
1259 dfs.append(df[param_cols + data_cols])
1260
1261 # Return a concatenated dataframe
1262 return pd.concat(dfs)
1263
1264 def sel(self, indexers: Mapping[Any, Any] = None) -> NetworkSet:
1265 """
1266 Select Network(s) in the NetworkSet from a given value of a parameter.
1267
1268 Parameters
1269 ----------
1270 indexers : dict, optional
1271 A dict with keys matching dimensions and values given by scalars,
1272 or arrays of parameters.
1273 Default is None, which returns the entire NetworkSet
1274
1275 Returns
1276 -------
1277 ns : NetworkSet
1278 NetworkSet containing the selected Networks or
1279 an empty NetworkSet if no match is found
1280
1281 Example
1282 -------
1283 Creating a dummy example:
1284
1285 >>> params = [
1286 {'a':0, 'X':10, 'c':'A'},
1287 {'a':1, 'X':10, 'c':'A'},
1288 {'a':2, 'X':10, 'c':'A'},
1289 {'a':1, 'X':20, 'c':'A'},
1290 {'a':0, 'X':20, 'c':'A'},
1291 ]
1292 >>> freq1 = rf.Frequency(75, 110, 101, 'ghz')
1293 >>> ntwks_params = [rf.Network(frequency=freq1,
1294 s=np.random.rand(len(freq1),2,2),
1295 name=f'ntwk_{m}',
1296 comment=f'ntwk_{m}',
1297 params=params) \
1298 for (m, params) in enumerate(params) ]
1299 >>> ns = rf.NetworkSet(ntwks_params)
1300
1301 Selecting the sub-NetworkSet matching scalar parameters:
1302
1303 >>> ns.sel({'a': 1}) # len == 2
1304 >>> ns.sel({'a': 0, 'X': 10}) # len == 1
1305
1306 Selectong the sub-NetworkSet matching a range of parameters:
1307
1308 >>> ns.sel({'a': 0, 'X': [10,20]}) # len == 2
1309 >>> ns.sel({'a': [0,1], 'X': [10,20]}) # len == 4
1310
1311 If using a parameter name of value that does not exist, returns empty NetworkSet:
1312
1313 >>> ns.sel({'a': -1}) # len == 0
1314 >>> ns.sel({'duh': 0}) # len == 0
1315
1316 """
1317 from collections.abc import Iterable
1318
1319 if not indexers: # None or {}
1320 return self.copy()
1321
1322 if not self.has_params():
1323 return NetworkSet()
1324
1325 if not isinstance(indexers, dict):
1326 raise TypeError('indexers should be a dictionary.')
1327
1328 for p in indexers.keys():
1329 if p not in self.dims:
1330 return NetworkSet()
1331
1332 ntwk_list = []
1333 for k in self.ntwk_set:
1334 match_list = [k.params[p] in (v if isinstance(v, Iterable) else [v])
1335 for (p, v) in indexers.items()]
1336 if all(match_list):
1337 ntwk_list.append(k)
1338
1339 if ntwk_list:
1340 return NetworkSet(ntwk_list)
1341 else: # no match found
1342 return NetworkSet()
1343
1344
1345 def interpolate_from_params(self, param: str, x: float,
1346 sub_params: dict=None, interp_kind: str = 'linear'):
1347 """
1348 Interpolate a Network from given parameters of NetworkSet's Networks.
1349
1350 Parameters
1351 ----------
1352 param : string
1353 Name of the parameter to interpolate the NetworkSet with
1354 x : float
1355 Point to evaluate the interpolated network at
1356 sub_params : dict, optional
1357 Dictionary of parameter/values to filter the NetworkSet,
1358 if necessary to avoid an ambiguity.
1359 Default is empty dict.
1360 interp_kind: str
1361 Specifies the kind of interpolation as a string: 'linear', 'nearest',
1362 'zero', 'slinear', 'quadratic', 'cubic'.
1363 Cf :class:`scipy.interpolate.interp1d` for detailed description.
1364 Default is 'linear'.
1365
1366 Returns
1367 -------
1368 ntw : class:`~skrf.network.Network`
1369 Network interpolated at x
1370
1371 Raises
1372 ------
1373 ValueError : if the interpolating param/value are incorrect or ambiguous
1374
1375 Example
1376 -------
1377 Creating a dummy example:
1378
1379 >>> params = [
1380 {'a':0, 'X':10, 'c':'A'},
1381 {'a':1, 'X':10, 'c':'A'},
1382 {'a':2, 'X':10, 'c':'A'},
1383 {'a':1, 'X':20, 'c':'A'},
1384 {'a':0, 'X':20, 'c':'A'},
1385 ]
1386 >>> freq1 = rf.Frequency(75, 110, 101, 'ghz')
1387 >>> ntwks_params = [rf.Network(frequency=freq1,
1388 s=np.random.rand(len(freq1),2,2),
1389 name=f'ntwk_{m}',
1390 comment=f'ntwk_{m}',
1391 params=params) \
1392 for (m, params) in enumerate(params) ]
1393 >>> ns = rf.NetworkSet(ntwks_params)
1394
1395 Interpolated Network for a=1.2 within X=10 Networks:
1396
1397 >>> ns.interpolate_from_params('a', 1.2, {'X': 10})
1398
1399 """
1400 # checking interpolating param and values
1401 if sub_params is None:
1402 sub_params = {}
1403 if param not in self.params:
1404 raise ValueError(f'Parameter {param} is not found in the NetworkSet params.')
1405 if isinstance(x, Number):
1406 if not (min(self.coords[param]) < x < max(self.coords[param])):
1407 raise ValueError(f'Out of bound values: {x} is not inside {self.coords[param]}. Cannot interpolate.')
1408 else:
1409 raise ValueError('Cannot interpolate between string-based parameters.')
1410
1411 # checking sub-parameters
1412 if sub_params:
1413 for (p, v) in sub_params.items():
1414 # of course it should exist
1415 if p not in self.dims:
1416 raise ValueError(f'Parameter {p} is not found in the NetworkSet params.')
1417
1418 # check if each sub-param exist in the parameters
1419 if v not in self.coords[p]: # also deals with string case
1420 raise ValueError(f'Parameter {p} value {v} is not found in the NetworkSet params.')
1421
1422
1423
1424 # interpolating the sub-NetworkSet matching the passed sub-parameters
1425 sub_ns = self.sel(sub_params)
1426 interp_ntwk = sub_ns.interpolate_from_network(sub_ns.coords[param],
1427 x, interp_kind)
1428
1429 return interp_ntwk
1430
1431 @copy_doc(skrf_plt.animate)
1432 def animate(self, *args, **kwargs):
1433 skrf_plt.animate(self, *args, **kwargs)
1434
1435 @copy_doc(skrf_plt.plot_uncertainty_bounds_component)
1436 def plot_uncertainty_bounds_component(self, *args, **kwargs):
1437 skrf_plt.plot_uncertainty_bounds_component(self, *args, **kwargs)
1438
1439 @copy_doc(skrf_plt.plot_minmax_bounds_component)
1440 def plot_minmax_bounds_component(self, *args, **kwargs):
1441 skrf_plt.plot_minmax_bounds_component(self, *args, **kwargs)
1442
1443 @copy_doc(skrf_plt.plot_uncertainty_bounds_s_db)
1444 def plot_uncertainty_bounds_s_db(self, *args, **kwargs):
1445 skrf_plt.plot_uncertainty_bounds_s_db(self, *args, **kwargs)
1446
1447 @copy_doc(skrf_plt.plot_minmax_bounds_s_db)
1448 def plot_minmax_bounds_s_db(self, *args, **kwargs):
1449 skrf_plt.plot_minmax_bounds_s_db(self, *args, **kwargs)
1450
1451 @copy_doc(skrf_plt.plot_minmax_bounds_s_db10)
1452 def plot_minmax_bounds_s_db10(self, *args, **kwargs):
1453 skrf_plt.plot_minmax_bounds_s_db10(self, *args, **kwargs)
1454
1455 @copy_doc(skrf_plt.plot_uncertainty_bounds_s_time_db)
1456 def plot_uncertainty_bounds_s_time_db(self, *args, **kwargs):
1457 skrf_plt.plot_uncertainty_bounds_s_time_db(self, *args, **kwargs)
1458
1459 @copy_doc(skrf_plt.plot_minmax_bounds_s_time_db)
1460 def plot_minmax_bounds_s_time_db(self, *args, **kwargs):
1461 skrf_plt.plot_minmax_bounds_s_time_db(self, *args, **kwargs)
1462
1463 @copy_doc(skrf_plt.plot_uncertainty_decomposition)
1464 def plot_uncertainty_decomposition(self, *args, **kwargs):
1465 skrf_plt.plot_uncertainty_decomposition(self, *args, **kwargs)
1466
1467 @copy_doc(skrf_plt.plot_logsigma)
1468 def plot_logsigma(self, *args, **kwargs):
1469 skrf_plt.plot_logsigma(self, *args, **kwargs)
1470
1471 @copy_doc(skrf_plt.signature)
1472 def signature(self, *args, **kwargs):
1473 skrf_plt.signature(self, *args, **kwargs)
1474
1475 @copy_doc(skrf_plt.plot_violin)
1476 def plot_violin(self, attribute, *args, **kwargs):
1477 if "time" not in attribute:
1478 skrf_plt.plot_violin(self, attribute, *args,**kwargs)
1479 else:
1480 raise NotImplementedError("Violin plots are not implemented for time based parameters")
1481
1482 def func_on_networks(ntwk_list, func, attribute='s',name=None, *args,\
1483 **kwargs):
1484 r"""
1485 Applies a function to some attribute of a list of networks.
1486
1487
1488 Returns the result in the form of a Network. This means information
1489 that may not be s-parameters is stored in the s-matrix of the
1490 returned Network.
1491
1492 Parameters
1493 -------------
1494 ntwk_list : list of :class:`~skrf.network.Network` objects
1495 list of Networks on which to apply `func` to
1496 func : function
1497 function to operate on `ntwk_list` s-matrices
1498 attribute : string
1499 attribute of Network's in ntwk_list for func to act on
1500 \*args,\*\*kwargs : arguments and keyword arguments
1501 passed to func
1502
1503 Returns
1504 ---------
1505 ntwk : :class:`~skrf.network.Network`
1506 Network with s-matrix the result of func, operating on
1507 ntwk_list's s-matrices
1508
1509
1510 Examples
1511 ----------
1512 averaging can be implemented with func_on_networks by
1513
1514 >>> func_on_networks(ntwk_list, mean)
1515
1516 """
1517 data_matrix = np.array([getattr(ntwk, attribute) for ntwk in ntwk_list])
1518
1519 new_ntwk = ntwk_list[0].copy()
1520 new_ntwk.s = func(data_matrix,axis=0,**kwargs)
1521
1522 if name is not None:
1523 new_ntwk.name = name
1524
1525 return new_ntwk
1526
1527 # short hand name for convenience
1528 fon = func_on_networks
1529
1530
1531 def getset(ntwk_dict, s, *args, **kwargs):
1532 r"""
1533 Creates a :class:`NetworkSet`, of all :class:`~skrf.network.Network`s
1534 objects in a dictionary that contain `s` in its key. This is useful
1535 for dealing with the output of
1536 :func:`~skrf.io.general.load_all_touchstones`, which contains
1537 Networks grouped by some kind of naming convention.
1538
1539 Parameters
1540 ------------
1541 ntwk_dict : dictionary of Network objects
1542 network dictionary that contains a set of keys `s`
1543 s : string
1544 string contained in the keys of ntwk_dict that are to be in the
1545 NetworkSet that is returned
1546 \*args,\*\*kwargs : passed to NetworkSet()
1547
1548 Returns
1549 --------
1550 ntwk_set : NetworkSet object
1551 A NetworkSet that made from values of ntwk_dict with `s` in
1552 their key
1553
1554 Examples
1555 ---------
1556 >>>ntwk_dict = rf.load_all_touchstone('my_dir')
1557 >>>set5v = getset(ntwk_dict,'5v')
1558 >>>set10v = getset(ntwk_dict,'10v')
1559 """
1560 ntwk_list = [ntwk_dict[k] for k in ntwk_dict if s in k]
1561 if len(ntwk_list) > 0:
1562 return NetworkSet( ntwk_list,*args, **kwargs)
1563 else:
1564 print(f'Warning: No keys in ntwk_dict contain \'{s}\'')
1565 return None
1566
1567
1568 def tuner_constellation(name='tuner', singlefreq=76, Z0=50, r_lin = 9, phi_lin=21, TNWformat=True):
1569 r = np.linspace(0.1,0.9,r_lin)
1570 a = np.linspace(0,2*np.pi,phi_lin)
1571 r_, a_ = np.meshgrid(r,a)
1572 c_ = r_ *np.exp(1j * a_)
1573 g= c_.flatten()
1574 x = np.real(g)
1575 y = np.imag(g)
1576
1577 if TNWformat :
1578 TNL = dict()
1579 # for ii, gi in enumerate(g) :
1580 for ii, gi in enumerate(g) :
1581 TNL['pos'+str(ii)] = Network(f = [singlefreq ], s=[[[gi]]], z0=[[Z0]], name=name +'_' + str(ii))
1582 TNW = NetworkSet(TNL, name=name)
1583 return TNW, x,y,g
1584 else :
1585 return x,y,g