Debian Codegraph @

skrf/media/media.py

raw symbols SCIP
1 """
2 media (:mod:`skrf.media.media`)
3 ========================================
4
5 Media class.
6
7 .. autosummary::
8 :toctree: generated/
9
10 Media
11 DefinedGammaZ0
12
13 """
14 from __future__ import annotations
15
16 import re
17 import warnings
18 from abc import ABC, abstractmethod
19 from copy import deepcopy as copy
20 from numbers import Number
21 from pathlib import Path
22
23 import numpy as np
24 from numpy import any, array, gradient, imag, ones, real
25 from scipy import stats
26 from scipy.constants import c
27
28 from .. import mathFunctions as mf
29 from ..constants import INF, S_DEF_DEFAULT, ZERO, NumberLike, to_meters
30 from ..frequency import Frequency
31 from ..network import Network, connect, impedance_mismatch, innerconnect
32
33
34 class Media(ABC):
35 """
36 Abstract Base Class for a single mode on a transmission line media.
37
38
39 This class init's with `frequency` and `z0_port` (the port impedance);
40 attributes shared by all media. Methods defined here make use of the
41 properties :
42
43 * `gamma` - (complex) media propagation constant
44 * `z0` - (complex) media characteristic impedance
45
46 Which define the properties of a specific media. Any sub-class of Media
47 must implement these properties. `gamma` and `z0` should return
48 complex arrays of the same length as `frequency`. `gamma` must
49 follow the convention:
50
51 * positive real(gamma) = attenuation
52 * positive imag(gamma) = forward propagation
53
54 Parameters
55 ----------
56 frequency : :class:`~skrf.frequency.Frequency` object or None
57 frequency band of this transmission line medium.
58 Defaults to None, which produces a 1-10ghz band with 101 points.
59 z0_port : number, array-like, or None
60 `z0_port` is the port impedance for networks generated by the media.
61 If `z0_port` is not None, the networks generated by the media are
62 renormalized (or in other words embedded) from the characteristic
63 impedance z0 of the media to `z0_port`.
64 Else if `z0_port` is None, the networks port impedances will be the raw
65 characteristic impedance z0 of the media.
66 (Default is None)
67 z0_override : number, array-like, or None
68 `z0_override` override the characteristic impedance for the media.
69 If `z0_override` is not None, the networks generated by the media have
70 their characteristic impedance `z0` overridden by `z0_override`.
71 (Default is None)
72 z0 : number, array-like, or None
73 deprecated parameter, alias to `z0_override` if `z0_override` is None.
74 Emit a deprecation warning.
75
76
77 Notes
78 -----
79 Full-wave simulations results can be networks with complex and
80 frequency-dependant `z0` port impedances.
81 However, the regular touchstone (s-parameters) files generated by most VNA
82 measurements are normalized to a single real value, e. g. 1. or 50 ohm.
83 Manually setting the `z0_port` to a single real value enforce the second
84 behaviour. The default (`z0_port = None`) is the first behaviour.
85 """
86
87 def __init__(self, frequency: Frequency | None = None,
88 z0_port: NumberLike | None = None,
89 z0_override: NumberLike | None = None,
90 z0: NumberLike | None = None):
91 if frequency is None:
92 frequency = Frequency(1,10,101,'GHz')
93
94 if z0 is not None:
95 # warns of deprecation
96 warnings.warn(
97 'Use of `z0` in Media initialization is deprecated.\n'
98 'If `z0_override` is None, '
99 'then `z0_override` will take z0 value.\n'
100 '`z0` will be removed of Media initialization in version 1.0',
101 DeprecationWarning, stacklevel = 2)
102 if z0_override is None:
103 z0_override = z0
104
105 self.frequency = frequency.copy()
106 self.z0_port = z0_port
107 self.z0_override = z0_override
108
109 def mode(self, **kw) -> Media:
110 r"""
111 Create another mode in this medium.
112
113 Convenient way to return a copy this Media object
114 with eventually different properties.
115
116 Parameters
117 ----------
118 \*\*kwargs : keyword arguments passed to the copy
119
120 Returns
121 -------
122 copy : :class:`Media`
123 A copy of this Media object with \*\*kwargs attribute
124 """
125 out = copy(self)
126 for k in kw:
127 setattr(out, k, kw[k])
128 return out
129
130 def copy(self) -> Media:
131 """
132 Copy of this Media object.
133
134 Returns
135 -------
136 copy : :class:`Media`
137 A copy of this Media object
138 """
139 return copy(self)
140
141 def __eq__(self,other):
142 """
143 Test for numerical equality (up to :data:`~skrf.constants.ZERO`).
144 """
145
146 if self.frequency != other.frequency:
147 return False
148
149 if max(abs(self.z0 - other.z0)) > ZERO:
150 return False
151
152 if max(abs(self.gamma - other.gamma)) > ZERO:
153 return False
154
155 if self.z0_port is None and other.z0_port is not None:
156 if max(abs(self.z0 - other.z0_port)) > ZERO:
157 return False
158
159 return True
160
161 def __len__(self) -> int:
162 """
163 Length of frequency axis.
164 """
165 return len(self.frequency)
166
167 @property
168 def npoints(self) -> int:
169 """
170 Number of points of the frequency axis.
171
172 Returns
173 -------
174 npoints : int
175 Number of points of the frequency axis.
176 """
177 return self.frequency.npoints
178
179 @npoints.setter
180 def npoints(self, val):
181 self.frequency.npoints = val
182
183 @property
184 def z0_port(self) -> np.ndarray:
185 """
186 Port Impedance.
187
188 Returns
189 -------
190 z0_port : :class:`numpy.ndarray`
191 """
192 if self._z0_port is None:
193 return self._z0_port
194 return self._z0_port*ones(len(self))
195
196 @z0_port.setter
197 def z0_port(self, val):
198 self._z0_port = val
199
200 @property
201 def z0_override(self) -> np.ndarray:
202 """
203 Port Impedance.
204
205 Returns
206 -------
207 z0_port : :class:`numpy.ndarray`
208 """
209 if self._z0_override is None:
210 return self._z0_override
211 return self._z0_override*ones(len(self))
212
213 @z0_override.setter
214 def z0_override(self, val):
215 self._z0_override = val
216
217 @property
218 @abstractmethod
219 def gamma(self):
220 r"""
221 Propagation constant.
222
223 In skrf, defined as :math:`\gamma = \alpha + j \beta`.
224
225 Returns
226 -------
227 gamma : :class:`numpy.ndarray`
228 complex propagation constant for this media
229
230 Notes
231 -----
232 `gamma` must adhere to the following convention:
233
234 * positive real(gamma) = attenuation
235 * positive imag(gamma) = forward propagation
236 """
237 return None
238
239
240 @property
241 def alpha(self) -> np.ndarray:
242 """
243 Real (attenuation) component of gamma.
244
245 Returns
246 -------
247 alpha : :class:`numpy.ndarray`
248 """
249 return real(self.gamma)
250
251 @property
252 def beta(self) -> np.ndarray:
253 """
254 Imaginary (propagating) component of gamma.
255
256 Returns
257 -------
258 beta : :class:`numpy.ndarray`
259 """
260 return imag(self.gamma)
261
262 @property
263 @abstractmethod
264 def z0_characteristic(self):
265 """
266 Characteristic Impedance, :math:`z_0`.
267 This abstract method has to be defined in the Media Class.
268
269 Returns
270 -------
271 z0_characteristic : np.ndarray
272 Characteristic Impedance in units of ohms
273 """
274 return None
275
276 @property
277 def z0(self):
278 """
279 Return Characteristic Impedance `z0_characteristic`.
280 If `z0_override` is not None, it is returned instead.
281
282 Returns
283 -------
284 z0 : np.ndarray
285 z0_characteristic or z0_override in units of ohms
286 """
287 if self.z0_override is None:
288 return self.z0_characteristic
289 else:
290 return self.z0_override
291
292 # left for backward compatibility
293 @property
294 def Z0(self):
295 """
296 Characteristic Impedance
297
298 Returns
299 -------
300 z0 : np.ndarray
301 Characteristic Impedance in units of ohms
302 """
303 # warns of deprecation
304 warnings.warn(
305 'Use of `Z0` (uppercase) is deprecated and return `z0`.\n'
306 'Use characteristic impedance `z0` (lowercase) instead.\n'
307 '`Z0` will be removed in version 1.0.',
308 DeprecationWarning, stacklevel = 2)
309 return self.z0
310
311
312 @property
313 def v_p(self) -> np.ndarray:
314 r"""
315 Complex phase velocity (in m/s).
316
317 .. math::
318 j \cdot \omega / \gamma
319
320 Notes
321 -----
322 The `j` is used so that real phase velocity corresponds to
323 propagation
324
325 where:
326
327 * :math:`\omega` is angular frequency (rad/s),
328 * :math:`\gamma` is complex propagation constant (rad/m)
329
330 Returns
331 -------
332 v_p : :class:`numpy.ndarray`
333
334 See Also
335 --------
336 propagation_constant
337 gamma
338
339 """
340 return 1j*(self.frequency.w/self.gamma)
341
342
343 @property
344 def v_g(self):
345 r"""
346 Complex group velocity (in m/s).
347
348 .. math::
349 j \cdot d \omega / d \gamma
350
351
352 where:
353
354 * :math:`\omega` is angular frequency (rad/s),
355 * :math:`\gamma` is complex propagation constant (rad/m)
356
357 Notes
358 -----
359 the `j` is used to make propagation real, this is needed because
360 skrf defined the gamma as :math:`\gamma= \alpha +j\beta`.
361
362 Returns
363 -------
364 v_g : :class:`numpy.ndarray`
365
366 References
367 ----------
368 https://en.wikipedia.org/wiki/Group_velocity
369
370 See Also
371 --------
372 propagation_constant
373 v_p
374 gamma
375 """
376 dw = self.frequency.dw
377 dk = gradient(self.gamma)
378
379 return dw/dk
380
381
382 def get_array_of(self, x):
383 try:
384 if len(x)!= len(self):
385 # we have to make a decision
386 pass
387 except(TypeError):
388 y = x* ones(len(self))
389
390 return y
391
392 ## Other Functions
393 def theta_2_d(self, theta: NumberLike, deg:bool = True, bc: bool = True) -> NumberLike:
394 r"""
395 Convert electrical length to physical distance.
396
397 The electrical length is given by :math:`d=\theta/\beta`.
398
399 The given electrical length can be given either at the center frequency
400 or on the entire band depending of the parameter `bc`.
401
402 Parameters
403 ----------
404 theta : number
405 electrical length, at band center (see deg for unit)
406 deg : Boolean, optional
407 is theta in degrees?
408 Default is True (theta is assumed in degrees)
409 bc : bool, optional.
410 evaluate only at band center, or across the entire band?
411 Default is True (evaluation assumed at band center)
412
413 Returns
414 --------
415 d : number, array-like
416 physical distance in meters
417
418 """
419 if deg:
420 theta = mf.degree_2_radian(theta)
421
422 gamma = self.gamma
423 if bc:
424 return 1.0*theta/np.imag(gamma[int(gamma.size/2)])
425 else:
426 return 1.0*theta/np.imag(gamma)
427
428 def electrical_length(self, d: NumberLike, deg: bool = False) -> NumberLike:
429 r"""
430 Calculate the complex electrical length for a given distance.
431
432 Electrical length is given by :math:`\theta=\gamma d`.
433
434 Parameters
435 ----------
436 d: number or array-like
437 delay distance, in meters
438 deg: Boolean, optional
439 return electrical length in deg?
440 Default is False (returns electrical length in radians)
441
442 Returns
443 -------
444 theta: number or array-like
445 complex electrical length in radians or degrees, depending on
446 value of deg.
447 """
448 gamma = self.gamma
449
450 if not deg:
451 return gamma*d
452 else:
453 return mf.radian_2_degree(gamma*d)
454
455 ## Network creation
456
457 # lumped elements
458 def match(self, nports: int = 1, z0: NumberLike | None = None,
459 z0_norm: bool = False, **kwargs) -> Network:
460 r"""
461 Perfect matched load (:math:`\Gamma_0 = 0`).
462
463 Parameters
464 ----------
465 nports : int
466 number of ports
467 z0 : number, or array-like or None
468 port impedance. This sets the resultant
469 :class:`~skrf.network.Network`’s
470 :attr:`~skrf.network.Network.z0`.
471 Default is None, the Media’s :attr:`~skrf.media.Media.z0_port`
472 value is used. If :attr:`~skrf.media.Media.z0_port` is
473 also None (by default), in which case the Media's native
474 :attr:`~skrf.media.Media.z0` is used.
475 A Media's :attr:`~skrf.media.Media.z0_port` is an optional
476 attribute for renormalizing resultant
477 :class:`~skrf.network.Network` to a new
478 reference impedance that differs from a Media's native
479 :attr:`~skrf.media.Media.z0`.
480 z0_norm : bool
481 is z0 normalized to this media's `z0`?
482 \*\*kwargs : key word arguments
483 passed to :class:`~skrf.network.Network` initializer
484
485 Returns
486 -------
487 match : :class:`~skrf.network.Network` object
488 a n-port match
489
490 Examples
491 --------
492 >>> my_match = my_media.match(2,z0 = 50, name='Super Awesome Match')
493
494 """
495 result = Network(**kwargs)
496 result.frequency = self.frequency
497 result.s = np.zeros((self.frequency.npoints, nports, nports), dtype=complex)
498 result.port_modes = np.array(["S"] * result.nports)
499 if z0 is None:
500 if self.z0_port is None:
501 z0 = self.z0
502 else:
503 z0 = self.z0_port
504 else:
505 if isinstance(z0, str):
506 z0 = parse_z0(z0)*self.z0
507 if z0_norm:
508 z0 = z0*self.z0
509
510 result.z0 = z0
511 return result
512
513 def load(self, Gamma0: NumberLike, nports: int = 1,
514 z0: NumberLike | None = None, **kwargs) -> Network:
515 r"""
516 Load of given reflection coefficient.
517
518 Parameters
519 ----------
520 Gamma0 : number, array-like
521 Reflection coefficient of load (linear, not in db). If its
522 an array it must be of shape: `kxnxn`, where k is number of frequency
523 points in media, and n is `nports`
524 nports : int
525 number of ports
526 z0 : number, or array-like or None
527 port impedance. This sets the resultant
528 :class:`~skrf.network.Network`’s
529 :attr:`~skrf.network.Network.z0`.
530 Default is None, the Media’s :attr:`~skrf.media.Media.z0_port`
531 value is used. If :attr:`~skrf.media.Media.z0_port` is
532 also None (by default), in which case the Media's native
533 :attr:`~skrf.media.Media.z0` is used.
534 A Media's :attr:`~skrf.media.Media.z0_port` is an optional
535 attribute for renormalizing resultant
536 :class:`~skrf.network.Network` to a new
537 reference impedance that differs from a Media's native
538 :attr:`~skrf.media.Media.z0`.
539 \*\*kwargs : key word arguments
540 passed to :func:`match`, which is called initially to create a
541 'blank' network.
542
543 Returns
544 -------
545 load : :class:`~skrf.network.Network` object
546 n-port load, where S = Gamma0*eye(...)
547
548 See Also
549 --------
550 match
551 open
552 short
553 """
554 result = self.match(nports, z0 = z0, **kwargs)
555 result.s = np.array(Gamma0).reshape(-1, 1, 1) * \
556 np.eye(nports, dtype=complex).reshape((-1, nports, nports)).\
557 repeat(self.frequency.npoints, 0)
558 result.port_modes = np.array(["S"] * result.nports)
559 return result
560
561 def short(self, nports: int = 1,
562 z0: NumberLike | None = None, **kwargs) -> Network:
563 r"""
564 Short (:math:`\Gamma_0 = -1`)
565
566 For s_def = 'power' (:math:`-Z_{ref}^*/Z_{ref}`)
567
568 Parameters
569 ----------
570 nports : int
571 number of ports
572 \*\*kwargs : key word arguments passed to :func:`load`.
573 z0 : number, or array-like or None
574 port impedance. This sets the resultant
575 :class:`~skrf.network.Network`’s
576 :attr:`~skrf.network.Network.z0`.
577 Default is None, the Media’s :attr:`~skrf.media.Media.z0_port`
578 value is used. If :attr:`~skrf.media.Media.z0_port` is
579 also None (by default), in which case the Media's native
580 :attr:`~skrf.media.Media.z0` is used.
581 A Media's :attr:`~skrf.media.Media.z0_port` is an optional
582 attribute for renormalizing resultant
583 :class:`~skrf.network.Network` to a new
584 reference impedance that differs from a Media's native
585 :attr:`~skrf.media.Media.z0`.
586 Returns
587 -------
588 match : :class:`~skrf.network.Network` object
589 a n-port short circuit
590
591 Notes
592 -----
593 This calls ::
594
595 load(-1.0, nports, **kwargs)
596
597 See Also
598 --------
599 match
600 open
601 load
602 """
603 if z0 is None:
604 if self.z0_port is None:
605 z0 = self.z0
606 else:
607 z0 = self.z0_port
608 s_short = -1
609 # Powerwave short is not necessarily -1
610 if kwargs.get('s_def', S_DEF_DEFAULT) == 'power':
611 s_short = -np.conjugate(z0) / z0
612 return self.load(s_short, nports, z0 = z0, **kwargs)
613
614 def open(self, nports: int = 1, **kwargs) -> Network:
615 r"""
616 Open (:math:`\Gamma_0 = 1`).
617
618 Parameters
619 ----------
620 nports : int
621 number of ports
622 \*\*kwargs : key word arguments passed to :func:`load`
623
624 Returns
625 -------
626 match : :class:`~skrf.network.Network` object
627 a n-port open circuit
628
629 Notes
630 -----
631 This calls ::
632
633 load(1.0, nports, **kwargs)
634
635 See Also
636 --------
637 match
638 load
639 short
640 """
641
642 return self.load(1.0, nports, **kwargs)
643
644 def resistor(self, R: NumberLike, *args, **kwargs) -> Network:
645 r"""
646 Resistor.
647
648 Parameters
649 ----------
650 R : number, array
651 Resistance , in Ohms. If this is an array, must be of
652 same length as frequency vector.
653 \*args, \*\*kwargs : arguments, key word arguments
654 passed to :func:`match`, which is called initially to create a
655 'blank' network.
656
657 Returns
658 -------
659 resistor : a 2-port :class:`~skrf.network.Network`
660
661 See Also
662 --------
663 match
664 short
665 open
666 load
667 capacitor
668 inductor
669 """
670 s_def = kwargs.pop('s_def', S_DEF_DEFAULT)
671 result = self.match(nports=2, s_def='power', **kwargs)
672 s = np.zeros(shape=result.s.shape, dtype=complex)
673 R = np.array(R)
674 # Convert Y-parameters resistor to S-parameters in power wave to accommodate any R value.
675 # y[:, 0, 0] = 1.0 / R
676 # y[:, 1, 1] = 1.0 / R
677 # y[:, 0, 1] = -1.0 / R
678 # y[:, 1, 0] = -1.0 / R
679 z0_0, z0_1 = result.z0[:, 0], result.z0[:, 1]
680 denom = R + (z0_0 + z0_1)
681 s[:, 0, 0] = (R - z0_0.conj() + z0_1) / denom
682 s[:, 1, 1] = (R + z0_0 - z0_1.conj()) / denom
683 s[:, 0, 1] = 2 * (z0_0.real * z0_1.real)**0.5 / denom
684 s[:, 1, 0] = 2 * (z0_0.real * z0_1.real)**0.5 / denom
685 result.s = s
686
687 # Renormalize into s_def if required
688 if s_def != 'power':
689 result.renormalize(z_new=result.z0, s_def=s_def)
690
691 return result
692
693 def capacitor(self, C: NumberLike, **kwargs) -> Network:
694 r"""
695 Capacitor.
696
697 Parameters
698 ----------
699 C : number, array
700 Capacitance, in Farads. If this is an array, must be of
701 same length as frequency vector.
702 \*\*kwargs : key word arguments
703 passed to :func:`match`, which is called initially to create a
704 'blank' network.
705
706 Returns
707 -------
708 capacitor : a 2-port :class:`~skrf.network.Network`
709
710 See Also
711 --------
712 match
713 short
714 open
715 load
716 resistor
717 inductor
718 """
719 s_def = kwargs.pop('s_def', S_DEF_DEFAULT)
720 result = self.match(nports=2, s_def='power', **kwargs)
721 w = self.frequency.w
722 s = np.zeros(shape=result.s.shape, dtype=complex)
723 C = np.array(C)
724 # Convert Y-parameters capacitor to S-parameters in power wave to accommodate any C value.
725 # y[:, 0, 0] = 1j * w * C
726 # y[:, 1, 1] = 1j * w * C
727 # y[:, 0, 1] = -1j * w * C
728 # y[:, 1, 0] = -1j * w * C
729 z0_0, z0_1 = result.z0[:, 0], result.z0[:, 1]
730 denom = 1.0 + 1j * w * C * (z0_0 + z0_1)
731 s[:, 0, 0] = (1.0 - 1j * w * C * (z0_0.conj() - z0_1) ) / denom
732 s[:, 1, 1] = (1.0 - 1j * w * C * (z0_1.conj() - z0_0) ) / denom
733 s[:, 0, 1] = (2j * w * C * (z0_0.real * z0_1.real)**0.5) / denom
734 s[:, 1, 0] = (2j * w * C * (z0_0.real * z0_1.real)**0.5) / denom
735 result.s = s
736
737 # Renormalize into s_def if required
738 if s_def != 'power':
739 result.renormalize(z_new=result.z0, s_def=s_def)
740
741 return result
742
743 def inductor(self, L: NumberLike, **kwargs) -> Network:
744 r"""
745 Inductor.
746
747 Parameters
748 ----------
749 L : number, array
750 Inductance, in Henries. If this is an array, must be of
751 same length as frequency vector.
752 \*\*kwargs : key word arguments
753 passed to :func:`match`, which is called initially to create a
754 'blank' network.
755
756 Returns
757 -------
758 inductor : a 2-port :class:`~skrf.network.Network`
759
760 See Also
761 --------
762 match
763 short
764 open
765 load
766 capacitor
767 resistor
768 """
769 s_def = kwargs.pop('s_def', S_DEF_DEFAULT)
770 result = self.match(nports=2, s_def='power', **kwargs)
771 w = self.frequency.w
772 s = np.zeros(shape=result.s.shape, dtype=complex)
773 L = np.array(L)
774 # Convert Y-parameters inductor to S-parameters in power wave to accommodate any L value.
775 # y[:, 0, 0] = 1.0 / (1j * w * L)
776 # y[:, 1, 1] = 1.0 / (1j * w * L)
777 # y[:, 0, 1] = -1.0 / (1j * w * L)
778 # y[:, 1, 0] = -1.0 / (1j * w * L)
779 z0_0, z0_1 = result.z0[:, 0], result.z0[:, 1]
780 denom = (1j * w * L) + (z0_0 + z0_1)
781 s[:, 0, 0] = (1j * w * L - z0_0.conj() + z0_1) / denom
782 s[:, 1, 1] = (1j * w * L + z0_0 - z0_1.conj()) / denom
783 s[:, 0, 1] = 2 * (z0_0.real * z0_1.real)**0.5 / denom
784 s[:, 1, 0] = 2 * (z0_0.real * z0_1.real)**0.5 / denom
785 result.s = s
786
787 # Renormalize into s_def if required
788 if s_def != 'power':
789 result.renormalize(z_new=result.z0, s_def=s_def)
790
791 return result
792
793 def impedance_mismatch(self, z1: NumberLike, z2: NumberLike, **kwargs) -> Network:
794 r"""
795 Two-port network for an impedance mismatch.
796
797 Parameters
798 ----------
799 z1 : number, or array-like
800 complex impedance of port 1
801 z2 : number, or array-like
802 complex impedance of port 2
803 \*\*kwargs : key word arguments
804 passed to :func:`match`, which is called initially to create a
805 'blank' network.
806
807 Returns
808 -------
809 mismatch : :class:`~skrf.network.Network` object
810 a 2-port network representing the impedance mismatch
811
812 Notes
813 -----
814 If z1 and z2 are arrays, they must be of same length
815 as the :attr:`Media.frequency.npoints`
816
817 See Also
818 --------
819 match
820 short
821 open
822 load
823 capacitor
824 inductor
825 resistor
826 """
827 result = self.match(nports=2, **kwargs)
828 s_def = kwargs.get('s_def', S_DEF_DEFAULT)
829 z1 = np.array(z1)
830 z2 = np.array(z2)
831 mismatch = np.broadcast_to(impedance_mismatch(z1, z2, s_def), result.s.shape)
832 result.s = mismatch
833 return result
834
835
836 # splitter/couplers
837 def tee(self, **kwargs) -> Network:
838 r"""
839 Ideal, lossless tee. (3-port splitter).
840
841 Parameters
842 ----------
843 \*\*kwargs : key word arguments
844 passed to :func:`match`, which is called initially to create a
845 'blank' network.
846
847 Returns
848 -------
849 tee : :class:`~skrf.network.Network` object
850 a 3-port splitter
851
852 See Also
853 ----------
854 splitter : this just calls splitter(3)
855 match : called to create a 'blank' network
856 """
857 return self.splitter(3, **kwargs)
858
859 def splitter(self, nports: int, **kwargs) -> Network:
860 r"""
861 Ideal, lossless n-way splitter.
862
863 The port impedances can be mismatched and the power is split
864 accordingly.
865
866 For n > 2, the splitter is not matched because the power wave entering
867 one port meet the equivalent impedance of the other ports in parallel.
868
869 .. math::
870 s_{ii} = \frac{\frac{1}{\sum_{j\neq i}\frac{1}{Z_j}}-Z_i^{*}}
871 {\frac{1}{\sum_{j\neq i}\frac{1}{Z_j}}+Z_i}
872
873 The remaining power is split between the other ports depending their
874 impedances.
875
876 .. math::
877 S_{ij} = \frac{ 2 \sqrt{ {\Re}\left (Z_i \right) \cdot {\Re}\left (Z_j \right) } }
878 {Z_i \cdot Z_j \cdot \sum_{k=1 \dots n}\frac{1}{Z_j}}
879
880 Parameters
881 ----------
882 nports : int
883 number of ports
884 \*\*kwargs : key word arguments
885 passed to :func:`match`, which is called initially to create a
886 'blank' network.
887
888 Returns
889 -------
890 tee : :class:`~skrf.network.Network` object
891 a n-port splitter
892
893 See Also
894 --------
895 match : called to create a 'blank' network
896 splitter_s : actual S-parameter matrix generator algorithm.
897 """
898 result = self.match(nports, **kwargs)
899
900 result.s = splitter_s(result.z0)
901 return result
902
903 # transmission line
904
905 def to_meters(self, d: NumberLike, unit: str = 'deg') -> NumberLike:
906 """
907 Translate various units of distance into meters.
908
909 This is a method of media to allow for electrical lengths as
910 inputs. For dispersive media, mean group velocity is used to
911 translate time-based units to distance.
912
913 Parameters
914 ----------
915 d : number or array-like
916 the value
917 unit : str
918 the unit to that x is in:
919 ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
920
921 Returns
922 -------
923 d_m : number, array-like
924 d in meters
925
926 See Also
927 --------
928 skrf.constants.to_meters
929 """
930 unit = unit.lower()
931 #import pdb;pdb.set_trace()
932
933 d_dict ={'deg':self.theta_2_d(d,deg=True),
934 'rad':self.theta_2_d(d,deg=False),
935 }
936
937 if unit in d_dict:
938 return d_dict[unit]
939 else:
940 # mean group velocity is used to translate time-based
941 # units to distance
942 if 's' in unit:
943 # they are specifying a time unit so calculate
944 # the group velocity. (note this fails for media of
945 # too little points, as it uses gradient)
946 v_g = -self.v_g.imag.mean()
947 else:
948 v_g = c
949 return to_meters(d=d,unit=unit, v_g=v_g)
950
951 def thru(self,
952 z0: NumberLike | None = None,
953 **kwargs) -> Network:
954 r"""
955 Matched transmission line of length 0.
956
957 Parameters
958 ----------
959 z0 : number, or array-like or None
960 port impedance. This sets the resultant
961 :class:`~skrf.network.Network`’s
962 :attr:`~skrf.network.Network.z0`.
963 Default is None, the Media’s :attr:`~skrf.media.Media.z0_port`
964 value is used. If :attr:`~skrf.media.Media.z0_port` is
965 also None (by default), in which case the Media's native
966 :attr:`~skrf.media.Media.z0` is used.
967 A Media's :attr:`~skrf.media.Media.z0_port` is an optional
968 attribute for renormalizing resultant
969 :class:`~skrf.network.Network` to a new
970 reference impedance that differs from a Media's native
971 :attr:`~skrf.media.Media.z0`.
972 \*\*kwargs : key word arguments
973 passed to :func:`match`, which is called initially to create a
974 'blank' network.
975
976 Returns
977 -------
978 thru : :class:`~skrf.network.Network` object
979 matched transmission line of 0 length
980
981 See Also
982 --------
983 line : this just calls line(0)
984 open, short, match
985 """
986 if z0 is None:
987 if self.z0_port is None:
988 z0 = self.z0
989 else:
990 z0 = self.z0_port
991 return self.line(0, z0 = z0, **kwargs)
992
993 def line(self, d: NumberLike, unit: str = 'deg',
994 z0: NumberLike | str | None = None, embed: bool = False, **kwargs) -> Network:
995 r"""
996 Transmission line of a given length and impedance.
997
998 The units of `length` are interpreted according to the value
999 of `unit`. If `z0` is not None, then a line specified impedance
1000 is produced. if `embed` is also True, then the line is embedded
1001 in this media's z0 environment, creating a mismatched line.
1002
1003 Parameters
1004 ----------
1005 d : number
1006 the length of transmission line (see unit argument)
1007 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1008 the units of d. See :func:`to_meters`, for details
1009 z0 : number, string, or array-like or None
1010 the characteristic impedance of the line, if different
1011 from self.z0. To set z0 in terms of normalized impedance,
1012 pass a string, like `z0='1+.2j'`
1013 embed : bool
1014 deprecated parameter that only emit a warning if set to true.
1015 \*\*kwargs : key word arguments
1016 passed to :func:`match`, which is called initially to create a
1017 'blank' network.
1018
1019 Returns
1020 -------
1021 line : :class:`~skrf.network.Network` object
1022 matched transmission line of given length
1023
1024 Examples
1025 --------
1026 >>> my_media.line(1, 'mm', z0=100)
1027 >>> my_media.line(90, 'deg', z0='2') # set z0 as normalized impedance
1028
1029 """
1030 if embed:
1031 # warns of deprecation
1032 warnings.warn(
1033 'Use of `embed` is deprecated and has no more effect.\n'
1034 'Lines are renormalized to the media port impedance `z0_port`'
1035 'if it is not None, otherwise they use characterisic'
1036 'impedance `z0`.\n'
1037 '`embed` will be removed in version 1.0',
1038 DeprecationWarning, stacklevel = 2)
1039
1040 if isinstance(z0, str):
1041 z0 = parse_z0(z0) * self.z0
1042
1043 if z0 is None:
1044 z0 = self.z0
1045
1046 s_def = kwargs.pop('s_def', S_DEF_DEFAULT)
1047
1048 # The use of either traveling or pseudo waves s-parameters definition
1049 # is required here.
1050 # The definition of the reflection coefficient for power waves has
1051 # conjugation.
1052 result = self.match(nports=2, z0 = z0, s_def='traveling', **kwargs)
1053
1054 theta = self.electrical_length(self.to_meters(d=d, unit=unit))
1055
1056 s11 = np.zeros(self.frequency.npoints, dtype=complex)
1057 s21 = np.exp(-1*theta)
1058 result.s = \
1059 np.array([[s11, s21],[s21,s11]]).transpose().reshape(-1,2,2)
1060
1061 # renormalize (or embed) into z0_port if required
1062 if self.z0_port is not None:
1063 result.renormalize(self.z0_port)
1064 result.renormalize(result.z0, s_def=s_def)
1065
1066 return result
1067
1068 def line_floating(self, d: NumberLike, unit: str = 'deg',
1069 z0: NumberLike | str | None = None, **kwargs) -> Network:
1070 r"""
1071 Floating transmission line of a given length and impedance.
1072
1073 This method returns a transmission line with floating shields.
1074 This is a four-port network, as opposed to the two-port _line_ method.
1075 Ports 1 and 3 are one side of the line, and electrically connect to
1076 ports 2 and 4 on the other side, respectively.
1077
1078 The units of `length` are interpreted according to the value
1079 of `unit`. If `z0` is not None, then a line specified impedance
1080 is produced.
1081
1082 Parameters
1083 ----------
1084 d : number
1085 the length of transmission line (see unit argument)
1086 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1087 the units of d. See :func:`to_meters`, for details
1088 z0 : number, string, or array-like or None
1089 the characteristic impedance of the line, if different
1090 from `media.z0`. To set z0 in terms of normalized impedance,
1091 pass a string, like `z0='1+.2j'`
1092 \*\*kwargs : key word arguments
1093 passed to :func:`match`, which is called initially to create a
1094 'blank' network.
1095
1096 Returns
1097 -------
1098 line_floating : :class:`~skrf.network.Network` object
1099 matched, floating transmission line of given length
1100
1101 Examples
1102 --------
1103 >>> my_media.line_floating(1, 'mm', z0=100)
1104 >>> my_media.line_floating(90, 'deg', z0='2') # set z0 as normalized impedance
1105
1106 """
1107 if isinstance(z0, str):
1108 z0 = self.parse_z0(z0) * self.z0
1109
1110 if z0 is None:
1111 z0 = self.z0
1112
1113 s_def = kwargs.pop('s_def', S_DEF_DEFAULT)
1114
1115 # The use of either traveling or pseudo waves s-parameters definition
1116 # is required here.
1117 # The definition of the reflection coefficient for power waves has
1118 # conjugation.
1119 result = self.match(nports=4, z0=z0, s_def='traveling', **kwargs)
1120
1121 t = self.electrical_length(self.to_meters(d=d, unit=unit))
1122
1123 denom = -1 + 9*np.exp(2*t)
1124 s11 = (1 + 3*np.exp(2*t)) / denom
1125 s12 = 4*np.exp(t) / denom
1126 s13 = (-2 + 6*np.exp(2*t)) / denom
1127 s14 = -s12
1128
1129 result.s = np.array([[s11, s12, s13, s14],
1130 [s12, s11, s14, s13],
1131 [s13, s14, s11, s12],
1132 [s14, s13, s12, s11]]).transpose(2, 0, 1)
1133
1134 # renormalize (or embed) into z0_port if required
1135 if self.z0_port is not None:
1136 result.renormalize(self.z0_port)
1137 result.renormalize(result.z0, s_def=s_def)
1138
1139 return result
1140
1141
1142 def delay_load(self, Gamma0: NumberLike, d: Number, unit: str = 'deg', **kwargs) -> Network:
1143 r"""
1144 Delayed load.
1145
1146 A load with reflection coefficient `Gamma0` at the end of a
1147 matched line of length `d`.
1148
1149 Parameters
1150 ----------
1151 Gamma0 : number, array-like
1152 reflection coefficient of load (not in dB)
1153 d : number
1154 the length of transmission line (see unit argument)
1155 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1156 the units of d. See :func:`to_meters`, for details
1157 \*\*kwargs : key word arguments
1158 passed to :func:`line` and :func:`load`
1159
1160 Returns
1161 -------
1162 delay_load : :class:`~skrf.network.Network` object
1163 a delayed load
1164
1165 Examples
1166 ----------
1167 >>> my_media.delay_load(-.5, 90, 'deg', Z0=50)
1168
1169 Notes
1170 -----
1171 This calls ::
1172
1173 line(d, unit, **kwargs) ** load(Gamma0, **kwargs)
1174
1175 See Also
1176 --------
1177 line : creates the network for line
1178 load : creates the network for the load
1179 delay_short
1180 delay_open
1181 """
1182 return self.line(d=d, unit=unit, **kwargs) ** self.load(Gamma0=Gamma0,
1183 **kwargs)
1184
1185 def delay_short(self, d: Number, unit: str = 'deg', **kwargs) -> Network:
1186 r"""
1187 Delayed Short.
1188
1189 A transmission line of given length terminated with a short.
1190
1191 Parameters
1192 ----------
1193 d : number
1194 the length of transmission line (see unit argument)
1195 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1196 the units of d. See :func:`to_meters`, for details
1197 \*\*kwargs : key word arguments passed to :func:`delay_load`.
1198
1199 Returns
1200 -------
1201 delay_short : :class:`~skrf.network.Network` object
1202 a delayed short
1203
1204 Notes
1205 -----
1206 This calls::
1207
1208 delay_load(Gamma0=-1.0, d=d, unit=unit, **kwargs)
1209
1210 See Also
1211 --------
1212 delay_load
1213 delay_open
1214 """
1215 return self.delay_load(Gamma0=-1.0, d=d, unit=unit, **kwargs)
1216
1217 def delay_open(self, d: Number, unit: str = 'deg', **kwargs) -> Network:
1218 r"""
1219 Delayed open transmission line.
1220
1221 Parameters
1222 ----------
1223 d : number
1224 the length of transmission line (see unit argument)
1225 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1226 the units of d. See :func:`to_meters`, for details
1227 \*\*kwargs : key word arguments passed to :func:`delay_load`
1228
1229 Returns
1230 -------
1231 delay_open : :class:`~skrf.network.Network` object
1232 a delayed open
1233
1234 Notes
1235 -----
1236 This calls::
1237
1238 delay_load(Gamma0=1.0, d=d, unit=unit, **kwargs)
1239
1240 See Also
1241 --------
1242 delay_load
1243 delay_short
1244 """
1245 return self.delay_load(Gamma0=1.0, d=d, unit=unit, **kwargs)
1246
1247 def shunt(self, ntwk: Network, **kwargs) -> Network:
1248 r"""
1249 Shunts a :class:`~skrf.network.Network`.
1250
1251 This creates a :func:`tee` and connects
1252 `ntwk` to port 1, and returns the result.
1253
1254 Parameters
1255 ----------
1256 ntwk : :class:`~skrf.network.Network` object
1257 \*\*kwargs : keyword arguments passed to :func:`tee`
1258
1259 Returns
1260 -------
1261 shunted_ntwk : :class:`~skrf.network.Network` object
1262 a shunted a ntwk. The resultant shunted_ntwk will have
1263 (2 + ntwk.number_of_ports -1) ports.
1264
1265 See Also
1266 --------
1267 shunt_delay_load
1268 shunt_delay_open
1269 shunt_delay_short
1270 shunt_resistor
1271 shunt_capacitor
1272 shunt_inductor
1273 """
1274 return connect(self.tee(**kwargs), 1, ntwk, 0)
1275
1276 def shunt_delay_load(self, *args, **kwargs) -> Network:
1277 r"""
1278 Shunted delayed load.
1279
1280 Parameters
1281 ----------
1282 \*args,\*\*kwargs : arguments, keyword arguments
1283 passed to func:`delay_load`
1284
1285 Returns
1286 --------
1287 shunt_delay_load : :class:`~skrf.network.Network` object
1288 a shunted delayed load (2-port)
1289
1290 Notes
1291 -----
1292 This calls::
1293
1294 shunt(delay_load(*args, **kwargs))
1295
1296 See Also
1297 --------
1298 shunt
1299 shunt_delay_open
1300 shunt_delay_short
1301 shunt_resistor
1302 shunt_capacitor
1303 shunt_inductor
1304 """
1305 return self.shunt(self.delay_load(*args, **kwargs), **kwargs)
1306
1307 def shunt_delay_open(self,*args,**kwargs) -> Network:
1308 r"""
1309 Shunted delayed open.
1310
1311 Parameters
1312 ----------
1313 \*args,\*\*kwargs : arguments, keyword arguments
1314 passed to func:`delay_open`
1315
1316 Returns
1317 -------
1318 shunt_delay_open : :class:`~skrf.network.Network` object
1319 shunted delayed open (2-port)
1320
1321 Notes
1322 -----
1323 This calls::
1324
1325 shunt(delay_open(*args, **kwargs))
1326
1327 See Also
1328 --------
1329 shunt
1330 shunt_delay_load
1331 shunt_delay_short
1332 shunt_resistor
1333 shunt_capacitor
1334 shunt_inductor
1335 """
1336 return self.shunt(self.delay_open(*args, **kwargs), **kwargs)
1337
1338 def shunt_delay_short(self, *args, **kwargs) -> Network:
1339 r"""
1340 Shunted delayed short.
1341
1342 Parameters
1343 ----------
1344 \*args,\*\*kwargs : arguments, keyword arguments
1345 passed to func:`delay_short`
1346
1347 Returns
1348 -------
1349 shunt_delay_load : :class:`~skrf.network.Network` object
1350 shunted delayed open (2-port)
1351
1352 Notes
1353 -----
1354 This calls::
1355
1356 shunt(delay_short(*args, **kwargs))
1357
1358 See Also
1359 --------
1360 shunt
1361 shunt_delay_load
1362 shunt_delay_open
1363 shunt_capacitor
1364 shunt_inductor
1365 """
1366 return self.shunt(self.delay_short(*args, **kwargs), **kwargs)
1367
1368 def shunt_resistor(self, R: NumberLike, **kwargs) -> Network:
1369 r"""
1370 Shunted resistor.
1371
1372 Parameters
1373 ----------
1374 R : number, array-like
1375 Resistor in Ohm.
1376 \*\*kwargs : arguments, keyword arguments
1377 passed to func:`resistor`
1378
1379 Returns
1380 -------
1381 shunt_resistor : :class:`~skrf.network.Network` object
1382 shunted resistor (2-port)
1383
1384 Notes
1385 -----
1386 This calls::
1387
1388 shunt(resistor(R, **kwargs) ** short())
1389
1390 See Also
1391 --------
1392 shunt
1393 shunt_delay_load
1394 shunt_delay_open
1395 shunt_delay_short
1396 shunt_inductor
1397 shunt_capacitor
1398 """
1399 return self.shunt(self.resistor(R=R, **kwargs) **
1400 self.short(**kwargs), **kwargs)
1401
1402 def shunt_capacitor(self, C: NumberLike, **kwargs) -> Network:
1403 r"""
1404 Shunted capacitor.
1405
1406 Parameters
1407 ----------
1408 C : number, array-like
1409 Capacitance in Farads.
1410 \*\*kwargs : arguments, keyword arguments
1411 passed to func:`capacitor`
1412
1413 Returns
1414 -------
1415 shunt_capacitor : :class:`~skrf.network.Network` object
1416 shunted capacitor (2-port)
1417
1418 Notes
1419 -----
1420 This calls::
1421
1422 shunt(capacitor(C, **kwargs) ** short())
1423
1424 See Also
1425 --------
1426 shunt
1427 shunt_delay_load
1428 shunt_delay_open
1429 shunt_delay_short
1430 shunt_resistor
1431 shunt_inductor
1432 """
1433 return self.shunt(self.capacitor(C=C, **kwargs) **
1434 self.short(**kwargs), **kwargs)
1435
1436 def shunt_inductor(self, L: NumberLike, **kwargs) -> Network:
1437 r"""
1438 Shunted inductor.
1439
1440 Parameters
1441 ----------
1442 L : number, array-like
1443 Inductance in Henries.
1444 \*\*kwargs : arguments, keyword arguments
1445 passed to func:`inductor`
1446
1447 Returns
1448 -------
1449 shunt_inductor : :class:`~skrf.network.Network` object
1450 shunted inductor(2-port)
1451
1452 Notes
1453 -----
1454 This calls::
1455
1456 shunt(inductor(L, **kwargs) ** short())
1457
1458 See Also
1459 --------
1460 shunt
1461 shunt_delay_load
1462 shunt_delay_open
1463 shunt_delay_short
1464 shunt_resistor
1465 shunt_capacitor
1466 """
1467 return self.shunt(self.inductor(L=L, **kwargs) **
1468 self.short(**kwargs), **kwargs)
1469
1470 def capacitor_q(self, C: NumberLike, f_0: NumberLike, q_factor: NumberLike, **kwargs) -> Network:
1471 r"""
1472 Capacitor with Q factor.
1473
1474 Parameters
1475 ----------
1476 C : number, array-like
1477 Capacitance in Farads.
1478 f_0 : number
1479 Frequency at which Q is defined, in Hz.
1480 q_factor : number
1481 Q-factor of capacitor
1482 \*\*kwargs : arguments, keyword arguments
1483 passed to func:`capacitor`
1484
1485 Returns
1486 -------
1487 capacitor_q : :class:`~skrf.network.Network` object
1488 capacitor_q (2-port)
1489
1490 """
1491 idea_cap = self.shunt(self.capacitor(C=C, **kwargs), **kwargs)
1492 rac = q_factor / (C * 2 * np.pi * f_0)
1493 idea_res = self.shunt(self.resistor(R=rac), **kwargs)
1494
1495 return innerconnect(connect(idea_cap, 1, idea_res, 2), 1, 3)
1496
1497 def inductor_q(self,
1498 L: NumberLike,
1499 f_0: NumberLike,
1500 q_factor: NumberLike,
1501 rdc: NumberLike = 0.0,
1502 **kwargs) -> Network:
1503 r"""
1504 Inductor with Q factor.
1505
1506 Parameters
1507 ----------
1508 L : number, array-like
1509 Inductance in Henries.
1510 f_0 : number
1511 Frequency at which Q is defined, in Hz.
1512 q_factor : number
1513 Q-factor of inductor
1514 rdc: number, optional
1515 DC resistance, in Ohms. Default is 0 Ohm.
1516 \*\*kwargs : arguments, keyword arguments
1517 passed to func:`inductor`
1518
1519 Returns
1520 -------
1521 inductor_q : :class:`~skrf.network.Network` object
1522 inductor_q (2-port)
1523
1524 """
1525 w_q = 2 * np.pi * f_0
1526
1527 if rdc == 0.0:
1528 rdc = 0.05 * w_q * L / q_factor
1529
1530 rq1 = w_q * L / q_factor
1531 rq2 = np.sqrt(rq1**2 - rdc**2)
1532 qt = w_q * L / rq2
1533 rac = self.frequency.w * L / qt
1534 r1 = np.sqrt(rdc**2 + rac**2)
1535
1536 return self.inductor(L=L, **kwargs) ** self.resistor(R=r1)
1537
1538 def attenuator(self, s21: NumberLike, db: bool = True, d: Number = 0,
1539 unit: str = 'deg', name: str = '', **kwargs) -> Network:
1540 r"""
1541 Ideal matched attenuator of a given length.
1542
1543 Parameters
1544 ----------
1545 s21 : number, array-like
1546 the attenuation
1547 db : bool, optional
1548 is s21 in dB? otherwise assumes linear. Default is True (dB).
1549 d : number, optional
1550 length of attenuator. Default is 0.
1551 unit : ['deg','rad','m','cm','um','in','mil','s','us','ns','ps']
1552 the units of d. See :func:`to_meters`, for details.
1553 Default is 'deg'
1554 name : str
1555 Name for the returned attenuator Network
1556 \*\*kwargs : arguments, keyword arguments
1557 passed to func:`line`
1558
1559 Returns
1560 -------
1561 ntwk : :class:`~skrf.network.Network` object
1562 2-port attenuator
1563
1564 """
1565
1566 s21 = np.array(s21)
1567 if db:
1568 s21 = mf.db_2_magnitude(s21)
1569
1570 result = self.match(nports=2)
1571 result.s[:, 0, 1] = s21
1572 result.s[:, 1, 0] = s21
1573 result = result ** self.line(d=d, unit=unit, **kwargs)
1574 result.name = name
1575 return result
1576
1577 def lossless_mismatch(self, s11: NumberLike, db: bool = True, **kwargs) -> Network:
1578 r"""
1579 Lossless, symmetric mismatch defined by its return loss.
1580
1581 Parameters
1582 ----------
1583 s11 : complex number, number, or array-like
1584 the reflection coefficient. if db==True, then phase is ignored
1585
1586 db : bool, optional
1587 is s11 in db? otherwise assumes linear. Default is True (dB)
1588
1589 \*\*kwargs : arguments, keyword arguments
1590 passed to func:`match`
1591
1592 Returns
1593 -------
1594 ntwk : :class:`~skrf.network.Network` object
1595 2-port lossless mismatch
1596
1597 """
1598
1599 result = self.match(nports=2, **kwargs)
1600 s11 = np.array(s11)
1601 if db:
1602 s11 = mf.db_2_magnitude(s11)
1603
1604 result.s[:, 0, 0] = s11
1605 result.s[:, 1, 1] = s11
1606
1607 s21_mag = np.sqrt(1 - np.abs(s11) ** 2)
1608 s21_phase = np.angle(s11) + np.pi / 2 * (np.angle(s11) <= 0) - np.pi / 2 * (np.angle(s11) > 0)
1609 result.s[:, 0, 1] = s21_mag * np.exp(1j * s21_phase)
1610 result.s[:, 1, 0] = result.s[:, 0, 1]
1611 return result
1612
1613 def isolator(self, source_port: int = 0, **kwargs) -> Network:
1614 r"""
1615 Two-port isolator.
1616
1617 Parameters
1618 -------------
1619 source_port: int in [0,1], optional
1620 port at which power can flow from. Default is 0.
1621 \*\*kwargs : arguments, keyword arguments
1622 passed to func:`thru`
1623
1624 Returns
1625 -------
1626 ntwk : :class:`~skrf.network.Network` object
1627 2-port isolator
1628
1629 """
1630 result = self.thru(**kwargs)
1631 if source_port == 0:
1632 result.s[:, 0, 1] = 0
1633 elif source_port == 1:
1634 result.s[:, 1, 0] = 0
1635 return result
1636
1637
1638
1639 ## Noisy Networks
1640
1641 def white_gaussian_polar(self, phase_dev: Number, mag_dev: Number,
1642 n_ports: int = 1, **kwargs) -> Network:
1643 r"""
1644 Complex zero-mean gaussian white-noise network.
1645
1646 Creates a network whose s-matrix is complex zero-mean gaussian
1647 white-noise, of given standard deviations for phase and
1648 magnitude components.
1649 This 'noise' network can be added to networks to simulate
1650 additive noise.
1651
1652 Parameters
1653 ----------
1654 phase_mag : number
1655 standard deviation of magnitude
1656 phase_dev : number
1657 standard deviation of phase
1658 n_ports : int
1659 number of ports.
1660 \*\*kwargs : passed to :class:`~skrf.network.Network`
1661 initializer
1662
1663 Returns
1664 --------
1665 result : :class:`~skrf.network.Network` object
1666 a noise network
1667 """
1668 shape = (self.frequency.npoints, n_ports,n_ports)
1669 phase_rv= stats.norm(loc=0, scale=phase_dev).rvs(size = shape)
1670 mag_rv = stats.norm(loc=0, scale=mag_dev).rvs(size = shape)
1671
1672 result = Network(**kwargs)
1673 result.frequency = self.frequency
1674 result.s = mag_rv*np.exp(1j*phase_rv)
1675 return result
1676
1677 def random(self, n_ports: int = 1, reciprocal: bool = False, matched: bool = False,
1678 symmetric: bool = False, rng: None | np.random.Generator = None,
1679 **kwargs) -> Network:
1680 r"""
1681 Complex random network.
1682
1683 Creates a n-port network whose s-matrix is filled with random
1684 complex numbers. Optionally, result can be matched or reciprocal.
1685
1686 Parameters
1687 ----------
1688 n_ports : int
1689 number of ports.
1690 reciprocal : bool
1691 makes s-matrix symmetric ($S_{mn} = S_{nm}$)
1692 symmetric : bool
1693 makes s-matrix diagonal have single value ($S_{mm}=S_{nn}$)
1694 matched : bool
1695 makes diagonals of s-matrix zero
1696 rng : :class:`numpy.random.Generator` or None
1697 override the global :mod:`numpy` random number generator,
1698 useful for multi-threaded programs since
1699 :func:`skrf.mathFunctions.set_rand_rng` is not thread-safe.
1700
1701 \*\*kwargs : passed to :class:`~skrf.network.Network`
1702 initializer
1703
1704 Returns
1705 -------
1706 result : :class:`~skrf.network.Network` object
1707 the network
1708 """
1709 result = self.match(nports = n_ports, **kwargs)
1710 result.s = mf.rand_c(self.frequency.npoints, n_ports,n_ports, rng=rng)
1711 result.port_modes = np.array(["S"] * result.nports)
1712 if reciprocal and n_ports>1:
1713 for m in range(n_ports):
1714 for n in range(n_ports):
1715 if m>n:
1716 result.s[:,m,n] = result.s[:,n,m]
1717 if symmetric:
1718 for m in range(n_ports):
1719 for n in range(n_ports):
1720 if m==n:
1721 result.s[:,m,n] = result.s[:,0,0]
1722 if matched:
1723 for m in range(n_ports):
1724 for n in range(n_ports):
1725 if m==n:
1726 result.s[:,m,n] = 0
1727
1728 return result
1729
1730 ## OTHER METHODS
1731 def extract_distance(self, ntwk: Network) -> NumberLike:
1732 """
1733 Determines physical distance from a transmission or reflection Network.
1734
1735 Given a matched transmission or reflection measurement the
1736 physical distance is estimated at each frequency point based on
1737 the scattering parameter phase of the ntwk and propagation constant.
1738
1739 Notes
1740 -----
1741 If the Network is a reflect measurement, the returned distance will
1742 be twice the physical distance.
1743
1744 Parameters
1745 ----------
1746 ntwk : `Network`
1747 A one-port network of either the reflection or the transmission.
1748
1749 Returns
1750 -------
1751 d : number or array_like
1752 physical distance
1753
1754 Examples
1755 --------
1756 >>> air = rf.air50
1757 >>> l = air.line(1, 'cm')
1758 >>> d_found = air.extract_distance(l.s21)
1759 >>> d_found
1760 """
1761 if ntwk.nports ==1:
1762 dphi = gradient(ntwk.s_rad_unwrap.flatten())
1763 dgamma = gradient(self.gamma.imag)
1764 return -dphi/dgamma
1765 else:
1766 raise ValueError('ntwk must be one-port. Select s21 or s12 for a two-port.')
1767
1768
1769
1770 def plot(self, *args, **kw):
1771 return self.frequency.plot(*args, **kw)
1772
1773
1774
1775 def write_csv(self, filename: str = 'f,gamma,Z0,z0.csv'):
1776 """
1777 write this media's frequency, gamma, Z0, and z0 to a csv file.
1778
1779 Parameters
1780 ----------
1781 filename : string, optional
1782 file name to write out data to.
1783 Default is 'f,gamma,Z0,z0.csv', so you probably want to specify it.
1784
1785 See Also
1786 --------
1787 from_csv : class method to initialize Media object from a
1788 csv file written from this function
1789 """
1790
1791 header = f'f[{self.frequency.unit}], Re(z0), Im(z0), Re(gamma), Im(gamma), Re(z0_port), Im(z0_port)\n'
1792
1793 g,z,pz = self.gamma, \
1794 self.z0, self.z0_port if self.z0_port is not None else self.z0
1795
1796 data = np.vstack(\
1797 [self.frequency.f_scaled, z.real, z.imag, \
1798 g.real, g.imag, pz.real, pz.imag]).T
1799
1800 np.savetxt(filename,data,delimiter=',',header=header)
1801
1802
1803
1804 class DefinedGammaZ0(Media):
1805 """
1806 A media directly defined by its propagation constant and characteristic impedance.
1807
1808 Parameters
1809 ----------
1810 frequency : :class:`~skrf.frequency.Frequency` object or None
1811 frequency band of this transmission line medium.
1812 Default is None, which produces a 1-10ghz band with 101 points.
1813 z0_port : number, array-like, or None
1814 `z0_port` is the port impedance for networks generated by the media.
1815 If `z0_port` is not None, the networks generated by the media are
1816 renormalized (or in other words embedded) from the characteristic
1817 impedance Z0 of the media to `z0_port`.
1818 Else if `z0_port` is None, the networks port impedances will be the raw
1819 characteristic impedance Z0 of the media.
1820 (Default is None)
1821 gamma : number or array-like, optional
1822 complex propagation constant. `gamma` must adhere to
1823 the following convention:
1824
1825 * positive real(gamma) = attenuation
1826 * positive imag(gamma) = forward propagation
1827 Default is 1j (lossless).
1828 z0 : number or array-like, optional.
1829 complex characteristic impedance of the media.
1830 Default is 50 ohm.
1831 Z0 : number, array-like, or None
1832 deprecated parameter, only emit a deprecation warning.
1833 """
1834
1835 def __init__(self, frequency: Frequency | None = None,
1836 z0_port: NumberLike | None = None,
1837 z0: NumberLike = 50,
1838 Z0: NumberLike | None = None,
1839 gamma: NumberLike = 1j):
1840 super().__init__(frequency=frequency, z0_port=z0_port)
1841
1842 self.gamma= gamma
1843 self.z0_characteristic = z0
1844
1845 if Z0 is not None:
1846 # warns of deprecation
1847 warnings.warn(
1848 'Use of `Z0` in DefinedGammaZ0 initialization is deprecated.\n'
1849 '`Z0` has no effect. Use `z0` instead\n'
1850 '`Z0` will be removed in version 1.0',
1851 DeprecationWarning, stacklevel = 2)
1852
1853 @classmethod
1854 def from_csv(cls, filename: str, *args, **kwargs) -> Media:
1855 """
1856 Create a Media from numerical values stored in a csv file.
1857
1858 The csv file format must be written by the function :func:`write_csv`,
1859 or similar method which produces the following format::
1860
1861 f[$unit], Re(Z0), Im(Z0), Re(gamma), Im(gamma), Re(port Z0), Im(port Z0)
1862 1, 1, 1, 1, 1, 1, 1
1863 2, 1, 1, 1, 1, 1, 1
1864 .....
1865
1866 See Also
1867 --------
1868 write_csv
1869 """
1870 try:
1871 fid = open(filename)
1872 except(TypeError):
1873 # they may have passed a file
1874 fid = filename
1875
1876 header = fid.readline()
1877 # this is not the correct way to do this ... but whatever
1878 f_unit = header.split(',')[0].split('[')[1].split(']')[0]
1879
1880 f,z_re,z_im,g_re,g_im,pz_re,pz_im = \
1881 np.loadtxt(fid, delimiter=',').T
1882
1883 if isinstance(filename, (str, Path)):
1884 fid.close()
1885
1886 return cls(
1887 frequency = Frequency.from_f(f, unit=f_unit),
1888 z0 = z_re+1j*z_im,
1889 gamma = g_re+1j*g_im,
1890 z0_port = pz_re+1j*pz_im,
1891 **kwargs
1892 )
1893
1894 @property
1895 def npoints(self):
1896 return self.frequency.npoints
1897
1898 @npoints.setter
1899 def npoints(self,val):
1900 # this is done to trigger checks on vector lengths for
1901 # gamma/Z0/z0
1902 new_freq= self.frequency.copy()
1903 new_freq.npoints = val
1904 self.frequency = new_freq
1905
1906
1907 @property
1908 def frequency(self):
1909 return self._frequency
1910
1911 @frequency.setter
1912 def frequency(self, val):
1913 if hasattr(self, '_frequency') and self._frequency is not None:
1914
1915 # they are updating the frequency, we may have to do something
1916 attrs_to_test = [self._gamma, self._z0, self._z0_port]
1917 if any([has_len(k) for k in attrs_to_test]):
1918 raise NotImplementedError("updating a Media frequency, with non-constant "
1919 "gamma/Z0/z0 is not worked out yet")
1920 self._frequency = val
1921
1922 @property
1923 def z0_characteristic(self):
1924 """
1925 Characteristic Impedance, :math:`z_0`.
1926
1927 Returns
1928 -------
1929 z0_characteristic : np.ndarray
1930 Characteristic Impedance in units of ohms
1931 """
1932 return self._z0*ones(len(self))
1933
1934 @z0_characteristic.setter
1935 def z0_characteristic(self, val):
1936 self._z0 = val
1937
1938 @property
1939 def gamma(self):
1940 """
1941 Propagation constant.
1942
1943 Returns
1944 ---------
1945 gamma : :class:`numpy.ndarray`
1946 complex propagation constant for this media
1947
1948 Notes
1949 ------
1950 `gamma` must adhere to the following convention:
1951
1952 * positive real(gamma) = attenuation
1953 * positive imag(gamma) = forward propagation
1954 """
1955 return self._gamma*ones(len(self))
1956
1957 @gamma.setter
1958 def gamma(self, val):
1959 self._gamma = val
1960
1961 def has_len(x: NumberLike) -> bool:
1962 """
1963 Test of x has any length (ie is a vector).
1964
1965 This is slightly non-trivial because [3] has len() but is
1966 doesn't really have any length.
1967 """
1968 try:
1969 return (len(array(x))>1)
1970 except TypeError:
1971 return False
1972
1973 def parse_z0(s: str) -> NumberLike:
1974 """
1975 Parse a z0 string.
1976
1977 Parameters
1978 ----------
1979 s : str
1980 z0 string, like '50+10j'
1981
1982 Returns
1983 -------
1984 z0 : np.ndarray
1985
1986 Raises
1987 ------
1988 ValueError
1989 If could not arse the z0 string.
1990 """
1991 # they passed a string for z0, try to parse it
1992 re_numbers = re.compile(r'\d+')
1993 numbers = re.findall(re_numbers, s)
1994 if len(numbers)==2:
1995 out = float(numbers[0]) +1j*float(numbers[1])
1996 elif len(numbers)==1:
1997 out = float(numbers[0])
1998 else:
1999 raise ValueError('couldnt parse z0 string')
2000 return out
2001
2002 def get_z0_load(z0: np.ndarray, port_idx: int) -> np.ndarray:
2003 r"""
2004 Calculate the load impedance for a given port index by parallel combining the impedances
2005 of all other ports.
2006
2007 .. math::
2008 Zload_{i} = \frac{1}{\sum_{j\neq i}\frac{1}{Z_j}}
2009
2010 Parameters
2011 ----------
2012 z0 : ndarray
2013 Port impedances, shape (n_frequencies, n_ports).
2014 port_idx : int
2015 The port index for which to calculate the load impedance.
2016
2017 Returns
2018 -------
2019 z0_load : number or None
2020 the load impedance for the given port index, or None if the
2021 media does not have a load impedance for that port index.
2022
2023 Raises
2024 ------
2025 IndexError
2026 If the port index is out of range for the given port impedances.
2027 """
2028 nports: int = z0.shape[1]
2029
2030 if port_idx >= nports:
2031 raise IndexError(f"Port index {port_idx} is out of range for Network, which has {nports} ports.")
2032
2033 if nports == 1:
2034 return np.ones_like(z0) * INF
2035
2036 mask = np.arange(nports) != port_idx
2037
2038 return 1. / np.sum(1. / z0[:, mask], axis=1)
2039
2040
2041 def splitter_s(z0: np.ndarray) -> np.ndarray:
2042 r"""
2043 Generate ideal, lossless n-way splitter Network's s-parameters.
2044
2045 For n > 2, the splitter is not matched because the power wave entering
2046 one port meet the equivalent impedance of the other ports in parallel.
2047
2048 .. math::
2049 s_{ii} = \frac{\frac{1}{\sum_{j\neq i}\frac{1}{Z_j}}-Z_i^{*}}
2050 {\frac{1}{\sum_{j\neq i}\frac{1}{Z_j}}+Z_i}
2051
2052 The remaining power is split between the other ports depending their
2053 impedances.
2054
2055 .. math::
2056 S_{ij} = \frac{ 2 \sqrt{ {\Re}\left (Z_i \right) \cdot {\Re}\left (Z_j \right) } }
2057 {Z_i \cdot Z_j \cdot \sum_{k=1 \dots n}\frac{1}{Z_j}}
2058
2059 Parameters
2060 ----------
2061 z0 : :class:`numpy.ndarray`
2062 Impedances of the ports
2063
2064 Returns
2065 -------
2066 s : :class:`numpy.ndarray`
2067 S-parameters of the splitter with given impedances
2068
2069 See Also
2070 --------
2071 splitter : splitter generator method.
2072 """
2073 nports = z0.shape[1]
2074 s = 2 * np.sqrt(np.einsum('ki,kj->kij', z0.real, z0.real)) / np.einsum('ki,kj->kij', z0, z0)
2075 s /= np.sum(1. / z0, axis=1)[:, None, None]
2076
2077 ports_idx = np.arange(nports)
2078 z0_load = np.array([get_z0_load(z0=z0, port_idx=i) for i in ports_idx]).T
2079 s[:, ports_idx, ports_idx] = (z0_load - z0.conj()) / (z0_load + z0)
2080
2081 return s