Debian Codegraph @

skrf/network.py

raw symbols SCIP
1 """
2 .. module:: skrf.network
3 ========================================
4 network (:mod:`skrf.network`)
5 ========================================
6
7 Provide an n-port network class and associated functions.
8
9 Much of the functionality in this module is provided as methods and
10 properties of the :class:`Network` Class.
11
12
13 Network Class
14 ===============
15
16 .. autosummary::
17 :toctree: generated/
18
19 Network
20
21 Building Network
22 ----------------
23
24 .. autosummary::
25 :toctree: generated/
26
27 Network.from_z
28
29 Network Representations
30 ============================
31
32 .. autosummary::
33 :toctree: generated/
34
35 Network.s
36 Network.z
37 Network.y
38 Network.a
39 Network.t
40
41 Connecting Networks
42 ===============================
43
44 .. autosummary::
45 :toctree: generated/
46
47 connect
48 innerconnect
49 cascade
50 cascade_list
51 de_embed
52 flip
53 inv
54 parallelconnect
55
56
57
58 Interpolation and Concatenation Along Frequency Axis
59 =====================================================
60
61 .. autosummary::
62 :toctree: generated/
63
64 stitch
65 overlap
66 overlap_multi
67 Network.resample
68 Network.interpolate
69 Network.interpolate_self
70
71
72 Combining and Splitting Networks
73 ===================================
74
75 .. autosummary::
76 :toctree: generated/
77
78 subnetwork
79
80 one_port_2_two_port
81 twoport_to_nport
82 four_oneports_2_twoport
83 n_oneports_2_nport
84 n_twoports_2_nport
85 concat_ports
86
87
88
89 IO
90 ====
91
92 .. autosummary::
93
94 skrf.io.general.read
95 skrf.io.general.write
96 skrf.io.general.network_2_spreadsheet
97 Network.write
98 Network.write_touchstone
99 Network.read
100 Network.write_spreadsheet
101
102 Noise
103 ============
104 .. autosummary::
105 :toctree: generated/
106
107 Network.add_noise_polar
108 Network.add_noise_polar_flatband
109 Network.multiply_noise
110
111
112 Supporting Functions
113 ======================
114
115 .. autosummary::
116 :toctree: generated/
117
118 inv
119 connect_s
120 innerconnect_s
121 innerconnect_s_lstsq
122 s2s
123 s2z
124 s2y
125 s2t
126 s2a
127 s2g
128 s2h
129 z2s
130 z2y
131 z2t
132 z2a
133 y2s
134 y2z
135 y2t
136 t2s
137 t2z
138 t2y
139 h2s
140 h2z
141 s2s_active
142 s2z_active
143 s2y_active
144 s2vswr_active
145 fix_z0_shape
146 renormalize_s
147 passivity
148 reciprocity
149
150 Misc Functions
151 =====================
152 .. autosummary::
153 :toctree: generated/
154
155 average
156 stdev
157 s_error
158 impedance_mismatch
159 two_port_reflect
160 chopinhalf
161 Network.nudge
162 Network.renormalize
163 Network.drop_non_monotonic_increasing
164 evenodd2delta
165
166 Network utilities
167 =====================
168 .. autosummary::
169 :toctree: generated/
170
171 fix_param_shape
172 fix_z0_shape
173 check_frequency_exist
174 check_nports_equal
175 check_frequency_equal
176 check_z0_equal
177 assert_frequency_equal
178 assert_nports_equal
179 assert_frequency_exist
180 assert_z0_equal
181 assert_z0_at_ports_equal
182
183 """
184 from __future__ import annotations
185
186 import io
187 import os
188 import re
189 import warnings
190 import zipfile
191 from collections.abc import Callable, Sequence, Sized
192 from copy import deepcopy as copy
193 from functools import reduce
194 from itertools import product
195 from numbers import Number
196 from pathlib import Path
197 from pickle import UnpicklingError
198 from typing import Any, Literal, NoReturn, TextIO, get_args
199
200 import numpy as np
201 from numpy import gradient, ndarray, shape
202 from numpy.linalg import inv as npy_inv
203 from scipy import stats # for Network.add_noise_*, and Network.windowed
204 from scipy.integrate import cumulative_trapezoid
205 from scipy.interpolate import interp1d # for Network.interpolate()
206
207 from . import __version__
208 from . import mathFunctions as mf
209 from . import plotting as rfplt
210 from .constants import (
211 K_BOLTZMANN,
212 S_DEF_DEFAULT,
213 S_DEFINITIONS,
214 T0,
215 ZERO,
216 CircuitComponentT,
217 ComponentFuncT,
218 CoordT,
219 ErrorFunctionsT,
220 FrequencyUnitT,
221 InterpolKindT,
222 NumberLike,
223 PrimaryPropertiesT,
224 SdefT,
225 SparamFormatT,
226 )
227 from .frequency import Frequency
228 from .time import get_window, time_gate
229 from .util import Axes, axes_kwarg, copy_doc, find_nearest_index, get_extn, get_fid, partial_with_docs
230
231
232 class Network:
233 r"""
234 An n-port electrical network.
235
236 For instructions on how to create Network see :func:`__init__`.
237 An n-port network [#TwoPortWiki]_ may be defined by three quantities
238
239 * network parameter matrix (s, z, or y-matrix)
240 * port characteristic impedance matrix
241 * frequency information
242
243 The :class:`Network` class stores these data structures internally
244 in the form of complex :class:`numpy.ndarray`'s. These arrays are not
245 interfaced directly but instead through the use of the properties:
246
247 ===================== =============================================
248 Property Meaning
249 ===================== =============================================
250 :attr:`s` Scattering parameter matrix.
251 :attr:`z0` Characteristic impedance matrix.
252 :attr:`f` Frequency vector.
253 ===================== =============================================
254
255 Although these docs focus on s-parameters, other equivalent network
256 representations such as :attr:`z` and :attr:`y` are
257 available. Scalar projections of the complex network parameters
258 are accessible through properties as well. These also return
259 :class:`numpy.ndarray`'s.
260
261 ===================== =============================================
262 Property Meaning
263 ===================== =============================================
264 :attr:`s_re` Real part of the s-matrix.
265 :attr:`s_im` Imaginary part of the s-matrix.
266 :attr:`s_mag` Magnitude of the s-matrix.
267 :attr:`s_db` Magnitude in log scale of the s-matrix.
268 :attr:`s_deg` Phase of the s-matrix in degrees.
269 ===================== =============================================
270
271 The following operations act on the networks s-matrix.
272
273 ===================== =============================================
274 Operator Function
275 ===================== =============================================
276 \+ Element-wise addition of the s-matrix.
277 \- Element-wise difference of the s-matrix.
278 \* Element-wise multiplication of the s-matrix.
279 \/ Element-wise division of the s-matrix.
280 \*\* Cascading (only for 2-ports).
281 \// De-embedding (for 2-ports, see :attr:`inv`).
282 ===================== =============================================
283
284 Different components of the :class:`Network` can be visualized
285 through various plotting methods. These methods can be used to plot
286 individual elements of the s-matrix or all at once. For more info
287 about plotting see the :doc:`../../tutorials/Plotting` tutorial.
288
289 ========================= =============================================
290 Method Meaning
291 ========================= =============================================
292 :func:`plot_s_smith` Plot complex s-parameters on smith chart.
293 :func:`plot_s_re` Plot real part of s-parameters vs frequency.
294 :func:`plot_s_im` Plot imaginary part of s-parameters vs frequency.
295 :func:`plot_s_mag` Plot magnitude of s-parameters vs frequency.
296 :func:`plot_s_db` Plot magnitude (in dB) of s-parameters vs frequency.
297 :func:`plot_s_deg` Plot phase of s-parameters (in degrees) vs frequency.
298 :func:`plot_s_deg_unwrap` Plot phase of s-parameters (in unwrapped degrees) vs frequency.
299 ========================= =============================================
300
301 :class:`Network` objects can be created from a touchstone or pickle
302 file (see :func:`__init__`), by a
303 :class:`~skrf.media.media.Media` object, or manually by assigning the
304 network properties directly. :class:`Network` objects
305 can be saved to disk in the form of touchstone files with the
306 :func:`write_touchstone` method.
307
308 An exhaustive list of :class:`Network` Methods and Properties
309 (Attributes) are given below
310
311
312 References
313 ----------
314 .. [#TwoPortWiki] http://en.wikipedia.org/wiki/Two-port_network
315 """
316 PRIMARY_PROPERTIES: tuple[PrimaryPropertiesT, ...] = get_args(PrimaryPropertiesT)
317 """
318 Primary Network Properties list like 's', 'z', 'y', etc.
319 """
320
321 _func_lookup: dict[ComponentFuncT, tuple[str, Callable | None]] = {
322 're': ('Real Part', np.real),
323 'im': ('Imag Part', np.imag),
324 'mag': ('Magnitude', np.abs),
325 'db': ('Magnitude (dB)', mf.complex_2_db),
326 'db10': ('Magnitude (dB)', mf.complex_2_db10),
327 'rad': ('Phase (rad)', np.angle),
328 'deg': ('Phase (deg)', lambda x: np.angle(x, deg=True)),
329 'arcl': ('Arc Length',lambda x: np.angle(x) * np.abs(x)),
330 'rad_unwrap': ('Phase (rad)', lambda x: mf.unwrap_rad(np.angle(x))),
331 'deg_unwrap': ('Phase (deg)', lambda x: mf.radian_2_degree(mf.unwrap_rad(np.angle(x)))),
332 'arcl_unwrap': ('Arc Length', lambda x: mf.unwrap_rad(np.angle(x)) * np.abs(x)),
333 'vswr': ('VSWR', lambda x: (1 + abs(x)) / (1 - abs(x))),
334 'time': ('Time (real)', mf.ifft),
335 'time_db': ('Magnitude (dB)', lambda x: mf.complex_2_db(mf.ifft(x))),
336 'time_mag': ('Magnitude', lambda x: mf.complex_2_magnitude(mf.ifft(x))),
337 'time_impulse': ('Magnitude', None),
338 'time_step': ('Magnitude', None),
339 }
340
341 COMPONENT_FUNC_DICT: dict[ComponentFuncT, Callable | None] = {k: v[1] for k,v in _func_lookup.items()}
342
343 """
344 Component functions like 're', 'im', 'mag', 'db', etc.
345 """
346
347 @classmethod
348 def _generated_functions(cls) -> dict[str, tuple[Callable, str, str]]:
349 return {f"{p}_{func_name}": (func, p, func_name)
350 for p in cls.PRIMARY_PROPERTIES
351 for func_name, func in cls.COMPONENT_FUNC_DICT.items()}
352
353 # provides y-axis labels to the plotting functions
354 Y_LABEL_DICT: dict[ComponentFuncT, str] = {k: v[0] for k,v in _func_lookup.items()}
355 """
356 Y-axis labels to the plotting functions.
357 """
358
359 # CONSTRUCTOR
360 def __init__(self, file: str = None, name: str = None, params: dict = None,
361 comments: str = None, f_unit: FrequencyUnitT | None = None,
362 s_def: SdefT | None = None, **kwargs) -> None:
363 r"""
364 Network constructor.
365
366 Creates an n-port microwave network from a `file` or directly
367 from data. If no file or data is given, then an empty Network
368 is created.
369
370 Parameters
371 ----------
372
373 file : str, Path, or file-object
374 file to load information from. supported formats are:
375 * touchstone file (.s?p) (or .ts)
376 * io.StringIO object (with `.name` property which contains the file extension, such as `myfile.s4p`)
377 * pickled Network (.ntwk, .p) see :func:`write`
378 name : str, optional
379 Name of this Network. if None will try to use file, if it is a str
380 params : dict, optional
381 Dictionary of parameters associated with the Network
382 comments : str, optional
383 Comments associated with the Network
384 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
385 Scattering parameter definition : 'power' for power-waves definition,
386 'pseudo' for pseudo-waves definition.
387 'traveling' corresponds to the initial implementation.
388 Default is 'power'.
389 NB: results are the same for real-valued characteristic impedances.
390 \*\*kwargs :
391 key word arguments can be used to assign properties of the
392 Network, such as `s`, `f` and `z0`.
393 keyword `encoding` can be used to define the Touchstone file encoding.
394 keyword `noise_interp_kind` used to change the default interpolation
395 method for noisy networks. Options are 'linear', 'nearest',
396 'nearest-up', 'zero', 'slinear', 'quadratic', 'cubic',
397 'previous', or 'next'. Review `scipy.interpolate.interp_1d`
398 for details on each interpolation style. Defaults to 'linear'.
399 keyword `noise_fill_value` used to change the default interpolation
400 fill value for noisy networks. Defaults to np.nan.
401
402 Examples
403 --------
404 From a touchstone
405
406 >>> n = rf.Network('ntwk1.s2p')
407
408 From a pickle file
409
410 >>> n = rf.Network('ntwk1.ntwk')
411
412 Create a blank network, then fill in values
413
414 >>> n = rf.Network()
415 >>> freq = rf.Frequency(1, 3, 3, 'GHz')
416 >>> n.frequency, n.s, n.z0 = freq, [1,2,3], [1,2,3]
417
418 Directly from values
419
420 >>> n = rf.Network(f=[1,2,3], s=[1,2,3], z0=[1,2,3])
421
422 Define some parameters associated with the Network
423
424 >>> n = rf.Network('ntwk1.s2p', params={'temperature': 25, 'voltage':5})
425
426 See Also
427 --------
428 from_z : init from impedance values
429 read : read a network from a file
430 write : write a network to a file, using pickle
431 write_touchstone : write a network to a touchstone file
432 """
433 # allow for old kwarg for backward compatibility
434 if 'touchstone_filename' in kwargs:
435 file = kwargs['touchstone_filename']
436
437 # Default interpolation method.
438 self.noise_interp_kind = kwargs.get("noise_interp_kind", "linear")
439
440 # Default noise fill value when out of the s-parameter frequency bounds.
441 self.noise_fill_value = kwargs.get("noise_fill_value", np.nan)
442
443 self.name = name
444 self.params = params
445 self.comments = comments
446 self.port_names = None
447 self.encoding = kwargs.pop('encoding', None)
448
449 self.deembed = None
450 self.noise = None
451 self.noise_freq = None
452 self._z0 = np.array(50, dtype=complex)
453 self._port_modes = np.array([])
454 self._ext_attrs: dict[CircuitComponentT, bool] = {}
455
456 if s_def not in S_DEFINITIONS and s_def is not None:
457 raise ValueError('s_def parameter should be either:', S_DEFINITIONS)
458 else:
459 self.s_def = s_def
460
461 if file is not None:
462
463 # allows user to pass StringIO, filename or file obj
464 if isinstance(file, io.StringIO):
465 if not hasattr(file, "name") and name is not None:
466 file.name = name
467 self.read_touchstone(file, self.encoding)
468
469 else:
470 # open file in 'binary' mode because we are going to try and
471 # unpickle it first
472 fid = get_fid(file, 'rb')
473
474 try:
475 self.read(fid)
476 except UnicodeDecodeError: # Support for pickles created in Python2 and loaded in Python3
477 self.read(fid, encoding='latin1')
478 except (UnpicklingError, TypeError):
479 # if unpickling doesn't work then, close fid, reopen in
480 # non-binary mode and try to read it as touchstone
481 filename = fid.name
482 fid.close()
483 self.read_touchstone(filename, self.encoding)
484
485 if not fid.closed:
486 fid.close()
487
488 if name is None and isinstance(file, str):
489 name = os.path.splitext(os.path.basename(file))[0]
490
491 if self.frequency is not None and f_unit is not None:
492 self.frequency.unit = f_unit
493
494 # S-param definition. Done *after* reading data,
495 # where the S-param definition may have been guessed.
496 if self.s_def is None: # not guessed
497 self.s_def = S_DEF_DEFAULT
498
499 # Check for multiple attributes
500 params = [attr for attr in PRIMARY_PROPERTIES if attr in kwargs]
501 if len(params) > 1:
502 raise ValueError(f'Multiple input parameters provided: {params}')
503
504 # When initializing Network from different parameters than s
505 # we need to make sure that z0 has been set first because it will be
506 # needed in conversion to S-parameters. s is initialized with zeros here,
507 # to determine the correct z0 shape afterwards.
508
509 if params:
510 s_shape = np.array(kwargs[params[0]]).shape
511 self.s = np.zeros(s_shape, dtype=complex)
512
513 self.z0 = kwargs.get('z0', self._z0)
514 if not len(self.port_modes):
515 self.port_modes = np.array(["S"] * self.nports)
516
517
518 if "f" in kwargs.keys():
519 if f_unit is None:
520 f_unit = "hz"
521 kwargs["frequency"] = Frequency.from_f(kwargs.pop("f"), unit=f_unit)
522
523 for attr in list(PRIMARY_PROPERTIES) + ['frequency', 'noise', 'noise_freq']:
524 if attr in kwargs:
525 self.__setattr__(attr, kwargs[attr])
526
527 @classmethod
528 def from_z(cls, z: np.ndarray, *args, **kw) -> Network:
529 r"""
530 Create a Network from its Z-parameters.
531
532 Parameters
533 ----------
534 z : Numpy array
535 Impedance matrix. Should be of shape fxnxn,
536 where f is frequency axis and n is number of ports
537 \*\*kwargs :
538 key word arguments can be used to assign properties of the
539 Network, `f` and `z0`.
540
541 Returns
542 -------
543 ntw : :class:`Network`
544 Created Network
545
546 Examples
547 --------
548 >>> f = rf.Frequency(start=1, stop=2, npoints=4, unit="GHz") # 4 frequency points
549 >>> z = np.random.rand(len(f),2,2) + np.random.rand(len(f),2,2)*1j # 2-port z-matrix: shape=(4,2,2)
550 >>> ntw = rf.Network.from_z(z, frequency=f)
551
552 """
553 s = np.zeros(shape=z.shape)
554 me = cls(s=s, **kw)
555 me.z = z
556 return me
557
558 # OPERATORS
559 def __pow__(self, other: Network) -> Network:
560 """
561 Cascade this network with another network.
562
563 Returns
564 -------
565 ntw : :class:`Network`
566 Cascaded Network
567
568 See Also
569 --------
570 cascade
571
572 """
573 check_frequency_exist(self)
574
575 # if they pass a number then use power operator
576 if isinstance(other, Number):
577 out = self.copy()
578 out.s = out.s ** other
579 return out
580
581 else:
582 return cascade(self, other)
583
584 def __rshift__(self, other: Network) -> Network:
585 """
586 Cascade two 4-port networks with "1=>2/3=>4" port numbering.
587
588 Note
589 ----
590 connection diagram::
591
592 A B
593 +---------+ +---------+
594 -|0 1|---|0 1|-
595 -|2 3|---|1 3|-
596 ... ... ... ...
597 -|2N-4 2N-3|---|2N-4 2N-3|-
598 -|2N-2 2N-1|---|2N-2 2N-1|-
599 +---------+ +---------+
600
601 Returns
602 -------
603 ntw : :class:`Network`
604 Cascaded Network
605
606 See Also
607 --------
608 cascade
609
610 """
611 check_nports_equal(self, other)
612 check_frequency_exist(self)
613 (n,_) = shape(self.s[0])
614 if (n / 2) != (n // 2):
615 raise ValueError("Operator >> requires an even number of ports.")
616
617 ix_old = list(range(n))
618 n_2 = n//2
619 n_2_1 = list(range(n_2))
620 ix_new = list(sum(zip(n_2_1, list(map((lambda x: x + n_2), n_2_1))), ()))
621
622 _ntwk1 = self.copy()
623 _ntwk1.renumber(ix_old,ix_new)
624 _ntwk2 = other.copy()
625 _ntwk2.renumber(ix_old,ix_new)
626 _rslt = _ntwk1 ** _ntwk2
627 _rslt.renumber(ix_new,ix_old)
628 return _rslt
629
630 def __floordiv__(self, other: Network | tuple[Network, ...] ) -> Network:
631 """
632 De-embedding 1 or 2 network[s], from this network.
633
634 :param other: skrf.Network, list, tuple: Network(s) to de-embed
635 :return: skrf.Network: De-embedded network
636
637 Returns
638 -------
639 ntw : :class:`Network`
640
641 See Also
642 --------
643 inv : inverse s-parameters
644 """
645
646 if isinstance(other, list | tuple):
647 if len(other) >= 3:
648 raise ValueError('Incorrect number of networks.')
649 other_tpl = other[:2]
650 else:
651 other_tpl = (other, )
652
653 for o in other_tpl:
654 if o.number_of_ports != 2:
655 raise IndexError(f'Incorrect number of ports in network {o.name}.')
656
657 if len(other_tpl) == 1:
658 # if passed 1 network (A) and another network B
659 # e.g. A // B
660 # e.g. A // (B)
661 # then de-embed like B.inv * A
662 b = other_tpl[0]
663 result = self.copy()
664 result.s = (b.inv ** self).s
665 # de_embed(self.s, b.s)
666 return result
667 else:
668 # if passed 1 network (A) and a list/tuple of 2 networks (B, C),
669 # e.g. A // (B, C)
670 # e.g. A // [B, C]
671 # then de-embed like B.inv * A * C.inv
672 b = other_tpl[0]
673 c = other_tpl[1]
674 result = self.copy()
675 result.s = (b.inv ** self ** c.inv).s
676 # flip(de_embed(flip(de_embed(c.s, self.s)), b.s))
677 return result
678
679 def __mul__(self, other:Network) -> Network:
680 """
681 Element-wise complex multiplication of s-matrix.
682
683 Returns
684 -------
685 ntw : :class:`Network`
686 """
687 check_frequency_exist(self)
688
689 result = self.copy()
690
691 if isinstance(other, Network):
692 self.__compatable_for_scalar_operation_test(other)
693 result.s = self.s * other.s
694 else:
695 # other may be an array or a number
696 result.s = self.s * np.asarray(other).reshape(-1, self.nports, self.nports)
697
698 return result
699
700 def __rmul__(self, other: Network) -> Network:
701 """
702 Element-wise complex multiplication of s-matrix.
703
704 Returns
705 -------
706 ntw : :class:`Network`
707 """
708
709 result = self.copy()
710
711 if isinstance(other, Network):
712 self.__compatable_for_scalar_operation_test(other)
713 result.s = self.s * other.s
714 else:
715 # other may be an array or a number
716 result.s = self.s * np.asarray(other).reshape(-1, self.nports, self.nports)
717
718 return result
719
720 def __add__(self, other:Network) -> Network:
721 """
722 Element-wise complex addition of s-matrix.
723
724 Returns
725 -------
726 ntw : :class:`Network`
727 """
728 result = self.copy()
729
730 if isinstance(other, Network):
731 self.__compatable_for_scalar_operation_test(other)
732 result.s = self.s + other.s
733 else:
734 # other may be an array or a number
735 result.s = self.s + np.asarray(other).reshape(-1, self.nports, self.nports)
736
737 return result
738
739 def __radd__(self, other:Network) -> Network:
740 """
741 Element-wise complex addition of s-matrix.
742
743 Returns
744 -------
745 ntw : :class:`Network`
746 """
747 result = self.copy()
748
749 if isinstance(other, Network):
750 self.__compatable_for_scalar_operation_test(other)
751 result.s = self.s + other.s
752 else:
753 # other may be an array or a number
754 result.s = self.s + np.asarray(other).reshape(-1, self.nports, self.nports)
755
756 return result
757
758 def __sub__(self, other:Network) -> Network:
759 """
760 Element-wise complex subtraction of s-matrix.
761 """
762 result = self.copy()
763
764 if isinstance(other, Network):
765 self.__compatable_for_scalar_operation_test(other)
766 result.s = self.s - other.s
767 else:
768 # other may be an array or a number
769 result.s = self.s - np.asarray(other).reshape(-1, self.nports, self.nports)
770
771 return result
772
773 def __rsub__(self, other:Network) -> Network:
774 """
775 Element-wise complex subtraction of s-matrix.
776
777 Returns
778 -------
779 ntw : :class:`Network`
780 """
781 result = self.copy()
782
783 if isinstance(other, Network):
784 self.__compatable_for_scalar_operation_test(other)
785 result.s = other.s - self.s
786 else:
787 # other may be an array or a number
788 result.s = np.asarray(other).reshape(-1, self.nports, self.nports) - self.s
789
790 return result
791
792 def __truediv__(self, other: Network) -> Network:
793 return self.__div__(other)
794
795 def __div__(self, other: Network) -> Network:
796 """
797 Element-wise complex division of s-matrix.
798
799 Returns
800 -------
801 ntw : :class:`Network`
802 """
803 result = self.copy()
804
805 if isinstance(other, Network):
806 self.__compatable_for_scalar_operation_test(other)
807 result.s = self.s / other.s
808 else:
809 # other may be an array or a number
810 result.s = self.s / np.asarray(other).reshape(-1, self.nports, self.nports)
811
812 return result
813
814 def __eq__(self, other: object) -> bool:
815 if not isinstance(other, self.__class__):
816 return False
817 if len(self.f) != len(other.f):
818 return False
819 for prop in ['f','s','z0']:
820 if not np.all(np.abs(getattr(self,prop)-getattr(other,prop))< ZERO):
821 return False
822 # if z0 is imaginary s_def is compared. If real of z0 is equal but s_def differs, networks are still equal
823 if ((np.imag(self.z0) != 0).all()) or ((np.imag(other.z0) != 0).all()):
824 if self.s_def == other.s_def:
825 return True
826 else:
827 return np.allclose(self.z0.real, other.z0.real, atol = ZERO)
828 else:
829 return True
830
831 def __ne__(self, other:object) -> bool:
832 return (not self.__eq__(other))
833
834 def __getitem__(self, key: str | int | slice | Sized) -> Network:
835 """
836 Slice a Network object based on an index, or human readable string.
837
838 Parameters
839 ----------
840 key : str, or slice
841 if slice; like [2-10] then it is interpreted as the index of
842 the frequency.
843 if str, then should be like '50.1-75.5ghz', or just '50'.
844 If the frequency unit is omitted then self.frequency.unit is
845 used. This will also accept a 2 or 3 dimensional index of the
846 forms:
847 port1, port2
848 key, port1, port2
849 where port1 and port2 are allowed to be string port names if
850 the network has them defined (Network.port_names)
851 If port1 and port2 are integers, will return the single-port
852 network based on matrix notation (indices starts at 1 not 0)
853
854 Returns
855 -------
856 ntwk : skrf.Network
857 interpolated in frequency if single dimension provided
858 OR
859 1-port network if multi-dimensional index provided
860
861 Examples
862 --------
863 >>> from skrf.data import ring_slot
864 >>> a = ring_slot['80-90ghz']
865 >>> a.plot_s_db()
866
867 Multidimensional indexing:
868 >>> import skrf as rf
869 >>> b = rf.Network("sometouchstonefile.s2p")
870 >>> c = b['80mhz', 'first_port_name', 'second_port_name']
871 >>> d = b['first_port_name', 'second_port_name']
872
873 Equivalently:
874 >>> d = b[1,2]
875
876 Equivalent to:
877 >>> d = b.s12
878 """
879
880 # If user passes a multidimensional index, try to return that 1 port subnetwork
881 if isinstance(key, tuple):
882 if len(key) == 3:
883 slice_like, p1_name, p2_name = key
884 return self[slice_like][p1_name, p2_name]
885 elif len(key) == 2:
886 p1_name, p2_name = key
887 if isinstance(p1_name, int) and isinstance(p2_name, int): # allow integer indexing if desired
888 if p1_name <= 0 or p2_name <= 0 or p1_name > self.nports or p2_name > self.nports:
889 raise ValueError("Port index out of bounds")
890 p1_index = p1_name - 1
891 p2_index = p2_name - 1
892 else:
893 if self.port_names is None:
894 raise ValueError("Can't index without named ports")
895 try:
896 p1_index = self.port_names.index(p1_name)
897 except ValueError as err:
898 raise KeyError(f"Unknown port {p1_name}") from err
899 try:
900 p2_index = self.port_names.index(p2_name)
901 except ValueError as err:
902 raise KeyError(f"Unknown port {p2_name}") from err
903 ntwk = self.copy()
904 ntwk.s = self.s[:, p1_index, p2_index]
905 ntwk.z0 = self.z0[:, p1_index]
906 ntwk.name = f"{self.name}({p1_name}, {p2_name})"
907 ntwk.port_names = None
908 return ntwk
909 else:
910 raise ValueError(f"Don't understand index: {key}")
911 if isinstance(key, str):
912 sliced_frequency = self.frequency[key]
913 return self.interpolate(sliced_frequency)
914 if isinstance(key, Frequency):
915 return self.interpolate(key)
916 # The following avoids interpolation when the slice is done directly with indices
917 ntwk = self.copy_subset(key)
918 return ntwk
919
920 def __str__(self) -> str:
921 """
922 """
923 f = self.frequency
924 if self.name is None:
925 name = ''
926 else:
927 name = self.name
928
929 _z0 = self.z0
930
931 if _z0.ndim < 2:
932 z0 = _z0
933 else:
934 if _z0.size > 0:
935 z0 = _z0[0, :]
936 else:
937 # empty frequency range
938 z0 = '[]'
939
940 output = '%i-Port Network: \'%s\', %s, z0=%s' % (self.number_of_ports, name, str(f), str(z0))
941
942 return output
943
944 def __repr__(self) -> str:
945 return self.__str__()
946
947 def __len__(self) -> int:
948 """
949 length of frequency axis
950 """
951 return len(self.s)
952
953 # INTERNAL CODE GENERATION METHODS
954 def __compatable_for_scalar_operation_test(self, other:Network) -> None:
955 """
956 Test to make sure other network's s-matrix is of same shape.
957 """
958 if other.frequency != self.frequency:
959 raise IndexError('Networks must have same frequency. See `Network.interpolate`')
960
961 if other.s.shape != self.s.shape:
962 raise IndexError('Networks must have same number of ports.')
963
964 def __getattr__(self, name: str) -> Network:
965 m = re.match(r"s(\d+)_(\d+)", name)
966 if not m:
967 m = re.match(r"s(\d)(\d)", name)
968
969 if m:
970 t0 = int(m.group(1)) - 1
971 t1 = int(m.group(2)) - 1
972 ntwk = self.copy()
973 ntwk.s = self.s[:, t0, t1]
974 ntwk.z0 = self.z0[:, t0]
975 return ntwk
976 raise AttributeError(f'object does not have attribute {name}')
977
978 def __dir__(self):
979 ret = super().__dir__()
980
981 s_properties = [f"s{t1+1}_{t2+1}" for t1 in range(self.nports) for t2 in range(self.nports)]
982 s_properties += [f"s{t1+1}{t2+1}" for t1 in range(min(self.nports, 10)) for t2 in range(min(self.nports, 10))]
983
984 return ret + s_properties
985
986 def attribute(self, prop_name: PrimaryPropertiesT, conversion: ComponentFuncT) -> np.ndarray:
987 prop = getattr(self, prop_name)
988 return self.COMPONENT_FUNC_DICT[conversion](prop)
989
990 # PRIMARY PROPERTIES
991 @property
992 def s(self) -> np.ndarray:
993 """
994 Scattering parameter matrix.
995
996 The s-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
997 `fxnxn`, where `f` is frequency axis and `n` is number of ports.
998 Note that indexing starts at 0, so s11 can be accessed by
999 taking the slice s[:,0,0].
1000
1001
1002 Returns
1003 -------
1004 s : complex :class:`numpy.ndarray` of shape `fxnxn`
1005 The scattering parameter matrix.
1006
1007 See Also
1008 --------
1009 s
1010 y
1011 z
1012 t
1013 a
1014
1015 References
1016 ----------
1017 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters
1018 """
1019 return self._s
1020
1021 @s.setter
1022 def s(self, s: np.ndarray) -> None:
1023 """
1024 Scattering parameter matrix.
1025
1026 Parameters
1027 ----------
1028 s : :class:`numpy.ndarray`
1029 The input s-matrix should be of shape `fxnxn`,
1030 where f is frequency axis and n is number of ports.
1031 Note that to set this requires that the values are
1032 given in complex format. DB and MA aren't automatically translated
1033
1034 """
1035 self._s = fix_param_shape(s)
1036
1037 if self.z0.ndim == 0:
1038 self.z0 = self.z0
1039
1040 if len(self.port_modes) != self.nports:
1041 self.port_modes = np.array(["S"] * self.nports)
1042
1043 @property
1044 def s_traveling(self) -> np.ndarray:
1045 """
1046 Scattering parameter matrix with s_def = 'traveling'.
1047
1048 Returns
1049 -------
1050 s : complex :class:`numpy.ndarray` of shape `fxnxn`
1051 The scattering parameter [#]_ matrix.
1052
1053 See Also
1054 --------
1055 s
1056 s_power
1057 s_pseudo
1058 s_traveling
1059
1060 References
1061 ----------
1062 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters
1063 """
1064 return s2s(self._s, self.z0, 'traveling', self.s_def)
1065
1066 @s_traveling.setter
1067 def s_traveling(self, s) -> np.ndarray:
1068 self.s = s2s(s, self.z0, self.s_def, 'traveling')
1069
1070 @property
1071 def s_power(self) -> np.ndarray:
1072 """
1073 Scattering parameter matrix with s_def = 'power'.
1074
1075 Returns
1076 -------
1077 s : complex :class:`numpy.ndarray` of shape `fxnxn`
1078 The scattering parameter [#]_ matrix.
1079
1080 See Also
1081 --------
1082 s
1083 s_power
1084 s_pseudo
1085 s_traveling
1086
1087 References
1088 ----------
1089 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters
1090 """
1091 return s2s(self._s, self.z0, 'power', self.s_def)
1092
1093 @s_power.setter
1094 def s_power(self, s) -> np.ndarray:
1095 self.s = s2s(s, self.z0, self.s_def, 'power')
1096
1097 @property
1098 def s_pseudo(self) -> np.ndarray:
1099 """
1100 Scattering parameter matrix with s_def = 'pseudo'.
1101
1102 Returns
1103 -------
1104 s : complex :class:`numpy.ndarray` of shape `fxnxn`
1105 The scattering parameter [#]_ matrix.
1106
1107 See Also
1108 --------
1109 s
1110 s_power
1111 s_pseudo
1112 s_traveling
1113
1114 References
1115 ----------
1116 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters
1117 """
1118 return s2s(self._s, self.z0, 'pseudo', self.s_def)
1119
1120 @s_pseudo.setter
1121 def s_pseudo(self, s) -> np.ndarray:
1122 self.s = s2s(s, self.z0, self.s_def, 'pseudo')
1123
1124 @property
1125 def g(self) -> np.ndarray:
1126 """
1127 Inverse hybrid parameter matrix.
1128
1129 The g-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
1130 `fx2x2`, where `f` is frequency axis.
1131 Note that indexing starts at 0, so g11 can be accessed by
1132 taking the slice `g[:,0,0]`.
1133
1134
1135 Returns
1136 -------
1137 g : complex :class:`numpy.ndarray` of shape `fx2x2`
1138 the inverse hybrid parameter matrix.
1139
1140 See Also
1141 --------
1142 s
1143 y
1144 z
1145 t
1146 a
1147 h
1148
1149 References
1150 ----------
1151 .. [#] https://en.wikipedia.org/wiki/Two-port_network#Inverse_hybrid_parameters_(g-parameters)
1152 """
1153 return s2g(self.s, self.z0)
1154
1155 @g.setter
1156 def g(self, value: np.ndarray) -> None:
1157 self._s = g2s(fix_param_shape(value), self.z0)
1158
1159 @property
1160 def h(self) -> np.ndarray:
1161 """
1162 Hybrid parameter matrix.
1163
1164 The h-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
1165 `fx2x2`, where `f` is frequency axis.
1166 Note that indexing starts at 0, so h11 can be accessed by
1167 taking the slice `h[:,0,0]`.
1168
1169
1170 Returns
1171 -------
1172 h : complex :class:`numpy.ndarray` of shape `fx2x2`
1173 the hybrid parameter matrix.
1174
1175 See Also
1176 --------
1177 s
1178 y
1179 z
1180 t
1181 a
1182 h
1183
1184 References
1185 ----------
1186 .. [#] http://en.wikipedia.org/wiki/Two-port_network#Hybrid_parameters_(h-parameters)
1187 """
1188 return s2h(self.s, self.z0)
1189
1190 @h.setter
1191 def h(self, value: np.ndarray) -> None:
1192 self._s = h2s(fix_param_shape(value), self.z0)
1193
1194 @property
1195 def y(self) -> np.ndarray:
1196 """
1197 Admittance parameter matrix.
1198
1199 The y-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
1200 `fxnxn`, where `f` is frequency axis and `n` is number of ports.
1201 Note that indexing starts at 0, so y11 can be accessed by
1202 taking the slice `y[:,0,0]`.
1203
1204
1205 Returns
1206 -------
1207 y : complex :class:`numpy.ndarray` of shape `fxnxn`
1208 the admittance parameter matrix.
1209
1210 See Also
1211 --------
1212 s
1213 y
1214 z
1215 t
1216 a
1217
1218 References
1219 ----------
1220 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
1221 """
1222 return s2y(self._s, self.z0, s_def=self.s_def)
1223
1224 @y.setter
1225 def y(self, value: np.ndarray) -> None:
1226 self._s = y2s(fix_param_shape(value), self.z0, s_def=self.s_def)
1227
1228 @property
1229 def z(self) -> np.ndarray:
1230 """
1231 Impedance parameter matrix.
1232
1233 The z-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
1234 `fxnxn`, where `f` is frequency axis and `n` is number of ports.
1235 Note that indexing starts at 0, so z11 can be accessed by
1236 taking the slice `z[:,0,0]`.
1237
1238
1239 Returns
1240 -------
1241 z : complex :class:`numpy.ndarray` of shape `fxnxn`
1242 the Impedance parameter matrix.
1243
1244 See Also
1245 --------
1246 s
1247 y
1248 z
1249 t
1250 a
1251
1252 References
1253 ----------
1254 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
1255 """
1256 return s2z(self._s, self.z0, s_def=self.s_def)
1257
1258 @z.setter
1259 def z(self, value: np.ndarray) -> None:
1260 self._s = z2s(fix_param_shape(value), self.z0, s_def=self.s_def)
1261
1262 @property
1263 def t(self) -> np.ndarray:
1264 """
1265 Scattering transfer parameter matrix.
1266
1267 The t-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray`
1268 which has shape `fx2x2`, where `f` is frequency axis.
1269 Note that indexing starts at 0, so t11 can be accessed by
1270 taking the slice `t[:,0,0]`.
1271
1272 The t-matrix, also known as the wave cascading matrix, is
1273 only defined for a 2-port Network.
1274
1275 Returns
1276 -------
1277 t : complex np.ndarray of shape `fx2x2`
1278 t-parameters, aka scattering transfer parameters
1279
1280
1281 See Also
1282 --------
1283 s
1284 y
1285 z
1286 t
1287 a
1288
1289 References
1290 -----------
1291 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters#Scattering_transfer_parameters
1292 """
1293 return s2t(self.s)
1294
1295 @t.setter
1296 def t(self, value: np.ndarray) -> None:
1297 self._s = t2s(fix_param_shape(value))
1298
1299 @property
1300 def s_invert(self) -> np.ndarray:
1301 """
1302 Inverted scattering parameter matrix.
1303
1304 Inverted scattering parameters are simply inverted s-parameters,
1305 defined as a = 1/s. Useful in analysis of active networks.
1306 The a-matrix is a 3-dimensional :class:`numpy.ndarray` which has shape
1307 `fxnxn`, where `f` is frequency axis and `n` is number of ports.
1308 Note that indexing starts at 0, so a11 can be accessed by
1309 taking the slice a[:,0,0].
1310
1311
1312 Returns
1313 -------
1314 s_inv : complex :class:`numpy.ndarray` of shape `fxnxn`
1315 the inverted scattering parameter matrix.
1316
1317 See Also
1318 --------
1319 s
1320 y
1321 z
1322 t
1323 a
1324 """
1325 return 1 / self.s
1326
1327 @s_invert.setter
1328 def s_invert(self, value: np.ndarray) -> NoReturn:
1329 raise NotImplementedError
1330
1331 @property
1332 def a(self) -> np.ndarray:
1333 """
1334 abcd parameter matrix. Used to cascade two-ports.
1335
1336 The abcd-matrix [#]_ is a 3-dimensional :class:`numpy.ndarray` which has shape
1337 `fxnxn`, where `f` is frequency axis and `n` is number of ports.
1338 Note that indexing starts at 0, so abcd11 can be accessed by
1339 taking the slice `abcd[:,0,0]`.
1340
1341
1342 Returns
1343 -------
1344 abcd : complex :class:`numpy.ndarray` of shape `fxnxn`
1345 the Impedance parameter matrix.
1346
1347 See Also
1348 --------
1349 s
1350 y
1351 z
1352 t
1353 a
1354 abcd
1355
1356 References
1357 ----------
1358 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
1359 """
1360 return s2a(self.s, self.z0)
1361
1362 @a.setter
1363 def a(self, value: np.ndarray) -> None:
1364 self._s = a2s(fix_param_shape(value), self.z0)
1365
1366 @property
1367 def z0(self) -> np.ndarray:
1368 """
1369 Characteristic impedance[s] of the network ports.
1370
1371 This property stores the characteristic impedance of each port
1372 of the network. Because it is possible that each port has
1373 a different characteristic impedance each varying with
1374 frequency, `z0` is stored internally as a `fxn` array.
1375
1376 However because `z0` is frequently simple (like 50ohm), it can
1377 be set with just number as well.
1378
1379 Returns
1380 -------
1381 z0 : :class:`numpy.ndarray` of shape fxn
1382 characteristic impedance for network
1383
1384 """
1385 return self._z0
1386
1387 @z0.setter
1388 def z0(self, z0: NumberLike) -> None:
1389 # cast any array like type (tuple, list) to a np.array
1390 z0 = np.array(z0, dtype=complex)
1391
1392 # if _z0 is a vector or matrix, we check if _s is already assigned.
1393 # If not, we cannot proof the correct dimensions and silently accept
1394 # any vector or fxn array
1395 if not hasattr(self, '_s'):
1396 self._z0 = z0
1397 return
1398
1399 # if _z0 is a scalar, we broadcast to the correct shape.
1400 #
1401 # if _z0 is a vector, we check if the dimension matches with either
1402 # nports or frequency.npoints. If yes, we accept the value.
1403 # Note that there can be an ambiguity in theory, if nports == npoints
1404 #
1405 # if _z0 is a matrix, we check if the shape matches with _s
1406 # In any other case raise an Exception
1407 self._z0 = np.empty(self.s.shape[:2], dtype=complex)
1408 if z0.ndim == 0:
1409 self._z0[:] = z0
1410 elif z0.ndim == 1 and z0.shape[0] == self.s.shape[0]:
1411 self._z0[:] = z0[:, None]
1412 elif z0.ndim == 1 and z0.shape[0] == self.s.shape[1]:
1413 self._z0[:] = z0[None, :]
1414 elif z0.shape == self.s.shape[:2]:
1415 self._z0 = z0
1416 else:
1417 raise AttributeError(f'Unable to broadcast z0 shape {z0.shape} to s shape {self.s.shape}.')
1418
1419 @property
1420 def frequency(self) -> Frequency:
1421 """
1422 Frequency information for the network.
1423
1424 This property is a :class:`~skrf.frequency.Frequency` object.
1425 It holds the frequency vector, as well frequency unit, and
1426 provides other properties related to frequency information, such
1427 as start, stop, etc.
1428
1429 Returns
1430 -------
1431 frequency : :class:`~skrf.frequency.Frequency` object
1432 frequency information for the network.
1433
1434
1435 See Also
1436 --------
1437 f : property holding frequency vector in Hz
1438 change_frequency : updates frequency property, and
1439 interpolates s-parameters if needed
1440 interpolate : interpolate function based on new frequency
1441 info
1442 """
1443 try:
1444 return self._frequency
1445 except (AttributeError):
1446 self._frequency = Frequency(0, 0, 0, unit='Hz')
1447 return self._frequency
1448
1449 @frequency.setter
1450 def frequency(self, new_frequency: Frequency | int | Sequence[float] | np.ndarray) -> None:
1451 """
1452 Take a Frequency object, see frequency.py.
1453 """
1454 if isinstance(new_frequency, Frequency):
1455 self._frequency = new_frequency.copy()
1456 else:
1457 try:
1458 self._frequency = Frequency.from_f(new_frequency, unit=self.frequency.unit)
1459 except TypeError as err:
1460 raise TypeError('Could not convert argument to a frequency vector') from err
1461
1462 @property
1463 def inv(self) -> Network:
1464 """
1465 A :class:`Network` object with 'inverse' s-parameters.
1466
1467 This is used for de-embedding.
1468 It is defined such that the inverse of the s-matrix cascaded with itself
1469 is a unity scattering transfer parameter (T) matrix.
1470
1471 Returns
1472 -------
1473 inv : a :class:`Network` object
1474 a :class:`Network` object with 'inverse' s-parameters.
1475
1476 See Also
1477 --------
1478 inv : function which implements the inverse s-matrix
1479 """
1480 if self.number_of_ports < 2:
1481 raise (TypeError('One-Port Networks don\'t have inverses'))
1482 out = self.copy()
1483 out.s = inv(self.s)
1484 # flip the port impedances, nports is even guaranteed by inv() method
1485 port_pairs: int = self.nports // 2
1486 out.z0[:, :port_pairs] = self.z0[:, port_pairs:]
1487 out.z0[:, port_pairs:] = self.z0[:, :port_pairs]
1488 out.deembed = True
1489 return out
1490
1491 @property
1492 def f(self) -> np.ndarray:
1493 """
1494 The frequency vector for the network, in Hz.
1495
1496 Returns
1497 -------
1498 f : :class:`numpy.ndarray`
1499 frequency vector in Hz
1500
1501 See Also
1502 --------
1503 frequency : frequency property that holds all frequency
1504 information
1505 """
1506 return self.frequency.f
1507
1508 @f.setter
1509 def f(self, f: NumberLike | Frequency) -> None:
1510 warnings.warn('frequency.f parameter will be immutable in the next release.',
1511 DeprecationWarning, stacklevel=2)
1512
1513 if isinstance(f, Frequency):
1514 self.frequency = f
1515 else:
1516 tmpUnit = self.frequency.unit
1517 self.frequency = Frequency.from_f(f, unit=tmpUnit)
1518
1519 @property
1520 def noisy(self) -> bool:
1521 """
1522 Whether this network has noise.
1523 """
1524 return self.noise is not None and self.noise_freq is not None
1525
1526 @property
1527 def n(self) -> np.ndarray:
1528 """
1529 The ABCD form of the noise correlation matrix for the network.
1530 """
1531 if not self.noisy:
1532 raise ValueError('network does not have noise')
1533
1534 if self.noise_freq.f.size > 1:
1535 noise_real = interp1d(
1536 self.noise_freq.f,
1537 self.noise.real,
1538 axis=0,
1539 kind=self.noise_interp_kind,
1540 bounds_error=False,
1541 fill_value=complex(self.noise_fill_value).real
1542 )
1543 noise_imag = interp1d(
1544 self.noise_freq.f,
1545 self.noise.imag,
1546 axis=0,
1547 kind=self.noise_interp_kind,
1548 bounds_error=False,
1549 fill_value=complex(self.noise_fill_value).imag
1550 )
1551 return noise_real(self.frequency.f) + 1.0j * noise_imag(self.frequency.f)
1552 else:
1553 noise_real = self.noise.real
1554 noise_imag = self.noise.imag
1555 return noise_real + 1.0j * noise_imag
1556
1557 @property
1558 def f_noise(self) -> Frequency:
1559 """
1560 The frequency vector for the noise of the network, in Hz.
1561 """
1562 if not self.noisy:
1563 raise ValueError('network does not have noise')
1564 return self.noise_freq
1565
1566 @property
1567 def y_opt(self) -> np.ndarray:
1568 """
1569 The optimum source admittance to minimize noise.
1570 """
1571 noise = self.n
1572 return (np.sqrt(noise[:,1,1]/noise[:,0,0] - np.square(np.imag(noise[:,0,1]/noise[:,0,0])))
1573 + 1.j*np.imag(noise[:,0,1]/noise[:,0,0]))
1574
1575 @property
1576 def z_opt(self) -> np.ndarray:
1577 """
1578 The optimum source impedance to minimize noise.
1579 """
1580 return 1./self.y_opt
1581
1582 @property
1583 def g_opt(self) -> np.ndarray:
1584 """
1585 The optimum source reflection coefficient to minimize noise.
1586 """
1587 return z2s(self.z_opt.reshape((self.f.shape[0], 1, 1)), self.z0[:,0])[:,0,0]
1588
1589 @property
1590 def nfmin(self) -> np.ndarray:
1591 """
1592 The minimum noise figure for the network.
1593 """
1594 noise = self.n
1595 return np.real(1. + (noise[:,0,1] + noise[:,0,0] * np.conj(self.y_opt))/(2*K_BOLTZMANN*T0))
1596
1597 @property
1598 def nfmin_db(self) -> np.ndarray:
1599 """
1600 The minimum noise figure for the network in dB.
1601 """
1602 return mf.complex_2_db10(self.nfmin)
1603
1604 def nf(self, z: NumberLike) -> np.ndarray:
1605 """
1606 The noise figure for the network if the source impedance is z.
1607 """
1608 y_opt = self.y_opt
1609 fmin = self.nfmin
1610 rn = self.rn
1611
1612 ys = 1./z
1613 gs = np.real(ys)
1614 return fmin + rn/gs * np.square(np.absolute(ys - y_opt))
1615
1616 def nfdb_gs(self, gs: NumberLike) -> np.ndarray:
1617 """
1618 Return dB(NF) foreach gamma_source x noise_frequency.
1619 """
1620 g = self.copy().s11
1621 nfreq = self.noise_freq.npoints
1622
1623 if isinstance(gs, int | float | complex):
1624 g.s[:,0,0] = gs
1625 nfdb = 10.*np.log10(self.nf( g.z[:,0,0]))
1626 elif isinstance(gs, np.ndarray) :
1627 npt = gs.shape[0]
1628 z = self.z0[0,0] * (1+gs)/(1-gs)
1629 zf = np.broadcast_to(z[:,None], tuple((npt, nfreq)))
1630 nfdb = 10.*np.log10(self.nf( zf))
1631 else :
1632 g.s[:,0,0] = -1
1633 nfdb = 10.*np.log10(self.nf( g.z[:,0,0]))
1634 return nfdb
1635
1636 @property
1637 def rn(self) -> np.ndarray:
1638 """
1639 The equivalent noise resistance for the network.
1640 """
1641 return np.real(self.n[:,0,0]/(4.*K_BOLTZMANN*T0))
1642
1643 # SECONDARY PROPERTIES
1644 @property
1645 def number_of_ports(self) -> int:
1646 """
1647 The number of ports the network has.
1648
1649 Returns
1650 -------
1651 number_of_ports : number
1652 the number of ports the network has.
1653
1654 """
1655 try:
1656 return self.s.shape[1]
1657 except (AttributeError):
1658 return 0
1659
1660 @property
1661 def nports(self) -> int:
1662 """
1663 The number of ports the network has.
1664
1665 Returns
1666 -------
1667 number_of_ports : number
1668 the number of ports the network has.
1669
1670 """
1671 return self.number_of_ports
1672
1673 @property
1674 def port_modes(self) -> np.ndarray:
1675 """
1676 Array of size nports with the mode of each port.
1677
1678 This information is used to store mixed-modes networks in touchstone
1679 V2 format or to plot trace name with subscript like 'Sdd11'.
1680
1681 * 'C': common
1682 * 'D': differential
1683 * 'S': single-ended
1684
1685 Returns
1686 -------
1687 port_modes : :class:`numpy.ndarray`
1688 port modes
1689
1690 """
1691 return self._port_modes
1692
1693 @port_modes.setter
1694 def port_modes(self, port_modes: np.ndarray) -> None:
1695 self._port_modes = port_modes
1696
1697 @property
1698 def port_tuples(self) -> list[tuple[int, int]]:
1699 """
1700 Returns a list of tuples, for each port index pair.
1701
1702 A convenience function for the common task for iterating over
1703 all s-parameters index pairs.
1704
1705 This just calls::
1706
1707 [(y,x) for x in range(self.nports) for y in range(self.nports)]
1708
1709
1710 Returns
1711 -------
1712 ports_ind : list of tuples
1713 list of all port index tuples.
1714
1715 Examples
1716 --------
1717 >>> ntwk = skrf.data.ring_slot
1718 >>> for (idx_i, idx_j) in ntwk.port_tuples: print(idx_i, idx_j)
1719
1720 """
1721 return [(y, x) for x in range(self.nports) for y in range(self.nports)]
1722
1723 @property
1724 def passivity(self) -> ndarray:
1725 r"""
1726 Passivity metric for a multi-port network.
1727
1728 This returns a matrix who's diagonals are equal to the total
1729 power received at all ports, normalized to the power at a single
1730 excitement port.
1731
1732 Mathematically, this is a test for unitary-ness of the
1733 s-parameter matrix [#]_.
1734
1735 For two port this is
1736
1737 .. math::
1738
1739 ( |S_{11}|^2 + |S_{21}|^2 \, , \, |S_{22}|^2+|S_{12}|^2)
1740
1741 in general it is
1742
1743 .. math::
1744
1745 S^H \cdot S
1746
1747 where :math:`H` is conjugate transpose of S, and :math:`\cdot`
1748 is dot product.
1749
1750 Returns
1751 -------
1752 passivity : :class:`numpy.ndarray` of shape fxnxn
1753
1754 References
1755 ----------
1756 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters#Lossless_networks
1757 """
1758 return passivity(self.s)
1759
1760 @property
1761 def reciprocity(self) -> np.ndarray:
1762 """
1763 Reciprocity metric for a multi-port network.
1764
1765 This returns the difference between the s-parameter matrix
1766 and its transpose.
1767
1768 For two port this is
1769
1770 .. math::
1771
1772 S - S^T
1773
1774 where :math:`T` is transpose of S
1775
1776 Returns
1777 -------
1778 reciprocity : :class:`numpy.ndarray` of shape `fxnxn`
1779
1780 """
1781 return reciprocity(self.s)
1782
1783 @property
1784 def reciprocity2(self) -> np.ndarray:
1785 """
1786 Reciprocity metric #2
1787
1788 .. math::
1789
1790 abs(1 - S/S^T )
1791
1792 for the two port case, this evaluates to the distance of the
1793 determinant of the wave-cascading matrix from unity.
1794
1795 Returns
1796 -------
1797 reciprocity : :class:`numpy.ndarray` of shape `fxnxn`
1798
1799 """
1800 return abs(1 - self.s / self.s.swapaxes(1, 2))
1801
1802 @property
1803 def stability(self) -> np.ndarray:
1804 """
1805 Stability factor.
1806
1807 .. math::
1808
1809 K = ( 1 - |S_{11}|^2 - |S_{22}|^2 + |D|^2 ) / (2 * |S_{12}| * |S_{21}|)
1810
1811 with
1812
1813 D = S_{11} S_{22} - S_{12} S_{21}
1814
1815 Returns
1816 -------
1817 K : :class:`numpy.ndarray` of shape `f`
1818
1819 See Also
1820 --------
1821 stability_circle
1822
1823 """
1824 if self.nports != 2:
1825 raise ValueError("Stability factor K is only defined for two ports")
1826
1827 D = self.s[:, 0, 0] * self.s[:, 1, 1] - self.s[:, 0, 1] * self.s[:, 1, 0]
1828 denom = 2 * np.abs(self.s[:, 0, 1]) * np.abs(self.s[:, 1, 0])
1829 num = (1 - np.abs(self.s[:, 0, 0]) ** 2 - np.abs(self.s[:, 1, 1]) ** 2 + np.abs(D) ** 2)
1830 infs = np.full(num.shape, np.inf)
1831 # Handle divide by zero
1832 K = np.divide(num, denom, out=infs, where=denom!=0)
1833 return K
1834
1835 @property
1836 def max_stable_gain(self) -> np.ndarray:
1837 r"""
1838 Maximum stable power gain [1]_ (in linear).
1839
1840 .. math::
1841
1842 G_{ms} = |S_{21}| / |S_{12}|
1843
1844 Returns
1845 -------
1846 gms : :class:`numpy.ndarray` of shape `f`
1847
1848 References
1849 ----------
1850 .. [1] M. S. Gupta, "Power gain in feedback amplifiers, a classic revisited,"
1851 in IEEE Transactions on Microwave Theory and Techniques, vol. 40, no. 5, pp. 864-879, May 1992,
1852 doi: 10.1109/22.137392.
1853
1854 See Also
1855 --------
1856 max_gain : Maximum available and stable power gain
1857 unilateral_gain : Mason's unilateral power gain
1858 stability : Stability factor
1859
1860 """
1861 if self.nports != 2:
1862 raise ValueError("Maximum stable gain is only defined for two ports")
1863
1864 gms = np.abs(self.s[:, 1, 0]) / np.abs(self.s[:, 0, 1])
1865 return gms
1866
1867 @property
1868 def max_gain(self) -> np.ndarray:
1869 r"""
1870 Maximum available power gain for K > 1 and maximum stable power gain for K <= 1 (in linear).
1871
1872 .. math::
1873
1874 G_{max}|_{K>1} = \frac{|S_{21}|}{|S_{12}|} \times \frac{1}{K + \sqrt{K^2 - 1}}
1875
1876 G_{max}|_{K<=1} = \frac{|S_{21}|}{|S_{12}|}
1877
1878 Returns
1879 -------
1880 gmax : :class:`numpy.ndarray` of shape `f`
1881
1882 Note
1883 ----
1884 The maximum available power gain is defined for a unconditionally stable network (K > 1).
1885 For K <= 1, this property returns the maximum stable gain instead.
1886 This behavior is similar to the max_gain() function in Keysight's Advanced Design System
1887 (but differs in decibel or linear) [1]_ [2]_ [3]_.
1888
1889 References
1890 ----------
1891 .. [1] M. S. Gupta, "Power gain in feedback amplifiers, a classic revisited,"
1892 in IEEE Transactions on Microwave Theory and Techniques, vol. 40, no. 5, pp. 864-879, May 1992,
1893 doi: 10.1109/22.137392.
1894 .. [2] https://www.microwaves101.com/encyclopedias/stability-factor
1895 .. [3] https://edadocs.software.keysight.com/pages/viewpage.action?pageId=5920581
1896
1897 See Also
1898 --------
1899 max_stable_gain : Maximum stable power gain
1900 unilateral_gain : Mason's unilateral power gain
1901 stability : Stability factor
1902
1903 """
1904 if self.nports != 2:
1905 raise ValueError("Max gain is only defined for two ports")
1906
1907 K = self.stability
1908 K_clipped = np.clip(K, 1, None)
1909 gmax = self.max_stable_gain / (K_clipped + np.sqrt(np.square(K_clipped) - 1))
1910 return gmax
1911
1912 @property
1913 def unilateral_gain(self) -> np.ndarray:
1914 r"""
1915 Mason's unilateral power gain [1]_ (in linear).
1916
1917 .. math::
1918
1919 U = \frac{| \frac{S_{21}}{S_{12}} - 1| ^ 2}{2K \frac{|S_{21}|}{|S_{12}|} - 2Re(\frac{S_{21}}{S_{12}})}
1920
1921 Returns
1922 -------
1923 U : :class:`numpy.ndarray` of shape `f`
1924
1925 References
1926 ----------
1927 .. [1] M. S. Gupta, "Power gain in feedback amplifiers, a classic revisited,"
1928 in IEEE Transactions on Microwave Theory and Techniques, vol. 40, no. 5, pp. 864-879, May 1992,
1929 doi: 10.1109/22.137392.
1930
1931 See Also
1932 --------
1933 max_stable_gain : Maximum stable power gain
1934 max_gain : Maximum available and stable power gain
1935 stability : Stability factor
1936
1937 """
1938 if self.nports != 2:
1939 raise ValueError("Unilateral gain is only defined for two ports")
1940
1941 K = self.stability
1942 gms = self.max_stable_gain
1943 U = (np.abs((self.s[:, 1, 0] / self.s[:, 0, 1]) - 1) ** 2
1944 / (2 * K * gms - 2 * np.real(self.s[:, 1, 0] / self.s[:, 0, 1])))
1945 return U
1946
1947 @property
1948 def group_delay(self) -> np.ndarray:
1949 """
1950 Group delay.
1951
1952 Usually used as a measure of dispersion (or distortion).
1953
1954 Defined as the derivative of the unwrapped s-parameter phase
1955 (in rad) with respect to the frequency::
1956
1957 -d(self.s_rad_unwrap)/d(self.frequency.w)
1958
1959 Returns
1960 -------
1961 gd : :class:`numpy.ndarray` of shape `xnxn`
1962
1963 References
1964 ----------
1965 https://en.wikipedia.org/wiki/Group_delay_and_phase_delay
1966 """
1967 gd = self.s * 0 # quick way to make a new array of correct shape
1968
1969 phi = self.s_rad_unwrap
1970 dw = self.frequency.dw
1971
1972 for m, n in self.port_tuples:
1973 dphi = gradient(phi[:, m, n])
1974 gd[:, m, n] = -dphi / dw
1975
1976 return gd
1977
1978 ## NETWORK CLASSIFIERs
1979 def is_reciprocal(self, tol: float = mf.ALMOST_ZERO) -> bool:
1980 """
1981 Test for reciprocity.
1982
1983 Parameters
1984 ----------
1985 tol : float, optional
1986 Numerical tolerance. The default is :data:`skrf.mathFunctions.ALMOST_ZERO`.
1987
1988 Returns
1989 -------
1990 bool : boolean
1991
1992 See Also
1993 --------
1994 reciprocity
1995
1996 """
1997 return np.allclose(reciprocity(self.s), np.zeros_like(self.s), atol=tol)
1998
1999 def is_symmetric(self, n: int = 1, port_order: dict[int, int] = None, tol: float = mf.ALMOST_ZERO) -> bool:
2000 """
2001 Return whether the 2N-port network has n-th order reflection symmetry by checking.
2002 :math:`S_{i,i} == S_{j,j}` for appropriate pair(s) of :math:`i` and :math:`j`.
2003
2004 Parameters
2005 ----------
2006 n : int
2007 Order of line symmetry to test for
2008 port_order : dict[int, int]
2009 Renumbering of zero-indexed ports before testing
2010 tol : float
2011 Tolerance in numeric comparisons. Default is :data:`skrf.mathFunctions.ALMOST_ZERO`.
2012
2013 Returns
2014 -------
2015 bool : boolean
2016
2017 Raises
2018 ------
2019 ValueError
2020 (1) If the network has an odd number of ports
2021 (2) If n is not in the range 1 to N
2022 (3) If n does not evenly divide 2N
2023 (4) If port_order is not a valid reindexing of ports
2024 e.g. specifying x->y but not y->z, specifying x->y twice,
2025 or using an index outside the range 0 to 2N-1
2026
2027 References
2028 ----------
2029
2030 https://en.wikipedia.org/wiki/Two-port_network#Scattering_parameters_(S-parameters)
2031
2032 """
2033
2034 if port_order is None:
2035 port_order = {}
2036 nfreqs, ny, nx = self.s.shape # nfreqs is number of frequencies, and nx, ny both are number of ports (2N)
2037 if nx % 2 != 0 or nx != ny:
2038 raise ValueError('Using is_symmetric() is only valid for a 2N-port network (N=2,4,6,8,...)')
2039 n_ports = nx // 2
2040 if n <= 0 or n > n_ports:
2041 raise ValueError('specified order n = ' + str(n) + ' must be ' +
2042 'between 1 and N = ' + str(n_ports) + ', inclusive')
2043 if nx % n != 0:
2044 raise ValueError('specified order n = ' + str(n) + ' must evenly divide ' +
2045 'N = ' + str(n_ports))
2046
2047 from_ports = list(map(lambda key: int(key), port_order.keys()))
2048 to_ports = list(map(lambda val: int(val), port_order.values()))
2049 test_network = self.copy() # TODO: consider defining renumbered()
2050 if len(from_ports) > 0 and len(to_ports) > 0:
2051 test_network.renumber(from_ports, to_ports)
2052
2053 offs = np.array(range(0, n_ports)) # port index offsets from each mirror line
2054 for k in range(0, n_ports, n_ports // n): # iterate through n mirror lines
2055 mirror = k * np.ones_like(offs)
2056 i = mirror - 1 - offs
2057 j = mirror + offs
2058 if not np.allclose(test_network.s[:, i, i], test_network.s[:, j, j], atol=tol):
2059 return False
2060 return True
2061
2062 def is_passive(self, tol: float = mf.ALMOST_ZERO) -> bool:
2063 """
2064 Test for passivity.
2065
2066 Parameters
2067 ----------
2068 tol : float, optional
2069 Numerical tolerance. The default is :data:`skrf.mathFunctions.ALMOST_ZERO`
2070
2071 Returns
2072 -------
2073 bool : boolean
2074
2075 """
2076 try:
2077 M = np.square(self.passivity)
2078 except ValueError:
2079 return False
2080
2081 I = np.identity(M.shape[-1])
2082 for f_idx in range(len(M)):
2083 D = I - M[f_idx, :, :] # dissipation matrix
2084 if not mf.is_positive_definite(D) \
2085 and not mf.is_positive_semidefinite(mat=D, tol=tol):
2086 return False
2087 return True
2088
2089 def is_lossless(self, tol: float = mf.ALMOST_ZERO) -> bool:
2090 """
2091 Test for losslessness.
2092
2093 [S] is lossless if [S] is unitary, i.e. if :math:`([S][S]^* = [1])`
2094
2095
2096 Parameters
2097 ----------
2098 tol : float, optional
2099 Numerical tolerance. The default is :data:`skrf.mathFunctions.ALMOST_ZERO`
2100
2101 Returns
2102 -------
2103 bool : boolean
2104
2105 See Also
2106 --------
2107 is_passive, is_symmetric, is_reciprocal
2108
2109 References
2110 ----------
2111 https://en.wikipedia.org/wiki/Unitary_matrix
2112 """
2113 for f_idx in range(len(self.s)):
2114 mat = self.s[f_idx, :, :]
2115 if not mf.is_unitary(mat, tol=tol):
2116 return False
2117 return True
2118
2119 ## CLASS METHODS
2120 def copy(self, *, shallow_copy: bool = False) -> Network:
2121 """
2122 Return a copy of this Network.
2123
2124 Needed to allow pass-by-value for a Network instead of
2125 pass-by-reference
2126
2127 Parameters
2128 ----------
2129 shallow_copy : bool, optional
2130 If True, the method creates a new Network object with empty s-parameters that share the same shape
2131 as the original Network, but without copying the actual s-parameters data. This is useful when you
2132 plan to immediately modify the s-parameters after creating the Network, as a deep copy would be
2133 unnecessary and costly. Using `shallow_copy` improves performance by leveraging lazy initialization
2134 through `numpy's np.empty()`, which allocates virtual memory without immediate physical memory
2135 allocation, deferring actual memory initialization until first access. This approach can significantly
2136 enhance `copy()` performance when dealing with large `Network` objects, when you are intended for
2137 immediate modification after the Network's creation.
2138
2139 Note
2140 ----
2141 If you require a complete copy of the `Network` instance or need to perform operation on the s-parameters
2142 of the copied Network, it is essential not to use the `shallow_copy` parameter!
2143
2144 Returns
2145 -------
2146 ntwk : :class:`Network`
2147 Copy of the Network
2148
2149 """
2150 ntwk = Network(z0=self.z0, s_def=self.s_def, comments=self.comments)
2151
2152 ntwk._s = (
2153 np.empty(shape=self.s.shape, dtype=self.s.dtype)
2154 if shallow_copy
2155 else self.s.copy()
2156 )
2157 ntwk.frequency._f = self.frequency._f.copy()
2158 ntwk.frequency.unit = self.frequency.unit
2159 ntwk.port_modes = self.port_modes.copy()
2160
2161 if self.params is not None:
2162 ntwk.params = self.params.copy()
2163
2164 ntwk.name = self.name
2165
2166 if self.noise is not None and self.noise_freq is not None:
2167 ntwk.noise = self.noise.copy()
2168 ntwk.noise_freq = self.noise_freq.copy()
2169
2170 # copy special attributes (such as _is_circuit_port) but skip methods
2171 ntwk._ext_attrs = self._ext_attrs.copy()
2172
2173 try:
2174 ntwk.port_names = copy(self.port_names)
2175 except(AttributeError):
2176 ntwk.port_names = None
2177 return ntwk
2178
2179 def copy_from(self, other: Network) -> None:
2180 """
2181 Copy the contents of another Network into self.
2182
2183 Uses copy, so that the data is passed-by-value, not reference
2184
2185 Parameters
2186 ----------
2187 other : Network
2188 the network to copy the contents of
2189
2190 Examples
2191 --------
2192 >>> a = rf.N()
2193 >>> b = rf.N('my_file.s2p')
2194 >>> a.copy_from (b)
2195 """
2196 for attr in ['_s', 'frequency', '_z0', 'name']:
2197 setattr(self, attr, copy(getattr(other, attr)))
2198
2199 def copy_subset(self, key: np.ndarray) -> Network:
2200 """
2201 Return a copy of a frequency subset of this Network.
2202
2203 Needed to allow pass-by-value for a subset Network instead of
2204 pass-by-reference
2205
2206 Parameters
2207 -----------
2208 key : numpy array
2209 the array indices of the frequencies to take
2210
2211 Returns
2212 -------
2213 ntwk : :class:`Network`
2214 Copy of the frequency subset of the Network
2215
2216 """
2217 ntwk = Network(s=self.s[key,:],
2218 frequency=self.frequency[key].copy(),
2219 z0=self.z0[key,:],
2220 )
2221
2222 if isinstance(self.name, str):
2223 ntwk.name = self.name + '_subset'
2224 else:
2225 ntwk.name = self.name
2226
2227 if self.noise is not None and self.noise_freq is not None:
2228 ntwk.noise = np.copy(self.noise[key,:])
2229 ntwk.noise_freq = copy(self.noise_freq[key])
2230
2231 try:
2232 ntwk.port_names = copy(self.port_names)
2233 except(AttributeError):
2234 ntwk.port_names = None
2235 return ntwk
2236
2237 def drop_non_monotonic_increasing(self) -> None:
2238 """
2239 Drop invalid values based on duplicate and non increasing frequency values.
2240
2241 Example
2242 -------
2243
2244 The following example shows how to use the :func:`drop_non_monotonic_increasing`
2245 automatically, if invalid frequency data is detected and an
2246 :class:`~skrf.frequency.InvalidFrequencyWarning` is thrown.
2247
2248
2249 >>> import warnings
2250 >>> import skrf as rf
2251 >>> from skrf.frequency import InvalidFrequencyWarning
2252 >>> with warnings.catch_warnings(record=True) as warns:
2253 >>> net = rf.Network('corrupted_network.s2p')
2254 >>> w = [w for w in warns if issubclass(w.category, InvalidFrequencyWarning)]
2255 >>> if w:
2256 >>> net.drop_non_monotonic_increasing()
2257
2258 """
2259 idx = self.frequency.drop_non_monotonic_increasing()
2260
2261 # z0 getter and setter depend on s.shape matching z0.shape.
2262 # Call z0 getter and setter only when s and z0 shapes match.
2263 z0_new = np.delete(self.z0, idx, axis=0)
2264 self.s = np.delete(self.s, idx, axis=0)
2265 self.z0 = z0_new
2266
2267 if self.noisy:
2268 idx = self.noise_freq.drop_non_monotonic_increasing()
2269 self.noise = np.delete(self.noise, idx, axis=0)
2270
2271
2272 def set_noise_a(self, noise_freq: Frequency = None, nfmin_db: float = 0,
2273 gamma_opt: float = 0, rn: NumberLike = 1 ) -> None:
2274 """
2275 Set the "A" (ie cascade) representation of the correlation matrix, based on the
2276 noise frequency and input parameters.
2277 """
2278 sh_fr = noise_freq.f.shape
2279 nfmin_db = np.broadcast_to(np.atleast_1d(nfmin_db), sh_fr)
2280 gamma_opt = np.broadcast_to(np.atleast_1d(gamma_opt), sh_fr)
2281 rn = np.broadcast_to(np.atleast_1d(rn), sh_fr)
2282
2283
2284 nf_min = np.power(10., nfmin_db/10.)
2285 # TODO maybe interpolate z0 as above
2286 y_opt = 1./(self.z0[0, 0] * (1. + gamma_opt)/(1. - gamma_opt))
2287 noise = 4.*K_BOLTZMANN*T0*np.array(
2288 [[rn, (nf_min-1.)/2. - rn*np.conj(y_opt)],
2289 [(nf_min-1.)/2. - rn*y_opt, np.square(np.absolute(y_opt)) * rn]]
2290 )
2291 self.noise = noise.swapaxes(0, 2).swapaxes(1, 2)
2292 self.noise_freq = noise_freq
2293
2294
2295
2296
2297 # touchstone file IO
2298 def read_touchstone(self, filename: str | Path | TextIO,
2299 encoding: str | None = None) -> None:
2300 """
2301 Load values from a touchstone file.
2302
2303 The work of this function is done through the
2304 :class:`~skrf.io.touchstone` class.
2305
2306 Parameters
2307 ----------
2308 filename : str, Path, or file-object
2309 touchstone file name.
2310 encoding : str, optional
2311 define the file encoding to use. Default value is None,
2312 meaning the encoding is guessed.
2313
2314 Note
2315 ----
2316 Only the scattering parameters format is supported at the moment.
2317
2318
2319 """
2320 from .io import touchstone
2321 touchstoneFile = touchstone.Touchstone(filename, encoding=encoding)
2322
2323 self.comments = touchstoneFile.get_comments()
2324 self.comments_after_option_line = touchstoneFile.comments_after_option_line
2325
2326
2327 self.variables = touchstoneFile.get_comment_variables()
2328
2329 self.port_names = touchstoneFile.port_names
2330
2331 f, self.s = touchstoneFile.get_sparameter_arrays() # note: freq in Hz
2332 self.frequency = Frequency.from_f(f, unit='hz')
2333 self.frequency.unit = touchstoneFile.frequency_unit
2334
2335 self.gamma = touchstoneFile.gamma
2336 self.z0 = touchstoneFile.z0
2337 self.s_def = touchstoneFile.s_def if self.s_def is None else self.s_def
2338 self.port_modes = touchstoneFile.port_modes
2339
2340 if touchstoneFile.noise is not None:
2341 noise_freq = touchstoneFile.noise[:, 0]
2342 nfmin_db = touchstoneFile.noise[:, 1]
2343 gamma_opt_mag = touchstoneFile.noise[:, 2]
2344 gamma_opt_angle = np.deg2rad(touchstoneFile.noise[:, 3])
2345
2346 # TODO maybe properly interpolate z0?
2347 # it probably never actually changes
2348 if touchstoneFile.version == '1.0':
2349 rn = touchstoneFile.noise[:, 4] * self.z0[0, 0]
2350 else:
2351 rn = touchstoneFile.noise[:, 4]
2352
2353 gamma_opt = gamma_opt_mag * np.exp(1j * gamma_opt_angle)
2354
2355 # use the voltage/current correlation matrix; this works nicely with
2356 # cascading networks
2357 self.noise_freq = Frequency.from_f(noise_freq, unit='hz')
2358 self.noise_freq.unit = touchstoneFile.frequency_unit
2359 self.set_noise_a(self.noise_freq, nfmin_db, gamma_opt, rn)
2360
2361 if self.name is None:
2362 try:
2363 self.name = os.path.basename(os.path.splitext(filename)[0])
2364 # this may not work if filename is a file object
2365 except(AttributeError, TypeError):
2366 # in case they pass a file-object instead of file name,
2367 # get the name from the touchstone file
2368 self.name = os.path.basename(os.path.splitext(touchstoneFile.filename)[0])
2369
2370 @classmethod
2371 def zipped_touchstone(cls, filename: str | Path, archive: zipfile.ZipFile) -> Network:
2372 """
2373 Read a Network from a Touchstone file in a ziparchive.
2374
2375 Parameters
2376 ----------
2377 filename : str
2378 the full path filename of the touchstone file
2379 archive : zipfile.ZipFile
2380 the opened zip archive
2381
2382 Returns
2383 -------
2384 ntwk : :class:`Network`
2385 Network from the Touchstone file
2386
2387 """
2388
2389 # Convert a path filename to a string
2390 filename = str(filename.resolve()) if isinstance(filename, Path) else filename
2391
2392 # Touchstone requires file objects to be seekable (for get_gamma_z0_from_fid)
2393 # A ZipExtFile object is not seekable prior to Python 3.7, so use StringIO
2394 # and manually add a name attribute
2395 fileobj = io.StringIO(archive.open(filename).read().decode('UTF-8'))
2396 fileobj.name = filename
2397 ntwk = Network(fileobj)
2398 return ntwk
2399
2400 def write_touchstone(self, filename: str | Path = None, dir: str | Path = None,
2401 write_z0: bool = False, skrf_comment: bool = True,
2402 return_string: bool = False, to_archive: bool = None,
2403 form: SparamFormatT = 'ri', format_spec_A: str = '{}', format_spec_B: str = '{}',
2404 format_spec_freq: str = '{}', r_ref: float = None,
2405 format_spec_nf_freq: str = '{}', format_spec_nf_min: str = '{}',
2406 format_spec_g_opt_mag: str = '{}', format_spec_g_opt_phase: str = '{}',
2407 format_spec_rn: str = '{}', write_noise: bool = True,
2408 parameter: Literal["S", "Y", "Z", "G", "H"] = "S") -> str | None:
2409
2410 """
2411 Write a contents of the :class:`Network` to a touchstone file.
2412
2413 Parameters
2414 ----------
2415 filename : a string or Path, optional
2416 touchstone filename, without extension. if 'None', then
2417 will use the network's :attr:`name`.
2418 dir : string or Path, optional
2419 the directory to save the file in.
2420 write_z0 : boolean
2421 write impedance information into touchstone as comments,
2422 like Ansoft HFSS does
2423 skrf_comment : bool, optional
2424 write `created by skrf <version>` comment
2425 return_string : bool, optional
2426 return the file_string rather than write to a file
2427 to_archive : zipfile.Zipfile
2428 opened ZipFile object to place touchstone file in
2429 form : string
2430 format to write data:
2431 'db': db, deg. 'ma': mag, deg. 'ri': real, imag.
2432 format_spec_A : string, optional
2433 Any valid format specifying string as given by
2434 https://docs.python.org/3/library/string.html#format-string-syntax
2435 This specifies the formatting in the resulting touchstone file for the A part of the S parameter,
2436 (e.g. the dB magnitude for 'db' format, the linear
2437 magnitude for 'ma' format, or the real part for 'ri' format)
2438 format_spec_B : string, optional
2439 Any valid format specifying string as given by
2440 https://docs.python.org/3/library/string.html#format-string-syntax
2441 This specifies the formatting in the resulting touchstone file for the B part of the S parameter,
2442 (e.g. the angle in degrees for 'db' format,
2443 the angle in degrees for 'ma' format, or the imaginary part for 'ri' format)
2444 format_spec_freq : string, optional
2445 Any valid format specifying string as given by
2446 https://docs.python.org/3/library/string.html#format-string-syntax
2447 This specifies the formatting in the resulting touchstone file for the frequency.
2448 r_ref : float
2449 Reference impedance to renormalize the network.
2450 If None network port impedance is used if possible. If None and
2451 network port impedance is complex and not equal at all ports and
2452 frequency points raises ValueError.
2453 format_spec_nf_freq : string, optional
2454 Any valid format specifying string as given by
2455 https://docs.python.org/3/library/string.html#format-string-syntax
2456 This specifies the formatting in the resulting touchstone file for the noise data frequency.
2457 format_spec_nf_min : string, optional
2458 Any valid format specifying string as given by
2459 https://docs.python.org/3/library/string.html#format-string-syntax
2460 This specifies the formatting in the resulting touchstone file for the minimum NF.
2461 format_spec_g_opt_mag : string, optional
2462 Any valid format specifying string as given by
2463 https://docs.python.org/3/library/string.html#format-string-syntax
2464 This specifies the formatting in the resulting touchstone file for the GammaOpt magnitude.
2465 format_spec_g_opt_phase : string, optional
2466 Any valid format specifying string as given by
2467 https://docs.python.org/3/library/string.html#format-string-syntax
2468 This specifies the formatting in the resulting touchstone file for the GammaOpt phase.
2469 format_spec_rn : string, optional
2470 Any valid format specifying string as given by
2471 https://docs.python.org/3/library/string.html#format-string-syntax
2472 This specifies the formatting in the resulting touchstone file for the noise resistance.
2473 write_noise : bool, optional
2474 Write noise parameters.
2475 parameter : string
2476 Specify the network parameter ("S", "Y", "Z", "G", "H") to write, defaults to "S".
2477 "G" and "H" is only available for 2-port Networks.
2478
2479 Note
2480 ----
2481 Format supported at the moment are [Hz/kHz/MHz/GHz] S [DB/MA/RI]
2482 Frequency unit can be changed by setting Network.frequency.unit property
2483
2484
2485 Note
2486 ----
2487 The functionality of this function should take place in the
2488 :class:`~skrf.io.touchstone.Touchstone` class.
2489
2490 """
2491 # according to Touchstone 2.0 spec
2492 # [no tab, max. 4 coeffs per line, etc.]
2493
2494 have_complex_ports = np.any(self.z0.imag != 0)
2495 equal_z0 = np.all(self.z0 == self.z0[0, 0])
2496
2497 ntwk = self.copy()
2498
2499 if r_ref is None and not write_z0:
2500 if not equal_z0:
2501 raise ValueError(
2502 "Network has unequal port impedances but reference impedance for renormalization"
2503 " 'r_ref' is not specified."
2504 )
2505 if have_complex_ports:
2506 raise ValueError(
2507 "Network port impedances are complex but reference impedance for renormalization"
2508 " 'r_ref' is not specified."
2509 )
2510 r_ref = ntwk.z0[0, 0]
2511 elif r_ref is not None:
2512 if not np.isscalar(r_ref):
2513 raise ValueError('r_ref must be scalar')
2514 if r_ref.imag != 0:
2515 raise ValueError('r_ref must be real')
2516 ntwk.renormalize(r_ref)
2517
2518 if filename is None:
2519 if ntwk.name is not None:
2520 filename = ntwk.name
2521 else:
2522 raise ValueError('No filename given. Network must have a name, or you must provide a filename')
2523
2524 # set internal variables according to form
2525 form = form.lower()
2526
2527 parameter = parameter.upper()
2528 if parameter not in ["S", "Y", "Z", "G", "H"] or (parameter in ["G", "H"] and ntwk.nports != 2):
2529 msg = f"Invalid network parameter {parameter}"
2530 raise AttributeError(msg)
2531
2532 pdata = ntwk.s
2533 if parameter != "S":
2534 pdata = globals()[f"s2{parameter.lower()}"](pdata, 1)
2535
2536 if get_extn(filename) is None:
2537 if isinstance(filename, Path):
2538 filename = str(filename.resolve())
2539
2540 filename = f"{filename}.{parameter.lower()}{ntwk.nports}p"
2541
2542 if dir is not None:
2543 filename = os.path.join(dir, filename)
2544
2545 # Create format string for full frequency block
2546 # Build according to touchstone specs:
2547 # - One line for each matrix row with 4 format_spec_A / format_spec_B pairs max.
2548 # - Frequency with format_spec_freq on the first line
2549 # - continuation lines (anything except first) go with indent
2550 # this is not part of the spec, but many tools handle it this way
2551 # -> allows to parse without knowledge of number of ports
2552 # Special case for 2-port networks:
2553 # single line, and S21, S12 in reverse order by transposing matrix
2554 fmt_str = format_spec_freq
2555 for _ in range(ntwk.number_of_ports if ntwk.number_of_ports > 2 else 1):
2556 for n in range(ntwk.number_of_ports if ntwk.number_of_ports != 2 else 4):
2557 if (n > 0 and (n % 4) == 0):
2558 fmt_str += '\n'
2559 fmt_str += f' {format_spec_A} {format_spec_B}'
2560 fmt_str += '\n'
2561 if ntwk.number_of_ports == 2:
2562 # transpose matrix:
2563 pdata = np.transpose(pdata, (0, 2, 1))
2564
2565 # expand complex numbers into real parts according to form
2566 # creating a new array with shape (nfreqs, nports, nports*2)
2567 if form == "ri":
2568 formatDic = {"labelA": "Re", "labelB": "Im", "param": parameter}
2569 data = np.ascontiguousarray(pdata).view(float)
2570 elif form == "db":
2571 formatDic = {"labelA": "dB", "labelB": "ang", "param": parameter}
2572 data = np.empty((pdata.shape[0], pdata.shape[1], pdata.shape[2] * 2), dtype='float64')
2573 data[:, :, 0::2] = mf.complex_2_db(pdata)
2574 data[:, :, 1::2] = mf.complex_2_degree(pdata)
2575 elif form == "ma":
2576 formatDic = {"labelA": "mag", "labelB": "ang", "param": parameter}
2577 data = np.empty((pdata.shape[0], pdata.shape[1], pdata.shape[2] * 2), dtype='float64')
2578 data[:, :, 0::2] = mf.complex_2_magnitude(pdata)
2579 data[:, :, 1::2] = mf.complex_2_degree(pdata)
2580 else:
2581 raise ValueError('`form` must be either `db`,`ma`,`ri`')
2582
2583 # flatten inner two dimensions and combining with frequency column:
2584 # array with one line per frequency point
2585 data = np.column_stack([ntwk.frequency.f_scaled, data.reshape((data.shape[0],-1))])
2586
2587 def get_buffer() -> io.StringIO:
2588 if return_string is True or type(to_archive) is zipfile.ZipFile:
2589 from .io.general import StringBuffer # avoid circular import
2590 buf = StringBuffer()
2591 else:
2592 buf = open(filename, "w")
2593 return buf
2594
2595 with get_buffer() as output:
2596 # Add '!' Touchstone comment delimiters to the start of every line in ntwk.comments
2597 commented_header = ''
2598 try:
2599 if ntwk.comments:
2600 for comment_line in ntwk.comments.split('\n'):
2601 commented_header += f'!{comment_line}\n'
2602 except AttributeError:
2603 pass
2604 if skrf_comment:
2605 commented_header += '! Created with skrf ' + __version__ + ' (http://scikit-rf.org).\n'
2606
2607 output.write(commented_header)
2608
2609 # write header file.
2610 # the '#' line is NOT a comment it is essential and it must be
2611 # exactly this format, to work
2612 # [HZ/KHZ/MHZ/GHZ] [S/Y/Z/G/H] [MA/DB/RI] [R n]
2613 if write_z0:
2614 output.write('! Data is not renormalized\n')
2615 output.write(f'! S-parameter uses the {self.s_def} definition\n')
2616 output.write(f'# {ntwk.frequency.unit} {parameter} {form.upper()} R\n')
2617 else:
2618 # Write "r_ref.real" instead of "r_ref", so we get a real number "a" instead
2619 # of a complex number "(a+0j)", which is unsupported by the standard Touchstone
2620 # format (non-HFSS). We already checked in the beginning that "r_ref" must be
2621 # real in this case (write_z0 == False).
2622 assert r_ref.imag == 0, "Complex reference impedance is encountered when " \
2623 "generating a standard Touchstone (non-HFSS), this " \
2624 "should never happen in scikit-rf."
2625 output.write(f'# {ntwk.frequency.unit} {parameter} {form.upper()} R {r_ref.real} \n')
2626
2627 # write ports
2628 try:
2629 if ntwk.port_names and len(ntwk.port_names) == ntwk.number_of_ports:
2630 ports = ''
2631 for port_idx, port_name in enumerate(ntwk.port_names):
2632 ports += f'! Port[{port_idx+1}] = {port_name}\n'
2633 output.write(ports)
2634 except AttributeError:
2635 pass
2636
2637 if ntwk.number_of_ports == 2:
2638 # 2-port is a special case with
2639 # - single line, and
2640 # - S21,S12 in reverse order: legacy ?
2641
2642 # write comment line for users (optional)
2643 output.write(
2644 ("!freq {labelA}{param}11 {labelB}{param}11 {labelA}{param}21 {labelB}{param}21 "
2645 "{labelA}{param}12 {labelB}{param}12 {labelA}{param}22 {labelB}{param}22\n").format(
2646 **formatDic))
2647 else:
2648 # general n-port
2649 # - matrix is written line by line
2650 # - 4 complex numbers / 8 real numbers max. for a single line
2651 # - continuation lines (anything except first) go with indent
2652 # this is not part of the spec, but many tools handle it this way
2653 # -> allows to parse without knowledge of number of ports
2654
2655 # write comment line for users (optional)
2656 output.write('!freq')
2657 for m in range(1, 1 + ntwk.number_of_ports):
2658 for n in range(1, 1 + ntwk.number_of_ports):
2659 if (n > 0 and (n % 4) == 0):
2660 output.write('\n!')
2661 output.write(" {labelA}{param}{m}{n} {labelB}{param}{m}{n}".format(m=m, n=n, **formatDic))
2662 output.write('\n!')
2663 output.write('\n')
2664
2665 # write out data one frequency at a time
2666 for f in range(len(ntwk.f)):
2667 output.write(fmt_str.format(*data[f]))
2668 if write_z0:
2669 output.write('! Port Impedance')
2670 for n in range(ntwk.number_of_ports):
2671 output.write(f' {ntwk.z0[f, n].real:.14f} {ntwk.z0[f, n].imag:.14f}')
2672 output.write('\n')
2673
2674 if ntwk.number_of_ports == 2:
2675 # write noise data if it exists
2676 if ntwk.noisy and write_noise:
2677 self._write_noisedata(output, format_spec_nf_freq, format_spec_nf_min,
2678 format_spec_g_opt_mag, format_spec_g_opt_phase,
2679 format_spec_rn)
2680
2681 if type(to_archive) is zipfile.ZipFile:
2682 to_archive.writestr(filename, output.getvalue())
2683 elif return_string is True:
2684 return output.getvalue()
2685 return None
2686
2687 def _write_noisedata(self, output, format_spec_nf_freq: str = '{}', format_spec_nf_min: str = '{}',
2688 format_spec_g_opt_mag: str = '{}', format_spec_g_opt_phase: str = '{}',
2689 format_spec_rn: str = '{}'):
2690 ntwk = self.copy()
2691
2692 output.write("! Noise Data\n! freq\tnf_min_db\tmagGOpt\tdegGOpt\tRn_eff\n")
2693 new = ntwk.copy()
2694 new.resample(ntwk.f_noise) # only write data from original noise freqs
2695 for f, nf, g_opt, rn, z0 in zip(new.f_noise.f_scaled, new.nfmin_db, new.g_opt, new.rn, new.z0):
2696 output.write(format_spec_nf_freq.format(f) + ' ' \
2697 + format_spec_nf_min.format(nf) + ' ' \
2698 + format_spec_g_opt_mag.format(mf.complex_2_magnitude(g_opt)) + ' ' \
2699 + format_spec_g_opt_phase.format(mf.complex_2_degree(g_opt)) + ' ' \
2700 + format_spec_rn.format(rn/z0[0].real) + ' ' "\n")
2701
2702
2703 def write(self, file: str | Path = None, *args, **kwargs) -> None:
2704 r"""
2705 Write the Network to disk using the :mod:`pickle` module.
2706
2707 The resultant file can be read either by using the Networks
2708 constructor, :func:`__init__` , the read method :func:`read`, or
2709 the general read function :func:`skrf.io.general.read`
2710
2711
2712 Parameters
2713 ----------
2714 file : str, Path, or file-object
2715 filename or a file-object. If left as None then the
2716 filename will be set to Network.name, if its not None.
2717 If both are None, ValueError is raised.
2718 \*args, \*\*kwargs :
2719 passed through to :func:`~skrf.io.general.write`
2720
2721
2722 Note
2723 ----
2724 If the self.name is not None and file is can left as None
2725 and the resultant file will have the `.ntwk` extension appended
2726 to the filename.
2727
2728
2729 Examples
2730 --------
2731 >>> n = rf.N(f=[1,2,3],s=[1,1,1],z0=50, name = 'open')
2732 >>> n.write()
2733 >>> n2 = rf.read('open.ntwk')
2734
2735 See Also
2736 --------
2737 skrf.io.general.write : write any skrf object
2738 skrf.io.general.read : read any skrf object
2739 """
2740 # this import is delayed until here because of a circular dependency
2741 from .io.general import write
2742
2743 if file is None:
2744 if self.name is None:
2745 raise (ValueError('No filename given. You must provide a filename, or set the name attribute'))
2746 file = self.name
2747
2748 write(file, self, *args, **kwargs)
2749
2750 def read(self, *args, **kwargs) -> None:
2751 r"""
2752 Read a Network from a 'ntwk' file.
2753
2754 A ntwk file is written with :func:`write`. It is just a pickled
2755 file.
2756
2757 Parameters
2758 ----------
2759 \*args, \*\*kwargs : args and kwargs
2760 passed to :func:`skrf.io.general.read`
2761
2762
2763 Note
2764 ----
2765 This function calls :func:`skrf.io.general.read`.
2766
2767
2768 Examples
2769 --------
2770 >>> rf.read('myfile.ntwk')
2771 >>> rf.read('myfile.p')
2772
2773 See Also
2774 --------
2775 skrf.io.general.read
2776 write
2777 skrf.io.general.write
2778 """
2779 from .io.general import read
2780 self.copy_from(read(*args, **kwargs))
2781
2782 def write_spreadsheet(self, *args, **kwargs) -> None:
2783 """
2784 Write contents of network to a spreadsheet, for your boss to use.
2785
2786 See Also
2787 --------
2788 skrf.io.general.network_2_spreadsheet
2789 """
2790 from .io.general import network_2_spreadsheet
2791 network_2_spreadsheet(self, *args, **kwargs)
2792
2793 def to_dataframe(self, attrs: list[str] =None,
2794 ports: list[tuple[int, int]] = None, port_sep: str | None = None):
2795 """
2796 Convert attributes of a Network to a pandas DataFrame.
2797
2798 Use the same parameters than :func:`skrf.io.general.network_2_dataframe`
2799
2800 Parameters
2801 ----------
2802 attrs : list of string
2803 Network attributes to convert, like ['s_db','s_deg']
2804 ports : list of tuples
2805 list of port pairs to write. defaults to ntwk.port_tuples
2806 (like [[0,0]])
2807 port_sep : string
2808 defaults to None, which means a empty string "" is used for
2809 networks with lower than 10 ports. (s_db 11, s_db 21)
2810 For more than ten ports a "_" is used to avoid ambiguity.
2811 (s_db 1_1, s_db 2_1)
2812 For consistent behaviour it's recommended to specify "_" or
2813 "," explicitly.
2814
2815 Returns
2816 -------
2817 df : `pandas.DataFrame`
2818
2819
2820 See Also
2821 ---------
2822 skrf.io.general.network_2_dataframe
2823 """
2824 from .io.general import network_2_dataframe
2825 if attrs is None:
2826 attrs = ['s_db']
2827 return network_2_dataframe(self, attrs=attrs, ports=ports, port_sep=port_sep)
2828
2829 def write_to_json_string(self) -> str:
2830 """
2831 Serialize and convert network to a JSON string.
2832
2833 This is ~3x faster than writing to and reading back from touchstone
2834 for a 4port 20,000 point device.
2835
2836 Returns
2837 -------
2838 jsonstr : string
2839 JSON string
2840
2841 See Also
2842 --------
2843 skrf.io.general.to_json_string
2844 """
2845 from .io.general import to_json_string
2846 return to_json_string(self)
2847
2848
2849
2850 # interpolation
2851 def interpolate(self, freq_or_n: Frequency | NumberLike, basis: str = 's',
2852 coords: CoordT = 'cart', f_kwargs: dict = None, return_array: bool = False,
2853 kind: InterpolKindT | None = None, **kwargs) -> Network | np.ndarray:
2854 r"""
2855 Interpolate a Network along frequency axis.
2856
2857 The input 'freq_or_n` can be either a new
2858 :class:`~skrf.frequency.Frequency` or an `int`, or a new
2859 frequency vector (in Hz).
2860
2861 This interpolates a given `basis`, ie s, z, y, etc, in the
2862 coordinate system defined by `coord` like polar or cartesian.
2863 Different interpolation types ('linear', 'quadratic') can be used
2864 by passing appropriate `\*\*kwargs`. This function returns an
2865 interpolated Network. Alternatively :func:`~Network.interpolate_self`
2866 will interpolate self.
2867
2868 Parameters
2869 ----------
2870 freq_or_n : :class:`~skrf.frequency.Frequency` or int or list-like
2871 The new frequency over which to interpolate. this arg may be
2872 one of the following:
2873
2874 * a new :class:`~skrf.frequency.Frequency` object
2875
2876 * an int: the current frequency span is resampled linearly.
2877
2878 * a list-like: create a new frequency using :meth:`~skrf.frequency.Frequency.from_f`
2879
2880 basis : ['s','z','y','a'], etc
2881 The network parameter to interpolate
2882 coords : string
2883 Coordinate system to use for interpolation: 'cart' or 'polar':
2884 'cart' is cartesian is Re/Im. 'polar' is unwrapped phase/mag
2885 return_array: bool
2886 return the interpolated array instead of re-assigning it to
2887 a given attribute
2888 **kwargs : keyword arguments
2889 passed to interpolate method.
2890 `freq_cropped` kwarg controls whether to use pre-cropped frequency
2891 points for interpolation. Defaults to True.
2892
2893 passed to :func:`scipy.interpolate.interp1d` initializer.
2894 `kind` controls interpolation type.
2895
2896 `kind` = `rational` uses interpolation by rational polynomials.
2897
2898 `d` kwarg controls the degree of rational polynomials
2899 when `kind`=`rational`. Defaults to 4.
2900
2901 Returns
2902 -------
2903 result : :class:`Network`
2904 an interpolated Network, or array
2905
2906 Note
2907 ----
2908 Frequency cropping is only supported with methods from
2909 `scipy.interpolate.interpolate.interp1d`. The 'rational' method does
2910 not support frequency cropping.
2911
2912 The interpolation coordinate system (`coords`) makes a big
2913 difference for large amounts of interpolation. polar works well
2914 for duts with slowly changing magnitude. try them all.
2915
2916 See :func:`scipy.interpolate.interpolate.interp1d` for useful
2917 kwargs. For example:
2918
2919 kind : string or int
2920 Specifies the kind of interpolation as a string ('linear',
2921 'nearest', 'zero', 'slinear', 'quadratic, 'cubic') or
2922 as an integer specifying the order of the spline
2923 interpolator to use.
2924
2925
2926 See Also
2927 --------
2928 resample
2929 interpolate_self
2930 interpolate_from_f
2931
2932 Examples
2933 --------
2934 .. ipython::
2935
2936 @suppress
2937 In [21]: import skrf as rf
2938
2939 In [21]: n = rf.data.ring_slot
2940
2941 In [21]: n
2942
2943 In [21]: new_freq = rf.Frequency(75,110,501,'ghz')
2944
2945 In [21]: n.interpolate(new_freq, kind = 'cubic')
2946
2947 """
2948 # make new network and fill with interpolated values
2949 if f_kwargs is None:
2950 f_kwargs = {}
2951 result = self.copy()
2952
2953 is_rational = False
2954 freq_cropped = kwargs.pop('freq_cropped', True)
2955 if kind == 'rational':
2956 f_interp = mf.rational_interp
2957 #Not supported by rational_interp
2958 is_rational = True
2959 else:
2960 kwargs["kind"] = kind if kind is not None else "linear"
2961 f_interp = interp1d
2962
2963 # interpret input
2964 if isinstance(freq_or_n, Frequency):
2965 # input is a frequency object
2966 new_frequency = freq_or_n
2967
2968 else:
2969 dim = len(shape(freq_or_n))
2970 if dim == 0:
2971 # input is a number
2972 new_frequency = Frequency(start=self.frequency.start_scaled,
2973 stop=self.frequency.stop_scaled,
2974 unit=self.frequency.unit,
2975 npoints=freq_or_n)
2976 elif dim == 1:
2977 # input is a array, or list
2978 new_frequency = Frequency.from_f(freq_or_n, **f_kwargs)
2979
2980 # set new frequency and pull some variables
2981 result.frequency = new_frequency
2982 f = self.frequency.f
2983 f_new = new_frequency.f
2984
2985 # Pre-cropped the frequency
2986 l_idx = max(np.searchsorted(f, f_new[0], side="left") - 8, 0)
2987 r_idx = min(np.searchsorted(f, f_new[-1], side="right") + 8, len(f))
2988
2989 # rational method or prohibit frequency clipping
2990 if is_rational or not freq_cropped:
2991 l_idx, r_idx = 0, len(f)
2992 f_cropped = f[l_idx:r_idx]
2993
2994 # interpolate z0 ( this must happen first, because its needed
2995 # to compute the basis transform below (like y2s), if basis!='s')
2996 if np.all(self.z0 == self.z0[0]):
2997 # If z0 is constant we don't need to interpolate it
2998 z0_shape = list(self.z0.shape)
2999 z0_shape[0] = len(f_new)
3000 result._z0 = np.ones(z0_shape) * self.z0[0]
3001 else:
3002 result._z0 = f_interp(f_cropped, self.z0[l_idx:r_idx], axis=0, **kwargs)(f_new)
3003
3004 # interpolate parameter for a given basis
3005 x: np.ndarray = getattr(self, basis)
3006 x_cropped = x[l_idx:r_idx]
3007 if coords == 'cart':
3008 x_new = f_interp(f_cropped, x_cropped, axis=0, **kwargs)(f_new)
3009 elif coords == 'polar':
3010 rad = np.unwrap(np.angle(x_cropped), axis=0)
3011 mag = np.abs(x_cropped)
3012 interp_rad = f_interp(f_cropped, rad, axis=0, **kwargs)
3013 interp_mag = f_interp(f_cropped, mag, axis=0, **kwargs)
3014 x_new = interp_mag(f_new) * np.exp(1j * interp_rad(f_new))
3015 else:
3016 raise ValueError(f'Unknown coords {coords}')
3017
3018 # interpolate noise data too
3019 if self.noisy:
3020 f_noise = self.noise_freq.f
3021 f_noise_new = new_frequency.f
3022 noise_new = f_interp(f_noise, self.noise, axis=0, **kwargs)(f_noise_new)
3023
3024 if return_array:
3025 return x_new
3026 else:
3027 result.__setattr__(basis, x_new)
3028 if self.noisy:
3029 result.noise = noise_new
3030 result.noise_freq = new_frequency
3031 return result
3032
3033 def interpolate_self(self, freq_or_n: Frequency | NumberLike, **kwargs) -> None:
3034 """
3035 Interpolate the current Network along frequency axis (inplace).
3036
3037 The input 'freq_or_n` can be either a new
3038 :class:`~skrf.frequency.Frequency` or an `int`, or a new
3039 frequency vector (in Hz).
3040
3041 See :func:`~Network.interpolate` for more information.
3042
3043 Parameters
3044 ----------
3045 freq_or_n : :class:`~skrf.frequency.Frequency` or int or list-like
3046 The new frequency over which to interpolate. this arg may be
3047 one of the following:
3048
3049 * a new :class:`~skrf.frequency.Frequency` object
3050
3051 * an int: the current frequency span is resampled linearly.
3052
3053 * a list-like: create a new frequency using :meth:`~skrf.frequency.Frequency.from_f`
3054
3055 **kwargs : keyword arguments
3056 passed to :func:`scipy.interpolate.interp1d` initializer.
3057
3058 Returns
3059 -------
3060 None
3061 The interpolation is performed inplace.
3062
3063 See Also
3064 --------
3065 resample
3066 interpolate
3067 interpolate_from_f
3068 """
3069 ntwk = self.interpolate(freq_or_n, **kwargs)
3070 self.frequency, self.s, self.z0 = ntwk.frequency, ntwk.s, ntwk.z0
3071 if self.noisy:
3072 self.noise, self.noise_freq = ntwk.noise, ntwk.noise_freq
3073
3074 ##convenience
3075 resample = interpolate_self
3076
3077 def extrapolate_to_dc(self, points: int = None, dc_sparam: NumberLike | None = None,
3078 kind: InterpolKindT = 'cubic', coords: CoordT = 'cart',
3079 **kwargs) -> Network:
3080 """
3081 Extrapolate S-parameters down to 0 Hz and interpolate to uniform spacing.
3082
3083 If frequency vector needs to be interpolated aliasing will occur in
3084 time-domain. For the best results first frequency point should be a
3085 multiple of the frequency step so that points from DC to
3086 the first measured point can be added without interpolating rest of the
3087 frequency points.
3088
3089 Parameters
3090 ----------
3091 points : int or None
3092 Number of frequency points to be used in interpolation.
3093 If None number of points is calculated based on the frequency step size
3094 and spacing between 0 Hz and first measured frequency point.
3095 dc_sparam : class:`np.ndarray` or None
3096 NxN S-parameters matrix at 0 Hz.
3097 If None S-parameters at 0 Hz are determined by linear extrapolation.
3098 kind : str or int, default is 'cubic'
3099 Specifies the kind of interpolation as a string ('linear',
3100 'nearest', 'zero', 'slinear', 'quadratic, 'cubic') or
3101 as an integer specifying the order of the spline
3102 interpolator to use for `scipy.interp1d`.
3103
3104 `kind` = 'rational' uses interpolation by rational polynomials.
3105
3106 `d` kwarg controls the degree of rational polynomials
3107 when `kind` is 'rational'. Defaults to 4.
3108 coords : str
3109 Coordinate system to use for interpolation: 'cart' or 'polar'.
3110 'cart' is cartesian is Re/Im, 'polar' is unwrapped phase/mag.
3111 Passed to :func:`Network.interpolate`
3112
3113 Returns
3114 -------
3115 result : :class:`Network`
3116 Extrapolated Network
3117
3118 See Also
3119 --------
3120 interpolate
3121 impulse_response
3122 step_response
3123 """
3124 result = self.copy()
3125
3126 if self.frequency.f[0] == 0:
3127 return result
3128
3129 if points is None:
3130 fstep = self.frequency.f[1] - self.frequency.f[0]
3131 points = len(self) + int(round(self.frequency.f[0]/fstep))
3132 if dc_sparam is None:
3133 #Interpolate DC point alone first using linear interpolation, because
3134 #interp1d can't extrapolate with other methods.
3135 #TODO: Option to enforce passivity
3136 x = result.s[:2]
3137 f = result.frequency.f[:2]
3138 rad = np.unwrap(np.angle(x), axis=0)
3139 mag = np.abs(x)
3140 interp_rad = interp1d(f, rad, axis=0, fill_value='extrapolate')
3141 interp_mag = interp1d(f, mag, axis=0, fill_value='extrapolate')
3142 dc_sparam = interp_mag(0) * np.exp(1j * interp_rad(0))
3143 # Extrapolate other points and insert
3144 fstep = self.frequency.f[-1]/(points-1)
3145 if self.frequency.f[0] >= 2*fstep:
3146 len_interp = points - len(self)
3147 extrapolated_f = Frequency(fstep, (len_interp-1) * fstep, len_interp-1, unit="Hz")
3148 for freq in reversed(extrapolated_f.f):
3149 interp_sparam = interp_mag(freq) * np.exp(1j * interp_rad(freq))
3150 result.s = np.insert(result.s, 0, interp_sparam, axis=0)
3151 result.frequency._f = np.insert(result.frequency.f, 0, freq)
3152 result.z0 = np.insert(result.z0, 0, result.z0[0], axis=0)
3153 else:
3154 #Make numpy array if argument was list
3155 dc_sparam = np.array(dc_sparam)
3156
3157 result.s = np.insert(result.s, 0, dc_sparam, axis=0)
3158 result.frequency._f = np.insert(result.frequency.f, 0, 0)
3159 result.z0 = np.insert(result.z0, 0, result.z0[0], axis=0)
3160
3161 if result.noisy:
3162 result.noise = np.insert(result.noise, 0, 0, axis=0)
3163 result.noise_freq._f = np.insert(result.noise_freq.f, 0, 0)
3164
3165 new_f = Frequency(0, result.frequency.f_scaled[-1], points,
3166 unit=result.frequency.unit)
3167 #None of the default interpolation methods are too good
3168 #and cause aliasing in the time domain.
3169 #Best results are obtained when no interpolation is needed,
3170 #e.g. first frequency point is a multiple of frequency step.
3171 result.interpolate_self(new_f, kind=kind, coords=coords, **kwargs)
3172 #DC value must have zero imaginary part
3173 result.s[0,:,:] = result.s[0,:,:].real
3174 return result
3175
3176
3177 def subnetwork(self, ports: Sequence[int], offby: int = 1) -> Network:
3178 """
3179 Return a subnetwork of a the Network from a list of port numbers.
3180
3181 A subnetwork is Network which S-parameters corresponds to selected ports,
3182 with all non-selected ports considered matched.
3183
3184 The resulting subNetwork is given a new Network.name property
3185 from the initial name and adding the kept ports indices
3186 (ex: 'device' -> 'device13'). Such name should make easier the use
3187 of functions such as n_twoports_2_nport.
3188
3189 Parameters
3190 ----------
3191 ports : list of int
3192 List of ports to keep in the resultant Network.
3193 Indices are the Python indices (starts at 0)
3194 offby : int
3195 starting value for s-parameters indexes in the sub-Network name parameter.
3196 A value of `1`, assumes that a s21 = ntwk.s[:,1,0]. Default is 1.
3197
3198 Returns
3199 -------
3200 subntw : :class:`Network` object
3201 Resulting subnetwork of the Network from the given ports
3202
3203 See also
3204 --------
3205 subnetwork, n_twoports_2_nport
3206
3207 """
3208 return subnetwork(self, ports, offby)
3209
3210 def crop(self, f_start: float, f_stop: float, unit: str = None) -> None:
3211 """
3212 Crop Network based on start and stop frequencies.
3213
3214 No interpolation is done.
3215
3216 Parameters
3217 ----------
3218 f_start : number
3219 start frequency of crop range, in units of self.frequency.unit.
3220 If `f_start` is lower than the lowest frequency, no change to the network is made by the lower bound.
3221 f_stop : number
3222 stop frequency of crop range, in units of self.frequency.unit
3223 If `f_stop` is higher than the highest frequency, no change to the network is made by the higher bound.
3224 unit : string
3225 Units that `f_start` and `f_stop` are described in. This must be a string recognized by the Frequency
3226 class, e.g. 'Hz','MHz', etc. A value of `None` assumes units are same as `self`
3227
3228 See Also
3229 --------
3230 cropped
3231
3232 """
3233 if f_start is None:
3234 f_start = -np.inf
3235 if f_stop is None:
3236 f_stop = np.inf
3237
3238 if f_stop<f_start:
3239 raise ValueError(f"`f_stop` was {f_stop}, which was smaller than `f_start`, which was {f_start}")
3240
3241 if unit is not None: # if `unit` is specified, we must retranslate the frequency units
3242 # make a multiplier to put f_start and f_stop in the right units, e.g. 'GHz' -> 'MHz'
3243 scaleFactor = Frequency.multiplier_dict[unit.lower()]/self.frequency.multiplier
3244 f_start *=scaleFactor
3245 f_stop *=scaleFactor
3246
3247 if f_start > self.frequency.f_scaled.max():
3248 raise ValueError(f"`f_start` was {f_start}, which was larger than the largest frequency "
3249 "in this Network object, which was {self.frequency.f_scaled.max()}")
3250 if f_stop < self.frequency.f_scaled.min():
3251 raise ValueError(f"`f_stop` was {f_stop}, which was smaller than the smallest frequency "
3252 "in this Network object, which was {self.frequency.f_scaled.min()}")
3253
3254 start_idx,stop_idx = 0,self.frequency.npoints-1 # start with entire frequency range selected
3255
3256 if f_start > self.frequency.f_scaled.min():
3257 start_idx = find_nearest_index(self.frequency.f_scaled, f_start)
3258 # we do not want the start index to be at a frequency lower than `f_start`
3259 if f_start > self.frequency.f_scaled[start_idx]:
3260 start_idx += 1
3261 if f_stop < self.frequency.f_scaled.max():
3262 stop_idx = find_nearest_index(self.frequency.f_scaled, f_stop)
3263 # we don't want the stop index to be at a frequency higher than `f_stop`
3264 if f_stop < self.frequency.f_scaled[stop_idx]:
3265 stop_idx -=1
3266
3267 if stop_idx < start_idx :
3268 raise ValueError("Stop index/frequency lower than start: "
3269 f"stop_idx: {stop_idx}, "
3270 f"start_idx: {start_idx}, "
3271 f"self.frequency.f[stop_idx]: {self.frequency.f[stop_idx]}, "
3272 f"self.frequency.f[start_idx]: {self.frequency.f[start_idx]}")
3273 ntwk = self[start_idx:stop_idx + 1]
3274 self.frequency, self.s, self.z0 = ntwk.frequency, ntwk.s, ntwk.z0
3275
3276 def cropped(self, f_start: float, f_stop: float, unit: str = None) -> Network:
3277 """
3278 Returns a cropped network, leaves self alone.
3279
3280 Parameters
3281 ----------
3282 f_start : number
3283 start frequency of crop range, in units of self.frequency.unit.
3284 If `f_start` is lower than the lowest frequency, no change to the network is made by the lower bound.
3285 f_stop : number
3286 stop frequency of crop range, in units of self.frequency.unit
3287 If `f_stop` is higher than the highest frequency, no change to the network is made by the higher bound.
3288 unit : string
3289 Units that `f_start` and `f_stop` are described in. This must be a string recognized by the Frequency
3290 class, e.g. 'Hz','MHz', etc. A value of `None` assumes units are same as `self`
3291
3292 Returns
3293 -------
3294 ntwk : :class:`Network` object
3295 Resulting cropped network
3296
3297 See Also
3298 --------
3299 crop
3300
3301 """
3302 out = self.copy()
3303 out.crop(f_start=f_start, f_stop=f_stop,unit=unit)
3304 return out
3305
3306 def flip(self) -> None:
3307 """
3308 Swap the ports of a 2n-port Network (inplace).
3309
3310 In case the network is 2n-port and n > 1, 'second' numbering scheme is
3311 assumed to be consistent with the ** cascade operator::
3312
3313 +--------+ +--------+
3314 0-|0 n|-n 0-|n 0|-n
3315 1-|1 n+1|-n+1 flip 1-|n+1 1|-n+1
3316 ... ... => ... ...
3317 n-1-|n-1 2n-1|-2n-1 n-1-|2n-1 n-1|-2n-1
3318 +--------+ +--------+
3319
3320 See Also
3321 --------
3322 flipped
3323 renumber
3324 renumbered
3325
3326 """
3327 if self.number_of_ports % 2 == 0:
3328 n = int(self.number_of_ports / 2)
3329 old = list(range(0, 2*n))
3330 new = list(range(n, 2*n)) + list(range(0, n))
3331 self.renumber(old, new)
3332 else:
3333 raise ValueError('you can only flip two-port Networks')
3334
3335 def flipped(self) -> Network:
3336 """
3337 Returns a flipped network, leaves self alone.
3338
3339 Returns
3340 -------
3341 ntwk : :class:`Network` object
3342 Resulting flipped Network
3343
3344 See Also
3345 --------
3346 flip
3347 renumber
3348 renumbered
3349
3350 """
3351 out = self.copy()
3352 out.flip()
3353 return out
3354
3355 def renormalize(self, z_new: NumberLike, s_def: SdefT | None = None) -> None:
3356 """
3357 Renormalize s-parameter matrix given a new port impedances.
3358
3359 Parameters
3360 ----------
3361 z_new : complex array of shape FxN, F, N or a scalar
3362 new port impedances
3363
3364 s_def : str -> s_def : can be: None, 'power', 'pseudo' or 'traveling'
3365 None to use the definition set in the network `s_def` attribute.
3366 Scattering parameter definition : 'power' for power-waves definition,
3367 'pseudo' for pseudo-waves definition.
3368 'traveling' corresponds to the initial implementation.
3369 Default is 'power'.
3370 NB: results are the same for real-valued characteristic impedances.
3371
3372 See Also
3373 --------
3374 renormalize_s
3375 fix_z0_shape
3376 """
3377 # cast any array like type (tuple, list) to a np.array
3378 z_new = np.array(z_new, dtype=complex)
3379 # make sure the z_new shape can be compared with self.z0
3380 z_new = fix_z0_shape(z_new, self.frequency.npoints, self.nports)
3381 if s_def is None:
3382 s_def = self.s_def
3383 # Try to avoid renormalization if possible since it goes through
3384 # Z-parameters which can cause numerical inaccuracies.
3385 # We need to renormalize if z_new is different from z0
3386 # or s_def is different and there is at least one complex port.
3387 need_to_renorm = False
3388 if np.any(self.z0 != z_new):
3389 need_to_renorm = True
3390 if s_def != self.s_def and (self.z0.imag != 0).any():
3391 need_to_renorm = True
3392 if need_to_renorm:
3393 # We can use s2s if z0 is the same. This is numerically much more
3394 # accurate.
3395 if (self.z0 == z_new).all():
3396 self.s = s2s(self.s, self.z0, s_def, self.s_def)
3397 else:
3398 self.s = renormalize_s(self.s, self.z0, z_new, s_def, self.s_def)
3399 # Update s_def if it was changed
3400 self.s_def = s_def
3401 self.z0 = z_new
3402
3403 def renumber(self, from_ports: Sequence[int], to_ports: Sequence[int], only_z0: bool = False) -> None:
3404 """
3405 Renumber ports of a Network (inplace).
3406
3407 Parameters
3408 ----------
3409 from_ports : list-like
3410 List of port indices to change. Size between 1 and N_ports.
3411 to_ports : list-like
3412 List of desired port indices. Size between 1 and N_ports.
3413 only_z0 : bool
3414 If true only z0 is renumbered, s-parameters are not affected.
3415 This should only be used after executing the "connect_s" method
3416 which keeps the port index where you expect it to be.
3417
3418 NB : from_ports and to_ports must have same size.
3419
3420 Returns
3421 -------
3422 None
3423 The reorganization of the Network's port is performed inplace.
3424
3425
3426 Examples
3427 --------
3428
3429 In the following example, the ports of a 3-ports Network are
3430 reorganized. Dummy reference impedances are set only to follow more
3431 easily the renumbering.
3432
3433 >>> f = rf.Frequency(1, 1, 1, 'hz')
3434 >>> s = np.arange(9).reshape(1, 3, 3)
3435 >>> z0 = [10, 20, 30]
3436 >>> ntw = rf.Network(frequency=f, s=s, z0=z0) # our OEM Network
3437
3438 In picture, we have::
3439
3440 Order in Original Order Scatter Parameters
3441 skrf.Network 0 1 2
3442 ┌───────────────────┐ ┌──────────────────────┐
3443 │ OEM │ │ │
3444 │ │ │ │
3445 0 ────────┤ A (10 Ω) │ ┤ 0.+0.j 1.+0.j 2.+0.j │
3446 │ │ │ │
3447 │ │ │ │
3448 1 ────────┤ B (20 Ω) │ ┤ 3.+0.j 4.+0.j 5.+0.j │
3449 │ │ │ │
3450 │ │ │ │
3451 2 ────────┤ C (30 Ω) │ ┤ 6.+0.j 7.+0.j 8.+0.j │
3452 │ │ │ │
3453 └───────────────────┘ └──────────────────────┘
3454
3455 While after renumbering
3456
3457 >>> ntw.renumber([0, 1, 2], [1, 2, 0])
3458
3459 we now have::
3460
3461 Order in Scatter Parameters
3462 skrf.Network 0 1 2
3463 ┌───────────────────┐ ┌──────────────────────┐
3464 │ OEM │ │ │
3465 │ │ │ │
3466 0 ────────┤ C (30 Ω) │ ┤ 8.+0.j 6.+0.j 7.+0.j │
3467 │ │ │ │
3468 │ │ │ │
3469 1 ────────┤ A (10 Ω) │ ┤ 2.+0.j 0.+0.j 1.+0.j │
3470 │ │ │ │
3471 │ │ │ │
3472 2 ────────┤ B (20 Ω) │ ┤ 5.+0.j 3.+0.j 4.+0.j │
3473 │ │ │ │
3474 └───────────────────┘ └──────────────────────┘
3475
3476 **Other examples:**
3477
3478 Reorganized only the reference impedance of the ports, while keeping
3479 the order of the scattering parameters is also supported. This is
3480 beneficial in some special cases.
3481
3482 >>> ntw.renumber([1, 2, 0], [0, 1, 2], only_z0=True)
3483
3484 we now have::
3485
3486 Order in Scatter Parameters
3487 skrf.Network 0 1 2
3488 ┌───────────────────┐ ┌──────────────────────┐
3489 │ OEM │ │ │
3490 │ │ │ │
3491 0 ────────┤ A (10 Ω) │ ┤ 8.+0.j 6.+0.j 7.+0.j │
3492 │ │ │ │
3493 │ │ │ │
3494 1 ────────┤ B (20 Ω) │ ┤ 2.+0.j 0.+0.j 1.+0.j │
3495 │ │ │ │
3496 │ │ │ │
3497 2 ────────┤ C (30 Ω) │ ┤ 5.+0.j 3.+0.j 4.+0.j │
3498 │ │ │ │
3499 └───────────────────┘ └──────────────────────┘
3500
3501 To flip the ports of a 2-port network 'foo':
3502
3503 >>> foo.renumber( [0,1], [1,0] )
3504
3505 To rotate the ports of a 3-port network 'bar' so that port 0 becomes port 1:
3506
3507 >>> bar.renumber( [0,1,2], [1,2,0] )
3508
3509 To swap the first and last ports of an N-port (N>=2) Network 'duck':
3510
3511 >>> duck.renumber( [0,-1], [-1,0] )
3512
3513 See Also
3514 --------
3515 renumbered
3516 flip
3517 flipped
3518
3519 """
3520 from_ports = np.array(from_ports)
3521 to_ports = np.array(to_ports)
3522 if len(np.unique(from_ports)) != len(from_ports):
3523 raise ValueError('an index can appear at most once in from_ports or to_ports')
3524 if any(np.unique(from_ports) != np.unique(to_ports)):
3525 raise ValueError('from_ports and to_ports must have the same set of indices')
3526
3527 if not only_z0:
3528 self.s[:, to_ports, :] = self.s[:, from_ports, :] # renumber rows
3529 self.s[:, :, to_ports] = self.s[:, :, from_ports] # renumber columns
3530 self.z0[:, to_ports] = self.z0[:, from_ports]
3531 if self.port_names is not None:
3532 _port_names = np.array(self.port_names)
3533 _port_names[to_ports] = _port_names[from_ports]
3534 self.port_names = _port_names.tolist()
3535
3536 def renumbered(self, from_ports: Sequence[int], to_ports: Sequence[int]) -> Network:
3537 """
3538 Return a renumbered Network, leave self alone.
3539
3540 Parameters
3541 ----------
3542 from_ports : list-like
3543 List of port indices to change. Size between 1 and N_ports.
3544 to_ports : list-like
3545 List of desired port indices. Size between 1 and N_ports.
3546
3547 NB: from_ports and to_ports must have same size.
3548
3549 Returns
3550 -------
3551 ntwk : :class:`Network` object
3552 Resulting renumbered Network
3553
3554 See Also
3555 --------
3556 renumber
3557 flip
3558 flipped
3559
3560 """
3561 out = self.copy()
3562 out.renumber(from_ports, to_ports)
3563 return out
3564
3565 def rotate(self, theta: NumberLike, unit: str = 'deg') -> None:
3566 """
3567 Rotate S-parameters
3568 """
3569 if unit == 'deg':
3570 theta = mf.degree_2_radian(theta )
3571
3572 self.s = self.s * np.exp(-1j*theta)
3573
3574 def delay(self, d: float, unit: str = 'deg', port: int = 0, media: Any = None, **kw) -> Network:
3575 """
3576 Add phase delay to a given port.
3577
3578 This will connect a transmission line of length `d/2` to the selected `port`. If no propagation properties are
3579 specified for the line (`media=None`), then freespace is assumed to convert a distance `d` into an electrical
3580 length. If a phase angle is specified for `d`, it will be evaluated at the center frequency of the network.
3581
3582 Parameters
3583 ----------
3584 d : float
3585 The angle/length/delay of the transmission line (see `unit` argument)
3586 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
3587 The units of d. See :func:`Media.to_meters`, for details
3588 port : int
3589 Port to add the delay to.
3590 media: skrf.media.Media
3591 Media object to use for generating the delay. If None, this will
3592 default to freespace.
3593
3594 Returns
3595 -------
3596 ntwk : :class:`Network` object
3597 A delayed copy of the `Network`.
3598
3599 """
3600 if d ==0:
3601 return self
3602 d=d/2.
3603 if media is None:
3604 from .media import Freespace
3605 media = Freespace(frequency=self.frequency,
3606 z0_override = self.z0[:,port])
3607
3608 l =media.line(d=d, unit=unit,**kw)
3609 return connect(self, port, l, 0)
3610
3611 def windowed(self, window: str | float | tuple[str, float] | Callable =('kaiser', 6),
3612 normalize: bool = True, center_to_dc: bool = None) -> Network:
3613 """
3614 Return a windowed version of s-matrix. Used in time-domain analysis.
3615
3616 When using time domain through :attr:`s_time_db`,
3617 or similar properties, the spectrum is usually windowed,
3618 before the IFFT is taken. This is done to
3619 compensate for the band-pass nature of a spectrum [#]_.
3620
3621 This function calls :func:`scipy.signal.get_window` which gives
3622 more details about the windowing or a custom window function with
3623 the required length as parameter.
3624
3625 Parameters
3626 ----------
3627 window : string, float, tuple or callable
3628 The type of window to create. See :func:`scipy.signal.get_window`
3629 for details.
3630 normalize : bool
3631 Normalize the window to preserve power. ie
3632 sum(ntwk.s,axis=0) == sum(ntwk.windowed().s,axis=0)
3633 center_to_dc : bool or None
3634 If True only the positive half of the window is applied to the signal.
3635 This should be used if frequency vector begins from DC or from "close enough" to DC.
3636 If False full window is used which also attenuates low frequencies.
3637 If None then value is determined automatically based on if frequency
3638 vector begins from 0.
3639
3640 Returns
3641 -------
3642 ntwk : :class:`Network` object
3643 Resulting windowed Network
3644
3645 Examples
3646 --------
3647 >>> ntwk = rf.Network('myfile.s2p')
3648 >>> ntwk_w = ntwk.windowed()
3649 >>> ntwk_w.plot_s_time_db()
3650
3651 References
3652 ----------
3653 .. [#] Agilent Time Domain Analysis Using a Network Analyzer Application Note 1287-12
3654
3655 """
3656
3657 if center_to_dc is None:
3658 center_to_dc = self.frequency.f[0] == 0
3659
3660 if center_to_dc:
3661 window = get_window(window, 2*len(self))[len(self):]
3662 else:
3663 window = get_window(window, len(self))
3664
3665 window = window.reshape(-1, 1, 1) * np.ones((len(self),
3666 self.nports,
3667 self.nports))
3668 windowed = self * window
3669 if normalize:
3670 # normalize the s-parameters to account for power lost in windowing
3671 windowed.s = windowed.s * np.sum(self.s_mag, axis=0) / \
3672 np.sum(windowed.s_mag, axis=0)
3673
3674 return windowed
3675
3676 def time_gate(self, *args, **kw) -> Network:
3677 """
3678 Time gate this Network.
3679
3680 Returns
3681 -------
3682 ntwk : :class:`Network` object
3683 Resulting time-gated Network
3684
3685 see `skrf.time_domain.time_gate`
3686 """
3687 return time_gate(self, *args, **kw)
3688
3689
3690 # noise
3691 def add_noise_polar(self, mag_dev: float, phase_dev: float, **kwargs) -> None:
3692 """
3693 Adds a complex zero-mean gaussian white-noise.
3694
3695 adds a complex zero-mean gaussian white-noise of a given
3696 standard deviation for magnitude and phase
3697
3698 Parameters
3699 ----------
3700 mag_dev : number
3701 standard deviation of magnitude
3702 phase_dev : number
3703 standard deviation of phase [in degrees]
3704
3705 """
3706
3707 phase_rv = stats.norm(loc=0, scale=phase_dev).rvs(size=self.s.shape)
3708 mag_rv = stats.norm(loc=0, scale=mag_dev).rvs(size=self.s.shape)
3709
3710 phase = (self.s_deg + phase_rv)
3711 mag = self.s_mag + mag_rv
3712 self.s = mag * np.exp(1j * np.pi / 180. * phase)
3713
3714 def add_noise_polar_flatband(self, mag_dev: float, phase_dev: float, **kwargs) -> None:
3715 """
3716 Add a flatband complex zero-mean gaussian white-noise signal of
3717 given standard deviations for magnitude and phase.
3718
3719 Parameters
3720 ----------
3721 mag_dev : number
3722 standard deviation of magnitude
3723 phase_dev : number
3724 standard deviation of phase [in degrees]
3725
3726 """
3727 phase_rv = stats.norm(loc=0, scale=phase_dev).rvs(size=self.s[0].shape)
3728 mag_rv = stats.norm(loc=0, scale=mag_dev).rvs(size=self.s[0].shape)
3729
3730 phase = (self.s_deg + phase_rv)
3731 mag = self.s_mag + mag_rv
3732 self.s = mag * np.exp(1j * np.pi / 180. * phase)
3733
3734 def multiply_noise(self, mag_dev: float, phase_dev: float, **kwargs) -> None:
3735 """
3736 Multiply a complex bivariate gaussian white-noise signal
3737 of given standard deviations for magnitude and phase.
3738 The mean of the magnitude is 1, and the mena of the phase is 0.
3739
3740 Parameters
3741 ----------
3742 mag_dev: float
3743 standard deviation of magnitude
3744 phase_dev: float
3745 standard deviation of phase [in degrees]
3746
3747
3748 """
3749 phase_rv = stats.norm(loc=0, scale=phase_dev).rvs( \
3750 size=self.s.shape)
3751 mag_rv = stats.norm(loc=1, scale=mag_dev).rvs( \
3752 size=self.s.shape)
3753 self.s = mag_rv * np.exp(1j * np.pi / 180. * phase_rv) * self.s
3754
3755 def nudge(self, amount: float = 1e-12) -> Network:
3756 """
3757 Perturb s-parameters by small amount.
3758
3759 This is useful to work-around numerical bugs.
3760
3761 Parameters
3762 ----------
3763 amount : float
3764 amount to add to s parameters
3765
3766 Returns
3767 -------
3768 ntwk : :class:`Network` object
3769 Resulting renumbered Network
3770
3771
3772 Note
3773 ----
3774 This function is::
3775
3776 self.s = self.s + amount
3777
3778 """
3779 self.s = self.s + amount
3780
3781 # other
3782 def func_on_parameter(self, func: Callable, attr: str = 's', *args, **kwargs) -> Network:
3783 r"""
3784 Apply a function parameter matrix, one frequency slice at a time.
3785
3786 This is useful for functions that can only operate on 2d arrays,
3787 like numpy.linalg.inv. This loops over f and calls
3788 `func(ntwkA.s[f,:,:], \*args, \*\*kwargs)`
3789
3790 Parameters
3791 ----------
3792 func : func
3793 function to apply to s-parameters, on a single-frequency slice.
3794 (ie `func(ntwkA.s[0,:,:], \*args, \*\*kwargs)`
3795 attr: string
3796 Name of the parameter to operate on. Ex: 's', 'z', etc.
3797 Default is 's'.
3798
3799 \*args, \*\*kwargs :
3800 passed to the func
3801
3802 Returns
3803 -------
3804 ntwk : :class:`Network` object
3805 Resulting renumbered Network
3806
3807 Examples
3808 --------
3809 >>> from numpy.linalg import inv
3810 >>> ntwk.func_on_parameter(inv)
3811 """
3812 ntwkB = self.copy()
3813 p = getattr(self, attr)
3814 ntwkB.s = np.r_[[func(p[k, :, :], *args, **kwargs) \
3815 for k in range(len(p))]]
3816 return ntwkB
3817
3818 def nonreciprocity(self, m: int, n: int, normalize: bool = False) -> Network:
3819 r"""
3820 Normalized non-reciprocity metric.
3821
3822 This is a port-by-port measure of how non-reciprocal an n-port
3823 network is. It is defined by,
3824
3825 .. math::
3826
3827 (S_{mn} - S_{nm}) / \sqrt ( S_{mn} S_{nm} )
3828
3829 Parameters
3830 ----------
3831 m : int
3832 m index
3833 n : int
3834 n index
3835 normalize : bool
3836 Normalize the result. Default is False.
3837
3838 Returns
3839 -------
3840 ntwk : :class:`Network` object
3841 Resulting renumbered Network
3842
3843 """
3844 forward = getattr(self, f"s{m}_{n}")
3845 reverse = getattr(self, f"s{n}_{m}")
3846 if normalize:
3847 denom = forward * reverse
3848 denom.s = np.sqrt(denom.s)
3849 return (forward - reverse) / denom
3850 else:
3851 return (forward - reverse)
3852
3853 def s_error(self, ntwk: Network, error_function: ErrorFunctionsT = "average_l2_norm") -> np.ndarray:
3854 """
3855 Compute the error between s-parameters of this network and another network `ntwk`.
3856
3857 See `skrf.s_error()`.
3858 """
3859 return s_error(ntwkA=self, ntwkB=ntwk, error_function=error_function)
3860
3861 # generalized mixed mode transformations
3862 def se2gmm(self, p: int, z0_mm: np.ndarray = None, s_def : str = None) -> None:
3863 """
3864 Transform network from single ended parameters to generalized mixed mode parameters [#]_.
3865
3866 Parameters
3867 ----------
3868 p : int
3869 number of differential ports
3870 z0_mm : Numpy array
3871 `f x 2*p x 2*p` matrix of mixed mode impedances, optional.
3872 If input is None, 2 * z0 Ohms differential and z0 / 2 Ohms common mode
3873 reference impedance is used, where z0 is average of the differential
3874 pair ports reference impedance.
3875 Single-ended ports not converted to differential mode keep their z0.
3876 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
3877 Scattering parameter definition :
3878 None to use the definition set in the network `s_def` attribute.
3879 'power' for power-waves definition [#Kurokawa]_,
3880 'pseudo' for pseudo-waves definition [#Marks]_.
3881 All the definitions give the same result if z0 is real valued.
3882
3883 Note Odd Number of Ports
3884
3885 In the case where there are an odd number of ports (such as a 3-port network
3886 with ports 0, 1, and 2), se2gmm() assumes that the last port (port 2) remains
3887 single-ended and ports 0 and 1 are converted to differential mode and common
3888 mode, respectively. For networks in which the port ordering is not suitable,
3889 port renumbering can be used.
3890
3891 Examples
3892 --------
3893 For example, a 3-port single-ended network is converted to mixed-mode
3894 parameters::
3895
3896 | Port 0 (single-ended, 50 ohms) --> Port 0 (single-ended, 50 ohms)
3897 | Port 1 (single-ended, 50 ohms) --> Port 1 (differential mode, 100 ohms)
3898 | Port 2 (single-ended, 50 ohms) --> Port 2 (common mode, 25 ohms)
3899
3900 >>> ntwk.renumber([0,1,2], [2,1,0])
3901 >>> ntwk.se2gmm(p=1)
3902 >>> ntwk.renumber([0,1,2], [1,2,0])
3903
3904 In the resulting network, port 0 is single-ended, port 1 is
3905 differential mode, and port 2 is common mode.
3906
3907 In following examples, sx is single-mode port x, dy is
3908 differential-mode port y, and cz is common-mode port z. The low
3909 insertion loss path of a transmission line is symbolized by ==.
3910
3911 2-Port diagram::
3912
3913 +-----+ +-----+
3914 0-|s0 | 0-|d0 |
3915 | | =se2gmm=> | |
3916 1-|s1 | 1-|c0 |
3917 +-----+ +-----+
3918
3919 3-Port diagram::
3920
3921 +-----+ +-----+
3922 0-|s0 | 0-|d0 |
3923 1-|s1 | =se2gmm=> 1-|c0 |
3924 2-|s2 | 2-|s2 |
3925 +-----+ +-----+
3926
3927 Note: The port s2 remain in single-mode.
3928
3929 4-Port diagram::
3930
3931 +------+ +------+
3932 0-|s0==s2|-2 0-|d0==d1|-1
3933 | | =se2gmm=> | |
3934 1-|s1==s3|-3 2-|c0==c1|-3
3935 +------+ +------+
3936
3937 5-Port diagram::
3938
3939 +------+ +------+
3940 0-|s0==s2|-2 0-|d0==d1|-1
3941 1-|s1==s3|-3 =se2gmm=> 2-|c0==c1|-3
3942 | s4|-4 | s4|-4
3943 +------+ +------+
3944
3945 Note: The port s4 remain in single-mode.
3946
3947 8-Port diagram::
3948
3949 +------+ +------+
3950 0-|s0==s2|-2 0-|d0==d1|-1
3951 1-|s1==s3|-3 2-|d2==d3|-3
3952 | | =se2gmm=> | |
3953 4-|s4==s6|-6 4-|c0==c1|-5
3954 5-|s5==s7|-7 6-|c2==c3|-7
3955 +------+ +------+
3956
3957 2N-Port diagram::
3958
3959 A B
3960 +------------+ +-----------+
3961 0-|s0========s2|-2 0-|d0=======d1|-1
3962 1-|s1========s3|-3 2-|d2=======d3|-3
3963 ... ... =se2gmm=> ... ...
3964 2N-4-|s2N-4==s2N-2|-2N-2 2N-4-|cN-4===cN-3|-2N-3
3965 2N-3-|s2N-3==s2N-1|-2N-1 2N-2-|cN-2===cN-1|-2N-1
3966 +------------+ +-----------+
3967
3968 Note: The network `A` is not cascadable with the `**` operator
3969 along transmission path.
3970
3971 References
3972 ----------
3973 .. [#] Ferrero and Pirola; Generalized Mixed-Mode S-Parameters; IEEE Transactions on
3974 Microwave Theory and Techniques; Vol. 54; No. 1; Jan 2006
3975
3976 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
3977 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
3978
3979 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
3980 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
3981
3982 See Also
3983 --------
3984 gmm2se
3985
3986 """
3987 if 2*p > self.nports or p < 0:
3988 raise ValueError('Invalid number of differential ports')
3989
3990 self.port_modes[:p] = "D"
3991 self.port_modes[p:2 * p] = "C"
3992 if s_def is None:
3993 s_def = self.s_def
3994 if s_def != self.s_def:
3995 # Need to first renormalize to the new s_def if we have complex ports
3996 self.renormalize(self.z0, s_def)
3997 self.s_def = s_def
3998 # Assumes 'proper' order (first differential ports, then single ended ports)
3999 if z0_mm is None:
4000 z0_mm = self.z0.copy()
4001 z0_avg = 0.5*(z0_mm[:, 0:2*p:2] + z0_mm[:, 1:2*p:2])
4002 z0_mm[:, 0:p] = 2*z0_avg # differential mode impedance
4003 z0_mm[:, p:2 * p] = 0.5*z0_avg # common mode impedance
4004 else:
4005 # Make sure shape is correct
4006 # Only set mixed mode ports
4007 _z0_mm = self.z0.copy()
4008 shape = [self.z0.shape[0], 2 * p]
4009 z0_p = np.broadcast_to(z0_mm, shape)
4010 _z0_mm[:,:2*p] = z0_p
4011 z0_mm = _z0_mm
4012 Xi_tilde_11, Xi_tilde_12, Xi_tilde_21, Xi_tilde_22 = self._Xi_tilde(p, self.z0, z0_mm, s_def)
4013 A = Xi_tilde_21 + np.einsum('...ij,...jk->...ik', Xi_tilde_22, self.s)
4014 B = Xi_tilde_11 + np.einsum('...ij,...jk->...ik', Xi_tilde_12, self.s)
4015 self.s = mf.rsolve(B, A)
4016 self.z0 = z0_mm
4017
4018 def gmm2se(self, p: int, z0_se: NumberLike = None, s_def : str = None) -> None:
4019 """
4020 Transform network from generalized mixed mode parameters [#]_ to single ended parameters.
4021
4022 Parameters
4023 ----------
4024
4025 p : int
4026 number of differential ports
4027 z0_se: Numpy array
4028 `f x 2*p x 2*p` matrix of single ended impedances, optional
4029 if input is None, extract the reference impedance from the differential network
4030 calculated as 0.5 * (0.5 * z0_diff + 2 * z0_comm) for each differential port.
4031 Single-ended ports not converted to differential mode keep their z0.
4032 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
4033 Scattering parameter definition:
4034 None to use the definition set in the network `s_def` attribute.
4035 'power' for power-waves definition [#Kurokawa]_,
4036 'pseudo' for pseudo-waves definition [#Marks]_.
4037 All the definitions give the same result if z0 is real valued.
4038
4039 Examples
4040 --------
4041
4042 In following examples, sx is single-mode port x, dy is
4043 differential-mode port y, and cz is common-mode port z. The low
4044 insertion loss path of a transmission line is symbolized by ==.
4045
4046 2-Port diagram::
4047
4048 +-----+ +-----+
4049 0-|s0 | 0-|d0 |
4050 | | <=gmm2se= | |
4051 1-|s1 | 1-|c0 |
4052 +-----+ +-----+
4053
4054 3-Port diagram::
4055
4056 +-----+ +-----+
4057 0-|s0 | 0-|d0 |
4058 1-|s1 | <=gmm2se= 1-|c0 |
4059 2-|s2 | 2-|s2 |
4060 +-----+ +-----+
4061
4062 Note: The port s2 remain in single-mode.
4063
4064 4-Port diagram::
4065
4066 +------+ +------+
4067 0-|s0==s2|-2 0-|d0==d1|-1
4068 | | <=gmm2se= | |
4069 1-|s1==s3|-3 2-|c0==c1|-3
4070 +------+ +------+
4071
4072 5-Port diagram::
4073
4074 +------+ +------+
4075 0-|s0==s2|-2 0-|d0==d1|-1
4076 1-|s1==s3|-3 <=gmm2se= 2-|c0==c1|-3
4077 | s4|-4 | s4|-4
4078 +------+ +------+
4079
4080 Note: The port s4 remain in single-mode.
4081
4082 8-Port diagram::
4083
4084 +------+ +------+
4085 0-|s0==s2|-2 0-|d0==d1|-1
4086 1-|s1==s3|-3 2-|d2==d3|-3
4087 | | <=gmm2se= | |
4088 4-|s4==s6|-6 4-|c0==c1|-5
4089 5-|s5==s7|-7 6-|c2==c3|-7
4090 +------+ +------+
4091
4092 2N-Port diagram::
4093
4094 A B
4095 +------------+ +-----------+
4096 0-|s0========s2|-2 0-|d0=======d1|-1
4097 1-|s1========s3|-3 2-|d2=======d3|-3
4098 ... ... <=gmm2se= ... ...
4099 2N-4-|s2N-4==s2N-2|-2N-2 2N-4-|cN-4===cN-3|-2N-3
4100 2N-3-|s2N-3==s2N-1|-2N-1 2N-2-|cN-2===cN-1|-2N-1
4101 +------------+ +-----------+
4102
4103 Note: The network `A` is not cascadable with the `**` operator
4104 along transmission path.
4105
4106 References
4107 ----------
4108 .. [#] Ferrero and Pirola; Generalized Mixed-Mode S-Parameters; IEEE Transactions on
4109 Microwave Theory and Techniques; Vol. 54; No. 1; Jan 2006
4110
4111 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
4112 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
4113
4114 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
4115 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
4116
4117 See Also
4118 --------
4119 se2gmm
4120
4121 """
4122 if 2*p > self.nports or p < 0:
4123 raise ValueError('Invalid number of differential ports')
4124
4125 self.port_modes[:2*p] = "S"
4126 if s_def is None:
4127 s_def = self.s_def
4128 if s_def != self.s_def:
4129 # Need to first renormalize to the new s_def if we have complex ports
4130 self.renormalize(self.z0, s_def)
4131 self.s_def = s_def
4132 # Assumes 'proper' order (differential ports, single ended ports)
4133 if z0_se is None:
4134 z0_se = self.z0.copy()
4135 z0_avg = 0.5*(0.5*z0_se[:, 0:p] + 2*z0_se[:, p:2*p])
4136 z0_se[:, 0:p] = z0_avg
4137 z0_se[:, p:2 * p] = z0_avg
4138 else:
4139 # Make sure shape is correct
4140 # Only set mixed mode ports
4141 _z0_se = self.z0.copy()
4142 shape = [self.z0.shape[0], 2 * p]
4143 z0_p = np.broadcast_to(z0_se, shape)
4144 _z0_se[:,:2*p] = z0_p
4145 z0_se = _z0_se
4146 Xi_tilde_11, Xi_tilde_12, Xi_tilde_21, Xi_tilde_22 = self._Xi_tilde(p, z0_se, self.z0, s_def)
4147 A = Xi_tilde_22 - np.einsum('...ij,...jk->...ik', self.s, Xi_tilde_12)
4148 # Note that B sign is incorrect in the paper. Inverted B here gives the
4149 # correct result.
4150 B = -Xi_tilde_21 + np.einsum('...ij,...jk->...ik', self.s, Xi_tilde_11)
4151 self.s = np.linalg.solve(A, B) # (35)
4152 self.z0 = z0_se
4153
4154 # generalized mixed mode supplement functions
4155 _T = np.array([[1, 0, -1, 0], [0, 0.5, 0, -0.5], [0.5, 0, 0.5, 0], [0, 1, 0, 1]]) # (5)
4156
4157 def _m(self, z0: np.ndarray, s_def : str) -> np.ndarray:
4158 if s_def == 'pseudo':
4159 scaling = np.sqrt(z0.real) / (2 * np.abs(z0))
4160 Z = np.ones((z0.shape[0], 2, 2), dtype=np.complex128)
4161 Z[:, 0, 1] = z0
4162 Z[:, 1, 1] = -z0
4163 return scaling[:, np.newaxis, np.newaxis] * Z
4164 elif s_def == 'power':
4165 scaling = 1 / (2 * np.sqrt(z0.real))
4166 Z = np.ones((z0.shape[0], 2, 2), dtype=np.complex128)
4167 Z[:, 0, 1] = z0
4168 Z[:, 1, 1] = -z0.conj()
4169 return scaling[:, np.newaxis, np.newaxis] * Z
4170 elif s_def == 'traveling':
4171 Z = np.ones((z0.shape[0], 2, 2), dtype=np.complex128)
4172 sqrtz0 = np.sqrt(z0)
4173 Z[:, 0, 0] = 1 / sqrtz0
4174 Z[:, 0, 1] = sqrtz0
4175 Z[:, 1, 0] = 1 / sqrtz0
4176 Z[:, 1, 1] = -sqrtz0
4177 return 0.5 * Z
4178 else:
4179 raise ValueError('Unknown s_def')
4180
4181 def _M(self, j: int, k: int, z0_se: np.ndarray, s_def : str) -> np.ndarray: # (14)
4182 M = np.zeros((self.f.shape[0], 4, 4), dtype=np.complex128)
4183 M[:, :2, :2] = self._m(z0_se[:, j], s_def)
4184 M[:, 2:, 2:] = self._m(z0_se[:, k], s_def)
4185 return M
4186
4187 def _M_circle(self, l: int, p: int, z0_mm: np.ndarray, s_def : str) -> np.ndarray: # (12)
4188 M = np.zeros((self.f.shape[0], 4, 4), dtype=np.complex128)
4189 M[:, :2, :2] = self._m(z0_mm[:, l], s_def) # differential mode impedance of port pair
4190 M[:, 2:, 2:] = self._m(z0_mm[:, p + l], s_def) # common mode impedance of port pair
4191 return M
4192
4193 def _X(self,
4194 j: int,
4195 k: int ,
4196 l: int,
4197 p: int,
4198 z0_se: np.ndarray,
4199 z0_mm: np.ndarray,
4200 s_def : str) -> np.ndarray: # (15)
4201 # matrix multiplication elementwise for each frequency
4202 return np.einsum('...ij,...jk->...ik',
4203 self._M_circle(l, p, z0_mm, s_def).dot(self._T),
4204 np.linalg.inv(self._M(j, k, z0_se, s_def)))
4205 def _P(self, p: int) -> np.ndarray: # (27) (28)
4206 n = self.nports
4207
4208 Pda = np.zeros((p, 2 * n), dtype=bool)
4209 Pdb = np.zeros((p, 2 * n), dtype=bool)
4210 Pca = np.zeros((p, 2 * n), dtype=bool)
4211 Pcb = np.zeros((p, 2 * n), dtype=bool)
4212 Pa = np.zeros((n - 2 * p, 2 * n), dtype=bool)
4213 Pb = np.zeros((n - 2 * p, 2 * n), dtype=bool)
4214 for l in np.arange(p):
4215 Pda[l, 4 * (l + 1) - 3 - 1] = True
4216 Pca[l, 4 * (l + 1) - 1 - 1] = True
4217 Pdb[l, 4 * (l + 1) - 2 - 1] = True
4218 Pcb[l, 4 * (l + 1) - 1] = True
4219 for l in np.arange(n - 2 * p):
4220 Pa[l, 4 * p + 2 * (l + 1) - 1 - 1] = True
4221 Pb[l, 4 * p + 2 * (l + 1) - 1] = True
4222 return np.concatenate((Pda, Pca, Pa, Pdb, Pcb, Pb))
4223
4224 def _Q(self) -> np.ndarray: # (29) error corrected
4225 n = self.nports
4226
4227 Qa = np.zeros((n, 2 * n), dtype=bool)
4228 Qb = np.zeros((n, 2 * n), dtype=bool)
4229 for l in np.arange(n):
4230 Qa[l, 2 * (l + 1) - 1 - 1] = True
4231 Qb[l, 2 * (l + 1) - 1] = True
4232 return np.concatenate((Qa, Qb))
4233
4234 def _Xi(self, p: int, z0_se: np.ndarray, z0_mm: np.ndarray, s_def : str) -> np.ndarray: # (24)
4235 n = self.nports
4236 Xi = np.ones(self.f.shape[0])[:, np.newaxis, np.newaxis] * np.eye(2 * n, dtype=np.complex128)
4237 for l in np.arange(p):
4238 Xi[:, 4 * l:4 * l + 4, 4 * l:4 * l + 4] = self._X(l * 2, l * 2 + 1, l, p, z0_se, z0_mm, s_def)
4239 return Xi
4240
4241 def _Xi_tilde(
4242 self, p: int, z0_se: np.ndarray, z0_mm: np.ndarray, s_def: SdefT
4243 ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: # (31)
4244 n = self.nports
4245 P = np.ones(self.f.shape[0])[:, np.newaxis, np.newaxis] * self._P(p)
4246 QT = np.ones(self.f.shape[0])[:, np.newaxis, np.newaxis] * self._Q().T
4247 Xi = self._Xi(p, z0_se, z0_mm, s_def)
4248 Xi_tilde: np.ndarray = np.einsum("...ij,...jk->...ik", np.einsum("...ij,...jk->...ik", P, Xi), QT)
4249 return Xi_tilde[:, :n, :n], Xi_tilde[:, :n, n:], Xi_tilde[:, n:, :n], Xi_tilde[:, n:, n:]
4250
4251 def impulse_response(
4252 self,
4253 window: str = "hamming",
4254 n: int | None = None,
4255 pad: int = 0,
4256 bandpass: bool | None = None,
4257 squeeze: bool = True,
4258 ) -> tuple[np.ndarray, np.ndarray]:
4259 """Calculate time-domain impulse response of one-port.
4260
4261 First frequency must be 0 Hz for the transformation to be accurate and
4262 the frequency step must be uniform. Positions of the reflections are
4263 accurate even if the frequency doesn't begin from 0, but shapes will
4264 be distorted.
4265
4266 Real measurements should be extrapolated to DC and interpolated to
4267 uniform frequency spacing.
4268
4269 Y-axis is the reflection coefficient.
4270
4271 Parameters
4272 ----------
4273 window : string
4274 FFT windowing function. (Default is 'hamming')
4275 n : int
4276 Length of impulse response output.
4277 If n is not specified, 2m - 1 points are used in low-pass mode,
4278 or m points in band-pass mode, where m = len(self) + pad. (default is None).
4279 pad : int
4280 Number of zeros to add as padding for FFT.
4281 Adding more zeros improves accuracy of peaks. (Default is 0)
4282 bandpass : bool or None
4283 If False window function is center on 0 Hz.
4284 If True full window is used and low frequencies are attenuated.
4285 If None value is determined automatically based on if the
4286 frequency vector begins from 0. (Default is None)
4287 squeeze: bool
4288 Squeeze impulse response to one dimension,
4289 if a oneport gets transformed.
4290 Has no effect when transforming a multiport.
4291 (Default is True)
4292
4293 Returns
4294 -------
4295 t : class:`np.ndarray`
4296 Time vector
4297 y : class:`np.ndarray`
4298 Impulse response
4299
4300 See Also
4301 --------
4302 step_response
4303 extrapolate_to_dc
4304 """
4305 if bandpass is None:
4306 bandpass = self.f[0] != 0
4307
4308 t = self.frequency._t_padded(pad=pad, n=n, bandpass=bandpass)
4309 n = len(t)
4310
4311 if window is not None:
4312 w = self.windowed(window=window, normalize=False, center_to_dc=not bandpass)
4313 else:
4314 w = self
4315
4316 if bandpass:
4317 ir = np.fft.fftshift(np.fft.ifft(w.s, axis=0, n=n), axes=0)
4318 else:
4319 ir = np.fft.fftshift(np.fft.irfft(w.s, axis=0, n=n), axes=0)
4320
4321 if squeeze:
4322 ir = ir.squeeze()
4323
4324 return t, ir
4325
4326 def step_response(
4327 self, window: str = "hamming", n: int | None = None, pad: int = 0, squeeze: bool = True
4328 ) -> tuple[np.ndarray, np.ndarray]:
4329 """Calculate time-domain step response of one-port.
4330
4331 First frequency must be 0 Hz for the transformation to be accurate and
4332 the frequency step must be uniform.
4333
4334 Real measurements should be extrapolated to DC and interpolated to
4335 uniform frequency spacing.
4336
4337 Y-axis is the reflection coefficient.
4338 `step_resonse` is equal to the cumulative trapezoid integration of the
4339 `impulse_response` function.
4340
4341 Parameters
4342 ----------
4343 window : string
4344 FFT windowing function. (Default is 'hamming')
4345 n : int
4346 Length of step response output.
4347 If n is not specified, 2m - 1 points are used in low-pass mode
4348 where m = len(self) + pad. (default is None).
4349 pad : int
4350 Number of zeros to add as padding for FFT.
4351 Adding more zeros improves accuracy of peaks. (Default is 0)
4352 squeeze: bool
4353 Squeeze step response to one dimension,
4354 if a oneport gets transformed.
4355 Has no effect when transforming a multiport.
4356 (Default is True)
4357
4358 Returns
4359 -------
4360 t : class:`np.ndarray`
4361 Time vector
4362 y : class:`np.ndarray`
4363 Step response
4364
4365 Raises
4366 ------
4367 ValueError
4368 If used with an Network with more than one port
4369
4370 NotImplementedError
4371 If used with non equidistant sampled frequency vector
4372
4373 See Also
4374 --------
4375 impulse_response
4376 extrapolate_to_dc
4377 """
4378 if self.frequency.sweep_type != 'lin':
4379 raise NotImplementedError(
4380 'Unable to transform non equidistant sampled points to time domain')
4381
4382 if self.frequency.f[0] != 0:
4383 warnings.warn(
4384 "Frequency doesn't begin from 0. Step response will not be correct.",
4385 RuntimeWarning, stacklevel=2
4386 )
4387
4388 t, y = self.impulse_response(window=window, n=n, pad=pad, bandpass=False, squeeze=squeeze)
4389 return t, cumulative_trapezoid(y, initial=0, axis=0)
4390
4391 # Network Active s/z/y/vswr parameters
4392 def s_active(self, a: np.ndarray) -> np.ndarray:
4393 r"""
4394 Returns the active s-parameters of the network for a defined wave excitation a.
4395
4396 The active s-parameter at a port is the reflection coefficients
4397 when other ports are excited. It is an important quantity for active
4398 phased array antennas.
4399
4400 Active s-parameters are defined by [#]_:
4401
4402 .. math::
4403
4404 \mathrm{active(s)}_{m} = \sum_{i=1}^N s_{mi}\frac{a_i}{a_m}
4405
4406 where :math:`s` are the scattering parameters and :math:`N` the number of ports
4407
4408 Parameters
4409 ----------
4410 a : complex array of shape (n_ports)
4411 forward wave complex amplitude (pseudowave formulation [#]_)
4412
4413 Returns
4414 -------
4415 s_act : complex array of shape (n_freqs, n_ports)
4416 active S-parameters for the excitation a
4417
4418 See Also
4419 --------
4420 z_active : active Z-parameters
4421 y_active : active Y-parameters
4422 vswr_active : active VSWR
4423
4424 References
4425 ----------
4426 .. [#] D. M. Pozar, IEEE Trans. Antennas Propag. 42, 1176 (1994).
4427
4428 .. [#] D. Williams, IEEE Microw. Mag. 14, 38 (2013).
4429
4430 """
4431 return s2s_active(self.s, a)
4432
4433 def z_active(self, a: np.ndarray) -> np.ndarray:
4434 r"""
4435 Return the active Z-parameters of the network for a defined wave excitation a.
4436
4437 The active Z-parameters are defined by:
4438
4439 .. math::
4440
4441 \mathrm{active}(z)_{m} = z_{0,m} \frac{1 + \mathrm{active}(s)_m}{1 - \mathrm{active}(s)_m}
4442
4443 where :math:`z_{0,m}` is the characteristic impedance and
4444 :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
4445
4446 Parameters
4447 ----------
4448 a : complex array of shape (n_ports)
4449 forward wave complex amplitude
4450
4451 Returns
4452 -------
4453 z_act : complex array of shape (nfreqs, nports)
4454 active Z-parameters for the excitation a
4455
4456 See Also
4457 --------
4458 s_active : active S-parameters
4459 y_active : active Y-parameters
4460 vswr_active : active VSWR
4461 """
4462 return s2z_active(self.s, self.z0, a)
4463
4464 def y_active(self, a: np.ndarray) -> np.ndarray:
4465 r"""
4466 Return the active Y-parameters of the network for a defined wave excitation a.
4467
4468 The active Y-parameters are defined by:
4469
4470 .. math::
4471
4472 \mathrm{active}(y)_{m} = y_{0,m} \frac{1 - \mathrm{active}(s)_m}{1 + \mathrm{active}(s)_m}
4473
4474 where :math:`y_{0,m}` is the characteristic admittance and
4475 :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
4476
4477 Parameters
4478 ----------
4479 a : complex array of shape (n_ports)
4480 forward wave complex amplitude
4481
4482 Returns
4483 -------
4484 y_act : complex array of shape (nfreqs, nports)
4485 active Y-parameters for the excitation a
4486
4487 See Also
4488 --------
4489 s_active : active S-parameters
4490 z_active : active Z-parameters
4491 vswr_active : active VSWR
4492 """
4493 return s2y_active(self.s, self.z0, a)
4494
4495 def vswr_active(self, a: np.ndarray) -> np.ndarray:
4496 r"""
4497 Return the active VSWR of the network for a defined wave excitation a.
4498
4499 The active VSWR is defined by :
4500
4501 .. math::
4502
4503 \mathrm{active}(vswr)_{m} = \frac{1 + |\mathrm{active}(s)_m|}{1 - |\mathrm{active}(s)_m|}
4504
4505 where :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
4506
4507 Parameters
4508 ----------
4509 a : complex array of shape (n_ports)
4510 forward wave complex amplitude
4511
4512 Returns
4513 -------
4514 vswr_act : complex array of shape (nfreqs, nports)
4515 active VSWR for the excitation a
4516
4517 See Also
4518 --------
4519 s_active : active S-parameters
4520 z_active : active Z-parameters
4521 y_active : active Y-parameters
4522 """
4523 return s2vswr_active(self.s, a)
4524
4525 def stability_circle(self, target_port: int, npoints: int = 181) -> np.ndarray:
4526 r"""
4527 Returns loci of stability circles for a given port (0 or 1). The network must have two ports.
4528 The center and radius of the load (here target_port=1) stability circle are calculated by the following equation
4529 [#]_.
4530
4531 .. math::
4532
4533 C_{L} = \frac{(S_{22} - DS_{11}^*)^*}{|S_{22}|^{2} - |D|^{2}}
4534
4535 R_{L} = |\frac{S_{12}S_{21}}{|S_{22}|^2 - |D|^{2}}|
4536
4537 with
4538
4539 D = S_{11} S_{22} - S_{12} S_{21}
4540
4541 Similarly, those of the source side (here target_port=0) are calculated by the following equations.
4542
4543 .. math::
4544
4545 C_{S} = \frac{(S_{11} - DS_{22}^*)^*}{|S_{11}|^{2} - |D|^{2}}
4546
4547 R_{S} = |\frac{S_{12}S_{21}}{|S_{11}|^2 - |D|^{2}}|
4548
4549 Parameters
4550 ----------
4551 target_port : int
4552 Specifies the port number (0 or 1) to calculate stability circles.
4553 npoints : int, optional
4554 The number of points on the circumference of the circle.
4555 More points result in a smoother circle, but require more computation. Default is 181.
4556
4557 Returns
4558 -------
4559 sc : :class:`numpy.ndarray` (shape is `npoints x f`)
4560 Loci of stability circles in complex numbers
4561
4562 Example
4563 --------
4564 >>> import skrf as rf
4565 >>> import matplotlib.pyplot as plt
4566
4567 Create a two-port network object
4568
4569 >>> ntwk = rf.Network('fet.s2p')
4570
4571 Calculate the load stability circles for all the frequencies
4572
4573 >>> lsc = ntwk.stability_circle(target_port=1)
4574
4575 Plot the circles on the smith chart
4576
4577 >>> rf.plotting.plot_smith(s=lsc, smith_r=5, marker='o')
4578 >>> plt.show()
4579
4580 Slicing the network allows you to specify a frequency
4581
4582 >>> lsc = ntwk['1GHz'].stability_circle(target_port=1)
4583 >>> rf.plotting.plot_smith(s=lsc, smith_r=5, marker='o')
4584 >>> plt.show()
4585
4586 References
4587 ----------
4588 .. [#] David. M. Pozar, "Microwave Engineering, Fourth Edition," Wiley, p. 566, 2011.
4589
4590 See Also
4591 --------
4592 gain_circle
4593 nf_circle
4594 stability
4595
4596 """
4597
4598 if self.nports != 2:
4599 raise ValueError("Stability circle is only defined for two ports")
4600
4601 if npoints <= 0:
4602 raise ValueError("npoints must be a positive integer")
4603
4604 # Calculate the determinant of the scattering matrix
4605 D = self.s[:, 0, 0] * self.s[:, 1, 1] - self.s[:, 0, 1] * self.s[:, 1, 0]
4606
4607 # Calculate the center and radius of the stability circle
4608 if target_port == 1:
4609 sc_center = ((self.s[:, 1, 1] - self.s[:, 0, 0].conjugate() * D).conjugate()
4610 / (np.abs(self.s[:, 1, 1]) ** 2 - np.abs(D) ** 2))
4611 sc_radius = np.abs(self.s[:, 0, 1] * self.s[:, 1, 0]
4612 / (np.abs(self.s[:, 1, 1] ) ** 2 - np.abs(D) ** 2))
4613 elif target_port == 0:
4614 sc_center = ((self.s[:, 0, 0] - self.s[:, 1, 1].conjugate() * D).conjugate()
4615 / (np.abs(self.s[:, 0, 0]) ** 2 - np.abs(D) ** 2))
4616 sc_radius = np.abs(self.s[:, 0, 1] * self.s[:, 1, 0]
4617 / (np.abs(self.s[:, 0, 0] ) ** 2 - np.abs(D) ** 2))
4618 else:
4619 raise ValueError("Invalid target_port. Specify 0 or 1.")
4620
4621 # Generate theta values for the points on the circle
4622 theta = np.linspace(0, 2 * np.pi, npoints)
4623
4624 # Calculate real and imaginary parts of points on the load stability circle
4625 sc_real = np.outer(sc_center.real, np.ones(npoints)) + np.outer(sc_radius, np.cos(theta))
4626 sc_imag = np.outer(sc_center.imag, np.ones(npoints)) + np.outer(sc_radius, np.sin(theta))
4627
4628 # Combine real and imaginary parts to create the load stability circle
4629 sc = (sc_real + 1j * sc_imag).T
4630 return sc
4631
4632 def gain_circle(self, target_port: int, gain: float, npoints: int = 181) -> np.ndarray:
4633 r"""
4634 Returns loci of gain circles for a given port (0 or 1) and a specified gain. The network must have two ports.
4635 The center and radius of the source (here target_port=0) gain circle are calculated by the following equations
4636 [#]_ [#]_.
4637
4638 .. math::
4639
4640 C_{S} = \frac{g_{S}S_{11}^*}{1 - (1 - g_{S})|S_{11}|^{2}}
4641
4642 R_{S} = |\frac{\sqrt{(1 - g_{S})}(1 - |S_{11}|^{2})}{1 - (1 - g_{S})|S_{11}|^{2}}
4643
4644 where :math:`g_{S}` is obtained by normalizing the specified gain by the maximum gain of the source
4645 matching network :math:`G_{Smax}`
4646
4647 .. math::
4648
4649 g_{S} = \frac{gain}{G_{Smax}} = gain * (1 - |S_{11}|^{2})
4650
4651 Similarly, those of the load side (here target_port=1) are calculated by the following equations.
4652
4653 .. math::
4654
4655 C_{L} = \frac{g_{L}S_{22}^*}{1 - (1 - g_{L})|S_{22}|^{2}}
4656
4657 R_{L} = |\frac{\sqrt{(1 - g_{L})}(1 - |S_{22}|^{2})}{1 - (1 - g_{L})|S_{22}|^{2}}
4658
4659 with
4660
4661 g_{L} = \frac{gain}{G_{Lmax}} = gain * (1 - |S_{22}|^{2})
4662
4663 Parameters
4664 ----------
4665 target_port : int
4666 Specifies the port number (0 or 1) to calculate gain circles.
4667 gain : float
4668 Gain of source or load matching network in decibels.
4669 npoints : int, optional
4670 The number of points on the circumference of the circle.
4671 More points result in a smoother circle, but require more computation. Default is 181.
4672
4673 Returns
4674 -------
4675 gc : :class:`numpy.ndarray` (shape is `npoints x f`)
4676 Loci of gain circles in complex numbers
4677
4678 Example
4679 --------
4680 >>> import skrf as rf
4681 >>> import matplotlib.pyplot as plt
4682
4683 Create a two-port network object
4684
4685 >>> ntwk = rf.Network('fet.s2p')
4686
4687 Calculate the source gain circles for all the frequencies at a gain of 2 dB
4688
4689 >>> sgc = ntwk.gain_circle(target_port=0, gain=2.0)
4690
4691 Plot the circles on the smith chart
4692
4693 >>> rf.plotting.plot_smith(s=sgc, smith_r=1, marker='o')
4694 >>> plt.show()
4695
4696 Slicing the network allows you to specify a frequency
4697
4698 >>> sgc = ntwk['1GHz'].gain_circle(target_port=0, gain=2.0)
4699 >>> rf.plotting.plot_smith(s=sgc, smith_r=1, marker='o')
4700 >>> plt.show()
4701
4702 References
4703 ----------
4704 .. [#] David. M. Pozar, "Microwave Engineering, Fourth Edition," Wiley, p. 576, 2011.
4705 .. [#] https://www.allaboutcircuits.com/technical-articles/designing-a-unilateral-rf-amplifier-for-a-specified-gain/
4706
4707 See Also
4708 --------
4709 stability_circle
4710 nf_circle
4711 max_gain : Maximum available and stable power gain
4712 max_stable_gain : Maximum stable power gain
4713 unilateral_gain : Mason's unilateral power gain
4714
4715 """
4716
4717 if self.nports != 2:
4718 raise ValueError("Gain circles are defined only for two-port networks")
4719
4720 if npoints <= 0:
4721 raise ValueError("npoints must be a positive integer")
4722
4723 # Calculate the center and radius of the gain circle
4724 if target_port == 0:
4725 reflection = self.s[:, 0, 0]
4726 elif target_port == 1:
4727 reflection = self.s[:, 1, 1]
4728 else:
4729 raise ValueError("Invalid target_port. Specify 0 or 1.")
4730
4731 gain_factor = mf.db10_2_mag(gain) * (1 - np.abs(reflection) ** 2)
4732 if np.any(gain_factor > 1):
4733 warnings.warn("The specified gain is greater than the maximum gain achievable by the matching network. "
4734 "Specify a smaller gain.", RuntimeWarning, stacklevel=2)
4735 gain_factor = np.minimum(gain_factor, 1)
4736 gc_center = gain_factor * reflection.conjugate() / (1 - (1 - gain_factor) * np.abs(reflection) ** 2)
4737 gc_radius = (np.sqrt(1 - gain_factor) * (1 - np.abs(reflection) ** 2)
4738 / (1 - (1 - gain_factor) * np.abs(reflection) ** 2))
4739
4740 # Generate theta values for the points on the circle
4741 theta = np.linspace(0, 2 * np.pi, npoints)
4742
4743 # Calculate real and imaginary parts of points on the gain circle
4744 gc_real = np.outer(gc_center.real, np.ones(npoints)) + np.outer(gc_radius, np.cos(theta))
4745 gc_imag = np.outer(gc_center.imag, np.ones(npoints)) + np.outer(gc_radius, np.sin(theta))
4746
4747 # Combine real and imaginary parts to create the load gain circle
4748 gc = (gc_real + 1j * gc_imag).T
4749 return gc
4750
4751 def nf_circle(self, nf: float, npoints: int = 181) -> np.ndarray:
4752 r"""
4753 Returns loci of noise figure circles for a specified noise figure. The network must have two ports and noise
4754 data. The center and radius of the noise figure circle are calculated by the following equations [#]_.
4755
4756 .. math::
4757
4758 C_{F} = \frac{\Gamma_{opt}}{N + 1}
4759
4760 .. math::
4761
4762 R_{F} = \frac{\sqrt{N(N +1 - |\Gamma_{opt}|^2)}}{N + 1}
4763
4764 where :math:`N` is the noise figure parameter defined by
4765
4766 .. math::
4767
4768 N = \frac{|\Gamma_{s}-\Gamma_{opt}|^2}{1-|\Gamma_{s}|^2} = \frac{F-F_{min}}{4R_{N}/Z_{0}}|1+\Gamma_{opt}|^2
4769
4770
4771 Parameters
4772 ----------
4773 nf : float
4774 Noise figure of network in decibels.
4775 npoints : int, optional
4776 The number of points on the circumference of the circle.
4777 More points result in a smoother circle, but require more computation. Default is 181.
4778
4779 Returns
4780 -------
4781 nfc : :class:`numpy.ndarray` (shape is `npoints x f`)
4782 Loci of noise figure circles in complex numbers
4783
4784 Example
4785 --------
4786 >>> import skrf as rf
4787 >>> import matplotlib.pyplot as plt
4788
4789 Create a two-port network object
4790
4791 >>> ntwk = rf.Network('ntwk_noise.s2p')
4792
4793 Calculate the noise figure circles for all the frequencies at a noise figure of 1 dB
4794
4795 >>> nfc = ntwk.nf_circle(nf=1.0)
4796
4797 Plot the circles on the smith chart
4798
4799 >>> rf.plotting.plot_smith(s=nfc, smith_r=1, marker='o')
4800 >>> plt.show()
4801
4802 Slicing the network allows you to specify a frequency
4803
4804 >>> nfc = ntwk['1GHz'].nf_circle(nf=1.0)
4805 >>> rf.plotting.plot_smith(s=nfc, smith_r=1, marker='o')
4806 >>> plt.show()
4807
4808 References
4809 ----------
4810 .. [#] David. M. Pozar, "Microwave Engineering, Fourth Edition," Wiley, p. 580, 2011.
4811
4812 See Also
4813 --------
4814 stability_circle
4815 gain_circle
4816 g_opt: The optimum source reflection coefficient to minimize noise.
4817 nfmin : The minimum noise figure of the network.
4818 nfmin_db : The minimum noise figure for the network in dB.
4819 rn : The equivalent noise resistance of the network.
4820
4821 """
4822 if self.nports != 2:
4823 raise ValueError("Noise figure circles are defined only for two-port networks")
4824
4825 if npoints <= 0:
4826 raise ValueError("npoints must be a positive integer")
4827
4828 if not self.noisy:
4829 raise ValueError("Network must have noise data")
4830
4831 if nf < self.nfmin_db.any():
4832 warnings.warn("The specified noise figure is less than the minimum achievable by the matching network. "
4833 "Specify a larger noise figure.", RuntimeWarning, stacklevel=2)
4834
4835 # Compute noise figure circle center and radius
4836 N = np.abs(1+self.g_opt)**2 * (10**(nf/10) - self.nfmin) / (4*self.rn / self.z0[0, 0])
4837 nfc_center = self.g_opt / (N + 1)
4838 nfc_radius = np.sqrt(N*(N + 1 - abs(self.g_opt) ** 2)) / (N + 1)
4839
4840 # Generate theta values for the points on the circle
4841 theta = np.linspace(0, 2 * np.pi, npoints)
4842
4843 # Calculate real and imaginary parts of points on the noise figure circle
4844 nfc_real = np.outer(nfc_center.real, np.ones(npoints)) + np.outer(nfc_radius, np.cos(theta))
4845 nfc_imag = np.outer(nfc_center.imag, np.ones(npoints)) + np.outer(nfc_radius, np.sin(theta))
4846
4847 # Combine real and imaginary parts to create the noise figure circle
4848 nfc = (nfc_real + 1j * nfc_imag).T
4849 return nfc
4850
4851 _plot_attribute_doc = r"""
4852 plot the Network attribute :attr:`{attribute}_{conversion}` component vs {x_axis}.
4853
4854 Parameters
4855 ----------
4856 m : int, optional
4857 first index of s-parameter matrix, if None will use all
4858 n : int, optional
4859 second index of the s-parameter matrix, if None will use all
4860 ax : :class:`matplotlib.Axes` object, optional
4861 An existing Axes object to plot on
4862 show_legend : Boolean
4863 draw legend or not
4864 y_label : string, optional
4865 the y-axis label
4866 logx : Boolean, optional
4867 Enable logarithmic x-axis, default off
4868 \**kwargs : arguments, keyword arguments
4869 passed to :func:`matplotlib.plot`
4870
4871 Note
4872 ----
4873 This function is dynamically generated upon Network
4874 initialization. This is accomplished by calling
4875 :func:`Network.plot_attribute`
4876
4877 Examples
4878 --------
4879 >>> myntwk.plot_{attribute}_{conversion}(m=1,n=0,color='r')
4880
4881 """
4882
4883 @axes_kwarg
4884 def plot_attribute( self,
4885 attribute: PrimaryPropertiesT,
4886 conversion: ComponentFuncT,
4887 m=None,
4888 n=None,
4889 ax: Axes=None,
4890 show_legend=True,
4891 y_label=None,
4892 logx=False, **kwargs):
4893
4894 # create y_label if not provided
4895 if y_label is None:
4896 y_label = Network.Y_LABEL_DICT[conversion]
4897 # create index lists, if not provided by user
4898 if m is None:
4899 M = range(self.number_of_ports)
4900 else:
4901 M = [m]
4902 if n is None:
4903 N = range(self.number_of_ports)
4904 else:
4905 N = [n]
4906
4907 if 'label' not in kwargs.keys():
4908 gen_label = True
4909 else:
4910 gen_label = False
4911
4912 if conversion in ["time_impulse", "time_step"]:
4913 xlabel = "Time (ns)"
4914
4915 t_func_kwargs = {"squeeze": False}
4916 for key in {"window", "n", "pad", "bandpass"} & kwargs.keys():
4917 t_func_kwargs[key] = kwargs.pop(key)
4918
4919 if conversion == "time_impulse":
4920 x, y = self.impulse_response(**t_func_kwargs)
4921 else:
4922 x, y = self.step_response(**t_func_kwargs)
4923
4924 if attribute[0].lower() == "z":
4925 y_label = "Z (Ohm)"
4926 y[y == 1.] = 1. - 1e-12 # solve numerical singularity
4927 y = self.z0[0].real * (1+y) / (1-y)
4928
4929 for m in M:
4930 for n in N:
4931 # set the legend label for this trace to the networks
4932 # name if it exists, and they didn't pass a name key in
4933 # the kwargs
4934 if gen_label:
4935 kwargs['label'] = rfplt._get_label_str(self, attribute[0].upper(), m, n)
4936
4937 if conversion in ["time_impulse", "time_step"]:
4938 rfplt.plot_rectangular(x=x * 1e9,
4939 y=y[:, m, n],
4940 x_label=xlabel,
4941 y_label=y_label,
4942 show_legend=show_legend, ax=ax,
4943 **kwargs)
4944
4945 else:
4946 # plot the desired attribute vs frequency
4947 if "time" in conversion:
4948 xlabel = 'Time (ns)'
4949 x = self.frequency.t_ns
4950 y=self.attribute(attribute, conversion)[:, m, n]
4951 if conversion in ["time_mag", "time"]:
4952 y = np.abs(y)
4953
4954 else:
4955 xlabel = f'Frequency ({self.frequency.unit})'
4956 # x = self.frequency.f_scaled
4957 x = self.frequency.f # always plot f, and then scale the ticks instead
4958 y = self.attribute(attribute, conversion)[:, m, n]
4959
4960 # scale the ticklabels according to the frequency unit and set log-scale if desired:
4961 if logx:
4962 ax.set_xscale('log')
4963
4964 rfplt.scale_frequency_ticks(ax, self.frequency.unit)
4965
4966
4967
4968 rfplt.plot_rectangular(x=x,
4969 y=y,
4970 x_label=xlabel,
4971 y_label=y_label,
4972 show_legend=show_legend, ax=ax,
4973 **kwargs)
4974
4975 plot_attribute.__doc__ = _plot_attribute_doc.format(
4976 attribute="conversion",
4977 conversion="attribute",
4978 x_axis="frequency or time")
4979
4980 @copy_doc(rfplt.plot)
4981 def plot(self, *args, **kwargs):
4982 return rfplt.plot(self, *args, **kwargs)
4983
4984 @copy_doc(rfplt.plot_passivity)
4985 def plot_passivity(self, port=None, label_prefix=None, *args, **kwargs):
4986 return rfplt.plot_passivity(self, port, label_prefix, *args, **kwargs)
4987
4988 @copy_doc(rfplt.plot_reciprocity)
4989 def plot_reciprocity(self, db=False, *args, **kwargs):
4990 return rfplt.plot_reciprocity(self, db, *args, **kwargs)
4991
4992 @copy_doc(rfplt.plot_reciprocity2)
4993 def plot_reciprocity2(self, db=False, *args, **kwargs):
4994 return rfplt.plot_reciprocity2(self, db, *args, **kwargs)
4995
4996 @copy_doc(rfplt.plot_s_db_time)
4997 def plot_s_db_time(self, center_to_dc=None, *args, **kwargs):
4998 return rfplt.plot_s_db_time(self, *args, center_to_dc=center_to_dc, **kwargs)
4999
5000 @copy_doc(rfplt.plot_s_smith)
5001 def plot_s_smith(self, m=None, n=None,r=1, ax=None, show_legend=True,\
5002 chart_type='z', draw_labels=False, label_axes=False, draw_vswr=None, *args,**kwargs):
5003 return rfplt.plot_s_smith(self, m, n, r, ax, show_legend, chart_type,
5004 draw_labels, label_axes, draw_vswr, *args, **kwargs)
5005
5006 @copy_doc(rfplt.plot_it_all)
5007 def plot_it_all(self, *args, **kwargs):
5008 return rfplt.plot_it_all(self, *args, **kwargs)
5009
5010 @copy_doc(rfplt.plot_prop_complex)
5011 def plot_prop_complex(self, *args, **kwargs):
5012 return rfplt.plot_prop_complex(self, *args, **kwargs)
5013
5014 @copy_doc(rfplt.plot_prop_polar)
5015 def plot_prop_polar(self, *args, **kwargs):
5016 return rfplt.plot_prop_polar(self, *args, **kwargs)
5017
5018 def _fmt_trace_name(self, m: int, n: int) -> str:
5019 port_sep = "_" if self.nports > 9 else ""
5020 subscript = f"{self.port_modes[m].lower()}{self.port_modes[n].lower()}"
5021 # do not add subscript for single-ended to single-ended
5022 subscript = "" if subscript == "ss" else subscript
5023
5024 return f"{subscript}{m + 1}{port_sep}{n + 1}"
5025
5026
5027 for func_name, (_func, prop_name, conversion) in Network._generated_functions().items():
5028
5029 func_name = f"{prop_name}_{conversion}"
5030 doc = f"""
5031 The {conversion} component of the {prop_name}-matrix.
5032
5033 See Also
5034 --------
5035 {prop_name}
5036 """
5037
5038 setattr(Network, func_name, property(
5039 fget=lambda self,
5040 prop_name=prop_name,
5041 conversion=conversion:
5042
5043 self.attribute(prop_name, conversion), doc=doc))
5044
5045 for func_name, (_func, prop_name, conversion) in Network._generated_functions().items():
5046 plotfunc = partial_with_docs(Network.plot_attribute, prop_name, conversion)
5047 plotfunc.__doc__ = Network._plot_attribute_doc.format(
5048 attribute=prop_name,
5049 conversion=conversion,
5050 x_axis="time" if "time" in conversion else "frequency")
5051
5052 setattr(Network, f"plot_{func_name}", plotfunc)
5053
5054
5055 for prop_name in Network.PRIMARY_PROPERTIES:
5056 setattr(Network, f"plot_{prop_name}_polar", partial_with_docs(Network.plot_prop_polar, prop_name))
5057 setattr(Network, f"plot_{prop_name}_complex", partial_with_docs(Network.plot_prop_complex, prop_name))
5058
5059 COMPONENT_FUNC_DICT = Network.COMPONENT_FUNC_DICT
5060 PRIMARY_PROPERTIES = Network.PRIMARY_PROPERTIES
5061 Y_LABEL_DICT = Network.Y_LABEL_DICT
5062
5063 ## Functions operating on Network[s]
5064 def connect(ntwkA: Network, k: int, ntwkB: Network, l: int, num: int = 1) -> Network:
5065 """
5066 Connect two n-port networks together.
5067
5068 Connect ports `k` thru `k+num-1` on `ntwkA` to ports
5069 `l` thru `l+num-1` on `ntwkB`. The resultant network has
5070 (ntwkA.nports+ntwkB.nports-2*num) ports. The port indices ('k','l')
5071 start from 0. Port impedances **are** taken into account.
5072 When the two networks have overlapping frequencies, the resulting
5073 network will contain only the overlapping frequencies.
5074
5075
5076 Note
5077 ----
5078 The effect of mis-matched port impedances is handled by inserting
5079 a 2-port 'mismatch' network between the two connected ports.
5080 This mismatch Network is calculated with the
5081 :func:`impedance_mismatch` function.
5082
5083
5084 Parameters
5085 ----------
5086 ntwkA : :class:`Network`
5087 network 'A'
5088 k : int
5089 starting port index on `ntwkA` ( port indices start from 0 )
5090 ntwkB : :class:`Network`
5091 network 'B'
5092 l : int
5093 starting port index on `ntwkB`
5094 num : int
5095 number of consecutive ports to connect (default 1)
5096
5097
5098 Returns
5099 -------
5100 ntwkC : :class:`Network`
5101 new network of rank (ntwkA.nports + ntwkB.nports - 2*num)
5102
5103
5104 See Also
5105 --------
5106 connect_s : actual S-parameter connection algorithm.
5107 innerconnect_s : actual S-parameter connection algorithm.
5108 innerconnect_s_lstsq : actual S-parameter connection algorithm using lstsq.
5109
5110
5111 Examples
5112 --------
5113 To implement a *cascade* of two networks
5114
5115 >>> ntwkA = rf.Network('ntwkA.s2p')
5116 >>> ntwkB = rf.Network('ntwkB.s2p')
5117 >>> ntwkC = rf.connect(ntwkA, 1, ntwkB,0)
5118
5119 """
5120 # some checking
5121 try:
5122 check_frequency_equal(ntwkA, ntwkB)
5123 except IndexError as e:
5124 common_freq = np.intersect1d(ntwkA.frequency.f, ntwkB.frequency.f, return_indices=True)
5125 if common_freq[0].size == 0:
5126 raise e
5127 else:
5128 ntwkA = ntwkA[common_freq[1]]
5129 ntwkB = ntwkB[common_freq[2]]
5130 warnings.warn("Using a frequency subset:\n" + str(ntwkA.frequency), stacklevel=2)
5131
5132 if (k + num - 1 > ntwkA.nports - 1):
5133 raise IndexError('Port `k` out of range')
5134 if (l + num - 1 > ntwkB.nports - 1):
5135 raise IndexError('Port `l` out of range')
5136
5137 # create port_names if required
5138 if ntwkB.port_names is None:
5139 if ntwkA.port_names is not None:
5140 ntwkB = ntwkB.copy()
5141 ntwkB.port_names = [str(x) for x in range(ntwkB.nports)]
5142
5143 have_complex_ports = (ntwkA.z0.imag != 0).any() or (ntwkB.z0.imag != 0).any()
5144
5145 # If definitions aren't identical and there are complex ports renormalize first
5146 # Output will have ntwkA s_def if they are different.
5147 if ntwkA.s_def != ntwkB.s_def and have_complex_ports:
5148 warnings.warn('Connecting two networks with different s_def and complex ports. '
5149 'The resulting network will have s_def of the first network: ' + ntwkA.s_def + '. '\
5150 'To silence this warning explicitly convert the networks to same s_def '
5151 'using `renormalize` function.', stacklevel=2)
5152 ntwkB = ntwkB.copy()
5153 ntwkB.renormalize(ntwkB.z0, ntwkA.s_def)
5154
5155 s_def_original = ntwkA.s_def
5156 if ntwkA.s_def == 'power' and have_complex_ports:
5157 # When port impedance is complex, power-waves are discontinuous across
5158 # a junction between two identical transmission lines while traveling
5159 # waves and pseudo-waves are continuous. The connection algorithm relies
5160 # on continuity and 'power' networks must be first converted to either
5161 # of the other definition.
5162 ntwkA = ntwkA.copy()
5163 ntwkA.renormalize(ntwkA.z0, 'pseudo')
5164 ntwkB = ntwkB.copy()
5165 ntwkB.renormalize(ntwkB.z0, 'pseudo')
5166
5167 s_def = ntwkA.s_def
5168 if s_def == 'power':
5169 # Ports are real. Save some time by not copying the networks
5170 # and use the definition that works with real ports
5171 s_def = 'traveling'
5172
5173 # create output Network, from copy of input
5174 # Since ntwkC's s-parameters will change later, use shallow_copy for speedup
5175 ntwkC = ntwkA.copy(shallow_copy=True)
5176
5177 # if networks' z0's are not identical, then connect a impedance
5178 # mismatch, which takes into account the effect of differing port
5179 # impedances.
5180 # import pdb;pdb.set_trace()
5181 z0_equal = assert_z0_at_ports_equal(ntwkA, k, ntwkB, l)
5182 if not z0_equal:
5183 # connect a impedance mismatch, which will takes into account the
5184 # effect of differing port impedances
5185 mismatch = impedance_mismatch(ntwkA.z0[:, k], ntwkB.z0[:, l], s_def)
5186 ntwkC.s = connect_s(ntwkA.s, k, mismatch, 0, num=-1)
5187 # the connect_s() put the mismatch's output port at the end of
5188 # ntwkC's ports. Fix the new port's impedance, then insert it
5189 # at position k where it belongs.
5190 ntwkC.z0[:, k:] = np.hstack((ntwkC.z0[:, k + 1:], ntwkB.z0[:, [l]]))
5191 ntwkC.renumber(from_ports=[ntwkC.nports - 1] + list(range(k, ntwkC.nports - 1)),
5192 to_ports=list(range(k, ntwkC.nports)))
5193 # call s-matrix connection function
5194 ntwkC.s = connect_s(ntwkC.s if not z0_equal else ntwkA.s, k, ntwkB.s, l, num)
5195
5196 # combine z0 and port_names arrays and remove ports which were `connected`
5197 ntwkC.z0 = np.hstack(
5198 (np.delete(ntwkA.z0, range(k, k + 1), 1), np.delete(ntwkB.z0, range(l, l + 1), 1)))
5199 if ntwkA.port_names is not None:
5200 ntwkC.port_names = np.concatenate(
5201 (np.delete(ntwkA.port_names, k), np.delete(ntwkB.port_names, l)))
5202
5203 # if we're connecting more than one port, call innerconnect recursively
5204 # until all connections are made to finish the job
5205 if num > 1:
5206 ntwkC = innerconnect(ntwkC, k, ntwkA.nports - 1 + l, num - 1)
5207
5208 # if ntwkB is a 2port, then keep port indices where you expect.
5209 if ntwkB.nports == 2 and ntwkA.nports >= 2 and num == 1:
5210 from_ports = list(range(ntwkC.nports))
5211 to_ports = list(range(ntwkC.nports))
5212 to_ports.pop(k)
5213 to_ports.append(k)
5214
5215 ntwkC.renumber(from_ports=from_ports,
5216 to_ports=to_ports,
5217 only_z0=True)
5218
5219 # Clear the ntwkC's ext_attrs, since they may have been inherited from ntwkA
5220 # If a open, ground or port terminal is connected, this property should not be inherited
5221 ntwkC._ext_attrs = {}
5222
5223 # if ntwkA and ntwkB are both 2port, and either one has noise, calculate ntwkC's noise
5224 either_are_noisy = False
5225 either_are_noisy = ntwkA.noisy or ntwkB.noisy
5226
5227 if num == 1 and ntwkA.nports == 2 and ntwkB.nports == 2 and either_are_noisy:
5228 if ntwkA.noise_freq is not None and ntwkB.noise_freq is not None and ntwkA.noise_freq != ntwkB.noise_freq:
5229 raise IndexError('Networks must have same noise frequency. See `Network.interpolate`')
5230 cA = ntwkA.noise
5231 cB = ntwkB.noise
5232
5233 noise_freq = ntwkA.noise_freq
5234 if noise_freq is None:
5235 noise_freq = ntwkB.noise_freq
5236
5237 if cA is None:
5238 cA = np.broadcast_arrays(np.array([[0., 0.], [0., 0.]]), ntwkB.noise)[0]
5239 if cB is None:
5240 cB = np.broadcast_arrays(np.array([[0., 0.], [0., 0.]]), ntwkA.noise)[0]
5241
5242 if k == 0:
5243 # if we're connecting to the "input" port of ntwkA, recalculate the equivalent noise of ntwkA,
5244 # since we're modeling the noise as a pair of sources at the "input" port
5245 # TODO
5246 raise (NotImplementedError)
5247 if l == 1:
5248 # if we're connecting to the "output" port of ntwkB, recalculate the equivalent noise,
5249 # since we're modeling the noise as a pair of sources at the "input" port
5250 # TODO
5251 raise (NotImplementedError)
5252
5253 # interpolate abcd into the set of noise frequencies
5254 if ntwkA.deembed:
5255 if ntwkA.frequency.f.size > 1:
5256 a_real = interp1d(
5257 ntwkA.frequency.f,
5258 ntwkA.inv.a.real,
5259 axis=0,
5260 bounds_error=False,
5261 kind=ntwkA.noise_interp_kind
5262 )
5263 a_imag = interp1d(
5264 ntwkA.frequency.f,
5265 ntwkA.inv.a.imag,
5266 axis=0,
5267 bounds_error=False,
5268 kind=ntwkA.noise_interp_kind
5269 )
5270 a = a_real(noise_freq.f) + 1.j * a_imag(noise_freq.f)
5271 else:
5272 a_real = ntwkA.inv.a.real
5273 a_imag = ntwkA.inv.a.imag
5274 a = a_real + 1.j * a_imag
5275
5276 a = npy_inv(a)
5277 a_H = np.conj(a.transpose(0, 2, 1))
5278 cC = np.matmul(a, np.matmul(cB -cA, a_H))
5279 else:
5280 if ntwkA.frequency.f.size > 1:
5281 a_real = interp1d(
5282 ntwkA.frequency.f,
5283 ntwkA.a.real,
5284 axis=0,
5285 bounds_error=False,
5286 kind=ntwkA.noise_interp_kind
5287 )
5288 a_imag = interp1d(
5289 ntwkA.frequency.f,
5290 ntwkA.a.imag,
5291 axis=0,
5292 bounds_error=False,
5293 kind=ntwkA.noise_interp_kind
5294 )
5295 a = a_real(noise_freq.f) + 1.j * a_imag(noise_freq.f)
5296 else :
5297 a_real = ntwkA.a.real
5298 a_imag = ntwkA.a.imag
5299 a = a_real + 1.j * a_imag
5300
5301 a_H = np.conj(a.transpose(0, 2, 1))
5302 cC = np.matmul(a, np.matmul(cB, a_H)) + cA
5303 ntwkC.noise = cC
5304 ntwkC.noise_freq = noise_freq
5305
5306 if ntwkC.s_def != s_def_original:
5307 ntwkC.renormalize(ntwkC.z0, s_def_original)
5308
5309 return ntwkC
5310
5311
5312 def connect_fast(ntwkA: Network, k: int, ntwkB: Network, l: int) -> Network:
5313 """
5314 Alias for connect.
5315
5316 Parameters
5317 ----------
5318 ntwkA : :class:`Network`
5319 network 'A'
5320 k : int
5321 starting port index on `ntwkA` ( port indices start from 0 )
5322 ntwkB : :class:`Network`
5323 network 'B'
5324 l : int
5325 starting port index on `ntwkB`
5326
5327
5328 Returns
5329 -------
5330 ntwkC : :class:`Network`
5331 new network of rank `(ntwkA.nports + ntwkB.nports - 2)`
5332 """
5333 warnings.warn("connect_fast is deprecated. Use connect.", DeprecationWarning, stacklevel=2)
5334 return connect(ntwkA, k, ntwkB, l)
5335
5336
5337 def parallelconnect(ntwks: Sequence[Network] | Network,
5338 ports: Sequence[int | Sequence[int]],
5339 name: str | None = None) -> Network:
5340 """
5341 Connects a series of multi-port networks in parallel, ensuring that the specified port
5342 indices share the concatenated intersection.
5343
5344 Parameters
5345 ----------
5346 ntwks : :Sequence[`Network`] | `Network`
5347 A sequence of multi-port networks or a single network to be connected in parallel.
5348 ports : Sequence[int | Sequence[int]]
5349 A sequence of port indices, where each entry can be an int or a sequence of ints
5350 corresponding to the ports of the respective network. The length of `ports` should
5351 match the length of `networks`. Each specified port index is connect to the
5352 concatenated intersection, implying they are electrically common.
5353 name : str, optional
5354 define the connected network's name. Default is None.
5355
5356
5357 Returns
5358 -------
5359 connected_network : :class:`Network`
5360 A new network created from the parallel connection of the input networks.
5361 The number of ports in the resulting network equals the sum of ports in `ntwks`,
5362 minus the number of ports specified in `ports` that were connected in parallel.
5363 The remaining ports follow the original port order of the input networks, after
5364 removing those involved in the parallel connection.
5365
5366
5367 Note
5368 ----
5369 This function calculates the resulting scattering parameters after parallel connecting
5370 a set of networks. This algorithm [#]_, adapted from the `Circuit.s` method, constructs the
5371 concatenated intersection matrix [X] and the global scattering matrix [C] to perform
5372 the calculations.
5373
5374
5375 See Also
5376 --------
5377 connect_s : actual S-parameter connection algorithm.
5378 innerconnect_s : actual S-parameter connection algorithm.
5379 innerconnect_s_lstsq : actual S-parameter connection algorithm using lstsq.
5380
5381
5382 Examples
5383 --------
5384
5385 The following examples demonstrate how to use the :func:`parallelconnect` in
5386 different ways, such as open a port, connect two networks, innerconnect one
5387 network, and parallel multiple networks.
5388
5389 >>> # Prepare the example Networks
5390 >>> ntwkA = rf.Network('ntwkA.s2p')
5391 >>> ntwkB = rf.Network('ntwkB.s2p')
5392 >>> ntwkC = rf.connect('ntwkC.s4p')
5393 >>>
5394 >>> # 1) Open port 1 of ntwkA
5395 >>> # +-----+
5396 >>> # [0] A [1]--Open
5397 >>> # +-----+
5398 >>> #
5399 >>> rf.parallelconnect(ntwkA, [1])
5400 >>>
5401 >>>
5402 >>> # 2) Connect ntwkA's port 1 to ntwkB's port 0
5403 >>> # +-----+ +-----+
5404 >>> # [0] A [1]---[0] B [1]
5405 >>> # +-----+ +-----+
5406 >>> #
5407 >>> rf.parallelconnect([ntwkA, ntwkB], [1, 0])
5408 >>>
5409 >>>
5410 >>> # 3) Innerconnect the ntwkC's port 1 and 3
5411 >>> # +-----+
5412 >>> # | [1]--+
5413 >>> # [0] C [2] |
5414 >>> # | [3]--+
5415 >>> # +-----+
5416 >>> #
5417 >>> rf.parallelconnect(ntwkC, [[2, 3]])
5418 >>>
5419 >>>
5420 >>> # 4) Parallel connect the ntwkA's port 1, ntwkB's port 1 and ntwkC's port 0
5421 >>> # +-----+
5422 >>> # [0] A [1]---+ +-----+
5423 >>> # +-----+ | | [1]
5424 >>> # |---[0] C [2]
5425 >>> # +-----+ | | [3]
5426 >>> # [0] B [1]---+ +-----+
5427 >>> # +-----+
5428 >>> #
5429 >>> rf.parallelconnect([ntwkA, ntwkB, ntwkC], [1, 1, 0])
5430 >>>
5431 >>>
5432 >>> # 5) The port order of connected ntwk follows the order of ntwks and ports
5433 >>> # as shown in example 4:
5434 >>> # +-----+
5435 >>> # [0] A [1]---+ +-----+ +---------------+
5436 >>> # +-----+ | | [1] [0]=A[0] C[3]=[3]
5437 >>> # |---[0] C [2] ===> [1]=B[0] |
5438 >>> # +-----+ | | [3] [2]=C[1] C[3]=[4]
5439 >>> # [0] B [1]---+ +-----+ +---------------+
5440 >>> # +-----+
5441
5442 References
5443 ----------
5444 .. [#] P. Hallbjörner, Microw. Opt. Technol. Lett. 38, 99 (2003).
5445 """
5446 # Handle single network input
5447 if isinstance(ntwks, Network):
5448 ntwks = [ntwks]
5449
5450 if len(ntwks) != len(ports):
5451 raise ValueError(f'ntwks and ports must have the same length ({len(ntwks)} != {len(ports)})')
5452
5453 # Ensure unique networks
5454 if len(set(ntw.name for ntw in ntwks)) != len(ntwks):
5455 raise ValueError('ntwks should not be duplicated.')
5456
5457 # Get the index of each network in the list
5458 dim, off = sum(ntw.nports for ntw in ntwks), 0
5459 inter_indices, exter_indices = [], []
5460 z0_in, z0_ext = [], []
5461
5462 # Assign the global scattering matrix [X] and concatenated intersection matrix [C]
5463 X = np.zeros((ntwks[0].frequency.npoints, dim, dim), dtype='complex')
5464 C = np.zeros((ntwks[0].frequency.npoints, dim, dim), dtype='complex')
5465
5466 for ntw, port in zip(ntwks, ports):
5467 # Get the nports of Network
5468 nports: int = ntw.nports
5469
5470 # Convert the int port to list
5471 port = [port] if isinstance(port, int) else port
5472
5473 # Che the port indices valid or not
5474 if len(port) != len(set(port)):
5475 raise ValueError(f"{ntw.name}'s port should not be duplicated.")
5476 if max(port) >= nports or min(port) < 0:
5477 raise ValueError(f"{ntw.name}'s port index should be between 0 and {nports-1}")
5478
5479 # Check the frequency equal or not
5480 check_frequency_equal(ntw, ntwks[0])
5481
5482 # Append the port index with offset to indices list
5483 for p in range(nports):
5484 if p in port:
5485 inter_indices.append(p + off)
5486 z0_in.append(ntw.z0[:, p])
5487 else:
5488 exter_indices.append(p + off)
5489 z0_ext.append(ntw.z0[:, p])
5490
5491 # Assign the scattering matrix of each network to the global scattering matrix
5492 X[:, off:off+nports, off:off+nports] = ntw.s_traveling
5493
5494 # Update the offset
5495 off += nports
5496
5497 # Compute interaction matrix for internal connections
5498 z0s = np.array(z0_in).T
5499 y0s = 1./z0s
5500 y_tot = y0s.sum(axis=1)
5501
5502 s = 2 *np.sqrt(np.einsum('ki,kj->kij', y0s, y0s)) / y_tot[:, None, None]
5503 np.einsum('kii->ki', s)[:] -= 1 # Sii
5504
5505 # Get the index of internal port and external port from global matrix
5506 in_ind = np.meshgrid(inter_indices, inter_indices, indexing='ij')
5507 out_ind = np.meshgrid(exter_indices, exter_indices, indexing='ij')
5508
5509 # Update the concatenated intersection matrix
5510 C[:, in_ind[0], in_ind[1]] = s
5511
5512 # Get the global scattering matrix
5513 s = X @ np.linalg.inv(np.identity(dim) - C @ X)
5514
5515 return Network(frequency = ntwks[0].frequency,
5516 s = s[:, out_ind[0], out_ind[1]],
5517 z0 = np.array(z0_ext).T,
5518 name = name)
5519
5520
5521 def innerconnect(ntwkA: Network, k: int, l: int, num: int = 1) -> Network:
5522 """
5523 Connect ports of a single n-port network.
5524
5525 this results in a (n-2)-port network. remember port indices start
5526 from 0.
5527
5528
5529 Note
5530 ----
5531 A 2-port 'mismatch' network is inserted between the connected ports
5532 if their impedances are not equal.
5533
5534
5535 Parameters
5536 ----------
5537 ntwkA : :class:`Network`
5538 network 'A'
5539 k,l : int
5540 starting port indices on ntwkA ( port indices start from 0 )
5541 num : int
5542 number of consecutive ports to connect
5543
5544 Returns
5545 -------
5546 ntwkC : :class:`Network`
5547 new network of rank (ntwkA.nports - 2*num)
5548
5549 See Also
5550 --------
5551 connect_s : actual S-parameter connection algorithm.
5552 innerconnect_s : actual S-parameter connection algorithm.
5553 innerconnect_s_lstsq : actual S-parameter connection algorithm using lstsq.
5554
5555
5556 Examples
5557 --------
5558 To connect ports '0' and port '1' on ntwkA
5559
5560 >>> ntwkA = rf.Network('ntwkA.s3p')
5561 >>> ntwkC = rf.innerconnect(ntwkA, 0,1)
5562
5563 """
5564
5565 if (k + num - 1 > ntwkA.nports - 1):
5566 raise IndexError('Port `k` out of range')
5567 if (l + num - 1 > ntwkA.nports - 1):
5568 raise IndexError('Port `l` out of range')
5569
5570 # 'power' is not supported, convert to supported definition and back afterwards
5571 if ntwkA.s_def == 'power':
5572 ntwkA = ntwkA.copy()
5573 ntwkA.renormalize(ntwkA.z0, 'pseudo')
5574
5575 # create output Network, from copy of input
5576 # Since ntwkC's s-parameters will change later, use shallow_copy for speedup
5577 ntwkC = ntwkA.copy(shallow_copy=True)
5578
5579 s_def_original = ntwkC.s_def
5580
5581 z0_equal = (ntwkC.z0[:, k] == ntwkC.z0[:, l]).all()
5582
5583 if not z0_equal:
5584 if ntwkC.port_names is not None:
5585 port_names = ntwkC.port_names.copy()
5586 # connect a impedance mismatch, which will takes into account the
5587 # effect of differing port impedances
5588 mismatch = impedance_mismatch(ntwkA.z0[:, k], ntwkA.z0[:, l], ntwkA.s_def)
5589 ntwkC.s = connect_s(ntwkA.s, k, mismatch, 0, num=-1)
5590 # the connect_s() put the mismatch's output port at the end of
5591 # ntwkC's ports. Fix the new port's impedance, then insert it
5592 # at position k where it belongs.
5593 ntwkC.z0[:, k:] = np.hstack((ntwkC.z0[:, k + 1:], ntwkC.z0[:, [l]]))
5594 ntwkC.renumber(from_ports=[ntwkC.nports - 1] + list(range(k, ntwkC.nports - 1)),
5595 to_ports=list(range(k, ntwkC.nports)))
5596 if ntwkC.port_names is not None:
5597 ntwkC.port_names = port_names
5598
5599 # call s-matrix connection function
5600 ntwkC.s = innerconnect_s(ntwkC.s if not z0_equal else ntwkA.s, k, l)
5601
5602 # update the characteristic impedance matrix and port_names
5603 ntwkC.z0 = np.delete(ntwkC.z0, list(range(k, k + 1)) + list(range(l, l + 1)), 1)
5604 if ntwkC.port_names is not None:
5605 ntwkC.port_names = np.delete(ntwkC.port_names, [k] + [l]).tolist()
5606
5607 # recur if we're connecting more than one port
5608 if num > 1:
5609 ntwkC = innerconnect(ntwkC, k, l - 1, num - 1)
5610
5611 if ntwkC.s_def != s_def_original:
5612 ntwkC.renormalize(ntwkC.z0, s_def_original)
5613
5614 return ntwkC
5615
5616
5617 def cascade(ntwkA: Network, ntwkB: Network) -> Network:
5618 """
5619 Cascade two 2, 2N-ports Networks together.
5620
5621 Connects ports N through 2N-1 on `ntwkA` to ports 0 through N of
5622 `ntwkB`. This calls `connect()`, which is a more general function.
5623 Use `Network.renumber` to change port order if needed.
5624
5625 Note
5626 ----
5627 connection diagram::
5628
5629 A B
5630 +---------+ +---------+
5631 -|0 N |---|0 N |-
5632 -|1 N+1|---|1 N+1|-
5633 ... ... ... ...
5634 -|N-2 2N-2|---|N-2 2N-2|-
5635 -|N-1 2N-1|---|N-1 2N-1|-
5636 +---------+ +---------+
5637
5638 Parameters
5639 ----------
5640 ntwkA : :class:`Network`
5641 network `ntwkA`
5642 ntwkB : :class:`Network`
5643 network `ntwkB`
5644
5645 Returns
5646 -------
5647 C : :class:`Network`
5648 the resultant network of ntwkA cascaded with ntwkB
5649
5650 See Also
5651 --------
5652 connect : connects two Networks together at arbitrary ports.
5653 Network.renumber : changes the port order of a network
5654
5655 """
5656
5657 if ntwkA.nports<2:
5658 raise ValueError('nports must be >1')
5659
5660
5661 N = int(ntwkA.nports/2 )
5662 if ntwkB.nports == 1:
5663 # we are terminating an N-port with a 1-port.
5664 # which port on self to use is ambiguous. choose N
5665 return connect(ntwkA, N, ntwkB, 0)
5666
5667 elif ntwkA.nports % 2 == 0 and ntwkA.nports == ntwkB.nports:
5668 # we have two 2N-port balanced networks
5669 return connect(ntwkA, N, ntwkB, 0, num=N)
5670
5671 elif ntwkA.nports % 2 == 0 and ntwkA.nports == 2 * ntwkB.nports:
5672 # we have a 2N-port balanced network terminated by an N-port network
5673 return connect(ntwkA, N, ntwkB, 0, num=N)
5674
5675 else:
5676 raise ValueError('I dont know what to do, check port shapes of Networks')
5677
5678
5679
5680 def cascade_list(l: Sequence[Network]) -> Network:
5681 """
5682 Cascade a list of 2N-port networks.
5683
5684 all networks must have same frequency
5685
5686 Parameters
5687 ----------
5688 l : list-like
5689 (ordered) list of networks
5690
5691 Returns
5692 -------
5693 out : 2-port Network
5694 the results of cascading all networks in the list `l`
5695
5696 """
5697 return reduce(cascade, l)
5698
5699
5700 def de_embed(ntwkA: Network, ntwkB: Network) -> Network:
5701 """
5702 De-embed `ntwkA` from `ntwkB`.
5703
5704 This calls `ntwkA.inv ** ntwkB`. The syntax of cascading an inverse
5705 is more explicit, it is recommended that it be used instead of this
5706 function.
5707
5708 Parameters
5709 ----------
5710 ntwkA : :class:`Network`
5711 network `ntwkA`
5712 ntwkB : :class:`Network`
5713 network `ntwkB`
5714
5715 Returns
5716 -------
5717 C : Network
5718 the resultant network of ntwkB de-embedded from ntwkA
5719
5720 See Also
5721 --------
5722 connect : connects two Networks together at arbitrary ports.
5723
5724 """
5725 return ntwkA.inv ** ntwkB
5726
5727
5728 def stitch(ntwkA: Network, ntwkB: Network, **kwargs) -> Network:
5729 r"""
5730 Stitch ntwkA and ntwkB together.
5731
5732 Concatenates two networks' data. Given two networks that cover
5733 different frequency bands this can be used to combine their data
5734 into a single network.
5735
5736 Parameters
5737 ----------
5738 ntwkA, ntwkB : :class:`Network` objects
5739 Networks to stitch together
5740
5741 \*\*kwargs : keyword args
5742 passed to :class:`Network` constructor, for output network
5743
5744 Returns
5745 -------
5746 ntwkC : :class:`Network`
5747 result of stitching the networks `ntwkA` and `ntwkB` together
5748
5749 Examples
5750 --------
5751 >>> from skrf.data import wr2p2_line, wr1p5_line
5752 >>> rf.stitch(wr2p2_line, wr1p5_line)
5753 2-Port Network: 'wr2p2,line', 330-750 GHz, 402 pts, z0=[ 50.+0.j 50.+0.j]
5754 """
5755
5756 A, B = ntwkA, ntwkB
5757 C = Network(
5758 frequency=Frequency.from_f(np.r_[A.f[:], B.f[:]], unit='hz'),
5759 s=np.r_[A.s, B.s],
5760 z0=np.r_[A.z0, B.z0],
5761 name=A.name,
5762 **kwargs
5763 )
5764 C.frequency.unit = A.frequency.unit
5765 return C
5766
5767
5768 def overlap(ntwkA: Network, ntwkB: Network) -> tuple[Network, Network]:
5769 """
5770 Return the overlapping parts of two Networks, interpolating if needed.
5771
5772 If frequency vectors for each ntwk don't perfectly overlap, then
5773 ntwkB is interpolated so that the resultant networks have identical
5774 frequencies.
5775
5776 Parameters
5777 ----------
5778 ntwkA : :class:`Network`
5779 a ntwk which overlaps `ntwkB`. (the `dominant` network)
5780 ntwkB : :class:`Network`
5781 a ntwk which overlaps `ntwkA`.
5782
5783 Returns
5784 -------
5785 ntwkA_new : :class:`Network`
5786 part of `ntwkA` that overlapped `ntwkB`
5787 ntwkB_new : :class:`Network`
5788 part of `ntwkB` that overlapped `ntwkA`, possibly interpolated
5789
5790
5791 See Also
5792 --------
5793
5794 :func:`skrf.frequency.overlap_freq`
5795 :func:`skrf.network.overlap_multi`
5796
5797 """
5798
5799 new_freq = ntwkA.frequency.overlap(ntwkB.frequency)
5800 return ntwkA.interpolate(new_freq), ntwkB.interpolate(new_freq)
5801
5802 def overlap_multi(ntwk_list: Sequence[Network]):
5803 """
5804 Return the overlapping parts of multiple Networks, interpolating if needed.
5805
5806 If frequency vectors for each ntwk don't perfectly overlap, then
5807 all networks after the first are interpolated so that the resultant networks
5808 have identical frequencies.
5809
5810 Parameters
5811 ----------
5812 ntwk_list : list of skrf.Networks
5813 a list of networks with some overlap
5814
5815 Returns
5816 -------
5817 overlap_list : list of skrf.Networks
5818 a list of networks that mutually overlap
5819
5820
5821 See Also
5822 --------
5823
5824 :func:`skrf.frequency.overlap_freq`
5825 :func:`skrf.network.overlap`
5826
5827 """
5828
5829 new_freq = ntwk_list[0].frequency
5830 for ntwk in ntwk_list[1:]:
5831 new_freq = new_freq.overlap(ntwk.frequency)
5832
5833 return [ntwk.interpolate(new_freq) for ntwk in ntwk_list]
5834
5835 def concat_ports(ntwk_list: Sequence[Network], port_order: Literal["first", "second"] = "second",
5836 *args, **kw) -> Network:
5837 """
5838 Concatenate networks along the port axis.
5839
5840
5841 Note
5842 ----
5843 The `port_order` ='first', means front-to-back, while
5844 `port_order`='second' means left-to-right. So, for example, when
5845 concatenating two 2-networks, `A` and `B`, the ports are ordered as follows:
5846
5847 'first'
5848 a0 o---o a1 -> 0 o---o 1
5849 b0 o---o b1 -> 2 o---o 3
5850
5851 'second'
5852 a0 o---o a1 -> 0 o---o 2
5853 b0 o---o b1 -> 1 o---o 3
5854
5855
5856 use `Network.renumber` to change port ordering.
5857
5858 Parameters
5859 ----------
5860 ntwk_list : list of skrf.Networks
5861 ntwks to concatenate
5862 port_order : ['first', 'second']
5863
5864 Examples
5865 --------
5866
5867 >>> concat([ntwkA,ntwkB])
5868 >>> concat([ntwkA,ntwkB,ntwkC,ntwkD], port_order='second')
5869
5870 To put for lines in parallel
5871
5872 >>> from skrf import air
5873 >>> l1 = air.line(100, z0=[0,1])
5874 >>> l2 = air.line(300, z0=[2,3])
5875 >>> l3 = air.line(400, z0=[4,5])
5876 >>> l4 = air.line(400, z0=[6,7])
5877 >>> concat_ports([l1,l2,l3,l4], port_order='second')
5878
5879 See Also
5880 --------
5881 stitch : concatenate two networks along the frequency axis
5882 renumber : renumber ports
5883 """
5884 # if ntwk list is longer than 2, recursively call myself
5885 # until we are done
5886 if len(ntwk_list) > 2:
5887 def f(x, y):
5888 return concat_ports([x, y], port_order='first')
5889 out = reduce(f, ntwk_list)
5890 # if we want to renumber ports, we have to wait
5891 # until after the recursive calls
5892 if port_order == 'second':
5893 N = out.nports
5894 old_order = list(range(N))
5895 new_order = list(range(0, N, 2)) + list(range(1, N, 2))
5896 out.renumber(new_order, old_order)
5897 return out
5898
5899 ntwkA, ntwkB = ntwk_list
5900
5901 if ntwkA.frequency != ntwkB.frequency:
5902 raise ValueError('ntwks don\'t have matching frequencies')
5903 A = ntwkA.s
5904 B = ntwkB.s
5905
5906 nf = A.shape[0] # num frequency points
5907 nA = A.shape[1] # num ports on A
5908 nB = B.shape[1] # num ports on B
5909 nC = nA + nB # num ports on C
5910
5911 # create composite matrix, appending each sub-matrix diagonally
5912 C = np.zeros((nf, nC, nC), dtype='complex')
5913 C[:, :nA, :nA] = A.copy()
5914 C[:, nA:, nA:] = B.copy()
5915
5916 ntwkC = ntwkA.copy()
5917 ntwkC.s = C
5918 ntwkC.z0 = np.hstack([ntwkA.z0, ntwkB.z0])
5919 ntwkC.port_modes = np.hstack([ntwkA.port_modes, ntwkB.port_modes])
5920 if port_order == 'second':
5921 old_order = list(range(nC))
5922 new_order = list(range(0, nC, 2)) + list(range(1, nC, 2))
5923 ntwkC.renumber(old_order, new_order)
5924 return ntwkC
5925
5926
5927 def average(list_of_networks: Sequence[Network], polar: bool = False) -> Network:
5928 """
5929 Calculate the average network from a list of Networks.
5930
5931 This is complex average of the s-parameters for a list of Networks.
5932
5933
5934 Parameters
5935 ----------
5936 list_of_networks : list of :class:`Network` objects
5937 the list of networks to average
5938 polar : boolean, optional
5939 Average the mag/phase components individually. Default is False.
5940
5941 Returns
5942 -------
5943 ntwk : :class:`Network`
5944 the resultant averaged Network
5945
5946 Note
5947 ----
5948 This same function can be accomplished with properties of a
5949 :class:`~skrf.networkset.NetworkSet` class.
5950
5951 Examples
5952 --------
5953
5954 >>> ntwk_list = [rf.Network('myntwk.s1p'), rf.Network('myntwk2.s1p')]
5955 >>> mean_ntwk = rf.average(ntwk_list)
5956 """
5957 out_ntwk = list_of_networks[0].copy()
5958
5959 if polar:
5960 # average the mag/phase components individually
5961 raise NotImplementedError
5962 else:
5963 # average the re/im components individually
5964 for a_ntwk in list_of_networks[1:]:
5965 out_ntwk += a_ntwk
5966
5967 out_ntwk.s = out_ntwk.s / (len(list_of_networks))
5968
5969 return out_ntwk
5970
5971
5972 def stdev(list_of_networks: Sequence[Network], attr: str = 's') -> np.ndarray:
5973 """
5974 Calculate the standard deviation of a network attribute from a list of Networks.
5975
5976 This is the standard deviation for complex values of the s-parameters and other related attributes
5977 for a list of Networks.
5978
5979
5980 Parameters
5981 ----------
5982 list_of_networks : list of :class:`Network` objects
5983 the list of networks to average
5984 attr : str, optional
5985 name of attribute to average
5986
5987 Returns
5988 -------
5989 stdev_array : ndarray
5990 An array of standard deviation values computed after combining the s-parameter values of the given networks.
5991
5992 Examples
5993 --------
5994
5995 >>> ntwk_list = [rf.Network('myntwk.s1p'), rf.Network('myntwk2.s1p')]
5996 >>> ntwk_stdev = rf.stdev(ntwk_list)
5997 """
5998 return np.array([getattr(network, attr) for network in list_of_networks]).std(axis=0)
5999
6000
6001 def one_port_2_two_port(ntwk: Network) -> Network:
6002 """
6003 Calculate the 2-port network given a symmetric, reciprocal and lossless 1-port network.
6004
6005 Parameters
6006 ----------
6007 ntwk : :class:`Network`
6008 a symmetric, reciprocal and lossless one-port network.
6009
6010 Returns
6011 -------
6012 ntwk : :class:`Network`
6013 the resultant two-port Network
6014 """
6015 result = ntwk.copy()
6016 result.s = np.zeros((result.frequency.npoints, 2, 2), dtype=complex)
6017 s11 = ntwk.s[:, 0, 0]
6018 result.s[:, 0, 0] = s11
6019 result.s[:, 1, 1] = s11
6020 ## HACK: TODO: verify this mathematically
6021 result.s[:, 0, 1] = np.sqrt(1 - np.abs(s11) ** 2) * \
6022 np.exp(1j * (
6023 np.angle(s11) + np.pi / 2. * (np.angle(s11) < 0) - np.pi / 2 * (np.angle(s11) > 0)))
6024 result.s[:, 1, 0] = result.s[:, 0, 1]
6025
6026 result.z0 = np.hstack([ntwk.z0,ntwk.z0])
6027 return result
6028
6029
6030 def chopinhalf(ntwk: Network, *args, **kwargs) -> Network:
6031 r"""
6032 Chop a sandwich of identical, reciprocal 2-ports in half.
6033
6034 Given two identical, reciprocal 2-ports measured in series,
6035 this returns one.
6036
6037
6038 Note
6039 ----
6040 In other words, given
6041
6042 .. math::
6043
6044 B = A\cdot A
6045
6046 Return A, where A port2 is connected to A port1. The result may
6047 be found through signal flow graph analysis and is,
6048
6049 .. math::
6050
6051 a_{11} = \frac{b_{11}}{1+b_{12}}
6052
6053 a_{22} = \frac{b_{22}}{1+b_{12}}
6054
6055 a_{12}^2 = b_{21}(1-\frac{b_{11}b_{22}}{(1+b_{12})^2}
6056
6057 Parameters
6058 ----------
6059 ntwk : :class:`Network`
6060 a 2-port that is equal to two identical two-ports in cascade
6061
6062
6063 """
6064 if ntwk.nports != 2:
6065 raise ValueError('Only valid on 2ports')
6066
6067 b11, b22, b12 = ntwk.s11, ntwk.s22, ntwk.s12
6068 kwargs['name'] = kwargs.get('name', ntwk.name)
6069
6070 a11 = b11 / (1 + b12)
6071 a22 = b22 / (1 + b12)
6072 a21 = b12 * (1 - b11 * b22 / (1 + b12) ** 2) # this is a21^2 here
6073 a21.s = mf.sqrt_phase_unwrap(a21.s)
6074 A = n_oneports_2_nport([a11, a21, a21, a22], *args, **kwargs)
6075
6076 return A
6077
6078 def evenodd2delta(n: Network, z0: NumberLike = 50, renormalize: bool = True,
6079 doublehalf: bool = True) -> Network:
6080 """
6081 Convert ntwk's s-matrix from even/odd mode into a delta (normal) s-matrix.
6082
6083 This assumes even/odd ports are ordered [1e,1o,2e,2o].
6084
6085 This is useful for handling coupler sims. Only 4-ports supported for now.
6086
6087 Parameters
6088 ----------
6089 n : skrf.Network
6090 Network with an even/odd mode s-matrix
6091 z0: number, list of numbers
6092 the characteristic impedance to set output networks port impedance
6093 to , and used to renormalize s-matrix before conversio if
6094 `renormalize`=True.
6095 renormalize : Bool
6096 if impedances are in even/odd then they must be renormalized to
6097 get correct transformation
6098 doublehalf: Bool
6099 convert even/odd impedances to double/half their values. this is
6100 required if data comes from hfss waveports .
6101
6102 Returns
6103 -------
6104 out: skrf.Network
6105 same network as `n` but with s-matrix in normal delta basis
6106
6107 See Also
6108 --------
6109 Network.se2gmm, Network.gmm2se
6110
6111 """
6112
6113 # move even and odd ports, so we have even and odd
6114 # s-matrices contiguous
6115 n_eo = n.copy()
6116 n_eo.renumber([0,1,2,3],[0,2,1,3])
6117
6118 if doublehalf:
6119 n_eo.z0 = n_eo.z0*[2,2,.5,.5]
6120 # if the n_eo s-matrix is given with e/o z0's we need
6121 # to renormalize into 50
6122 if renormalize:
6123 n_eo.renormalize(z0)
6124
6125 even = n_eo.s[:,0:2,0:2]
6126 odd = n_eo.s[:,2:4,2:4]
6127
6128 # compute sub-networks for symmetric 4port
6129 s_a = .5*(even+odd)
6130 s_b = .5*(even-odd)
6131
6132 # create output network
6133 n_delta = n_eo.copy()
6134 n_delta.s[:,0:2,0:2] = n_delta.s[:,2:4,2:4] = s_a
6135 n_delta.s[:,2:4,0:2] = n_delta.s[:,0:2,2:4] = s_b
6136 n_delta.z0=z0
6137
6138 return n_delta
6139
6140
6141 def subnetwork(ntwk: Network, ports: Sequence[int], offby:int = 1) -> Network:
6142 """
6143 Return a subnetwork of a given Network from a list of port numbers.
6144
6145 A subnetwork is Network which S-parameters corresponds to selected ports,
6146 with all non-selected ports considered matched.
6147
6148 The resulting subNetwork is given a new Network.name property
6149 from the initial name and adding the kept ports indices
6150 (ex: 'device' -> 'device13'). Such name should make easier the use
6151 of functions such as n_twoports_2_nport.
6152
6153 Parameters
6154 ----------
6155 ntwk : :class:`Network` object
6156 Network to split into a subnetwork
6157 ports : list of int
6158 List of ports to keep in the resultant Network.
6159 Indices are the Python indices (starts at 0)
6160 offby : int
6161 starting value for s-parameters indexes in the sub-Network name parameter.
6162 A value of `1`, assumes that a s21 = ntwk.s[:,1,0]. Default is 1.
6163
6164 Returns
6165 -------
6166 subntwk : :class:`Network` object
6167 Resulting subnetwork from the given ports
6168
6169 See also
6170 --------
6171 Network.subnetwork, n_twoports_2_nport
6172
6173 Examples
6174 --------
6175
6176 >>> tee = rf.data.tee # 3 port Network
6177 >>> tee12 = rf.subnetwork(tee, [0, 1]) # 2 port Network from ports 1 & 2, port 3 matched
6178 >>> tee23 = rf.subnetwork(tee, [1, 2]) # 2 port Network from ports 2 & 3, port 1 matched
6179 >>> tee13 = rf.subnetwork(tee, [0, 2]) # 2 port Network from ports 1 & 3, port 2 matched
6180
6181 """
6182 # forging subnetwork name
6183 subntwk_name = (ntwk.name or 'p') + ''.join([str(index+offby) for index in ports])
6184 # create a dummy Network with same frequency and z0 from the original
6185 subntwk = Network(frequency=ntwk.frequency, z0=ntwk.z0[:,ports], name=subntwk_name)
6186 # keep requested rows and columns of the s-matrix. ports can be not contiguous
6187 subntwk.s = ntwk.s[np.ix_(np.arange(ntwk.s.shape[0]), ports, ports)]
6188 # keep port_modes
6189 subntwk.port_modes = [ntwk.port_modes[idx] for idx in ports]
6190 # keep port_names
6191 if ntwk.port_names:
6192 subntwk.port_names = [ntwk.port_names[idx] for idx in ports]
6193 return subntwk
6194
6195 def s_error(ntwkA: Network, ntwkB: Network, error_function: ErrorFunctionsT = "average_l2_norm") -> np.ndarray:
6196 r"""
6197 Compute the error between s-parameters of ntwkA and ntwkB.
6198
6199 Parameters
6200 ----------
6201 ntwkA : :class:`Network` object
6202 The first network.
6203 ntwkB : :class:`Network` object
6204 A second network used to compute the error with ntwkA
6205 error_function : str
6206 average_l1_norm, average_l2_norm, maximum_l1_norm, or average_normalized_l1_norm.
6207
6208 Returns
6209 -------
6210 error : :class:`numpy.ndarray`
6211 The error between ntwkA and ntwkB
6212
6213 Description
6214 -----------
6215 Average L1 Norm. The weighted difference is the average magnitude of the difference between each
6216 element of the S-parameter matrix.
6217
6218 .. math::
6219
6220 \delta = \frac{1}{N^2} \sum_{i=1}^{N} \sum_{j=1}^{N} |S_{ij}^A - S_{ij}^B|
6221
6222 Average L2 Norm. The weighted difference is the average squared magnitude of the difference
6223 between each element of the S-parameter matrix.
6224
6225 .. math::
6226
6227 \delta = \frac{1}{N^2} \sum_{i=1}^{N} \sum_{j=1}^{N} |S_{ij}^A - S_{ij}^B|^2
6228
6229 Maximum L1 Norm. The maximum difference is the magnitude of the maximum difference between each
6230 element of the S-parameter matrix (the magnitude of the largest difference between any pair of
6231 entries in the S-parameter matrices).
6232
6233 .. math::
6234
6235 \delta = \max(|S_{ij}^A - S_{ij}^B|)
6236
6237 Average Normalized L1 Norm. The magnitude of the difference between each element of the
6238 S-parameter matrix is calculated. Each difference is then normalized by the average magnitude of
6239 the two matrix elements (one from each set).
6240
6241 .. math::
6242
6243 \delta = \frac{2}{N^2} \sum_{i=1}^{N} \sum_{j=1}^{N} \frac{|S_{ij}^A - S_{ij}^B|}{|S_{ij}^A| + |S_{ij}^B|}
6244
6245 To express these in decibels, use:
6246
6247 .. math::
6248
6249 20\log_{10} \delta
6250 """
6251
6252 # check that ntwkA and ntwkB have the same frequency grid.
6253 if ntwkA.frequency != ntwkB.frequency:
6254 raise ValueError(f"Networks '{ntwkA.name}' and '{ntwkB.name}' must have the same frequency grid.")
6255
6256 nports_square = ntwkA.nports**2
6257
6258 # absolute value of the complex difference:
6259 absdiff = np.abs(ntwkA.s - ntwkB.s)
6260
6261 # make string comparisons on lower case
6262 error_function = error_function.lower()
6263
6264 if error_function == "average_l1_norm":
6265 error = absdiff.sum(axis=1).sum(axis=1) / nports_square
6266 elif error_function == "average_l2_norm":
6267 error = (absdiff**2).sum(axis=1).sum(axis=1) / nports_square
6268 elif error_function == "maximum_l1_norm":
6269 error = absdiff.max(axis=1).max(axis=1)
6270 elif error_function == "average_normalized_l1_norm":
6271 temp = 2 * absdiff / (np.abs(ntwkA.s) + np.abs(ntwkB.s))
6272 error = temp.sum(axis=1).sum(axis=1) / nports_square
6273 else:
6274 raise ValueError(f"Invalid error function '{error_function}'")
6275
6276 return error
6277
6278 ## Building composite networks from sub-networks
6279 def n_oneports_2_nport(ntwk_list: Sequence[Network], *args, **kwargs) -> Network:
6280 r"""
6281 Build an N-port Network from list of N one-ports.
6282
6283 Parameters
6284 ----------
6285 ntwk_list : list of :class:`Network` objects
6286 must follow left-right, top-bottom order, ie, s11,s12,s21,s22
6287 \*args, \*\*kwargs :
6288 passed to :func:`Network.__init__` for the N-port
6289
6290 Returns
6291 -------
6292 nport : n-port :class:`Network`
6293 result
6294 """
6295 nports = int(np.sqrt(len(ntwk_list)))
6296
6297 s_out = np.concatenate(
6298 [np.concatenate(
6299 [ntwk_list[(k + (l * nports))].s for k in range(nports)], 2) \
6300 for l in range(nports)], 1)
6301
6302 z0 = np.concatenate(
6303 [ntwk_list[k].z0 for k in range(0, nports ** 2, nports + 1)], 1)
6304 frequency = ntwk_list[0].frequency
6305 return Network(s=s_out, z0=z0, frequency=frequency, **kwargs)
6306
6307
6308 def n_twoports_2_nport(ntwk_list: Sequence[Network], nports: int,
6309 offby: int = 1, port_sep: str = "", **kwargs) -> Network:
6310 r"""
6311 Build an N-port Network from list of two-ports.
6312
6313 This method was made to reconstruct an n-port network from 2-port
6314 subnetworks as measured by a 2-port VNA. So, for example, given a
6315 3-port DUT, you might measure the set p12.s2p, p23.s2p, p13.s2p.
6316 From these measurements, you can construct p.s3p.
6317
6318 By default all entries of result.s are filled with 0's, in case you
6319 don't fully specify the entire s-matrix of the resultant ntwk.
6320
6321 Parameters
6322 ----------
6323 ntwk_list : list of :class:`Network` objects
6324 the names must contain the port index, ie 'p12' or 'p43',
6325 ie. define the Network.name property of the :class:`Network` object.
6326 nports: int
6327 Number of ports to expect by the parser.
6328 offby : int
6329 starting value for s-parameters indices. ie a value of `1`,
6330 assumes that a s21 = ntwk.s[:,1,0]
6331 port_sep: str, default ""
6332 string separating port 1 connection from port 2 for the vna connected to the
6333 DUT. If constructing nport network with a maximum of 10 ports, it can be left as "".
6334 To avoid ambiguity for more than 10 ports, port_sep is required to format the trace names
6335 like S{}
6336
6337 \*args, \*\*kwargs :
6338 passed to :func:`Network.__init__` for the N-port
6339
6340 Returns
6341 -------
6342 nport : n-port :class:`Network`
6343 result
6344
6345 See Also
6346 --------
6347 concat_ports : concatenate ntwks along their ports
6348 """
6349
6350 if (nports > 10) and (port_sep == ""):
6351 msg = "`port_sep` must not be empty when having more than 10 ports!"
6352 raise ValueError(msg)
6353
6354 frequency = ntwk_list[0].frequency
6355 nport = Network(frequency=frequency,
6356 s=np.zeros(shape=(frequency.npoints, nports, nports)),
6357 **kwargs)
6358
6359 for subntwk in ntwk_list:
6360 for m, n in nport.port_tuples:
6361 if m != n and m > n:
6362 if f"{m + offby}{port_sep}{n + offby}" in subntwk.name:
6363 pass
6364 elif f"{n + offby}{port_sep}{m + offby}" in subntwk.name:
6365 subntwk = subntwk.flipped()
6366 else:
6367 continue
6368
6369 for mn, jk in zip(product((m, n), repeat=2), product((0, 1), repeat=2)):
6370 m, n, j, k = mn[0], mn[1], jk[0], jk[1]
6371 nport.s[:, m, n] = subntwk.s[:, j, k]
6372 nport.z0[:, m] = subntwk.z0[:, j]
6373 return nport
6374
6375
6376 def four_oneports_2_twoport(s11: Network, s12: Network, s21: Network, s22: Network, *args, **kwargs) -> Network:
6377 r"""
6378 Build a 2-port Network from list of four 1-ports.
6379
6380 Parameters
6381 ----------
6382 s11 : one-port :class:`Network`
6383 s11
6384 s12 : one-port :class:`Network`
6385 s12
6386 s21 : one-port :class:`Network`
6387 s21
6388 s22 : one-port :class:`Network`
6389 s22
6390 \*args, \*\*kwargs :
6391 passed to :func:`Network.__init__` for the twoport
6392
6393 Returns
6394 -------
6395 twoport : two-port :class:`Network`
6396 result
6397
6398 See Also
6399 --------
6400 n_oneports_2_nport
6401 """
6402 return n_oneports_2_nport([s11, s12, s21, s22], *args, **kwargs)
6403
6404
6405 ## Functions operating on s-parameter matrices
6406 def connect_s(A: np.ndarray, k: int, B: np.ndarray, l: int, num: int = 1) -> np.ndarray:
6407 """
6408 Connect two n-port networks' s-matrices together.
6409
6410 Specifically, connect port `k` on network `A` to port `l` on network
6411 `B`. The resultant network has nports = (A.rank + B.rank-2). This
6412 function operates on, and returns s-matrices. The function
6413 :func:`connect` operates on :class:`Network` types.
6414
6415 Parameters
6416 ----------
6417 A : :class:`numpy.ndarray`
6418 S-parameter matrix of `A`, shape is fxnxn
6419 k : int
6420 port index on `A` (port indices start from 0)
6421 B : :class:`numpy.ndarray`
6422 S-parameter matrix of `B`, shape is fxnxn
6423 l : int
6424 port index on `B`
6425 num : int
6426 number of consecutive ports to connect (default 1)
6427
6428 Returns
6429 -------
6430 C : :class:`numpy.ndarray`
6431 new S-parameter matrix
6432
6433
6434 Note
6435 ----
6436 Internally, this function creates a larger composite network
6437 and calls the :func:`innerconnect_s` function. see that function for more
6438 details about the implementation
6439
6440
6441 See Also
6442 --------
6443 connect : operates on :class:`Network` types
6444 innerconnect_s : function which implements the connection algorithm
6445 innerconnect_s_lstsq : actual S-parameter connection algorithm using lstsq.
6446
6447
6448 """
6449
6450 if k > A.shape[-1] - 1 or l > B.shape[-1] - 1:
6451 raise (ValueError('port indices are out of range'))
6452
6453 nf = A.shape[0] # num frequency points
6454 nA = A.shape[1] # num ports on A
6455 nB = B.shape[1] # num ports on B
6456 nC = nA + nB # num ports on C
6457
6458 # create composite matrix, appending each sub-matrix diagonally
6459 C = np.zeros((nf, nC, nC), dtype='complex', order='F')
6460
6461 # if ntwkB is a 2port, then keep port indices where you expect.
6462 if nB == 2 and nA > 2 and num == 1:
6463 """
6464 Pre-renumber the s-parameters:
6465 |A1 A2| |A1 0 A2| |A1 A2 0|
6466 | | + |B| = |0 B 0 |, rather than |A3 A4 0|
6467 |A3 A4| |A3 0 A4| |0 0 B|
6468 """
6469 C[:, :k, :k] = A[:, :k, :k]
6470 C[:, :k, k + nB :] = A[:, :k, k:]
6471 C[:, k + nB :, :k] = A[:, k:, :k]
6472 C[:, k + nB :, k + nB :] = A[:, k:, k:]
6473 C[:, k : k + nB, k : k + nB] = B
6474
6475 # call innerconnect_s() on composite matrix C
6476 return innerconnect_s(C, k + nB, k + l)
6477 else:
6478 C[:, :nA, :nA] = A
6479 C[:, nA:, nA:] = B
6480
6481 # call innerconnect_s() on composite matrix C
6482 return innerconnect_s(C, k, nA + l)
6483
6484
6485 def innerconnect_s(A: np.ndarray, k: int, l: int) -> np.ndarray:
6486 """
6487 Connect two ports of a single n-port network's s-matrix.
6488
6489 Specifically, connect port `k` to port `l` on `A`. This results in
6490 a (n-2)-port network. This function operates on, and returns
6491 s-matrices. The function :func:`innerconnect` operates on
6492 :class:`Network` types.
6493
6494
6495 Note
6496 ----
6497 The algorithm used to calculate the resultant network is called a
6498 'sub-network growth', can be found in [#]_. The original paper
6499 describing the algorithm is given in [#]_.
6500
6501
6502 Parameters
6503 ----------
6504 A : :class:`numpy.ndarray`
6505 S-parameter matrix of `A`, shape is fxnxn
6506 k : int
6507 port index on `A` (port indices start from 0)
6508 l : int
6509 port index on `A`
6510
6511 Returns
6512 -------
6513 C : :class:`numpy.ndarray`
6514 new S-parameter matrix
6515
6516
6517 See Also
6518 --------
6519 innerconnect_s_lstsq : actual S-parameter connection algorithm using lstsq.
6520
6521
6522 References
6523 ----------
6524 .. [#] Compton, R.C.; , "Perspectives in microwave circuit analysis," Circuits and Systems, 1989.,
6525 Proceedings of the 32nd Midwest Symposium on , vol., no., pp.716-718 vol.2, 14-16 Aug 1989.
6526 URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=101955&isnumber=3167
6527
6528 .. [#] Filipsson, Gunnar; , "A New General Computer Algorithm for S-Matrix Calculation of Interconnected Multiports"
6529 ,Microwave Conference, 1981. 11th European , vol., no., pp.700-704, 7-11 Sept. 1981.
6530 URL: http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4131699&isnumber=4131585
6531
6532
6533 """
6534
6535 if k > A.shape[-1] - 1 or l > A.shape[-1] - 1:
6536 raise (ValueError("port indices are out of range"))
6537
6538 nA = A.shape[1] # num of ports on input s-matrix
6539
6540 # Vectorized version of the following loop
6541 # through ports to calculate resultant s-parameters
6542 # for i in range(nA):
6543 # for j in range(nA):
6544 # C[:, i, j] = A[:, i, j] + (
6545 # A[:, k, j] * A[:, i, l] * (1 - A[:, l, k])
6546 # + A[:, l, j] * A[:, i, k] * (1 - A[:, k, l])
6547 # + A[:, k, j] * A[:, l, l] * A[:, i, k]
6548 # + A[:, l, j] * A[:, k, k] * A[:, i, l]
6549 # ) / ((1 - A[:, k, l]) * (1 - A[:, l, k]) - A[:, k, k] * A[:, l, l])
6550 #
6551 # external ports index
6552 ext_i = [i for i in range(nA) if i not in (k, l)]
6553
6554 # Indexing sub-matrices of internal ports (only k, l)
6555 Akl = 1.0 - A[:, k, l]
6556 Alk = 1.0 - A[:, l, k]
6557 Akk = A[:, k, k]
6558 All = A[:, l, l]
6559
6560 # create temporary matrices for calculation
6561 det = (Akl * Alk - Akk * All)
6562
6563 # Check if the determinant is almost zero, in which case use lstsq solution
6564 if np.allclose(det, 0.0):
6565 warnings.warn(
6566 'Singular matrix detected, using numpy.linalg.lstsq instead.',
6567 RuntimeWarning,
6568 stacklevel=2
6569 )
6570 return innerconnect_s_lstsq(A, k, l)
6571
6572 # Indexing sub-matrices of other external ports
6573 Ake = A[:, k, ext_i].T
6574 Ale = A[:, l, ext_i].T
6575 Aek = A[:, ext_i, k].T
6576 Ael = A[:, ext_i, l].T
6577
6578 # Create an suit-sized s-matrix, to store the result
6579 i, j = np.meshgrid(ext_i, ext_i, indexing='ij', sparse=True)
6580 C = A[:, i, j]
6581
6582 tmp_a = Ael * (Alk / det) + Aek * (All / det)
6583 tmp_b = Ael * (Akk / det) + Aek * (Akl / det)
6584
6585 # loop through ports and calculates resultant s-parameters
6586 for i in range(nA - 2):
6587 C[:, i, :] += (Ake * tmp_a[i] + Ale * tmp_b[i]).T
6588
6589 return C
6590
6591 def innerconnect_s_lstsq(A: np.ndarray, k: int, l: int) -> np.ndarray:
6592 """
6593 Connect two ports of a single n-port network's s-matrix using a
6594 least-squares solution. It uses a least-squares approach to handle
6595 cases where the determinant of the sub-matrix is close to zero, which
6596 can lead to numerical instability in the direct formula.
6597
6598
6599 Note
6600 ----
6601 If the determinant of the sub-matrix is not close to zero, it is recommended
6602 to use the `innerconnect_s` function instead, which uses a direct formula
6603 for better numerical stability.
6604
6605
6606 Parameters
6607 ----------
6608 A : :class:`numpy.ndarray`
6609 S-parameter matrix of `A`, shape is fxnxn
6610 k : int
6611 port index on `A` (port indices start from 0)
6612 l : int
6613 port index on `A`
6614
6615 Returns
6616 -------
6617 AEE : :class:`numpy.ndarray`
6618 new S-parameter matrix
6619
6620
6621 See Also
6622 --------
6623 connect_s : actual S-parameter connection algorithm.
6624 innerconnect_s : actual S-parameter connection algorithm.
6625 """
6626
6627 if k > A.shape[-1] - 1 or l > A.shape[-1] - 1:
6628 raise (ValueError("port indices are out of range"))
6629
6630 nA = A.shape[1] # num of ports on input s-matrix
6631
6632 # Identify internal and external port indices
6633 int_i = (k, l)
6634 ext_i = [i for i in range(nA) if i not in int_i]
6635
6636 # Extract sub-matrices for internal and external ports
6637 AI = A[:, int_i[::-1], :]
6638 AE = A[:, ext_i, :]
6639 AII = AI[:, :, int_i]
6640 AIE = AI[:, :, ext_i]
6641 AEI = AE[:, :, int_i]
6642 AEE = AE[:, :, ext_i]
6643
6644 # Preprocess AII and AEE matrix
6645 AII = np.eye(2)[None, :, :] - AII
6646 C = np.array(AEE, order='C')
6647
6648 # Perform least-squares solution for each frequency
6649 for i in range(A.shape[0]):
6650 C[i, :, :] += AEI[i, :, :] @ np.linalg.lstsq(AII[i, :, :], AIE[i, :, :], rcond=None)[0]
6651
6652 return C
6653
6654
6655 ## network parameter conversion
6656 def s2z(s: np.ndarray, z0: NumberLike = 50, s_def: SdefT = S_DEF_DEFAULT) -> np.ndarray:
6657 r"""
6658 Convert scattering parameters [#]_ to impedance parameters [#]_.
6659
6660
6661 For power-waves, Eq.(19) from [#Kurokawa]_:
6662
6663 .. math::
6664 Z = F^{-1} (1 - S)^{-1} (S G + G^*) F
6665
6666 where :math:`G = diag([Z_0])` and :math:`F = diag([1/2\sqrt{|Re(Z_0)|}])`
6667
6668 For pseudo-waves, Eq.(74) from [#Marks]_:
6669
6670 .. math::
6671 Z = (1 - U^{-1} S U)^{-1} (1 + U^{-1} S U) G
6672
6673 where :math:`U = \sqrt{Re(Z_0)}/|Z_0|`
6674
6675 Parameters
6676 ----------
6677 s : complex array-like
6678 scattering parameters
6679 z0 : complex array-like or number
6680 port impedances.
6681 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
6682 Scattering parameter definition : 'power' for power-waves definition [#Kurokawa]_,
6683 'pseudo' for pseudo-waves definition [#Marks]_.
6684 'traveling' corresponds to the initial implementation.
6685 Default is 'power'.
6686
6687 Returns
6688 -------
6689 z : complex array-like
6690 impedance parameters
6691
6692 References
6693 ----------
6694 .. [#] http://en.wikipedia.org/wiki/S-parameters
6695
6696 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
6697
6698 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
6699 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
6700
6701 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
6702 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
6703
6704 """
6705 nfreqs, nports, nports = s.shape
6706 z0 = fix_z0_shape(z0, nfreqs, nports)
6707
6708 # Add a small real part in case of pure imaginary char impedance
6709 # to prevent numerical errors for both pseudo and power waves definitions
6710 z0 = z0.astype(dtype=complex)
6711 z0[z0.real == 0] += ZERO
6712
6713 s = np.array(s, dtype=complex)
6714
6715 # The following is a vectorized version of a for loop for all frequencies.
6716 # # Creating Identity matrices of shape (nports,nports) for each nfreqs
6717 Id = np.zeros_like(s) # (nfreqs, nports, nports)
6718 np.einsum('ijj->ij', Id)[...] = 1.0
6719
6720 if s_def == 'power':
6721 # Power-waves. Eq.(19) from [Kurokawa et al.]
6722 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
6723 F, G = np.zeros_like(s), np.zeros_like(s)
6724 np.einsum('ijj->ij', F)[...] = 1.0/(2*np.sqrt(z0.real))
6725 np.einsum('ijj->ij', G)[...] = z0
6726 z = np.linalg.solve(mf.nudge_eig((Id - s) @ F), (s @ G + np.conjugate(G)) @ F)
6727
6728 elif s_def == 'pseudo':
6729 # Pseudo-waves. Eq.(74) from [Marks et al.]
6730 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
6731 ZR, U = np.zeros_like(s), np.zeros_like(s)
6732 np.einsum('ijj->ij', U)[...] = np.sqrt(z0.real)/np.abs(z0)
6733 np.einsum('ijj->ij', ZR)[...] = z0
6734 USU = np.linalg.solve(U, s @ U)
6735 z = np.linalg.solve(mf.nudge_eig(Id - USU), (Id + USU) @ ZR)
6736
6737 elif s_def == 'traveling':
6738 # Traveling-waves definition. Cf.Wikipedia "Impedance parameters" page.
6739 # Creating diagonal matrices of shape (nports, nports) for each nfreqs
6740 sqrtz0 = np.zeros_like(s)
6741 np.einsum('ijj->ij', sqrtz0)[...] = np.sqrt(z0)
6742 z = sqrtz0 @ np.linalg.solve(mf.nudge_eig(Id - s), (Id + s) @ sqrtz0)
6743 else:
6744 raise ValueError(f'Unknown s_def: {s_def}')
6745
6746 return z
6747
6748 def s2y(s: np.ndarray, z0:NumberLike = 50, s_def: SdefT = S_DEF_DEFAULT) -> np.ndarray:
6749 """
6750 Convert scattering parameters [#]_ to admittance parameters [#]_.
6751
6752 Equations are the inverse of :func:`s2z`.
6753
6754 Parameters
6755 ----------
6756 s : complex array-like
6757 scattering parameters
6758 z0 : complex array-like or number
6759 port impedances
6760 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
6761 Scattering parameter definition : 'power' for power-waves definition [#]_,
6762 'pseudo' for pseudo-waves definition [#]_.
6763 'traveling' corresponds to the initial implementation.
6764 Default is 'power'.
6765
6766 Returns
6767 -------
6768 y : complex array-like
6769 admittance parameters
6770
6771 See Also
6772 --------
6773 s2z
6774 s2y
6775 s2t
6776 z2s
6777 z2y
6778 z2t
6779 y2s
6780 y2z
6781 y2t
6782 t2s
6783 t2z
6784 t2y
6785 Network.s
6786 Network.y
6787 Network.z
6788 Network.t
6789
6790 References
6791 ----------
6792 .. [#] http://en.wikipedia.org/wiki/S-parameters
6793
6794 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
6795
6796 .. [#] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
6797 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
6798
6799 .. [#] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
6800 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
6801
6802 """
6803 nfreqs, nports, nports = s.shape
6804 z0 = fix_z0_shape(z0, nfreqs, nports)
6805
6806 # Add a small real part in case of pure imaginary char impedance
6807 # to prevent numerical errors for both pseudo and power waves definitions
6808 z0 = z0.astype(dtype=complex)
6809 z0[z0.real == 0] += ZERO
6810
6811 s = np.array(s, dtype=complex)
6812
6813 # The following is a vectorized version of a for loop for all frequencies.
6814 # Creating Identity matrices of shape (nports,nports) for each nfreqs
6815 Id = np.zeros_like(s) # (nfreqs, nports, nports)
6816 np.einsum('ijj->ij', Id)[...] = 1.0
6817
6818 if s_def == 'power':
6819 # Power-waves. Inverse of Eq.(19) from [Kurokawa et al.]
6820 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
6821 F, G = np.zeros_like(s), np.zeros_like(s)
6822 np.einsum('ijj->ij', F)[...] = 1.0/(2*np.sqrt(z0.real))
6823 np.einsum('ijj->ij', G)[...] = z0
6824 y = np.linalg.solve(mf.nudge_eig((s @ G + np.conjugate(G)) @ F), (Id - s) @ F)
6825
6826 elif s_def == 'pseudo':
6827 # pseudo-waves. Inverse of Eq.(74) from [Marks et al.]
6828 YR, U = np.zeros_like(s), np.zeros_like(s)
6829 np.einsum('ijj->ij', U)[...] = np.sqrt(z0.real)/np.abs(z0)
6830 np.einsum('ijj->ij', YR)[...] = 1/z0
6831 USU = np.linalg.solve(U, s @ U)
6832 y = YR @ np.linalg.solve(mf.nudge_eig(Id + USU), Id - USU)
6833
6834 elif s_def == 'traveling':
6835 # Traveling-waves definition. Cf.Wikipedia "Impedance parameters" page.
6836 # Creating diagonal matrices of shape (nports, nports) for each nfreqs
6837 sqrty0 = np.zeros_like(s) # (nfreqs, nports, nports)
6838 np.einsum('ijj->ij', sqrty0)[...] = np.sqrt(1.0/z0)
6839 y = sqrty0 @ (Id - s) @ np.linalg.solve(mf.nudge_eig(Id + s), sqrty0)
6840 else:
6841 raise ValueError(f'Unknown s_def: {s_def}')
6842
6843 return y
6844
6845 def s2t(s: np.ndarray) -> np.ndarray:
6846 """
6847 Convert scattering parameters [#]_ to scattering transfer parameters [#]_.
6848
6849 transfer parameters are also referred to as
6850 'wave cascading matrix' [#]_, this function only operates on 2N-ports
6851 networks with same number of input and output ports, also known as
6852 'balanced networks'.
6853
6854 Parameters
6855 ----------
6856 s : :class:`numpy.ndarray` (shape fx2nx2n)
6857 scattering parameter matrix
6858
6859 Returns
6860 -------
6861 t : np.ndarray
6862 scattering transfer parameters (aka wave cascading matrix)
6863
6864 See Also
6865 --------
6866 inv : calculates inverse s-parameters
6867
6868 s2z
6869 s2y
6870 s2t
6871 z2s
6872 z2y
6873 z2t
6874 y2s
6875 y2z
6876 y2t
6877 t2s
6878 t2z
6879 t2y
6880 Network.s
6881 Network.y
6882 Network.z
6883 Network.t
6884
6885 References
6886 ----------
6887 .. [#] http://en.wikipedia.org/wiki/S-parameters
6888
6889 .. [#] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
6890
6891 .. [#] Janusz A. Dobrowolski, "Scattering Parameter in RF and Microwave Circuit Analysis and Design",
6892 Artech House, 2016, pp. 65-68
6893 """
6894 z, y, x = s.shape
6895 # test here for even number of ports.
6896 # s-parameter networks are square matrix, so x and y are equal.
6897 if(x % 2 != 0):
6898 raise IndexError('Network does not have an even number of ports')
6899 t = np.zeros((z, y, x), dtype=complex)
6900 yh = int(y/2)
6901 xh = int(x/2)
6902 # S_II,I^-1
6903 sinv = np.linalg.inv(s[:, yh:y, 0:xh])
6904 # np.linalg.inv test for singularity (matrix not invertible)
6905 for k in range(len(s)):
6906 w = sinv[k].dot(s[k, yh:y, xh:x])
6907 # T_I,I = S_I,II - S_I,I . S_II,I^-1 . S_II,II
6908 t[k, 0:yh, 0:xh] = s[k, 0:yh, xh:x] - s[k, 0:yh, 0:xh].dot(w)
6909 # T_I,II = S_I,I . S_II,I^-1
6910 t[k, 0:yh, xh:x] = s[k, 0:yh, 0:xh].dot(sinv[k])
6911 # T_II,I = -S_II,I^-1 . S_II,II
6912 t[k, yh:y, 0:xh] = -w
6913 # T_II,II = S_II,I^-1
6914 t[k, yh:y, xh:x] = sinv[k]
6915 return t
6916
6917 def s2s(s: NumberLike, z0: NumberLike, s_def_new: SdefT, s_def_old: SdefT):
6918 r"""
6919 Convert scattering parameters to scattering parameters with different
6920 definition.
6921
6922 Calculates port voltages and currents using the old definition and
6923 then calculates the incoming and reflected waves from the voltages
6924 using the new S-parameter definition.
6925
6926 Only has effect if z0 has at least one complex impedance port.
6927
6928 Parameters
6929 ----------
6930 s : complex array-like
6931 impedance parameters
6932 z0 : complex array-like or number
6933 port impedances
6934 s_def_new : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
6935 Scattering parameter definition of the output network.
6936 'power' for power-waves definition [#Kurokawa]_,
6937 'pseudo' for pseudo-waves definition [#Marks]_.
6938 'traveling' corresponds to the initial implementation.
6939 s_def_old : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
6940 Scattering parameter definition of the input network.
6941 'power' for power-waves definition [#Kurokawa]_,
6942 'pseudo' for pseudo-waves definition [#Marks]_.
6943 'traveling' corresponds to the initial implementation.
6944
6945 Returns
6946 -------
6947 s : complex array-like
6948 scattering parameters
6949
6950 References
6951 ----------
6952 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
6953 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
6954
6955 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
6956 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
6957
6958 """
6959 if s_def_new == s_def_old:
6960 # Nothing to do.
6961 return s
6962
6963 nfreqs, nports, nports = s.shape
6964 z0 = fix_z0_shape(z0, nfreqs, nports)
6965
6966 if np.isreal(z0).all():
6967 # Nothing to do because all port impedances are real so the used
6968 # definition (power or travelling) does not make a difference.
6969 return s
6970
6971 # Calculate port voltages and currents using the old s_def.
6972 F, G = np.zeros_like(s), np.zeros_like(s)
6973 if s_def_old == 'power':
6974 np.einsum('ijj->ij', F)[...] = 1.0/(np.sqrt(z0.real))
6975 np.einsum('ijj->ij', G)[...] = z0
6976 Id = np.eye(s.shape[1], dtype=complex)
6977 v = F @ (G.conjugate() + G @ s)
6978 i = F @ (Id - s)
6979 elif s_def_old == 'pseudo':
6980 np.einsum('ijj->ij', F)[...] = abs(z0)/np.sqrt(z0.real)
6981 np.einsum('ijj->ij', G)[...] = abs(z0)/(z0*np.sqrt(z0.real))
6982 Id = np.eye(s.shape[1], dtype=complex)
6983 v = F @ (Id + s)
6984 i = G @ (Id - s)
6985 elif s_def_old == 'traveling':
6986 np.einsum('ijj->ij', F)[...] = np.sqrt(z0)
6987 np.einsum('ijj->ij', G)[...] = 1/(np.sqrt(z0))
6988 Id = np.eye(s.shape[1], dtype=complex)
6989 v = F @ (Id + s)
6990 i = G @ (Id - s)
6991 else:
6992 raise ValueError(f'Unknown s_def: {s_def_old}')
6993
6994 # Calculate a and b waves from the voltages and currents.
6995 F, G = np.zeros_like(s), np.zeros_like(s)
6996 if s_def_new == 'power':
6997 np.einsum('ijj->ij', F)[...] = 1/(2*np.sqrt(z0.real))
6998 np.einsum('ijj->ij', G)[...] = z0
6999 a = F @ (v + G @ i)
7000 b = F @ (v - G.conjugate() @ i)
7001 elif s_def_new == 'pseudo':
7002 np.einsum('ijj->ij', F)[...] = np.sqrt(z0.real)/(2*abs(z0))
7003 np.einsum('ijj->ij', G)[...] = z0
7004 a = F @ (v + G @ i)
7005 b = F @ (v - G @ i)
7006 elif s_def_new == 'traveling':
7007 np.einsum('ijj->ij', F)[...] = 1/(np.sqrt(z0))
7008 np.einsum('ijj->ij', G)[...] = z0
7009 a = F @ (v + G @ i)
7010 b = F @ (v - G @ i)
7011 else:
7012 raise ValueError(f'Unknown s_def: {s_def_old}')
7013
7014 # New S-parameter matrix from a and b waves.
7015 s_new = np.zeros_like(s)
7016 for n in range(nports):
7017 for m in range(nports):
7018 s_new[:, m, n] = b[:, m, n] / a[:, n, n]
7019
7020 return s_new
7021
7022 def z2s(z: NumberLike, z0:NumberLike = 50, s_def: SdefT = S_DEF_DEFAULT) -> np.ndarray:
7023 r"""
7024 Convert impedance parameters [#]_ to scattering parameters [#]_.
7025
7026 For power-waves, Eq.(18) from [#Kurokawa]_:
7027
7028 .. math::
7029 S = F (Z – G^*) (Z + G)^{-1} F^{-1}
7030
7031 where :math:`G = diag([Z_0])` and :math:`F = diag([1/2\sqrt{|Re(Z_0)|}])`
7032
7033 For pseudo-waves, Eq.(73) from [#Marks]_:
7034
7035 .. math::
7036 S = U (Z - G) (Z + G)^{-1} U^{-1}
7037
7038 where :math:`U = \sqrt{Re(Z_0)}/|Z_0|`
7039
7040
7041 Parameters
7042 ----------
7043 z : complex array-like
7044 impedance parameters
7045 z0 : complex array-like or number
7046 port impedances
7047 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
7048 Scattering parameter definition : 'power' for power-waves definition [#Kurokawa]_,
7049 'pseudo' for pseudo-waves definition [#Marks]_.
7050 'traveling' corresponds to the initial implementation.
7051 Default is 'power'.
7052
7053 Returns
7054 -------
7055 s : complex array-like
7056 scattering parameters
7057
7058
7059
7060 References
7061 ----------
7062 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
7063
7064 .. [#] http://en.wikipedia.org/wiki/S-parameters
7065
7066 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
7067 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
7068
7069 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
7070 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
7071
7072 """
7073 nfreqs, nports, nports = z.shape
7074 z0 = fix_z0_shape(z0, nfreqs, nports)
7075
7076 # Add a small real part in case of pure imaginary char impedance
7077 # to prevent numerical errors for both pseudo and power waves definitions
7078 z0 = z0.astype(dtype=complex)
7079 z0[z0.real == 0] += ZERO
7080
7081 z = np.array(z, dtype=complex)
7082
7083 if s_def == 'power':
7084 # Power-waves. Eq.(18) from [Kurokawa et al.3]
7085 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
7086 F, G = np.zeros_like(z), np.zeros_like(z)
7087 np.einsum('ijj->ij', F)[...] = 1.0/(2*np.sqrt(z0.real))
7088 np.einsum('ijj->ij', G)[...] = z0
7089 s = mf.rsolve(F @ (z + G), F @ (z - np.conjugate(G)))
7090
7091 elif s_def == 'pseudo':
7092 # Pseudo-waves. Eq.(73) from [Marks et al.]
7093 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
7094 ZR, U = np.zeros_like(z), np.zeros_like(z)
7095 np.einsum('ijj->ij', U)[...] = np.sqrt(z0.real)/np.abs(z0)
7096 np.einsum('ijj->ij', ZR)[...] = z0
7097 s = mf.rsolve(U @ (z + ZR), U @ (z - ZR))
7098
7099 elif s_def == 'traveling':
7100 # Traveling-waves definition. Cf.Wikipedia "Impedance parameters" page.
7101 # Creating Identity matrices of shape (nports,nports) for each nfreqs
7102 Id, sqrty0 = np.zeros_like(z), np.zeros_like(z) # (nfreqs, nports, nports)
7103 np.einsum('ijj->ij', Id)[...] = 1.0
7104 np.einsum('ijj->ij', sqrty0)[...] = np.sqrt(1.0/z0)
7105 s = mf.rsolve(sqrty0 @ z @ sqrty0 + Id, sqrty0 @ z @ sqrty0 - Id)
7106 else:
7107 raise ValueError(f'Unknown s_def: {s_def}')
7108
7109 return s
7110
7111 def z2y(z: np.ndarray) -> np.ndarray:
7112 """
7113 Convert impedance parameters [#]_ to admittance parameters [#]_.
7114
7115
7116 .. math::
7117 y = z^{-1}
7118
7119 Parameters
7120 ----------
7121 z : complex array-like
7122 impedance parameters
7123
7124 Returns
7125 -------
7126 y : complex array-like
7127 admittance parameters
7128
7129 See Also
7130 --------
7131 s2z
7132 s2y
7133 s2t
7134 z2s
7135 z2y
7136 z2t
7137 y2s
7138 y2z
7139 y2t
7140 t2s
7141 t2z
7142 t2y
7143 Network.s
7144 Network.y
7145 Network.z
7146 Network.t
7147
7148 References
7149 ----------
7150 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
7151 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
7152 """
7153
7154 if np.amin(np.linalg.matrix_rank(z)) < np.shape(z)[1]:
7155 # matrix is deficient, direct inversion not possible
7156 # try detour via S parameters
7157 warnings.warn('The Z matrix is singular. Conversion to Y parameters could be invalid. Trying s2y(z2s(z)).',
7158 UserWarning, stacklevel=2)
7159 return s2y(z2s(z))
7160 else:
7161 # matrix has full rank, direct inversion possible
7162 return np.linalg.inv(z)
7163
7164 def z2t(z: np.ndarray) -> NoReturn:
7165 """
7166 Not Implemented yet.
7167
7168 Convert impedance parameters [#]_ to scattering transfer parameters [#]_.
7169
7170
7171 Parameters
7172 ----------
7173 z : complex array-like or number
7174 impedance parameters
7175
7176 Returns
7177 -------
7178 s : complex array-like or number
7179 scattering parameters
7180
7181 See Also
7182 --------
7183 s2z
7184 s2y
7185 s2t
7186 z2s
7187 z2y
7188 z2t
7189 y2s
7190 y2z
7191 y2t
7192 t2s
7193 t2z
7194 t2y
7195 Network.s
7196 Network.y
7197 Network.z
7198 Network.t
7199
7200
7201 References
7202 ----------
7203 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
7204 .. [#] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
7205 """
7206 raise (NotImplementedError)
7207
7208
7209 def a2s(a: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7210 """
7211 Convert abcd parameters to s parameters.
7212
7213 Parameters
7214 ----------
7215 a : complex array-like
7216 abcd parameters
7217 z0 : complex array-like or number
7218 port impedances
7219
7220 Returns
7221 -------
7222 s : complex array-like
7223 abcd parameters
7224
7225 """
7226 nfreqs, nports, nports = a.shape
7227
7228 if nports != 2:
7229 raise IndexError('abcd parameters are defined for 2-ports networks only')
7230
7231 z0 = fix_z0_shape(z0, nfreqs, nports)
7232 z01 = z0[:,0]
7233 z02 = z0[:,1]
7234 A = a[:,0,0]
7235 B = a[:,0,1]
7236 C = a[:,1,0]
7237 D = a[:,1,1]
7238 denom = A*z02 + B + C*z01*z02 + D*z01
7239
7240 s = np.array([
7241 [
7242 (A*z02 + B - C*z01.conj()*z02 - D*z01.conj() ) / denom,
7243 (2*np.sqrt(z01.real * z02.real)) / denom,
7244 ],
7245 [
7246 (2*(A*D - B*C)*np.sqrt(z01.real * z02.real)) / denom,
7247 (-A*z02.conj() + B - C*z01*z02.conj() + D*z01) / denom,
7248 ],
7249 ]).transpose()
7250 return s
7251
7252 #return z2s(a2z(a), z0)
7253
7254
7255
7256 def a2z(a: np.ndarray) -> np.ndarray:
7257 """
7258 Convert abcd parameters to z parameters [#]_.
7259
7260
7261 Parameters
7262 ----------
7263 a : :class:`numpy.ndarray` (shape fx2x2)
7264 abcd parameter matrix
7265
7266 Returns
7267 -------
7268 z : np.ndarray
7269 impedance parameters
7270
7271 See Also
7272 --------
7273 inv : calculates inverse s-parameters
7274
7275 s2z
7276 s2y
7277 s2t
7278 z2s
7279 z2y
7280 z2t
7281 y2s
7282 y2z
7283 y2t
7284 t2s
7285 t2z
7286 t2y
7287 Network.s
7288 Network.y
7289 Network.z
7290 Network.t
7291
7292 References
7293 -----------
7294 .. [#] https://en.wikipedia.org/wiki/Two-port_network
7295 """
7296
7297 return z2a(a)
7298
7299
7300 def z2a(z: np.ndarray) -> np.ndarray:
7301 """
7302 Converts impedance parameters to abcd parameters [#]_.
7303
7304
7305 Parameters
7306 ----------
7307 z : :class:`numpy.ndarray` (shape fx2x2)
7308 impedance parameter matrix
7309
7310 Returns
7311 -------
7312 abcd : np.ndarray
7313 scattering transfer parameters (aka wave cascading matrix)
7314
7315 See Also
7316 --------
7317 inv : calculates inverse s-parameters
7318
7319 s2z
7320 s2y
7321 s2t
7322 z2s
7323 z2y
7324 z2t
7325 y2s
7326 y2z
7327 y2t
7328 t2s
7329 t2z
7330 t2y
7331 Network.s
7332 Network.y
7333 Network.z
7334 Network.t
7335
7336 References
7337 ----------
7338 .. [#] https://en.wikipedia.org/wiki/Two-port_network
7339 """
7340 abcd = np.array([
7341 [z[:, 0, 0] / z[:, 1, 0],
7342 1. / z[:, 1, 0]],
7343 [(z[:, 0, 0] * z[:, 1, 1] - z[:, 1, 0] * z[:, 0, 1]) / z[:, 1, 0],
7344 z[:, 1, 1] / z[:, 1, 0]],
7345 ]).transpose()
7346 return abcd
7347
7348
7349 def s2a(s: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7350 """
7351 Convert scattering parameters to abcd parameters [#]_.
7352
7353 Parameters
7354 ----------
7355 s : :class:`numpy.ndarray` (shape `fx2x2`)
7356 impedance parameter matrix
7357
7358 z0: number or, :class:`numpy.ndarray` (shape `fx2`)
7359 port impedance
7360
7361 Returns
7362 -------
7363 abcd : np.ndarray
7364 scattering transfer parameters (aka wave cascading matrix)
7365
7366 References
7367 ----------
7368 .. [#] https://en.wikipedia.org/wiki/Two-port_network
7369
7370 """
7371 nfreqs, nports, nports = s.shape
7372
7373 if nports != 2:
7374 raise IndexError('abcd parameters are defined for 2-ports networks only')
7375
7376 z0 = fix_z0_shape(z0, nfreqs, nports)
7377 z01 = z0[:,0]
7378 z02 = z0[:,1]
7379 denom = (2*s[:,1,0]*np.sqrt(z01.real * z02.real))
7380 a = np.array([
7381 [
7382 ((z01.conj() + s[:,0,0]*z01)*(1 - s[:,1,1]) + s[:,0,1]*s[:,1,0]*z01) / denom,
7383 ((1 - s[:,0,0])*(1 - s[:,1,1]) - s[:,0,1]*s[:,1,0]) / denom,
7384 ],
7385 [
7386 ((z01.conj() + s[:,0,0]*z01)*(z02.conj() + s[:,1,1]*z02) - s[:,0,1]*s[:,1,0]*z01*z02) / denom,
7387 ((1 - s[:,0,0])*(z02.conj() + s[:,1,1]*z02) + s[:,0,1]*s[:,1,0]*z02) / denom,
7388 ],
7389 ]).transpose()
7390 return a
7391
7392
7393 def y2s(y: NumberLike, z0:NumberLike = 50, s_def: SdefT = S_DEF_DEFAULT) -> Network:
7394 r"""
7395 Convert admittance parameters [#]_ to scattering parameters [#]_.
7396
7397 For power-waves, from [#Kurokawa]_:
7398
7399 .. math::
7400 S = F (1 – G Y) (1 + G Y)^{-1} F^{-1}
7401
7402 where :math:`G = diag([Z_0])` and :math:`F = diag([1/2\sqrt{|Re(Z_0)|}])`
7403
7404 For pseudo-waves, Eq.(73) from [#Marks]_:
7405
7406 .. math::
7407 S = U (Y^{-1} - G) (Y^{-1} + G)^{-1} U^{-1}
7408
7409 where :math:`U = \sqrt{Re(Z_0)}/|Z_0|`
7410
7411
7412 Parameters
7413 ----------
7414 y : complex array-like
7415 admittance parameters
7416
7417 z0 : complex array-like or number
7418 port impedances
7419
7420 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
7421 Scattering parameter definition : 'power' for power-waves definition [#Kurokawa]_,
7422 'pseudo' for pseudo-waves definition [#Marks]_.
7423 'traveling' corresponds to the initial implementation.
7424 Default is 'power'.
7425
7426 Returns
7427 -------
7428 s : complex array-like or number
7429 scattering parameters
7430
7431 See Also
7432 --------
7433 s2z
7434 s2y
7435 s2t
7436 z2s
7437 z2y
7438 z2t
7439 y2s
7440 y2z
7441 y2t
7442 t2s
7443 t2z
7444 t2y
7445 Network.s
7446 Network.y
7447 Network.z
7448 Network.t
7449
7450
7451 References
7452 ----------
7453 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
7454
7455 .. [#] http://en.wikipedia.org/wiki/S-parameters
7456
7457 .. [#Kurokawa] Kurokawa, Kaneyuki "Power waves and the scattering matrix",
7458 IEEE Transactions on Microwave Theory and Techniques, vol.13, iss.2, pp. 194–202, March 1965.
7459
7460 .. [#Marks] Marks, R. B. and Williams, D. F. "A general waveguide circuit theory",
7461 Journal of Research of National Institute of Standard and Technology, vol.97, iss.5, pp. 533–562, 1992.
7462
7463 """
7464 nfreqs, nports, nports = y.shape
7465 z0 = fix_z0_shape(z0, nfreqs, nports)
7466
7467 # Add a small real part in case of pure imaginary char impedance
7468 # to prevent numerical errors for both pseudo and power waves definitions
7469 z0 = z0.astype(dtype=complex)
7470 z0[z0.real == 0] += ZERO
7471
7472 y = np.array(y, dtype=complex)
7473
7474 # The following is a vectorized version of a for loop for all frequencies.
7475 # Creating Identity matrices of shape (nports,nports) for each nfreqs
7476 Id = np.zeros_like(y) # (nfreqs, nports, nports)
7477 np.einsum('ijj->ij', Id)[...] = 1.0
7478
7479 if s_def == 'power':
7480 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
7481 F, G = np.zeros_like(y), np.zeros_like(y)
7482 np.einsum('ijj->ij', F)[...] = 1.0/(2*np.sqrt(z0.real))
7483 np.einsum('ijj->ij', G)[...] = z0
7484 s = mf.rsolve(F @ (Id + G @ y), F @ (Id - np.conjugate(G) @ y))
7485
7486 elif s_def == 'pseudo':
7487 # Pseudo-waves
7488 # Creating diagonal matrices of shape (nports,nports) for each nfreqs
7489 ZR, U = np.zeros_like(y), np.zeros_like(y)
7490 np.einsum('ijj->ij', U)[...] = np.sqrt(z0.real)/np.abs(z0)
7491 np.einsum('ijj->ij', ZR)[...] = z0
7492 # This formulation is not very good numerically
7493 UY = mf.rsolve(mf.nudge_eig(y, cond=1e-12), U)
7494 s = mf.rsolve(UY + U @ ZR, -2 * U @ ZR) + Id
7495
7496 elif s_def == 'traveling':
7497 # Traveling-waves definition. Cf.Wikipedia "Impedance parameters" page.
7498 # Creating diagonal matrices of shape (nports, nports) for each nfreqs
7499 sqrtz0 = np.zeros_like(y) # (nfreqs, nports, nports)
7500 np.einsum('ijj->ij', sqrtz0)[...] = np.sqrt(z0)
7501 s = mf.rsolve(Id + sqrtz0 @ y @ sqrtz0, Id - sqrtz0 @ y @ sqrtz0)
7502 else:
7503 raise ValueError(f'Unknown s_def: {s_def}')
7504
7505 return s
7506
7507 def y2z(y: np.ndarray) -> np.ndarray:
7508 """
7509 Convert admittance parameters [#]_ to impedance parameters [#]_.
7510
7511 .. math::
7512
7513 z = y^{-1}
7514
7515 Parameters
7516 ----------
7517 y : complex array-like
7518 admittance parameters
7519
7520 Returns
7521 -------
7522 z : complex array-like
7523 impedance parameters
7524
7525 See Also
7526 --------
7527 s2z
7528 s2y
7529 s2t
7530 z2s
7531 z2y
7532 z2t
7533 y2s
7534 y2z
7535 y2t
7536 t2s
7537 t2z
7538 t2y
7539 Network.s
7540 Network.y
7541 Network.z
7542 Network.t
7543
7544 References
7545 ----------
7546 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
7547 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
7548 """
7549
7550 if np.amin(np.linalg.matrix_rank(y)) < np.shape(y)[1]:
7551 # matrix is deficient, direct inversion not possible
7552 # try detour via S parameters
7553 warnings.warn('The Y matrix is singular. Conversion to Z parameters could be invalid. Trying s2z(y2s(y)).',
7554 UserWarning, stacklevel=2)
7555 return s2z(y2s(y))
7556 else:
7557 # matrix has full rank, direct inversion possible
7558 return np.linalg.inv(y)
7559
7560
7561 def y2t(y: np.ndarray) -> NoReturn:
7562 """
7563 Not Implemented Yet.
7564
7565 Convert admittance parameters [#]_ to scattering-transfer parameters [#]_.
7566
7567
7568 Parameters
7569 ----------
7570 y : complex array-like or number
7571 impedance parameters
7572
7573 Returns
7574 -------
7575 t : complex array-like or number
7576 scattering parameters
7577
7578 See Also
7579 --------
7580 s2z
7581 s2y
7582 s2t
7583 z2s
7584 z2y
7585 z2t
7586 y2s
7587 y2z
7588 y2t
7589 t2s
7590 t2z
7591 t2y
7592 Network.s
7593 Network.y
7594 Network.z
7595 Network.t
7596
7597 References
7598 ----------
7599 .. [#] http://en.wikipedia.org/wiki/Admittance_parameters
7600 .. [#] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
7601 """
7602 raise (NotImplementedError)
7603
7604
7605 def t2s(t: np.ndarray) -> np.ndarray:
7606 """
7607 Converts scattering transfer parameters [1]_ to scattering parameters [2]_.
7608
7609 transfer parameters are also referred to as
7610 'wave cascading matrix', this function only operates on 2N-ports
7611 networks with same number of input and output ports, also known as
7612 'balanced networks' [3]_.
7613
7614 Parameters
7615 ----------
7616 t : :class:`numpy.ndarray` (shape fx2nx2n)
7617 scattering transfer parameters
7618
7619 Returns
7620 -------
7621 s : :class:`numpy.ndarray`
7622 scattering parameter matrix.
7623
7624 See Also
7625 --------
7626 inv : calculates inverse s-parameters
7627 s2z
7628 s2y
7629 s2t
7630 z2s
7631 z2y
7632 z2t
7633 y2s
7634 y2z
7635 y2t
7636 t2s
7637 t2z
7638 t2y
7639 Network.s
7640 Network.y
7641 Network.z
7642 Network.t
7643
7644 References
7645 -----------
7646 .. [1] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
7647 .. [2] http://en.wikipedia.org/wiki/S-parameters
7648 .. [3] Janusz A. Dobrowolski, "Scattering Parameter in RF and Microwave Circuit Analysis and Design",
7649 Artech House, 2016, pp. 65-68
7650 """
7651 z, y, x = t.shape
7652 # test here for even number of ports.
7653 # t-parameter networks are square matrix, so x and y are equal.
7654 if(x % 2 != 0):
7655 raise IndexError('Network does not have an even number of ports')
7656 s = np.zeros((z, y, x), dtype=complex)
7657 yh = int(y/2)
7658 xh = int(x/2)
7659 # T_II,II^-1
7660 tinv = np.linalg.inv(t[:, yh:y, xh:x])
7661 # np.linalg.inv test for singularity (matrix not invertible)
7662 for k in range(len(s)):
7663 # S_I,I = T_I,II . T_II,II^-1
7664 s[k, 0:yh, 0:xh] = t[k, 0:yh, xh:x].dot(tinv[k])
7665 # S_I,II = T_I,I - T_I,I,II . T_II,II^-1 . T_II,I
7666 s[k, 0:yh, xh:x] = t[k, 0:yh, 0:xh]-t[k, 0:yh, xh:x].dot(tinv[k].dot(t[k, yh:y, 0:xh]))
7667 # S_II,I = T_II,II^-1
7668 s[k, yh:y, 0:xh] = tinv[k]
7669 # S_II,II = -T_II,II^-1 . T_II,I
7670 s[k, yh:y, xh:x] = -tinv[k].dot(t[k, yh:y, 0:xh])
7671 return s
7672
7673
7674 def t2z(t: np.ndarray) -> NoReturn:
7675 """
7676 Not Implemented Yet.
7677
7678 Convert scattering transfer parameters [#]_ to impedance parameters [#]_.
7679
7680
7681 Parameters
7682 ----------
7683 t : complex array-like or number
7684 impedance parameters
7685
7686 Returns
7687 -------
7688 z : complex array-like or number
7689 scattering parameters
7690
7691 See Also
7692 --------
7693 s2z
7694 s2y
7695 s2t
7696 z2s
7697 z2y
7698 z2t
7699 y2s
7700 y2z
7701 y2t
7702 t2s
7703 t2z
7704 t2y
7705 Network.s
7706 Network.y
7707 Network.z
7708 Network.t
7709
7710 References
7711 ----------
7712 .. [#] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
7713 .. [#] http://en.wikipedia.org/wiki/impedance_parameters
7714 """
7715 raise (NotImplementedError)
7716
7717
7718 def t2y(t: np.ndarray) -> NoReturn:
7719 """
7720 Not Implemented Yet.
7721
7722 Convert scattering transfer parameters to admittance parameters [#]_.
7723
7724
7725 Parameters
7726 ----------
7727 t : complex array-like or number
7728 t-parameters
7729
7730 Returns
7731 -------
7732 y : complex array-like or number
7733 admittance parameters
7734
7735 See Also
7736 --------
7737 s2z
7738 s2y
7739 s2t
7740 z2s
7741 z2y
7742 z2t
7743 y2s
7744 y2z
7745 y2t
7746 t2s
7747 t2z
7748 t2y
7749 Network.s
7750 Network.y
7751 Network.z
7752 Network.t
7753
7754 References
7755 ----------
7756 .. [#] http://en.wikipedia.org/wiki/Scattering_transfer_parameters#Scattering_transfer_parameters
7757
7758 """
7759 raise (NotImplementedError)
7760
7761
7762 def h2z(h: np.ndarray) -> np.ndarray:
7763 """
7764 Convert hybrid parameters to z parameters [#]_.
7765
7766
7767 Parameters
7768 ----------
7769 h : :class:`numpy.ndarray` (shape fx2x2)
7770 hybrid parameter matrix
7771
7772 Returns
7773 -------
7774 z : np.ndarray
7775 impedance parameters
7776
7777 See Also
7778 --------
7779 inv : calculates inverse s-parameters
7780
7781 s2z
7782 s2y
7783 s2t
7784 z2s
7785 z2y
7786 z2t
7787 y2s
7788 y2z
7789 y2t
7790 t2s
7791 t2z
7792 t2y
7793 Network.s
7794 Network.y
7795 Network.z
7796 Network.t
7797
7798 References
7799 -----------
7800 .. [#] https://en.wikipedia.org/wiki/Two-port_network
7801 """
7802
7803 return z2h(h)
7804
7805
7806 def h2s(h: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7807 """
7808 Convert hybrid parameters to s parameters.
7809
7810 Parameters
7811 ----------
7812 h : complex array-like
7813 hybrid parameters
7814 z0 : complex array-like or number
7815 port impedances
7816
7817 Returns
7818 -------
7819 s : complex array-like
7820 scattering parameters
7821
7822 """
7823
7824 return z2s(h2z(h), z0)
7825
7826
7827 def s2h(s: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7828 """
7829 Convert scattering parameters [#]_ to hybrid parameters [#]_.
7830
7831
7832 Parameters
7833 ----------
7834 s : complex array-like
7835 scattering parameters
7836 z0 : complex array-like or number
7837 port impedances.
7838
7839 Returns
7840 -------
7841 h : complex array-like
7842 hybrid parameters
7843
7844
7845
7846 References
7847 ----------
7848 .. [#] http://en.wikipedia.org/wiki/S-parameters
7849 .. [#] http://en.wikipedia.org/wiki/Two-port_network#Hybrid_parameters_(h-parameters)
7850
7851 """
7852 return z2h(s2z(s, z0))
7853
7854
7855 def z2h(z: np.ndarray) -> np.ndarray:
7856 """
7857 Convert impedance parameters to hybrid parameters [#]_.
7858
7859
7860 Parameters
7861 ----------
7862 z : :class:`numpy.ndarray` (shape fx2x2)
7863 impedance parameter matrix
7864
7865 Returns
7866 -------
7867 h : np.ndarray
7868 hybrid parameters
7869
7870 See Also
7871 --------
7872 inv : calculates inverse s-parameters
7873
7874 s2z
7875 s2y
7876 s2t
7877 z2s
7878 z2y
7879 z2t
7880 y2s
7881 y2z
7882 y2t
7883 t2s
7884 t2z
7885 t2y
7886 Network.s
7887 Network.y
7888 Network.z
7889 Network.t
7890
7891 References
7892 -----------
7893 .. [#] https://en.wikipedia.org/wiki/Two-port_network
7894 """
7895 h = np.array([
7896 [(z[:, 0, 0] * z[:, 1, 1] - z[:, 1, 0] * z[:, 0, 1]) / z[:, 1, 1],
7897 -z[:, 1, 0] / z[:, 1, 1]],
7898 [z[:, 0, 1] / z[:, 1, 1],
7899 1. / z[:, 1, 1]],
7900 ]).transpose()
7901 return h
7902
7903 def g2s(g: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7904 """
7905 Convert inverse hybrid parameters to s parameters.
7906
7907 Parameters
7908 ----------
7909 g : complex array-like
7910 inverse hybrid parameters
7911 z0 : complex array-like or number
7912 port impedances
7913
7914 Returns
7915 -------
7916 s : complex array-like
7917 scattering parameters
7918
7919 """
7920 return h2s(np.linalg.inv(g), z0)
7921
7922 def s2g(s: np.ndarray, z0: NumberLike = 50) -> np.ndarray:
7923 """
7924 Convert inverse hybrid parameters to s parameters.
7925
7926 Parameters
7927 ----------
7928 s : complex array-like
7929 scattering parameters
7930 z0 : complex array-like or number
7931 port impedances
7932
7933 Returns
7934 -------
7935 g : complex array-like
7936 inverse hybrid parameters
7937
7938 """
7939 return z2h(s2y(s, z0))
7940
7941
7942 ## these methods are used in the secondary properties
7943 def passivity(s: np.ndarray) -> np.ndarray:
7944 r"""
7945 Passivity metric for a multi-port network.
7946
7947 A metric which is proportional to the amount of power lost in a
7948 multiport network, depending on the excitation port. Specifically,
7949 this returns a matrix who's diagonals are equal to the total
7950 power received at all ports, normalized to the power at a single
7951 excitement port.
7952
7953 mathematically, this is a test for unitary-ness of the
7954 s-parameter matrix [#]_.
7955
7956 for two port this is
7957
7958 .. math::
7959
7960 \sqrt( |S_{11}|^2 + |S_{21}|^2 \, , \, |S_{22}|^2+|S_{12}|^2)
7961
7962 in general it is
7963
7964 .. math::
7965
7966 \sqrt( S^H \cdot S)
7967
7968 where :math:`H` is conjugate transpose of S, and :math:`\cdot`
7969 is dot product.
7970
7971 Note
7972 ----
7973 The total amount of power dissipated in a network depends on the
7974 port matches. For example, given a matched attenuator, this metric
7975 will yield the attenuation value. However, if the attenuator is
7976 cascaded with a mismatch, the power dissipated will not be equivalent
7977 to the attenuator value, nor equal for each excitation port.
7978
7979
7980 Returns
7981 -------
7982 passivity : :class:`numpy.ndarray` of shape fxnxn
7983
7984 References
7985 ------------
7986 .. [#] http://en.wikipedia.org/wiki/Scattering_parameters#Lossless_networks
7987 """
7988 if s.shape[-1] == 1:
7989 raise (ValueError('Doesn\'t exist for one ports'))
7990
7991 pas_mat = s.copy()
7992 for f in range(len(s)):
7993 pas_mat[f, :, :] = np.sqrt(np.dot(s[f, :, :].conj().T, s[f, :, :]))
7994
7995 return pas_mat
7996
7997
7998 def reciprocity(s: np.ndarray) -> np.ndarray:
7999 """
8000 Reciprocity metric for a multi-port network.
8001
8002 This returns the magnitude of the difference between the
8003 s-parameter matrix and its transpose.
8004
8005 for two port this is
8006
8007 .. math::
8008
8009 | S - S^T |
8010
8011
8012 where :math:`T` is transpose of S
8013
8014 Parameters
8015 ----------
8016 s : :class:`numpy.ndarray` of shape `fxnxn`
8017 s-parameter matrix
8018
8019 Returns
8020 -------
8021 reciprocity : :class:`numpy.ndarray` of shape `fxnxn`
8022 """
8023 if s.shape[-1] == 1:
8024 raise (ValueError('Doesn\'t exist for one ports'))
8025
8026 rec_mat = s.copy()
8027 for f in range(len(s)):
8028 rec_mat[f, :, :] = abs(s[f, :, :] - s[f, :, :].T)
8029
8030 return rec_mat
8031
8032
8033 ## renormalize
8034 def renormalize_s(
8035 s: np.ndarray, z_old: NumberLike, z_new: NumberLike,
8036 s_def: SdefT = S_DEF_DEFAULT, s_def_old: SdefT | None = None
8037 ) -> np.ndarray:
8038
8039 """
8040 Renormalize a s-parameter matrix given old and new port impedances.
8041 Can be also used to convert between different S-parameter definitions.
8042
8043
8044 Note
8045 ----
8046 This re-normalization assumes power-wave formulation per default.
8047 To use the pseudo-wave formulation, use s_def='pseudo'.
8048 However, results should be the same for real-valued characteristic impedances.
8049 See the [#Marks]_ and [#Anritsu]_ for more details.
8050
8051
8052 Note
8053 ----
8054 This just calls ::
8055
8056 z2s(s2z(s, z0=z_old, s_def=s_def_old), z0=z_new, s_def=s_def)
8057
8058
8059
8060 Parameters
8061 ----------
8062 s : complex array of shape `fxnxn`
8063 s-parameter matrix
8064
8065 z_old : complex array of shape `fxnxn` or a scalar
8066 old (original) port impedances
8067
8068 z_new : complex array of shape `fxnxn` or a scalar
8069 new port impedances
8070
8071 s_def : str -> s_def : can be: 'power', 'pseudo' or 'traveling'
8072 Scattering parameter definition of the output network:
8073 'power' for power-waves definition,
8074 'pseudo' for pseudo-waves definition.
8075 'traveling' corresponds to the initial implementation.
8076 Default is 'power'.
8077
8078 s_def_old : str -> s_def : can be: None, 'power', 'pseudo' or 'traveling'
8079 Scattering parameter definition of the input network:
8080 None to copy s_def.
8081 'power' for power-waves definition,
8082 'pseudo' for pseudo-waves definition.
8083 'traveling' corresponds to the initial implementation.
8084
8085 Returns
8086 -------
8087 :class:`numpy.ndarray`
8088 renormalized s-parameter matrix (shape `fxnxn`)
8089
8090 See Also
8091 --------
8092 Network.renormalize : method of Network to renormalize s
8093 fix_z0_shape
8094 s2z
8095 z2s
8096
8097 References
8098 ----------
8099 .. [#Marks] R. B. Marks and D. F. Williams, "A general waveguide circuit theory,"
8100 Journal of Research of the National Institute of Standards and Technology, vol. 97, no. 5, pp. 533-561, 1992.
8101
8102 .. [#Anritsu] Anritsu Application Note: Arbitrary Impedance,
8103 https://web.archive.org/web/20200111134414/https://archive.eetasia.com/www.eetasia.com/ARTICLES/2002MAY/2002MAY02_AMD_ID_NTES_AN.PDF?SOURCES=DOWNLOAD
8104
8105 Examples
8106 --------
8107 >>> s = zeros(shape=(101,2,2))
8108 >>> renormalize_s(s, 50,25)
8109
8110
8111 """
8112 if s_def_old not in S_DEFINITIONS and s_def_old is not None:
8113 raise ValueError('s_def_old parameter should be one of:', S_DEFINITIONS)
8114 if s_def_old is None:
8115 s_def_old = s_def
8116 if s_def not in S_DEFINITIONS:
8117 raise ValueError('s_def parameter should be one of:', S_DEFINITIONS)
8118 # that's a heck of a one-liner!
8119 return z2s(s2z(s, z0=z_old, s_def=s_def_old), z0=z_new, s_def=s_def)
8120
8121 def fix_param_shape(p: NumberLike):
8122 """
8123 Attempt to broadcast p to satisfy.
8124 np.shape(p) == (nfreqs, nports, nports)
8125
8126 Parameters
8127 ----------
8128 p : number, array-like
8129 p can be:
8130 * a number (one frequency, one port)
8131 * 1D array-like (many frequencies, one port)
8132 * 2D array-like (one frequency, many ports)
8133 * 3D array-like (many frequencies, many ports)
8134
8135 Returns
8136 -------
8137 p : array of shape == (nfreqs, nports, nports)
8138 p with the right shape for a nport Network
8139
8140 """
8141 # Ensure input is numpy array
8142 p = np.array(p, dtype=complex)
8143 if len(p.shape) == 0:
8144 # Scalar
8145 return p.reshape(1, 1, 1)
8146 if len(p.shape) == 1:
8147 # One port with many frequencies
8148 return p.reshape(p.shape[0], 1, 1)
8149 if p.shape[-1] != p.shape[-2]:
8150 raise ValueError('Input matrix must be square')
8151 if len(p.shape) == 2:
8152 # Many port with one frequency
8153 return p.reshape(-1, p.shape[0], p.shape[0])
8154 if len(p.shape) != 3:
8155 raise ValueError(f'Input array has too many dimensions. Shape: {p.shape}')
8156 return p
8157
8158 def fix_z0_shape(z0: NumberLike, nfreqs: int, nports: int) -> np.ndarray:
8159 """
8160 Make a port impedance of correct shape for a given network's matrix.
8161
8162 This attempts to broadcast z0 to satisfy
8163 np.shape(z0) == (nfreqs,nports)
8164
8165 Parameters
8166 ----------
8167 z0 : number, array-like
8168 z0 can be:
8169 * a number (same at all ports and frequencies)
8170 * an array-like of length == number ports.
8171 * an array-like of length == number frequency points.
8172 * the correct shape ==(nfreqs,nports)
8173
8174 nfreqs : int
8175 number of frequency points
8176 nports : int
8177 number of ports
8178
8179 Returns
8180 -------
8181 z0 : array of shape ==(nfreqs,nports)
8182 z0 with the right shape for a nport Network
8183
8184 Examples
8185 --------
8186 For a two-port network with 201 frequency points, possible uses may
8187 be
8188
8189 >>> z0 = rf.fix_z0_shape(50 , 201,2)
8190 >>> z0 = rf.fix_z0_shape([50,25] , 201,2)
8191 >>> z0 = rf.fix_z0_shape(range(201) , 201,2)
8192
8193
8194 """
8195 if np.shape(z0) == (nfreqs, nports):
8196 # z0 is of correct shape. super duper.return it quick.
8197 return z0.copy()
8198
8199 elif np.ndim(z0) == 0:
8200 # z0 is a single number or np.array without dimensions.
8201 return np.array(nfreqs * [nports * [z0]])
8202
8203 elif len(z0) == nports:
8204 # assume z0 is a list of impedances for each port,
8205 # but constant with frequency
8206 return np.array(nfreqs * [z0])
8207
8208 elif len(z0) == nfreqs:
8209 # assume z0 is a list of impedances for each frequency,
8210 # but constant with respect to ports
8211 return np.array(nports * [z0]).T
8212
8213 else:
8214 raise IndexError('z0 is not an acceptable shape')
8215
8216
8217 ## cascading assistance functions
8218 def inv(s: np.ndarray) -> np.ndarray:
8219 """
8220 Calculate 'inverse' s-parameter matrix, used for de-embedding.
8221
8222 This is not literally the inverse of the s-parameter matrix.
8223 Instead, it is defined such that the inverse of the s-matrix cascaded
8224 with itself is a unity scattering transfer parameter (T) matrix.
8225
8226 .. math::
8227
8228 inv(s) = t2s({s2t(s)}^{-1})
8229
8230 where :math:`x^{-1}` is the matrix inverse. In words, this
8231 is the inverse of the scattering transfer parameters matrix
8232 transformed into a scattering parameters matrix.
8233
8234 Parameters
8235 ----------
8236 s : :class:`numpy.ndarray` (shape fx2nx2n)
8237 scattering parameter matrix.
8238
8239 Returns
8240 -------
8241 s' : :class:`numpy.ndarray`
8242 inverse scattering parameter matrix.
8243
8244 See Also
8245 --------
8246 t2s : converts scattering transfer parameters to scattering parameters
8247 s2t : converts scattering parameters to scattering transfer parameters
8248
8249
8250 """
8251 # this idea is from lihan
8252 t = s2t(s)
8253 tinv = np.linalg.inv(t)
8254 sinv = t2s(tinv)
8255 #for f in range(len(i)):
8256 # i[f, :, :] = np.linalg.inv(i[f, :, :]) # could also be written as
8257 # # np.mat(i[f,:,:])**-1 -- Trey
8258
8259 return sinv
8260
8261
8262 def flip(a: np.ndarray) -> np.ndarray:
8263 """
8264 Invert the ports of a networks s-matrix, 'flipping' it over left and right.
8265
8266 In case the network is 2n-port and n > 1, 'second' numbering scheme is
8267 assumed to be consistent with the ** cascade operator::
8268
8269 +--------+ +--------+
8270 0-|0 n|-n 0-|n 0|-n
8271 1-|1 n+1|-n+1 flip 1-|n+1 1|-n+1
8272 ... ... => ... ...
8273 n-1-|n-1 2n-1|-2n-1 n-1-|2n-1 n-1|-2n-1
8274 +--------+ +--------+
8275
8276 Parameters
8277 ----------
8278 a : :class:`numpy.ndarray`
8279 scattering parameter matrix. shape should be `2nx2n`, or
8280 `fx2nx2n`
8281
8282 Returns
8283 -------
8284 c : :class:`numpy.ndarray`
8285 flipped scattering parameter matrix
8286
8287 See Also
8288 --------
8289 renumber
8290 """
8291 c = a.copy()
8292 n2 = a.shape[-1]
8293 m2 = a.shape[-2]
8294 n = int(n2/2)
8295 if (n2 == m2) and (n2 % 2 == 0):
8296 old = list(range(0,2*n))
8297 new = list(range(n,2*n)) + list(range(0,n))
8298 if(len(a.shape) == 2):
8299 c[new, :] = c[old, :] # renumber rows
8300 c[:, new] = c[:, old] # renumber columns
8301 else:
8302
8303 c[:, new, :] = c[:, old, :] # renumber rows
8304 c[:, :, new] = c[:, :, old] # renumber columns
8305 else:
8306 raise IndexError('matrices should be 2nx2n, or kx2nx2n')
8307 return c
8308
8309
8310 ## COMMON CHECKS (raise exceptions)
8311 def check_frequency_equal(ntwkA: Network, ntwkB: Network) -> None:
8312 """
8313 Check if two Networks have same frequency.
8314 """
8315 if not assert_frequency_equal(ntwkA, ntwkB):
8316 raise IndexError('Networks don\'t have matching frequency. See `Network.interpolate`')
8317
8318
8319 def check_frequency_exist(ntwk) -> None:
8320 """
8321 Check if a Network has a non-zero Frequency.
8322 """
8323 if not assert_frequency_exist(ntwk):
8324 raise ValueError('Network has no Frequency. Frequency points must be defined.')
8325
8326
8327 def check_z0_equal(ntwkA: Network, ntwkB: Network) -> None:
8328 """
8329 Check if two Networks have same port impedances.
8330 """
8331 # note you should check frequency equal before you call this
8332 if not assert_z0_equal(ntwkA, ntwkB):
8333 raise ValueError('Networks don\'t have matching z0.')
8334
8335
8336 def check_nports_equal(ntwkA: Network, ntwkB: Network) -> None:
8337 """
8338 Check if two Networks have same number of ports.
8339 """
8340 if not assert_nports_equal(ntwkA, ntwkB):
8341 raise ValueError('Networks don\'t have matching number of ports.')
8342
8343
8344 ## TESTs (return [usually boolean] values)
8345 def assert_frequency_equal(ntwkA: Network, ntwkB: Network) -> bool:
8346 """
8347 """
8348 return (ntwkA.frequency == ntwkB.frequency)
8349
8350
8351 def assert_frequency_exist(ntwk: Network) -> bool:
8352 """
8353 Test if the Network Frequency is defined.
8354
8355 Returns
8356 -------
8357 bool: boolean
8358
8359 """
8360 return bool(len(ntwk.frequency))
8361
8362
8363 def assert_z0_equal(ntwkA: Network, ntwkB: Network) -> bool:
8364 """
8365 """
8366 return (ntwkA.z0 == ntwkB.z0).all()
8367
8368
8369 def assert_z0_at_ports_equal(ntwkA: Network, k: int, ntwkB: Network, l: int) -> bool:
8370 """
8371 """
8372 return (ntwkA.z0[:, k] == ntwkB.z0[:, l]).all()
8373
8374
8375 def assert_nports_equal(ntwkA: Network, ntwkB: Network) -> bool:
8376 """
8377 """
8378 return (ntwkA.number_of_ports == ntwkB.number_of_ports)
8379
8380
8381 ## Other
8382 # don't belong here, but i needed them quickly
8383 # this is needed for port impedance mismatches
8384 def impedance_mismatch(z1: NumberLike, z2: NumberLike, s_def: SdefT = 'traveling') -> np.ndarray:
8385 """
8386 Create a two-port s-matrix for a impedance mismatch.
8387
8388 Parameters
8389 ----------
8390 z1 : number or array-like
8391 complex impedance of port 1
8392 z2 : number or array-like
8393 complex impedance of port 2
8394 s_def : str, optional. Default is 'traveling'.
8395 Scattering parameter definition:
8396 'power' for power-waves definition,
8397 'pseudo' for pseudo-waves definition.
8398 'traveling' corresponds to the initial implementation.
8399 NB: results are the same for real-valued characteristic impedances.
8400
8401 Returns
8402 -------
8403 s : 2-port s-matrix for the impedance mismatch
8404
8405 References
8406 ----------
8407 .. [#] R. B. Marks et D. F. Williams, A general waveguide circuit theory,
8408 J. RES. NATL. INST. STAN., vol. 97, no. 5, p. 533, sept. 1992.
8409 """
8410 from .tlineFunctions import zl_2_Gamma0
8411 gamma = zl_2_Gamma0(z1, z2)
8412 result = np.zeros(shape=(len(gamma), 2, 2), dtype='complex')
8413
8414 if s_def == 'traveling':
8415 result[:, 0, 0] = gamma
8416 result[:, 1, 1] = -gamma
8417 result[:, 1, 0] = (1 + gamma) * np.sqrt(1.0 * z1 / z2)
8418 result[:, 0, 1] = (1 - gamma) * np.sqrt(1.0 * z2 / z1)
8419 elif s_def == 'pseudo':
8420 n = np.abs(z2/z1) * np.sqrt(z1.real / z2.real)
8421 result[:, 0, 0] = gamma
8422 result[:, 1, 1] = -gamma
8423 result[:, 1, 0] = 2 * z2 / (n * (z1 + z2))
8424 result[:, 0, 1] = 2 * z1 * n / (z1 + z2)
8425 elif s_def == 'power':
8426 n = np.sqrt(z1.real / z2.real)
8427 result[:, 0, 0] = (z2 - z1.conjugate()) / (z1 + z2)
8428 result[:, 1, 1] = (z1 - z2.conjugate()) / (z1 + z2)
8429 result[:, 1, 0] = (2 * z1.real) / (n * (z1 + z2))
8430 result[:, 0, 1] = (2 * z2.real) * n / (z1 + z2)
8431 else:
8432 raise ValueError(f'Unsupported s_def: {s_def}')
8433
8434 return result
8435
8436
8437 def two_port_reflect(ntwk1: Network, ntwk2: Network | None = None, name : str | None = None) -> Network:
8438 """
8439 Generate a two-port reflective two-port, from two one-ports.
8440
8441
8442 Parameters
8443 ----------
8444 ntwk1 : one-port Network object
8445 network seen from port 1
8446 ntwk2 : one-port Network object, or None
8447 network seen from port 2. if None then will use ntwk1.
8448 name: Name for the combined network. If None, then construct the name
8449 from the names of the input networks
8450
8451 Returns
8452 -------
8453 result : Network object
8454 two-port reflective network
8455
8456
8457 Note
8458 ----
8459 The resultant Network is copied from `ntwk1`, so its various
8460 properties(name, frequency, etc.) are inherited from that Network.
8461
8462
8463 Examples
8464 --------
8465 >>> short,open = rf.Network('short.s1p', rf.Network('open.s1p')
8466 >>> rf.two_port_reflect(short,open)
8467 """
8468 result = ntwk1.copy()
8469 if ntwk2 is None:
8470 ntwk2 = ntwk1
8471 s11 = ntwk1.s[:, 0, 0]
8472 s22 = ntwk2.s[:, 0, 0]
8473 s21 = np.zeros(ntwk1.frequency.npoints, dtype=complex)
8474 result.s = np.array( \
8475 [[s11, s21], \
8476 [s21, s22]]). \
8477 transpose().reshape(-1, 2, 2)
8478 result.z0 = np.hstack([ntwk1.z0, ntwk2.z0])
8479
8480 if name is None:
8481 try:
8482 result.name = ntwk1.name + '-' + ntwk2.name
8483 except(TypeError):
8484 pass
8485 else:
8486 result.name = name
8487 return result
8488
8489 def s2s_active(s: np.ndarray, a:np.ndarray) -> np.ndarray:
8490 r"""
8491 Return active s-parameters for a defined wave excitation a.
8492
8493 The active s-parameter at a port is the reflection coefficients
8494 when other ports are excited. It is an important quantity for active
8495 phased array antennas.
8496
8497 Active s-parameters are defined by [#]_:
8498
8499 .. math::
8500
8501 \mathrm{active}(s)_{m} = \sum_{i=1}^N\left( s_{mi} a_i \right) / a_m
8502
8503 where :math:`s` are the scattering parameters and :math:`N` the number of ports
8504
8505 Parameters
8506 ----------
8507 s : complex array
8508 scattering parameters (nfreqs, nports, nports)
8509
8510 a : complex array of shape (n_ports)
8511 forward wave complex amplitude (pseudowave formulation [#]_)
8512
8513 Returns
8514 -------
8515 s_act : complex array of shape (n_freqs, n_ports)
8516 active S-parameters for the excitation a
8517
8518 See Also
8519 --------
8520 s2z_active : active Z-parameters
8521 s2y_active : active Y-parameters
8522 s2vswr_active : active VSWR
8523
8524 References
8525 ----------
8526 .. [#] D. M. Pozar, IEEE Trans. Antennas Propag. 42, 1176 (1994).
8527
8528 .. [#] D. Williams, IEEE Microw. Mag. 14, 38 (2013).
8529
8530 """
8531 a = np.asarray(a, dtype=complex)
8532 a[a == 0] = 1e-12 # solve numerical singularity
8533 s_act = np.einsum('fmi,i,m->fm', s, a, np.reciprocal(a))
8534 return s_act # shape : (n_freqs, n_ports)
8535
8536 def s2z_active(s: np.ndarray, z0: NumberLike, a: np.ndarray) -> np.ndarray:
8537 r"""
8538 Return the active Z-parameters for a defined wave excitation a.
8539
8540 The active Z-parameters are defined by:
8541
8542 .. math::
8543
8544 \mathrm{active}(z)_{m} = z_{0,m} \frac{1 + \mathrm{active}(s)_m}{1 - \mathrm{active}(s)_m}
8545
8546 where :math:`z_{0,m}` is the characteristic impedance and
8547 :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
8548
8549 Parameters
8550 ----------
8551 s : complex array
8552 scattering parameters (nfreqs, nports, nports)
8553
8554 z0 : complex array-like or number
8555 port impedances.
8556
8557 a : complex array of shape (n_ports)
8558 forward wave complex amplitude
8559
8560 Returns
8561 -------
8562 z_act : complex array of shape (nfreqs, nports)
8563 active Z-parameters for the excitation a
8564
8565 See Also
8566 --------
8567 s2s_active : active S-parameters
8568 s2y_active : active Y-parameters
8569 s2vswr_active : active VSWR
8570
8571 """
8572 # TODO : vectorize the for loop
8573 nfreqs, nports, nports = s.shape
8574 z0 = fix_z0_shape(z0, nfreqs, nports)
8575 s_act = s2s_active(s, a)
8576 z_act = np.einsum('fp,fp,fp->fp', z0, 1 + s_act, np.reciprocal(1 - s_act))
8577 return z_act
8578
8579 def s2y_active(s: np.ndarray, z0: NumberLike, a: np.ndarray) -> np.ndarray:
8580 r"""
8581 Return the active Y-parameters for a defined wave excitation a.
8582
8583 The active Y-parameters are defined by:
8584
8585 .. math::
8586
8587 \mathrm{active}(y)_{m} = y_{0,m} \frac{1 - \mathrm{active}(s)_m}{1 + \mathrm{active}(s)_m}
8588
8589 where :math:`y_{0,m}` is the characteristic admittance and
8590 :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
8591
8592 Parameters
8593 ----------
8594 s : complex array
8595 scattering parameters (nfreqs, nports, nports)
8596
8597 z0 : complex array-like or number
8598 port impedances.
8599
8600 a : complex array of shape (n_ports)
8601 forward wave complex amplitude
8602
8603 Returns
8604 -------
8605 y_act : complex array of shape (nfreqs, nports)
8606 active Y-parameters for the excitation a
8607
8608 See Also
8609 --------
8610 s2s_active : active S-parameters
8611 s2z_active : active Z-parameters
8612 s2vswr_active : active VSWR
8613 """
8614 nfreqs, nports, nports = s.shape
8615 z0 = fix_z0_shape(z0, nfreqs, nports)
8616 s_act = s2s_active(s, a)
8617 y_act = np.einsum('fp,fp,fp->fp', np.reciprocal(z0), 1 - s_act, np.reciprocal(1 + s_act))
8618 return y_act
8619
8620 def s2vswr_active(s: np.ndarray, a: np.ndarray) -> np.ndarray:
8621 r"""
8622 Return the active VSWR for a defined wave excitation a..
8623
8624 The active VSWR is defined by :
8625
8626 .. math::
8627
8628 \mathrm{active}(vswr)_{m} = \frac{1 + |\mathrm{active}(s)_m|}{1 - |\mathrm{active}(s)_m|}
8629
8630 where :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`.
8631
8632
8633 Parameters
8634 ----------
8635 s : complex array
8636 scattering parameters (nfreqs, nports, nports)
8637
8638 a : complex array of shape (n_ports)
8639 forward wave complex amplitude
8640
8641 Returns
8642 -------
8643 vswr_act : complex array of shape (nfreqs, nports)
8644 active VSWR for the excitation a
8645
8646 See Also
8647 --------
8648 s2s_active : active S-parameters
8649 s2z_active : active Z-parameters
8650 s2y_active : active Y-parameters
8651 """
8652 s_act = s2s_active(s, a)
8653 vswr_act = np.einsum('fp,fp->fp', (1 + np.abs(s_act)), np.reciprocal(1 - np.abs(s_act)))
8654 return vswr_act
8655
8656 def twoport_to_nport(ntwk: Network, port1: int, port2: int, nports: int, **kwargs):
8657 r"""
8658 Add ports to two-port. S-parameters of added ports are all zeros.
8659
8660 Parameters
8661 ----------
8662 ntwk : Two-port Network object
8663 port1: int
8664 First port of the two-port in the resulting N-port.
8665 port2: int
8666 Second port of the two-port in the resulting N-port.
8667 nports: int
8668 Number of ports in the N-port network.
8669 \*\*kwargs:
8670 Passed to :func:`Network.__init__` for resultant network.
8671
8672 Returns
8673 -------
8674 nport: N-port Network object
8675 """
8676 fpoints = len(ntwk.frequency)
8677 nport = Network(frequency=ntwk.frequency,
8678 s=np.zeros(shape=(fpoints, nports, nports)),
8679 name=ntwk.name,
8680 **kwargs)
8681 nport.s[:,port1,port1] = ntwk.s[:,0,0]
8682 nport.s[:,port2,port1] = ntwk.s[:,1,0]
8683 nport.s[:,port1,port2] = ntwk.s[:,0,1]
8684 nport.s[:,port2,port2] = ntwk.s[:,1,1]
8685 nport.z0[:,port1] = ntwk.z0[:,0]
8686 nport.z0[:,port2] = ntwk.z0[:,1]
8687 return nport