| 1 |
""" |
| 2 |
circuit (:mod:`skrf.circuit`) |
| 3 |
======================================== |
| 4 |
|
| 5 |
The Circuit class represents a circuit of arbitrary topology, |
| 6 |
consisting of an arbitrary number of N-ports networks. |
| 7 |
|
| 8 |
Like in an electronic circuit simulator, the circuit must have one or more ports |
| 9 |
connected to the circuit. The Circuit object allows one retrieving the M-ports network, |
| 10 |
where M is the number of ports defined. |
| 11 |
|
| 12 |
The results are returned in :class:`~skrf.circuit.Circuit` object. |
| 13 |
|
| 14 |
|
| 15 |
Building a Circuit |
| 16 |
------------------ |
| 17 |
.. autosummary:: |
| 18 |
:toctree: generated/ |
| 19 |
|
| 20 |
Circuit |
| 21 |
Circuit.Port |
| 22 |
Circuit.SeriesImpedance |
| 23 |
Circuit.ShuntAdmittance |
| 24 |
Circuit.Ground |
| 25 |
Circuit.Open |
| 26 |
Circuit.update_networks |
| 27 |
|
| 28 |
Representing a Circuit |
| 29 |
---------------------- |
| 30 |
.. autosummary:: |
| 31 |
:toctree: generated/ |
| 32 |
|
| 33 |
Circuit.plot_graph |
| 34 |
|
| 35 |
Network Representations |
| 36 |
----------------------- |
| 37 |
.. autosummary:: |
| 38 |
:toctree: generated/ |
| 39 |
|
| 40 |
Circuit.network |
| 41 |
Circuit.s |
| 42 |
Circuit.s_external |
| 43 |
Circuit.s_active |
| 44 |
Circuit.z_active |
| 45 |
Circuit.y_active |
| 46 |
Circuit.vswr_active |
| 47 |
Circuit.port_z0 |
| 48 |
|
| 49 |
Voltages and Currents |
| 50 |
--------------------- |
| 51 |
.. autosummary:: |
| 52 |
:toctree: generated/ |
| 53 |
|
| 54 |
Circuit.voltages |
| 55 |
Circuit.voltages_external |
| 56 |
Circuit.currents |
| 57 |
Circuit.currents_external |
| 58 |
|
| 59 |
Circuit internals |
| 60 |
------------------ |
| 61 |
.. autosummary:: |
| 62 |
:toctree: generated/ |
| 63 |
|
| 64 |
Circuit.networks_dict |
| 65 |
Circuit.networks_list |
| 66 |
Circuit.connections_nb |
| 67 |
Circuit.connections_list |
| 68 |
Circuit.nodes_nb |
| 69 |
Circuit.dim |
| 70 |
Circuit.intersections_dict |
| 71 |
Circuit.port_indexes |
| 72 |
Circuit.C |
| 73 |
Circuit.X |
| 74 |
|
| 75 |
Circuit reduction |
| 76 |
------------------ |
| 77 |
.. autosummary:: |
| 78 |
:toctree: generated/ |
| 79 |
|
| 80 |
reduce_circuit |
| 81 |
Circuit._REDUCE_OPTIONS |
| 82 |
|
| 83 |
Graph representation |
| 84 |
-------------------- |
| 85 |
.. autosummary:: |
| 86 |
:toctree: generated/ |
| 87 |
|
| 88 |
Circuit.graph |
| 89 |
Circuit.G |
| 90 |
Circuit.edges |
| 91 |
Circuit.edge_labels |
| 92 |
|
| 93 |
""" |
| 94 |
from __future__ import annotations |
| 95 |
|
| 96 |
import warnings |
| 97 |
from collections.abc import Sequence |
| 98 |
from functools import cached_property |
| 99 |
from itertools import chain |
| 100 |
from typing import TYPE_CHECKING, TypedDict |
| 101 |
|
| 102 |
import numpy as np |
| 103 |
from typing_extensions import NotRequired, Unpack |
| 104 |
|
| 105 |
from .constants import S_DEF_DEFAULT, MemoryLayoutT, NumberLike |
| 106 |
from .media import media |
| 107 |
from .network import Network, connect, innerconnect, s2s |
| 108 |
from .util import subplots |
| 109 |
|
| 110 |
if TYPE_CHECKING: |
| 111 |
from .frequency import Frequency |
| 112 |
|
| 113 |
|
| 114 |
class Circuit: |
| 115 |
""" |
| 116 |
Creates a circuit made of a set of N-ports networks. |
| 117 |
|
| 118 |
For instructions on how to create Circuit see :func:`__init__`. |
| 119 |
|
| 120 |
A Circuit object is representation a circuit assembly of an arbitrary |
| 121 |
number of N-ports networks connected together via an arbitrary topology. |
| 122 |
|
| 123 |
The algorithm used to calculate the resultant network can be found in [#]_. |
| 124 |
|
| 125 |
References |
| 126 |
---------- |
| 127 |
.. [#] P. Hallbjörner, Microw. Opt. Technol. Lett. 38, 99 (2003). |
| 128 |
|
| 129 |
""" |
| 130 |
@staticmethod |
| 131 |
def _get_nx(): |
| 132 |
"""Returns networkx module if available. |
| 133 |
|
| 134 |
Raises: |
| 135 |
------- |
| 136 |
ImportError: If networkx module is not installed |
| 137 |
|
| 138 |
Returns: |
| 139 |
-------- |
| 140 |
networkx module |
| 141 |
""" |
| 142 |
try: |
| 143 |
import networkx as nx |
| 144 |
return nx |
| 145 |
except ImportError as err: |
| 146 |
raise ImportError('networkx package as not been installed and is required.') from err |
| 147 |
|
| 148 |
class _REDUCE_OPTIONS(TypedDict): |
| 149 |
""" |
| 150 |
Optional parameters passed to `reduce_circuit`. |
| 151 |
|
| 152 |
Attributes |
| 153 |
---------- |
| 154 |
check_duplication : bool, optional. |
| 155 |
If True, check if the connections have duplicate names. Default is True. |
| 156 |
split_ground : bool, optional. |
| 157 |
If True, split the global ground connection to independent ground connections. Default is True. |
| 158 |
split_multi : bool, optional. |
| 159 |
If True, use a splitter to handle connections involving more than two components. This approach |
| 160 |
increases the computational load for individual computations. However, it proves advantageous for |
| 161 |
batch processing by enabling a more comprehensive reduction of circuits, leading to more efficiency |
| 162 |
in batch computations. Default is False. |
| 163 |
max_nports : int, optional. |
| 164 |
The maximum number of ports of a Network that can be reduced in circuit. If a Network in the |
| 165 |
circuit has a number of ports (nports), using the Network.connect() method to reduce the circuit's |
| 166 |
dimensions becomes less efficient compared to directly calculating it with Circuit.s_external. |
| 167 |
This value depends on the performance of the computer and the scale of the circuit. Default is 20. |
| 168 |
dynamic_networks : Sequence[Network], optional. |
| 169 |
A sequence of Networks to ignore in the reduction process. Default is an empty tuple. |
| 170 |
|
| 171 |
""" |
| 172 |
check_duplication: NotRequired[bool] |
| 173 |
split_ground: NotRequired[bool] |
| 174 |
split_multi: NotRequired[bool] |
| 175 |
max_nports: NotRequired[int] |
| 176 |
dynamic_networks: NotRequired[Sequence[Network]] |
| 177 |
|
| 178 |
CACHEDPROPERTIES = ('s', 'X', 'X_F', 'C', 'C_F', 'T') |
| 179 |
|
| 180 |
def __init__(self, |
| 181 |
connections: list[list[tuple[Network, int]]], |
| 182 |
name: str | None = None, |
| 183 |
*, |
| 184 |
auto_reduce: bool = False, **kwargs: Unpack[_REDUCE_OPTIONS]) -> None: |
| 185 |
""" |
| 186 |
Circuit constructor. Creates a circuit made of a set of N-ports networks. |
| 187 |
|
| 188 |
Parameters |
| 189 |
---------- |
| 190 |
connections : list of list of tuples |
| 191 |
Description of circuit connections. |
| 192 |
Each connection is a described by a list of tuple. |
| 193 |
Each tuple contains (network, network_port_nb). |
| 194 |
Port number indexing starts from zero. |
| 195 |
Network's port not explicitly listed will be treated as matched. |
| 196 |
Network's port listed individually will be treated as open. |
| 197 |
name : string, optional |
| 198 |
Name assigned to the circuit (Network). Default is None. |
| 199 |
auto_reduce : bool, optional |
| 200 |
If True, the circuit will be automatically reduced using :func:`reduce_circuit`. |
| 201 |
This will change the circuit connections description, affecting inner current and voltage distributions. |
| 202 |
Suitable for cases where only the S-parameters of the final circuit ports are of interest. Default is False. |
| 203 |
If `check_duplication`, `split_ground` or `max_nports` are provided as kwargs, `auto_reduce` will be |
| 204 |
automatically set to True, as this indicates an intent to use the `reduce_circuit` method. |
| 205 |
**kwargs : |
| 206 |
keyword arguments passed to `reduce_circuit` method. |
| 207 |
|
| 208 |
check_duplication : boolean. Default is True. |
| 209 |
Controls whether to check the connections have duplicate names. |
| 210 |
split_ground : boolean. Default is False. |
| 211 |
Controls whether to split the global ground connection to independent. |
| 212 |
split_multi : boolean, optional. |
| 213 |
If True, use a splitter to handle connections involving more than two components. This approach |
| 214 |
increases the computational load for individual computations. However, it proves advantageous for |
| 215 |
batch processing by enabling a more comprehensive reduction of circuits, leading to more efficiency |
| 216 |
in batch computations. Default is False. |
| 217 |
max_nports : int. Default is 20. |
| 218 |
Controls the maximum number of ports of a Network that can be reduced in circuit. If a |
| 219 |
Network in the circuit has a number of ports (nports), using the Network.connect() method to reduce the |
| 220 |
circuit's dimensions becomes less efficient compared to directly calculating it with Circuit.s_external. |
| 221 |
This value depends on the performance of the computer and the scale of the circuit. |
| 222 |
dynamic_networks : tuple. Default is an empty tuple. |
| 223 |
Sequence of Networks to be skipped during the reduction process. |
| 224 |
|
| 225 |
Examples |
| 226 |
-------- |
| 227 |
Example of connections between two 1-port networks:: |
| 228 |
|
| 229 |
connections = [ |
| 230 |
[(network1, 0), (network2, 0)], |
| 231 |
] |
| 232 |
|
| 233 |
Example of a connection between three 1-port networks connected |
| 234 |
to a single node:: |
| 235 |
|
| 236 |
connections = [ |
| 237 |
[(network1, 0), (network2, 0), (network3, 0)] |
| 238 |
] |
| 239 |
|
| 240 |
Example of a connection between two 1-port networks (port1 and port2) |
| 241 |
and two 2-ports networks (ntw1 and ntw2):: |
| 242 |
|
| 243 |
connections = [ |
| 244 |
[(port1, 0), (ntw1, 0)], |
| 245 |
[(ntw1, 1), (ntw2, 0)], |
| 246 |
[(ntw2, 1), (port2, 0)] |
| 247 |
] |
| 248 |
|
| 249 |
Example of a connection between three 1-port networks (port1, port2 and port3) |
| 250 |
and a 3-ports network (ntw):: |
| 251 |
|
| 252 |
connections = [ |
| 253 |
[(port1, 0), (ntw, 0)], |
| 254 |
[(port2, 0), (ntw, 1)], |
| 255 |
[(port3, 0), (ntw, 2)] |
| 256 |
] |
| 257 |
|
| 258 |
Example of a connection between three 1-port networks (port1, port2 and open) |
| 259 |
and a 3-ports network (ntw):: |
| 260 |
|
| 261 |
connections = [ |
| 262 |
[(port1, 0), (ntw, 0)], |
| 263 |
[(open, 0), (ntw, 1)], |
| 264 |
[(port2, 0), (ntw, 2)] |
| 265 |
] |
| 266 |
# or equivalently |
| 267 |
connections = [ |
| 268 |
[(port1, 0), (ntw, 0)], |
| 269 |
[(ntw, 1)], |
| 270 |
[(port2, 0), (ntw, 2)] |
| 271 |
] |
| 272 |
|
| 273 |
Example of a connection between three 1-port networks (port1, port2 and match) |
| 274 |
and a 3-ports network (ntw):: |
| 275 |
|
| 276 |
connections = [ |
| 277 |
[(port1, 0), (ntw, 0)], |
| 278 |
[(match, 0), (ntw, 1)], |
| 279 |
[(port2, 0), (ntw, 2)] |
| 280 |
] |
| 281 |
# or equivalently |
| 282 |
connections = [ |
| 283 |
[(port1, 0), (ntw, 0)], |
| 284 |
[(port2, 0), (ntw, 2)] |
| 285 |
] |
| 286 |
|
| 287 |
NB1: Creating 1-port network to be used as a port should be made with :func:`Port` |
| 288 |
|
| 289 |
NB2: The external ports indexing is defined by the order of appearance of |
| 290 |
the ports in the connections list. Thus, the first network identified |
| 291 |
as a port will be the 1st port of the resulting network (index 0), |
| 292 |
the second network identified as a port will be the second port (index 1), |
| 293 |
etc. |
| 294 |
|
| 295 |
NB3: When a port of a network is listed individually in the connections, the circuit |
| 296 |
will treat this port with a reflection coefficient of 1, equivalent to an Open. |
| 297 |
Conversely, if a port is not explicitly included in the connections,the circuit will |
| 298 |
treat it as matched. |
| 299 |
|
| 300 |
""" |
| 301 |
self._connections = connections |
| 302 |
self.name = name |
| 303 |
|
| 304 |
|
| 305 |
for cnx in self.connections: |
| 306 |
for (ntw, _) in cnx: |
| 307 |
if not self._is_named(ntw): |
| 308 |
raise AttributeError('All Networks must have a name. Faulty network:', ntw) |
| 309 |
|
| 310 |
|
| 311 |
ntws = self.networks_list() |
| 312 |
|
| 313 |
|
| 314 |
ref_freq = ntws[0].frequency |
| 315 |
for ntw in ntws: |
| 316 |
if ntw.frequency != ref_freq: |
| 317 |
raise AttributeError('All Networks must have same frequencies') |
| 318 |
|
| 319 |
self.frequency = ntws[0].frequency |
| 320 |
|
| 321 |
|
| 322 |
Circuit.check_duplicate_names(self.connections_list) |
| 323 |
|
| 324 |
|
| 325 |
kwargs_reduce = {k: kwargs[k] for k in self._REDUCE_OPTIONS.__annotations__.keys() if k in kwargs} |
| 326 |
|
| 327 |
|
| 328 |
if auto_reduce or any(kwargs_reduce): |
| 329 |
self.connections = reduce_circuit(self.connections, **kwargs_reduce) |
| 330 |
|
| 331 |
@property |
| 332 |
def connections(self) -> list[list[tuple[Network, int]]]: |
| 333 |
""" |
| 334 |
Circuit connections. |
| 335 |
|
| 336 |
Description of circuit connections. Each connection is a described by a |
| 337 |
list of tuple. Each tuple contains (network, network_port_nb). Port number |
| 338 |
indexing starts from zero. |
| 339 |
|
| 340 |
Returns |
| 341 |
------- |
| 342 |
connections : :class:`list[list[tuple[Network, int]]]` |
| 343 |
The circuit connections. |
| 344 |
|
| 345 |
""" |
| 346 |
return self._connections |
| 347 |
|
| 348 |
@connections.setter |
| 349 |
def connections(self, connections: list[list[tuple[Network, int]]]) -> None: |
| 350 |
""" |
| 351 |
Set the circuit connections. |
| 352 |
|
| 353 |
Parameters |
| 354 |
---------- |
| 355 |
connections : :class:`list[list[tuple[Network, int]]]` |
| 356 |
The circuit connections. |
| 357 |
|
| 358 |
""" |
| 359 |
self._connections = connections |
| 360 |
|
| 361 |
|
| 362 |
for item in self.CACHEDPROPERTIES: |
| 363 |
self.__dict__.pop(item, None) |
| 364 |
|
| 365 |
def update_networks( |
| 366 |
self, networks: tuple[Network], |
| 367 |
name: str | None = None, |
| 368 |
*, |
| 369 |
inplace: bool = False, |
| 370 |
auto_reduce: bool = False, **kwargs: Unpack[_REDUCE_OPTIONS]) -> Circuit | None: |
| 371 |
""" |
| 372 |
Update the circuit connections with a new set of networks. |
| 373 |
|
| 374 |
Parameters |
| 375 |
---------- |
| 376 |
networks : tuple[Network] |
| 377 |
A tuple of Networks to be updated in the circuit. |
| 378 |
name : string, optional |
| 379 |
Name assigned to the circuit (Network). Default is None. |
| 380 |
inplace : bool, optional |
| 381 |
If True, the circuit connections will be updated inplace. Default is False. |
| 382 |
auto_reduce : bool, optional |
| 383 |
If True, the circuit will be automatically reduced using :func:`reduce_circuit`. |
| 384 |
This will change the circuit connections description, affecting inner current and voltage distributions. |
| 385 |
Suitable for cases where only the S-parameters of the final circuit ports are of interest. Default is False. |
| 386 |
If `check_duplication`, `split_ground` or `max_nports` are provided as kwargs, `auto_reduce` will be |
| 387 |
automatically set to True, as this indicates an intent to use the `reduce_circuit` method. |
| 388 |
**kwargs : |
| 389 |
keyword arguments passed to `reduce_circuit` method. |
| 390 |
|
| 391 |
`check_duplication` kwarg controls whether to check the connections have duplicate names. Default is True. |
| 392 |
|
| 393 |
`split_ground` kwarg controls whether to split the global ground connection to independent. |
| 394 |
Default is False. |
| 395 |
|
| 396 |
`max_nports` kwarg controls the maximum number of ports of a Network that can be reduced in circuit. If a |
| 397 |
Network in the circuit has a number of ports (nports), using the Network.connect() method to reduce the |
| 398 |
circuit's dimensions becomes less efficient compared to directly calculating it with Circuit.s_external. |
| 399 |
This value depends on the performance of the computer and the scale of the circuit. Default is 20. |
| 400 |
|
| 401 |
`dynamic_networks` kwarg is a sequence of Networks to be skipped during the reduction process. |
| 402 |
Default is an empty tuple. |
| 403 |
|
| 404 |
Returns |
| 405 |
------- |
| 406 |
Circuit or None if inplace=True |
| 407 |
The updated `Circuit` with the specified networks. |
| 408 |
|
| 409 |
|
| 410 |
See Also |
| 411 |
-------- |
| 412 |
Circuit.__init__ : Circuit constructor method. |
| 413 |
|
| 414 |
|
| 415 |
Examples |
| 416 |
-------- |
| 417 |
>>> import skrf as rf |
| 418 |
>>> import numpy as np |
| 419 |
>>> |
| 420 |
>>> # Create a series of networks and build a circuit |
| 421 |
>>> connections = [ |
| 422 |
... ... |
| 423 |
... [(ntwk1, 0), (ntwk2, 0)], |
| 424 |
... [(ntwk2, 1), (ntwk3, 0)], |
| 425 |
... ... |
| 426 |
... ] |
| 427 |
>>> circuit = rf.Circuit(connections, dynamic_networks=[ntwk2]) |
| 428 |
>>> |
| 429 |
>>> # Update the networks' S-parameters |
| 430 |
>>> ntwk2.s = ntwk2.s @ ntwk2.s |
| 431 |
>>> |
| 432 |
>>> # Update the circuit in traditional way (ntwk2 has been updated) |
| 433 |
>>> connections_updated = [ |
| 434 |
... ... |
| 435 |
... [(ntwk1, 0), (ntwk2, 0)], |
| 436 |
... [(ntwk2, 1), (ntwk3, 0)], |
| 437 |
... ... |
| 438 |
... ] |
| 439 |
>>> |
| 440 |
>>> circuit_updated_a = rf.Circuit(connections_updated) |
| 441 |
>>> |
| 442 |
>>> # Update the circuit by dynamic networks |
| 443 |
>>> circuit_updated_b = circuit.update_networks(networks=[ntwk2]) |
| 444 |
>>> |
| 445 |
>>> np.allclose(circuit_updated_b.s_external, circuit_updated_b.s_external) |
| 446 |
True |
| 447 |
""" |
| 448 |
|
| 449 |
cnx_dict = self.networks_dict() |
| 450 |
|
| 451 |
|
| 452 |
for ntw in networks: |
| 453 |
if ntw.name in cnx_dict: |
| 454 |
cnx_dict[ntw.name] = ntw |
| 455 |
else: |
| 456 |
raise ValueError(f"Network {ntw.name} not found in circuit.") |
| 457 |
|
| 458 |
|
| 459 |
connections = [ |
| 460 |
[(cnx_dict[n.name], p) for n, p in cnx] for cnx in self.connections |
| 461 |
] |
| 462 |
|
| 463 |
|
| 464 |
kwargs_reduce = {k: kwargs[k] for k in self._REDUCE_OPTIONS.__annotations__.keys() if k in kwargs} |
| 465 |
|
| 466 |
|
| 467 |
if auto_reduce or any(kwargs_reduce): |
| 468 |
connections = reduce_circuit(connections, **kwargs_reduce) |
| 469 |
|
| 470 |
if inplace: |
| 471 |
self.connections = connections |
| 472 |
return None |
| 473 |
|
| 474 |
return Circuit(connections=connections, name=name) |
| 475 |
|
| 476 |
@classmethod |
| 477 |
def check_duplicate_names(cls, connections_list: list[tuple[int, tuple[Network, int]]]): |
| 478 |
""" |
| 479 |
Check that a (ntwk, port) combination appears only once in the connection map |
| 480 |
""" |
| 481 |
nodes = [(ntwk.name, port) for (_, (ntwk, port)) in connections_list] |
| 482 |
if len(nodes) > len(set(nodes)): |
| 483 |
duplicate_nodes = [node for node in nodes if nodes.count(node) > 1] |
| 484 |
raise AttributeError(f'Nodes {duplicate_nodes} appears twice in the connection description.') |
| 485 |
|
| 486 |
|
| 487 |
def _is_named(self, ntw: Network): |
| 488 |
""" |
| 489 |
Return True is the network has a name, False otherwise |
| 490 |
""" |
| 491 |
if not ntw.name or ntw.name == '': |
| 492 |
return False |
| 493 |
else: |
| 494 |
return True |
| 495 |
|
| 496 |
@classmethod |
| 497 |
def _is_port(cls, ntw: Network): |
| 498 |
""" |
| 499 |
Return True is the network is a port, False otherwise |
| 500 |
""" |
| 501 |
return ntw._ext_attrs.get("_is_circuit_port", False) |
| 502 |
|
| 503 |
@classmethod |
| 504 |
def _is_ground(cls, ntw: Network): |
| 505 |
""" |
| 506 |
Return True is the network is a ground, False otherwise |
| 507 |
""" |
| 508 |
return ntw._ext_attrs.get("_is_circuit_ground", False) |
| 509 |
|
| 510 |
@classmethod |
| 511 |
def _is_open(cls, ntw: Network): |
| 512 |
""" |
| 513 |
Return True is the network is a open, False otherwise |
| 514 |
""" |
| 515 |
return ntw._ext_attrs.get("_is_circuit_open", False) |
| 516 |
|
| 517 |
@classmethod |
| 518 |
def Port(cls, frequency: Frequency, name: str, z0: float = 50) -> Network: |
| 519 |
""" |
| 520 |
Return a 1-port Network to be used as a Circuit port. |
| 521 |
|
| 522 |
Parameters |
| 523 |
---------- |
| 524 |
frequency : :class:`~skrf.frequency.Frequency` |
| 525 |
Frequency common to all other networks in the circuit |
| 526 |
name : string |
| 527 |
Name of the port. |
| 528 |
z0 : real, optional |
| 529 |
Characteristic impedance of the port. Default is 50 Ohm. |
| 530 |
|
| 531 |
Returns |
| 532 |
------- |
| 533 |
port : :class:`~skrf.network.Network` object |
| 534 |
1-port network |
| 535 |
|
| 536 |
Examples |
| 537 |
-------- |
| 538 |
.. ipython:: |
| 539 |
|
| 540 |
@suppress |
| 541 |
In [16]: import skrf as rf |
| 542 |
|
| 543 |
In [17]: freq = rf.Frequency(start=1, stop=2, npoints=101) |
| 544 |
|
| 545 |
In [18]: port1 = rf.Circuit.Port(freq, name='Port1') |
| 546 |
""" |
| 547 |
_media = media.DefinedGammaZ0(frequency, z0=z0) |
| 548 |
port = _media.match(name=name) |
| 549 |
port._ext_attrs['_is_circuit_port'] = True |
| 550 |
return port |
| 551 |
|
| 552 |
@classmethod |
| 553 |
def SeriesImpedance(cls, frequency: Frequency, Z: NumberLike, name: str, z0: float = 50) -> Network: |
| 554 |
""" |
| 555 |
Return a 2-port network of a series impedance. |
| 556 |
|
| 557 |
Passing the frequency and name is mandatory. |
| 558 |
|
| 559 |
Parameters |
| 560 |
---------- |
| 561 |
frequency : :class:`~skrf.frequency.Frequency` |
| 562 |
Frequency common to all other networks in the circuit |
| 563 |
Z : complex array of shape n_freqs or complex |
| 564 |
Impedance |
| 565 |
name : string |
| 566 |
Name of the series impedance |
| 567 |
z0 : real, optional |
| 568 |
Characteristic impedance of the port. Default is 50 Ohm. |
| 569 |
|
| 570 |
Returns |
| 571 |
------- |
| 572 |
serie_impedance : :class:`~skrf.network.Network` object |
| 573 |
2-port network |
| 574 |
|
| 575 |
Examples |
| 576 |
-------- |
| 577 |
.. ipython:: |
| 578 |
|
| 579 |
@suppress |
| 580 |
In [16]: import skrf as rf |
| 581 |
|
| 582 |
In [17]: freq = rf.Frequency(start=1, stop=2, npoints=101) |
| 583 |
|
| 584 |
In [18]: open = rf.Circuit.SeriesImpedance(freq, rf.INF, name='series_impedance') |
| 585 |
|
| 586 |
""" |
| 587 |
A = np.zeros(shape=(len(frequency), 2, 2), dtype=complex) |
| 588 |
A[:, 0, 0] = 1 |
| 589 |
A[:, 0, 1] = Z |
| 590 |
A[:, 1, 0] = 0 |
| 591 |
A[:, 1, 1] = 1 |
| 592 |
ntw = Network(a=A, frequency=frequency, z0=z0, name=name) |
| 593 |
return ntw |
| 594 |
|
| 595 |
@classmethod |
| 596 |
def ShuntAdmittance(cls, frequency: Frequency, Y: NumberLike, name: str, z0: float = 50) -> Network: |
| 597 |
""" |
| 598 |
Return a 2-port network of a shunt admittance. |
| 599 |
|
| 600 |
Passing the frequency and name is mandatory. |
| 601 |
|
| 602 |
Parameters |
| 603 |
---------- |
| 604 |
frequency : :class:`~skrf.frequency.Frequency` |
| 605 |
Frequency common to all other networks in the circuit |
| 606 |
Y : complex array of shape n_freqs or complex |
| 607 |
Admittance |
| 608 |
name : string |
| 609 |
Name of the shunt admittance |
| 610 |
z0 : real, optional |
| 611 |
Characteristic impedance of the port. Default is 50 Ohm. |
| 612 |
|
| 613 |
Returns |
| 614 |
------- |
| 615 |
shunt_admittance : :class:`~skrf.network.Network` object |
| 616 |
2-port network |
| 617 |
|
| 618 |
Examples |
| 619 |
-------- |
| 620 |
.. ipython:: |
| 621 |
|
| 622 |
@suppress |
| 623 |
In [16]: import skrf as rf |
| 624 |
|
| 625 |
In [17]: freq = rf.Frequency(start=1, stop=2, npoints=101) |
| 626 |
|
| 627 |
In [18]: short = rf.Circuit.ShuntAdmittance(freq, rf.INF, name='shunt_admittance') |
| 628 |
|
| 629 |
""" |
| 630 |
A = np.zeros(shape=(len(frequency), 2, 2), dtype=complex) |
| 631 |
A[:, 0, 0] = 1 |
| 632 |
A[:, 0, 1] = 0 |
| 633 |
A[:, 1, 0] = Y |
| 634 |
A[:, 1, 1] = 1 |
| 635 |
ntw = Network(a=A, frequency=frequency, z0=z0, name=name) |
| 636 |
return ntw |
| 637 |
|
| 638 |
@classmethod |
| 639 |
def Ground(cls, frequency: Frequency, name: str, z0: float = 50) -> Network: |
| 640 |
""" |
| 641 |
Return a 1-port network of a grounded link. |
| 642 |
|
| 643 |
Passing the frequency and a name is mandatory. |
| 644 |
|
| 645 |
The ground link is implemented by media.short object. |
| 646 |
|
| 647 |
Parameters |
| 648 |
---------- |
| 649 |
frequency : :class:`~skrf.frequency.Frequency` |
| 650 |
Frequency common to all other networks in the circuit |
| 651 |
name : string |
| 652 |
Name of the ground. |
| 653 |
z0 : real, optional |
| 654 |
Characteristic impedance of the port. Default is 50 Ohm. |
| 655 |
|
| 656 |
Returns |
| 657 |
------- |
| 658 |
ground : :class:`~skrf.network.Network` object |
| 659 |
1-port network |
| 660 |
|
| 661 |
Examples |
| 662 |
-------- |
| 663 |
.. ipython:: |
| 664 |
|
| 665 |
@suppress |
| 666 |
In [16]: import skrf as rf |
| 667 |
|
| 668 |
In [17]: freq = rf.Frequency(start=1, stop=2, npoints=101) |
| 669 |
|
| 670 |
In [18]: ground = rf.Circuit.Ground(freq, name='GND') |
| 671 |
|
| 672 |
""" |
| 673 |
_media = media.DefinedGammaZ0(frequency, z0=z0) |
| 674 |
ground = _media.short(name=name) |
| 675 |
ground._ext_attrs['_is_circuit_ground'] = True |
| 676 |
return ground |
| 677 |
|
| 678 |
@classmethod |
| 679 |
def Open(cls, frequency: Frequency, name: str, z0: float = 50) -> Network: |
| 680 |
""" |
| 681 |
Return a 1-port network of an open link. |
| 682 |
|
| 683 |
Passing the frequency and name is mandatory. |
| 684 |
|
| 685 |
The open link is implemented by media.open object. |
| 686 |
|
| 687 |
Parameters |
| 688 |
---------- |
| 689 |
frequency : :class:`~skrf.frequency.Frequency` |
| 690 |
Frequency common to all other networks in the circuit |
| 691 |
name : string |
| 692 |
Name of the open. |
| 693 |
z0 : real, optional |
| 694 |
Characteristic impedance of the port. Default is 50 Ohm. |
| 695 |
|
| 696 |
Returns |
| 697 |
------- |
| 698 |
open : :class:`~skrf.network.Network` object |
| 699 |
1-port network |
| 700 |
|
| 701 |
Examples |
| 702 |
-------- |
| 703 |
.. ipython:: |
| 704 |
|
| 705 |
@suppress |
| 706 |
In [16]: import skrf as rf |
| 707 |
|
| 708 |
In [17]: freq = rf.Frequency(start=1, stop=2, npoints=101) |
| 709 |
|
| 710 |
In [18]: open = rf.Circuit.Open(freq, name='open') |
| 711 |
|
| 712 |
""" |
| 713 |
_media = media.DefinedGammaZ0(frequency, z0=z0) |
| 714 |
Open = _media.open(name=name) |
| 715 |
Open._ext_attrs['_is_circuit_open'] = True |
| 716 |
return Open |
| 717 |
|
| 718 |
def networks_dict(self, |
| 719 |
connections: list[list[tuple[Network, int]]] | None = None, |
| 720 |
min_nports: int = 1) -> dict[str, Network]: |
| 721 |
""" |
| 722 |
Return the dictionary of Networks from the connection setup X. |
| 723 |
|
| 724 |
Parameters |
| 725 |
---------- |
| 726 |
connections : List, optional |
| 727 |
connections list, by default None (then uses the `self.connections`) |
| 728 |
min_nports : int, optional |
| 729 |
min number of ports, by default 1 |
| 730 |
|
| 731 |
Returns |
| 732 |
------- |
| 733 |
dict |
| 734 |
Dictionary of Networks |
| 735 |
""" |
| 736 |
if not connections: |
| 737 |
connections = self.connections |
| 738 |
|
| 739 |
ntws: list[Network] = [] |
| 740 |
for cnx in connections: |
| 741 |
for (ntw, _port) in cnx: |
| 742 |
ntws.append(ntw) |
| 743 |
return {ntw.name: ntw for ntw in ntws if ntw.nports >= min_nports} |
| 744 |
|
| 745 |
def networks_list(self, |
| 746 |
connections: list[list[tuple[Network, int]]] | None = None, |
| 747 |
min_nports: int = 1) -> list[Network]: |
| 748 |
""" |
| 749 |
Return a list of unique networks (sorted by appearing order in connections). |
| 750 |
|
| 751 |
Parameters |
| 752 |
---------- |
| 753 |
connections : List, optional |
| 754 |
connections list, by default None (then uses the `self.connections`) |
| 755 |
min_nports : int, optional |
| 756 |
min number of ports, by default 1 |
| 757 |
|
| 758 |
Returns |
| 759 |
------- |
| 760 |
list |
| 761 |
List of unique networks |
| 762 |
""" |
| 763 |
if not connections: |
| 764 |
connections = self.connections |
| 765 |
|
| 766 |
ntw_dict = self.networks_dict(connections) |
| 767 |
return [ntw for ntw in ntw_dict.values() if ntw.nports >= min_nports] |
| 768 |
|
| 769 |
@property |
| 770 |
def connections_nb(self) -> int: |
| 771 |
""" |
| 772 |
Return the number of intersections in the circuit. |
| 773 |
""" |
| 774 |
return len(self.connections) |
| 775 |
|
| 776 |
@property |
| 777 |
def connections_list(self) -> list[tuple[int, tuple[Network, int]]]: |
| 778 |
""" |
| 779 |
Return the full list of connections, including intersections. |
| 780 |
|
| 781 |
The resulting list if of the form:: |
| 782 |
|
| 783 |
[ |
| 784 |
[connexion_number, connexion], |
| 785 |
[connexion_number, connexion], |
| 786 |
... |
| 787 |
] |
| 788 |
""" |
| 789 |
return list(enumerate(chain.from_iterable(self.connections))) |
| 790 |
|
| 791 |
@property |
| 792 |
def networks_nb(self) -> int: |
| 793 |
""" |
| 794 |
Return the number of connected networks (port excluded). |
| 795 |
""" |
| 796 |
return len(self.networks_list(self.connections)) |
| 797 |
|
| 798 |
@property |
| 799 |
def nodes_nb(self) -> int: |
| 800 |
""" |
| 801 |
Return the number of nodes in the circuit. |
| 802 |
""" |
| 803 |
return self.connections_nb + self.networks_nb |
| 804 |
|
| 805 |
@property |
| 806 |
def dim(self) -> int: |
| 807 |
""" |
| 808 |
Return the dimension of the C, X and global S matrices. |
| 809 |
|
| 810 |
It correspond to the sum of all connections. |
| 811 |
""" |
| 812 |
return np.sum([len(cnx) for cnx in self.connections]) |
| 813 |
|
| 814 |
@property |
| 815 |
def G(self): |
| 816 |
""" |
| 817 |
Generate the graph of the circuit. Convenience shortname for :func:`graph`. |
| 818 |
""" |
| 819 |
return self.graph() |
| 820 |
|
| 821 |
def graph(self): |
| 822 |
""" |
| 823 |
Generate the graph of the circuit. |
| 824 |
|
| 825 |
Returns |
| 826 |
------- |
| 827 |
G: :class:`networkx.Graph` |
| 828 |
graph object [#]_ . |
| 829 |
|
| 830 |
References |
| 831 |
---------- |
| 832 |
.. [#] https://networkx.github.io/ |
| 833 |
""" |
| 834 |
|
| 835 |
nx = self._get_nx() |
| 836 |
G = nx.Graph() |
| 837 |
|
| 838 |
G.add_nodes_from([it for it in self.networks_dict(self.connections)]) |
| 839 |
|
| 840 |
|
| 841 |
for (idx, cnx) in enumerate(self.connections): |
| 842 |
cnx_name = 'X'+str(idx) |
| 843 |
|
| 844 |
G.add_node(cnx_name) |
| 845 |
for (ntw, _ntw_port) in cnx: |
| 846 |
ntw_name = ntw.name |
| 847 |
G.add_edge(cnx_name, ntw_name) |
| 848 |
return G |
| 849 |
|
| 850 |
def is_connected(self) -> bool: |
| 851 |
""" |
| 852 |
Check if the circuit's graph is connected. |
| 853 |
|
| 854 |
Check if every pair of vertices in the graph is connected. |
| 855 |
""" |
| 856 |
|
| 857 |
nx = self._get_nx() |
| 858 |
return nx.algorithms.components.is_connected(self.G) |
| 859 |
|
| 860 |
|
| 861 |
@property |
| 862 |
def intersections_dict(self) -> dict: |
| 863 |
""" |
| 864 |
Return a dictionary of all intersections with associated ports and z0: |
| 865 |
|
| 866 |
:: |
| 867 |
|
| 868 |
{ k: [(ntw1_name, ntw1_port), (ntw1_z0, ntw2_name, ntw2_port), ntw2_z0], ... } |
| 869 |
""" |
| 870 |
inter_dict = {} |
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
for (k, cnx) in enumerate(self.connections): |
| 876 |
inter_dict[k] = [(ntw, ntw_port, ntw.z0[0, ntw_port]) \ |
| 877 |
for (ntw, ntw_port) in cnx] |
| 878 |
return inter_dict |
| 879 |
|
| 880 |
@property |
| 881 |
def edges(self) -> list: |
| 882 |
""" |
| 883 |
Return the list of all circuit connections |
| 884 |
""" |
| 885 |
return list(self.G.edges) |
| 886 |
|
| 887 |
@property |
| 888 |
def edge_labels(self) -> dict: |
| 889 |
""" |
| 890 |
Return a dictionary describing the port and z0 of all graph edges. |
| 891 |
|
| 892 |
Dictionary is in the form:: |
| 893 |
|
| 894 |
{('ntw1_name', 'X0'): '3 (50+0j)', |
| 895 |
('ntw2_name', 'X0'): '0 (50+0j)', |
| 896 |
('ntw2_name', 'X1'): '2 (50+0j)', ... } |
| 897 |
|
| 898 |
which can be used in `networkx.draw_networkx_edge_labels` |
| 899 |
""" |
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
edge_labels = {} |
| 905 |
for it in self.intersections_dict.items(): |
| 906 |
k, cnx = it |
| 907 |
for idx in range(len(cnx)): |
| 908 |
ntw, ntw_port, ntw_z0 = cnx[idx] |
| 909 |
|
| 910 |
edge_labels[(ntw.name, 'X'+str(k))] = str(ntw_port)+'\n'+\ |
| 911 |
str(np.round(ntw_z0, decimals=1)) |
| 912 |
|
| 913 |
return edge_labels |
| 914 |
|
| 915 |
|
| 916 |
def _Xk(self, |
| 917 |
cnx_k: list[tuple[Network, int]], |
| 918 |
order: MemoryLayoutT = 'C', |
| 919 |
inverse: bool = False) -> np.ndarray: |
| 920 |
""" |
| 921 |
Return the scattering matrices [X]_k of the individual intersections k. |
| 922 |
The results in [#]_ do not agree due to an error in the formula (3) |
| 923 |
for mismatched intersections. |
| 924 |
|
| 925 |
Due to the ideal power splitter is unitary, that is [X]_k^H * [X]_k = I, where [X]_k^H is |
| 926 |
the conjugate transpose of [X]_k. And considers the reciprocity, the inverse of [X]_k could |
| 927 |
be simplified as the conjugate of [X]_k, that is [X]_k^-1 = [X]_k^*. |
| 928 |
|
| 929 |
Parameters |
| 930 |
---------- |
| 931 |
cnx_k : list of tuples |
| 932 |
each tuple contains (network, port) |
| 933 |
order: str, optional |
| 934 |
'C' or 'F' for row-major or column-major order of the output array. |
| 935 |
Default is 'C'. |
| 936 |
inverse: bool, optional |
| 937 |
If True, return the inverse of the scattering matrix [X]_k. |
| 938 |
Default is False. |
| 939 |
|
| 940 |
Returns |
| 941 |
------- |
| 942 |
Xs : :class:`numpy.ndarray` |
| 943 |
shape `f x n x n` |
| 944 |
|
| 945 |
References |
| 946 |
---------- |
| 947 |
.. [#] P. Hallbjörner, Microw. Opt. Technol. Lett. 38, 99 (2003). |
| 948 |
""" |
| 949 |
|
| 950 |
y0s = np.array([1/ntw.z0[:,ntw_port] for (ntw, ntw_port) in cnx_k]).T |
| 951 |
y_k = y0s.sum(axis=1) |
| 952 |
|
| 953 |
Xs = np.zeros((len(self.frequency), len(cnx_k), len(cnx_k)), dtype='complex', order=order) |
| 954 |
|
| 955 |
Xs = 2 *np.sqrt(np.einsum('ij,ik->ijk', y0s, y0s)) / y_k[:, None, None] |
| 956 |
np.einsum('kii->ki', Xs)[:] -= 1 |
| 957 |
|
| 958 |
return np.conjugate(Xs) if inverse else Xs |
| 959 |
|
| 960 |
|
| 961 |
def _X(self, order: MemoryLayoutT = 'C', inverse: bool = False) -> np.ndarray: |
| 962 |
""" |
| 963 |
Return the concatenated intersection matrix [X] of the circuit. |
| 964 |
|
| 965 |
It is composed of the individual intersection matrices [X]_k assembled |
| 966 |
by block diagonal. |
| 967 |
|
| 968 |
Due to the concatenated intersection matrix [X] is a block diagonal matrix, |
| 969 |
the inverse of [X] could be simplified as the block diagonal matrix of the |
| 970 |
inverses of [X]_k. |
| 971 |
|
| 972 |
Parameters |
| 973 |
---------- |
| 974 |
order : str, optional |
| 975 |
'C' or 'F' for row-major or column-major order of the output array. |
| 976 |
Default is 'C'. |
| 977 |
|
| 978 |
inverse : bool, optional |
| 979 |
If True, return the inverse of the concatenated intersection matrix [X]. |
| 980 |
Default is False. |
| 981 |
|
| 982 |
Returns |
| 983 |
------- |
| 984 |
X : :class:`numpy.ndarray` |
| 985 |
|
| 986 |
Note |
| 987 |
---- |
| 988 |
The block diagonal matrix [X] has a numerical bottleneck that depends on the |
| 989 |
order specified: |
| 990 |
- When 'order' is 'C', the creation of the block diagonal matrix [X] in row-major |
| 991 |
order is a bottleneck. This is because the creation process is port-by-port, |
| 992 |
which does not align well with the row-major memory layout, leading to |
| 993 |
suboptimal performance. |
| 994 |
- When 'order' is 'F', the computation of the block diagonal matrix [X] in column-major |
| 995 |
order is a bottleneck. Numpy generally optimizes operators for 'C' order, which |
| 996 |
lead to performance issues when using 'F' order. |
| 997 |
""" |
| 998 |
Xks = [self._Xk(cnx, order, inverse) for cnx in self.connections] |
| 999 |
|
| 1000 |
Xf = np.zeros((len(self.frequency), self.dim, self.dim), dtype='complex', order=order) |
| 1001 |
off = np.array([0, 0]) |
| 1002 |
for Xk in Xks: |
| 1003 |
Xf[:, off[0]:off[0] + Xk.shape[1], off[1]:off[1]+Xk.shape[2]] = Xk |
| 1004 |
off += Xk.shape[1:] |
| 1005 |
|
| 1006 |
return Xf |
| 1007 |
|
| 1008 |
@cached_property |
| 1009 |
def X(self) -> np.ndarray: |
| 1010 |
""" |
| 1011 |
Return the concatenated intersection matrix [X] of the circuit in C-order. |
| 1012 |
|
| 1013 |
It is composed of the individual intersection matrices [X]_k assembled |
| 1014 |
by block diagonal. |
| 1015 |
|
| 1016 |
Returns |
| 1017 |
------- |
| 1018 |
X : :class:`numpy.ndarray` |
| 1019 |
|
| 1020 |
Note |
| 1021 |
---- |
| 1022 |
There is a numerical bottleneck in this function, |
| 1023 |
when creating the block diagonal matrice [X] from the [X]_k matrices. |
| 1024 |
""" |
| 1025 |
|
| 1026 |
if self.__dict__.get('X_F', None) is not None: |
| 1027 |
return np.ascontiguousarray(self.X_F) |
| 1028 |
|
| 1029 |
return self._X() |
| 1030 |
|
| 1031 |
@cached_property |
| 1032 |
def X_F(self) -> np.ndarray: |
| 1033 |
""" |
| 1034 |
Return the concatenated intersection matrix [X] of the circuit in F-order. |
| 1035 |
It is composed of the individual intersection matrices [X]_k assembled |
| 1036 |
by block diagonal. The results of this function are the same as :func:`X` |
| 1037 |
but in F-order. |
| 1038 |
|
| 1039 |
Returns |
| 1040 |
------- |
| 1041 |
X : :class:`numpy.ndarray` |
| 1042 |
|
| 1043 |
Note |
| 1044 |
---- |
| 1045 |
F-order has a numerical bottleneck in matrix operations, but the assignment |
| 1046 |
is more efficient. |
| 1047 |
""" |
| 1048 |
|
| 1049 |
if self.__dict__.get('X', None) is not None: |
| 1050 |
return np.asfortranarray(self.X) |
| 1051 |
|
| 1052 |
return self._X('F') |
| 1053 |
|
| 1054 |
@cached_property |
| 1055 |
def C(self) -> np.ndarray: |
| 1056 |
""" |
| 1057 |
Return the global scattering matrix [C] of the networks in C-order. |
| 1058 |
|
| 1059 |
Returns |
| 1060 |
------- |
| 1061 |
S : :class:`numpy.ndarray` |
| 1062 |
Global scattering matrix of the networks. |
| 1063 |
Shape `f x (nb_inter*nb_n) x (nb_inter*nb_n)` |
| 1064 |
""" |
| 1065 |
|
| 1066 |
if self.__dict__.get('C_F', None) is not None: |
| 1067 |
return np.ascontiguousarray(self.C_F) |
| 1068 |
|
| 1069 |
return self._C() |
| 1070 |
|
| 1071 |
@cached_property |
| 1072 |
def C_F(self) -> np.ndarray: |
| 1073 |
""" |
| 1074 |
Return the global scattering matrix [C] of the networks in F-order. The results |
| 1075 |
of this function are the same as :func:`C` but in F-order. |
| 1076 |
|
| 1077 |
Returns |
| 1078 |
------- |
| 1079 |
S : :class:`numpy.ndarray` |
| 1080 |
Global scattering matrix of the networks. |
| 1081 |
Shape `f x (nb_inter*nb_n) x (nb_inter*nb_n)` |
| 1082 |
|
| 1083 |
Note |
| 1084 |
---- |
| 1085 |
F-order has a numerical bottleneck in matrix operations, but the assignment |
| 1086 |
is more efficient. |
| 1087 |
""" |
| 1088 |
|
| 1089 |
if self.__dict__.get('C', None) is not None: |
| 1090 |
return np.asfortranarray(self.C) |
| 1091 |
|
| 1092 |
return self._C('F') |
| 1093 |
|
| 1094 |
def _C(self, order: MemoryLayoutT = 'C') -> np.ndarray: |
| 1095 |
""" |
| 1096 |
Return the global scattering matrix [C] of the networks. |
| 1097 |
|
| 1098 |
Args: |
| 1099 |
order : str, optional |
| 1100 |
'C' or 'F' for row-major or column-major order of the output array. |
| 1101 |
Default is 'C'. |
| 1102 |
|
| 1103 |
Returns |
| 1104 |
------- |
| 1105 |
S : :class:`numpy.ndarray` |
| 1106 |
Global scattering matrix of the networks. |
| 1107 |
Shape `f x (nb_inter*nb_n) x (nb_inter*nb_n)` |
| 1108 |
""" |
| 1109 |
|
| 1110 |
ntws = {k:v for k,v in self.networks_dict().items() if not Circuit._is_port(v)} |
| 1111 |
|
| 1112 |
|
| 1113 |
ntws_ports_reordering = {ntw:[] for ntw in ntws} |
| 1114 |
for (idx_cnx, (ntw, ntw_port)) in self.connections_list: |
| 1115 |
if ntw.name in ntws.keys(): |
| 1116 |
ntws_ports_reordering[ntw.name].append([ntw_port, idx_cnx]) |
| 1117 |
|
| 1118 |
|
| 1119 |
S = np.zeros((len(self.frequency), self.dim, self.dim), dtype='complex', order=order) |
| 1120 |
|
| 1121 |
for (ntw_name, ntw_ports) in ntws_ports_reordering.items(): |
| 1122 |
|
| 1123 |
ntw_ports = np.array(ntw_ports) |
| 1124 |
|
| 1125 |
|
| 1126 |
from_port = ntw_ports[:,0] |
| 1127 |
to_port = ntw_ports[:,1] |
| 1128 |
|
| 1129 |
for (_from, _to) in zip(from_port, to_port): |
| 1130 |
S[:, _to, to_port] = ntws[ntw_name].s_traveling[:, _from, from_port] |
| 1131 |
|
| 1132 |
return S |
| 1133 |
|
| 1134 |
@cached_property |
| 1135 |
def T(self) -> np.ndarray: |
| 1136 |
""" |
| 1137 |
Return the matrix of multiplication of the global scattering matrix [C] and concatenated |
| 1138 |
intersection matrix [X] of the networks, that is [T] = - [C] @ [X]. |
| 1139 |
|
| 1140 |
Returns |
| 1141 |
------- |
| 1142 |
T : :class:`numpy.ndarray` |
| 1143 |
Multiplication of the global scattering matrix [C] and concatenated intersection matrix |
| 1144 |
[X] of the networks. In practice, F-contiguous [C_F] and [X_F] are used. |
| 1145 |
Shape `f x (nb_inter*nb_n) x (nb_inter*nb_n)` |
| 1146 |
|
| 1147 |
Note |
| 1148 |
---- |
| 1149 |
This is an auxiliary matrix used to break the numerical bottleneck of [C_F] @ [X_F] using the |
| 1150 |
mathematical feature of block diagonal matrice [X]. |
| 1151 |
""" |
| 1152 |
X, C = self.X_F, self.C_F |
| 1153 |
|
| 1154 |
|
| 1155 |
T = np.empty_like(X, dtype="complex", order='F') |
| 1156 |
|
| 1157 |
|
| 1158 |
cnx_size = [len(cnx) for cnx in self.connections] |
| 1159 |
slice_ = np.cumsum([0] + cnx_size) |
| 1160 |
slices = [slice(slice_[i], slice_[i+1]) for i in range(len(cnx_size))] |
| 1161 |
|
| 1162 |
|
| 1163 |
for j_slice in slices: |
| 1164 |
|
| 1165 |
X_jj = - X[:, j_slice, j_slice] |
| 1166 |
C_j = C[:, :, j_slice] |
| 1167 |
|
| 1168 |
|
| 1169 |
for i_slice in slices: |
| 1170 |
T[:, i_slice, j_slice] = C_j[:, i_slice, :] @ X_jj |
| 1171 |
|
| 1172 |
return T |
| 1173 |
|
| 1174 |
@cached_property |
| 1175 |
def s(self) -> np.ndarray: |
| 1176 |
""" |
| 1177 |
Return the global scattering parameters of the circuit. |
| 1178 |
|
| 1179 |
Return the scattering parameters of both "inner" and "outer" ports. |
| 1180 |
|
| 1181 |
Note |
| 1182 |
---- |
| 1183 |
The original implementation of this method calculated the S-parameters [S] using the global |
| 1184 |
scattering matrix [C] and the concatenated intersection matrix [X] by solving the equation: |
| 1185 |
[S] = [X] @ ([E] - [C] @ [X])^-1 |
| 1186 |
|
| 1187 |
where [E] is the identity matrix. However, this approach is computationally inefficient for |
| 1188 |
large networks due to its numerical bottlenecks. |
| 1189 |
|
| 1190 |
The current implementation optimizes the calculation by leveraging matrix algebra to simplify |
| 1191 |
the relationship between the incident {a} and reflected {b} power waves. The key steps are as |
| 1192 |
follows: |
| 1193 |
|
| 1194 |
1. Define the relationship between {b} and {a} using [X] and [C]: |
| 1195 |
{b} = [X] @ ([E] - [C] @ [X])^-1 @ {a} |
| 1196 |
|
| 1197 |
2. Simplify the relationship between {a} and {b}: |
| 1198 |
{a} = ([X] @ ([E] - [C] @ [X])^-1)^-1 @ {b} |
| 1199 |
= ([E] - [C] @ [X]) @ [X]^-1 @ {b} |
| 1200 |
= ([X]^-1 - [C] @ [X] @ [X]^-1) @ {b} |
| 1201 |
= ([X]^-1 - [C]) @ {b} |
| 1202 |
|
| 1203 |
3. Derive the S-parameters matrix [S] from the simplified relationship: |
| 1204 |
[S] = ([X]^-1 - [C])^-1 |
| 1205 |
|
| 1206 |
4. Leverage the property of the concatenated intersection matrix [X]: |
| 1207 |
- [X] is a block diagonal matrix composed of individual intersection matrices [X]_k: |
| 1208 |
[X] = diag([X_1], [X_2], ..., [X_n]). |
| 1209 |
- Each [X]_k represents an ideal lossless power splitter, which is unitary: |
| 1210 |
[X]_k^H @ [X]_k = I, |
| 1211 |
where [X]_k^H is the conjugate transpose of [X]_k. |
| 1212 |
- Due to reciprocity, the inverse of [X]_k is its conjugate: |
| 1213 |
[X]_k^-1 = [X]_k^*. |
| 1214 |
|
| 1215 |
5. Substitute the property into the S-parameters equation: |
| 1216 |
[S] = ([X^T]^* - [C])^-1 |
| 1217 |
|
| 1218 |
This approach avoids the explicit computation of [X]^-1, significantly improving computational |
| 1219 |
efficiency for large-scale networks. |
| 1220 |
|
| 1221 |
Returns |
| 1222 |
------- |
| 1223 |
S : :class:`numpy.ndarray` |
| 1224 |
global scattering parameters of the circuit. |
| 1225 |
""" |
| 1226 |
return np.linalg.inv(self._X(inverse=True) - self.C) |
| 1227 |
|
| 1228 |
@property |
| 1229 |
def port_indexes(self) -> list[int]: |
| 1230 |
""" |
| 1231 |
Return the indexes of the "external" ports. |
| 1232 |
|
| 1233 |
Returns |
| 1234 |
------- |
| 1235 |
port_indexes : list |
| 1236 |
""" |
| 1237 |
port_indexes = [] |
| 1238 |
for (idx_cnx, (ntw, _)) in enumerate(chain.from_iterable(self.connections)): |
| 1239 |
if Circuit._is_port(ntw): |
| 1240 |
port_indexes.append(idx_cnx) |
| 1241 |
return port_indexes |
| 1242 |
|
| 1243 |
def _cnx_z0(self, cnx_k: list[tuple]) -> np.ndarray: |
| 1244 |
""" |
| 1245 |
Return the characteristic impedances of a specific connections. |
| 1246 |
|
| 1247 |
Parameters |
| 1248 |
---------- |
| 1249 |
cnx_k : list of tuples |
| 1250 |
each tuple contains (network, port) |
| 1251 |
|
| 1252 |
Returns |
| 1253 |
------- |
| 1254 |
z0s : :class:`numpy.ndarray` |
| 1255 |
shape `f x nb_ports_at_cnx` |
| 1256 |
""" |
| 1257 |
z0s = [] |
| 1258 |
for (ntw, ntw_port) in cnx_k: |
| 1259 |
z0s.append(ntw.z0[:,ntw_port]) |
| 1260 |
|
| 1261 |
return np.array(z0s).T |
| 1262 |
|
| 1263 |
@property |
| 1264 |
def port_z0(self) -> np.ndarray: |
| 1265 |
""" |
| 1266 |
Return the external port impedances. |
| 1267 |
|
| 1268 |
Returns |
| 1269 |
------- |
| 1270 |
z0s : :class:`numpy.ndarray` |
| 1271 |
shape `f x nb_ports` |
| 1272 |
""" |
| 1273 |
z0s = [] |
| 1274 |
for cnx in self.connections: |
| 1275 |
for (ntw, ntw_port) in cnx: |
| 1276 |
z0s.append(ntw.z0[:,ntw_port]) |
| 1277 |
|
| 1278 |
return np.array(z0s)[self.port_indexes, :].T |
| 1279 |
|
| 1280 |
@property |
| 1281 |
def s_external(self) -> np.ndarray: |
| 1282 |
""" |
| 1283 |
Return the scattering parameters for the external ports. |
| 1284 |
|
| 1285 |
Returns |
| 1286 |
------- |
| 1287 |
S : :class:`numpy.ndarray` |
| 1288 |
Scattering parameters of the circuit for the external ports. |
| 1289 |
Shape `f x nb_ports x nb_ports` |
| 1290 |
""" |
| 1291 |
|
| 1292 |
|
| 1293 |
|
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
port_indexes = self.port_indexes |
| 1301 |
in_idxs = [(i,) for i in range(self.dim) if i not in port_indexes] |
| 1302 |
ext_idxs = [(i,) for i in port_indexes] |
| 1303 |
ext_l, in_l = len(ext_idxs), len(in_idxs) |
| 1304 |
|
| 1305 |
|
| 1306 |
idx_a, idx_b, idx_c, idx_d = ( |
| 1307 |
np.repeat(i, l, axis=1) |
| 1308 |
for i, l in ( |
| 1309 |
(ext_idxs, ext_l), |
| 1310 |
(ext_idxs, in_l), |
| 1311 |
(in_idxs, ext_l), |
| 1312 |
(in_idxs, in_l), |
| 1313 |
) |
| 1314 |
) |
| 1315 |
|
| 1316 |
|
| 1317 |
A_idx = (slice(None), idx_a, idx_a.T) |
| 1318 |
B_idx = (slice(None), idx_b, idx_c.T) |
| 1319 |
C_idx = (slice(None), idx_c, idx_b.T) |
| 1320 |
D_idx = (slice(None), idx_d, idx_d.T) |
| 1321 |
|
| 1322 |
|
| 1323 |
|
| 1324 |
x, t = self.X_F, np.array(self.T) |
| 1325 |
np.einsum('...ii->...i', t)[:] += 1 |
| 1326 |
|
| 1327 |
|
| 1328 |
|
| 1329 |
try: |
| 1330 |
tmp_mat = np.linalg.solve(t[D_idx], t[C_idx]) |
| 1331 |
except np.linalg.LinAlgError: |
| 1332 |
warnings.warn('Singular matrix detected, using numpy.linalg.lstsq instead.', RuntimeWarning, stacklevel=2) |
| 1333 |
|
| 1334 |
tmp_mat = np.zeros((self.frequency.npoints, len(in_idxs), len(ext_idxs)), dtype='complex') |
| 1335 |
for i in range(self.frequency.npoints): |
| 1336 |
tmp_mat[i, :, :] = np.linalg.lstsq(t[i, D_idx[1], D_idx[2]], t[i, C_idx[1], C_idx[2]], rcond=None)[0] |
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
S_ext = (x[A_idx] - x[B_idx] @ tmp_mat) @ np.linalg.inv( |
| 1341 |
t[A_idx] - t[B_idx] @ tmp_mat |
| 1342 |
) |
| 1343 |
|
| 1344 |
S_ext = s2s(S_ext, self.port_z0, S_DEF_DEFAULT, 'traveling') |
| 1345 |
return S_ext |
| 1346 |
|
| 1347 |
@property |
| 1348 |
def network(self) -> Network: |
| 1349 |
""" |
| 1350 |
Return the Network associated to external ports. |
| 1351 |
|
| 1352 |
Returns |
| 1353 |
------- |
| 1354 |
ntw : :class:`~skrf.network.Network` |
| 1355 |
Network associated to external ports |
| 1356 |
""" |
| 1357 |
return Network(frequency = self.frequency, z0 = self.port_z0, |
| 1358 |
s = self.s_external, name = self.name) |
| 1359 |
|
| 1360 |
def s_active(self, a: NumberLike) -> np.ndarray: |
| 1361 |
r""" |
| 1362 |
Return "active" s-parameters of the circuit's network for a defined wave excitation `a`. |
| 1363 |
|
| 1364 |
The "active" s-parameter at a port is the reflection coefficients |
| 1365 |
when other ports are excited. It is an important quantity for active |
| 1366 |
phased array antennas. |
| 1367 |
|
| 1368 |
Active s-parameters are defined by [#]_: |
| 1369 |
|
| 1370 |
.. math:: |
| 1371 |
|
| 1372 |
\mathrm{active}(s)_{mn} = \sum_i s_{mi} \frac{a_i}{a_n} |
| 1373 |
|
| 1374 |
Parameters |
| 1375 |
---------- |
| 1376 |
a : complex array of shape (n_ports) |
| 1377 |
forward wave complex amplitude (power-wave formulation [#]_) |
| 1378 |
|
| 1379 |
Returns |
| 1380 |
------- |
| 1381 |
s_act : complex array of shape (n_freqs, n_ports) |
| 1382 |
active s-parameters for the excitation a |
| 1383 |
|
| 1384 |
|
| 1385 |
References |
| 1386 |
---------- |
| 1387 |
.. [#] D. M. Pozar, IEEE Trans. Antennas Propag. 42, 1176 (1994). |
| 1388 |
|
| 1389 |
.. [#] D. Williams, IEEE Microw. Mag. 14, 38 (2013). |
| 1390 |
|
| 1391 |
""" |
| 1392 |
return self.network.s_active(a) |
| 1393 |
|
| 1394 |
def z_active(self, a: NumberLike) -> np.ndarray: |
| 1395 |
r""" |
| 1396 |
Return the "active" Z-parameters of the circuit's network for a defined wave excitation a. |
| 1397 |
|
| 1398 |
The "active" Z-parameters are defined by: |
| 1399 |
|
| 1400 |
.. math:: |
| 1401 |
|
| 1402 |
\mathrm{active}(z)_{m} = z_{0,m} \frac{1 + \mathrm{active}(s)_m}{1 - \mathrm{active}(s)_m} |
| 1403 |
|
| 1404 |
where :math:`z_{0,m}` is the characteristic impedance and |
| 1405 |
:math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`. |
| 1406 |
|
| 1407 |
Parameters |
| 1408 |
---------- |
| 1409 |
a : complex array of shape (n_ports) |
| 1410 |
forward wave complex amplitude |
| 1411 |
|
| 1412 |
Returns |
| 1413 |
------- |
| 1414 |
z_act : complex array of shape (nfreqs, nports) |
| 1415 |
active Z-parameters for the excitation a |
| 1416 |
|
| 1417 |
See Also |
| 1418 |
-------- |
| 1419 |
s_active : active S-parameters |
| 1420 |
y_active : active Y-parameters |
| 1421 |
vswr_active : active VSWR |
| 1422 |
""" |
| 1423 |
return self.network.z_active(a) |
| 1424 |
|
| 1425 |
def y_active(self, a: NumberLike) -> np.ndarray: |
| 1426 |
r""" |
| 1427 |
Return the "active" Y-parameters of the circuit's network for a defined wave excitation a. |
| 1428 |
|
| 1429 |
The "active" Y-parameters are defined by: |
| 1430 |
|
| 1431 |
.. math:: |
| 1432 |
|
| 1433 |
\mathrm{active}(y)_{m} = y_{0,m} \frac{1 - \mathrm{active}(s)_m}{1 + \mathrm{active}(s)_m} |
| 1434 |
|
| 1435 |
where :math:`y_{0,m}` is the characteristic admittance and |
| 1436 |
:math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`. |
| 1437 |
|
| 1438 |
Parameters |
| 1439 |
---------- |
| 1440 |
a : complex array of shape (n_ports) |
| 1441 |
forward wave complex amplitude |
| 1442 |
|
| 1443 |
Returns |
| 1444 |
------- |
| 1445 |
y_act : complex array of shape (nfreqs, nports) |
| 1446 |
active Y-parameters for the excitation a |
| 1447 |
|
| 1448 |
See Also |
| 1449 |
-------- |
| 1450 |
s_active : active S-parameters |
| 1451 |
z_active : active Z-parameters |
| 1452 |
vswr_active : active VSWR |
| 1453 |
""" |
| 1454 |
return self.network.y_active(a) |
| 1455 |
|
| 1456 |
def vswr_active(self, a: NumberLike) -> np.ndarray: |
| 1457 |
r""" |
| 1458 |
Return the "active" VSWR of the circuit's network for a defined wave excitation a. |
| 1459 |
|
| 1460 |
The "active" VSWR is defined by : |
| 1461 |
|
| 1462 |
.. math:: |
| 1463 |
|
| 1464 |
\mathrm{active}(vswr)_{m} = \frac{1 + |\mathrm{active}(s)_m|}{1 - |\mathrm{active}(s)_m|} |
| 1465 |
|
| 1466 |
where :math:`\mathrm{active}(s)_m` the active S-parameter of port :math:`m`. |
| 1467 |
|
| 1468 |
Parameters |
| 1469 |
---------- |
| 1470 |
a : complex array of shape (n_ports) |
| 1471 |
forward wave complex amplitude |
| 1472 |
|
| 1473 |
Returns |
| 1474 |
------- |
| 1475 |
vswr_act : complex array of shape (nfreqs, nports) |
| 1476 |
active VSWR for the excitation a |
| 1477 |
|
| 1478 |
See Also |
| 1479 |
-------- |
| 1480 |
s_active : active S-parameters |
| 1481 |
z_active : active Z-parameters |
| 1482 |
y_active : active Y-parameters |
| 1483 |
""" |
| 1484 |
return self.network.vswr_active(a) |
| 1485 |
|
| 1486 |
@property |
| 1487 |
def z0(self) -> np.ndarray: |
| 1488 |
""" |
| 1489 |
Characteristic impedances of "internal" ports. |
| 1490 |
|
| 1491 |
Returns |
| 1492 |
------- |
| 1493 |
z0 : complex array of shape (nfreqs, nports) |
| 1494 |
Characteristic impedances of both "inner" and "outer" ports |
| 1495 |
|
| 1496 |
""" |
| 1497 |
z0s = [] |
| 1498 |
for _cnx_idx, (ntw, ntw_port) in self.connections_list: |
| 1499 |
z0s.append(ntw.z0[:,ntw_port]) |
| 1500 |
return np.array(z0s).T |
| 1501 |
|
| 1502 |
@property |
| 1503 |
def connections_pair(self) -> list: |
| 1504 |
""" |
| 1505 |
List the connections by pair. |
| 1506 |
|
| 1507 |
Each connection in the circuit is between a specific pair of two |
| 1508 |
(networks, port, z0). |
| 1509 |
|
| 1510 |
Returns |
| 1511 |
------- |
| 1512 |
connections_pair : list |
| 1513 |
list of pair of connections |
| 1514 |
|
| 1515 |
""" |
| 1516 |
return [self.connections_list[i:i+2] for i in range(0, len(self.connections_list), 2)] |
| 1517 |
|
| 1518 |
|
| 1519 |
@property |
| 1520 |
def _currents_directions(self) -> np.ndarray: |
| 1521 |
""" |
| 1522 |
Create a array of indices to define the sign of the current. |
| 1523 |
|
| 1524 |
The currents are defined positive when entering an internal network. |
| 1525 |
|
| 1526 |
Returns |
| 1527 |
------- |
| 1528 |
directions : array of int (nports, 2) |
| 1529 |
|
| 1530 |
Note |
| 1531 |
---- |
| 1532 |
This function is used in internal currents and voltages calculations. |
| 1533 |
|
| 1534 |
""" |
| 1535 |
directions = np.zeros((self.dim,2), dtype='int') |
| 1536 |
for cnx_pair in self.connections_pair: |
| 1537 |
(cnx_idx_A, cnx_A), (cnx_idx_B, cnx_B) = cnx_pair |
| 1538 |
directions[cnx_idx_A,:] = cnx_idx_A, cnx_idx_B |
| 1539 |
directions[cnx_idx_B,:] = cnx_idx_B, cnx_idx_A |
| 1540 |
return directions |
| 1541 |
|
| 1542 |
def _a(self, a_external: NumberLike) -> np.ndarray: |
| 1543 |
""" |
| 1544 |
Wave input array at "internal" ports. |
| 1545 |
|
| 1546 |
Parameters |
| 1547 |
---------- |
| 1548 |
a_external : array |
| 1549 |
power-wave input vector at ports |
| 1550 |
|
| 1551 |
Returns |
| 1552 |
------- |
| 1553 |
a_internal : array |
| 1554 |
Wave input array at internal ports |
| 1555 |
|
| 1556 |
""" |
| 1557 |
|
| 1558 |
a_internal = np.zeros(self.dim, dtype='complex') |
| 1559 |
a_internal[self.port_indexes] = a_external |
| 1560 |
return a_internal |
| 1561 |
|
| 1562 |
def _a_external(self, power: NumberLike, phase: NumberLike) -> np.ndarray: |
| 1563 |
r""" |
| 1564 |
Wave input array at Circuit's ports ("external" ports). |
| 1565 |
|
| 1566 |
The array is defined from power and phase by: |
| 1567 |
|
| 1568 |
.. math:: |
| 1569 |
|
| 1570 |
a = \sqrt(2 P_{in} ) e^{j \phi} |
| 1571 |
|
| 1572 |
The factor 2 is in order to deal with peak values. |
| 1573 |
|
| 1574 |
Parameters |
| 1575 |
---------- |
| 1576 |
power : list or array |
| 1577 |
Input power at external ports in Watts [W] |
| 1578 |
phase : list or array |
| 1579 |
Input phase at external ports in radian [rad] |
| 1580 |
|
| 1581 |
NB: the size of the power and phase array should match the number of ports |
| 1582 |
|
| 1583 |
Returns |
| 1584 |
------- |
| 1585 |
a_external: array |
| 1586 |
Wave input array at Circuit's ports |
| 1587 |
|
| 1588 |
""" |
| 1589 |
if len(power) != len(self.port_indexes): |
| 1590 |
raise ValueError('Length of power array does not match the number of ports of the circuit.') |
| 1591 |
if len(phase) != len(self.port_indexes): |
| 1592 |
raise ValueError('Length of phase array does not match the number of ports of the circuit.') |
| 1593 |
return np.sqrt(2*np.array(power))*np.exp(1j*np.array(phase)) |
| 1594 |
|
| 1595 |
def _b(self, a_internal: NumberLike) -> np.ndarray: |
| 1596 |
""" |
| 1597 |
Wave output array at "internal" ports |
| 1598 |
|
| 1599 |
Parameters |
| 1600 |
---------- |
| 1601 |
a_internal : array |
| 1602 |
Wave input array at internal ports |
| 1603 |
|
| 1604 |
Returns |
| 1605 |
------- |
| 1606 |
b_internal : array |
| 1607 |
Wave output array at internal ports |
| 1608 |
|
| 1609 |
Note |
| 1610 |
---- |
| 1611 |
Wave input array at internal ports can be derived from power and |
| 1612 |
phase excitation at "external" ports using `_a(power, phase)` method. |
| 1613 |
|
| 1614 |
""" |
| 1615 |
return self.s @ a_internal |
| 1616 |
|
| 1617 |
def currents(self, power: NumberLike, phase: NumberLike) -> np.ndarray: |
| 1618 |
""" |
| 1619 |
Currents at internal ports. |
| 1620 |
|
| 1621 |
NB: current direction is defined as positive when entering a node. |
| 1622 |
|
| 1623 |
NB: external current sign are opposite than corresponding internal ones, |
| 1624 |
as the internal currents are actually flowing into the "port" networks |
| 1625 |
|
| 1626 |
Parameters |
| 1627 |
---------- |
| 1628 |
power : list or array |
| 1629 |
Input power at external ports in Watts [W] |
| 1630 |
phase : list or array |
| 1631 |
Input phase at external ports in radian [rad] |
| 1632 |
|
| 1633 |
Returns |
| 1634 |
------- |
| 1635 |
I : complex array of shape (nfreqs, nports) |
| 1636 |
Currents in Amperes [A] (peak) at internal ports. |
| 1637 |
|
| 1638 |
""" |
| 1639 |
a = self._a(self._a_external(power, phase)) |
| 1640 |
b = self._b(a) |
| 1641 |
z0s = self.z0 |
| 1642 |
i, Is = 0, np.zeros_like(z0s) |
| 1643 |
|
| 1644 |
for cnx in self.connections: |
| 1645 |
cnx_len = len(cnx) |
| 1646 |
z0_segment = z0s[:, i : i + cnx_len] |
| 1647 |
tot_shunt_z0 = (1 / z0_segment).sum(axis=1) |
| 1648 |
Ij = np.zeros_like(z0_segment) |
| 1649 |
|
| 1650 |
|
| 1651 |
for j in range(cnx_len): |
| 1652 |
in_z0 = z0_segment[:, j] |
| 1653 |
out_z0 = 1 / (tot_shunt_z0 - 1 / in_z0) |
| 1654 |
tau = (2 * out_z0) / (out_z0 + in_z0) |
| 1655 |
Ij[:, j] = (b[:, i + j] / np.sqrt(in_z0)) * tau |
| 1656 |
|
| 1657 |
|
| 1658 |
|
| 1659 |
for j in range(cnx_len): |
| 1660 |
in_z0 = z0_segment[:, j] |
| 1661 |
out_z0 = 1 / (tot_shunt_z0 - 1 / in_z0) |
| 1662 |
Itmp = np.zeros_like(Is[:, i + j]) |
| 1663 |
for k in range(cnx_len): |
| 1664 |
tmp_z0 = z0_segment[:, k] |
| 1665 |
if j == k: |
| 1666 |
Itmp += Ij[:, k] * (tmp_z0 / out_z0) |
| 1667 |
else: |
| 1668 |
Itmp -= Ij[:, k] * (tmp_z0 / in_z0) |
| 1669 |
|
| 1670 |
Is[:, i + j] = Itmp |
| 1671 |
|
| 1672 |
i += cnx_len |
| 1673 |
|
| 1674 |
return Is |
| 1675 |
|
| 1676 |
|
| 1677 |
def voltages(self, power: NumberLike, phase: NumberLike) -> np.ndarray: |
| 1678 |
""" |
| 1679 |
Voltages at internal ports. |
| 1680 |
|
| 1681 |
Parameters |
| 1682 |
---------- |
| 1683 |
power : list or array |
| 1684 |
Input power at external ports in Watts [W] |
| 1685 |
phase : list or array |
| 1686 |
Input phase at external ports in radian [rad] |
| 1687 |
|
| 1688 |
Returns |
| 1689 |
------- |
| 1690 |
V : complex array of shape (nfreqs, nports) |
| 1691 |
Voltages in Volt [V] (peak) at internal ports. |
| 1692 |
|
| 1693 |
""" |
| 1694 |
a = self._a(self._a_external(power, phase)) |
| 1695 |
b = self._b(a) |
| 1696 |
z0s = self.z0 |
| 1697 |
i, Vs = 0, np.zeros_like(z0s) |
| 1698 |
|
| 1699 |
for cnx in self.connections: |
| 1700 |
cnx_len = len(cnx) |
| 1701 |
z0_segment = z0s[:, i : i + cnx_len] |
| 1702 |
tot_shunt_z0 = (1 / z0_segment).sum(axis=1) |
| 1703 |
Vk = np.zeros(shape=z0s.shape[0], dtype="complex128") |
| 1704 |
|
| 1705 |
|
| 1706 |
|
| 1707 |
for j in range(cnx_len): |
| 1708 |
in_z0 = z0_segment[:, j] |
| 1709 |
out_z0 = 1 / (tot_shunt_z0 - 1 / in_z0) |
| 1710 |
tau = (2 * out_z0) / (out_z0 + in_z0) |
| 1711 |
Vk += (b[:, i + j] * np.sqrt(in_z0)) * tau |
| 1712 |
|
| 1713 |
Vs[:, i : i + cnx_len] = Vk[:, None] |
| 1714 |
i += cnx_len |
| 1715 |
|
| 1716 |
return Vs |
| 1717 |
|
| 1718 |
def currents_external(self, power: NumberLike, phase: NumberLike) -> np.ndarray: |
| 1719 |
""" |
| 1720 |
Currents at external ports. |
| 1721 |
|
| 1722 |
NB: current direction is defined positive when "entering" into port. |
| 1723 |
|
| 1724 |
Parameters |
| 1725 |
---------- |
| 1726 |
power : list or array |
| 1727 |
Input power at external ports in Watts [W] |
| 1728 |
phase : list or array |
| 1729 |
Input phase at external ports in radian [rad] |
| 1730 |
|
| 1731 |
Returns |
| 1732 |
------- |
| 1733 |
I : complex array of shape (nfreqs, nports) |
| 1734 |
Currents in Amperes [A] (peak) at external ports. |
| 1735 |
|
| 1736 |
""" |
| 1737 |
a = self._a(self._a_external(power, phase)) |
| 1738 |
b = self._b(a) |
| 1739 |
z0s = self.z0 |
| 1740 |
Is = [] |
| 1741 |
for port_idx in self.port_indexes: |
| 1742 |
Is.append((a[port_idx] - b[:,port_idx])/np.sqrt(z0s[:,port_idx])) |
| 1743 |
return np.array(Is).T |
| 1744 |
|
| 1745 |
def voltages_external(self, power: NumberLike, phase: NumberLike) -> np.ndarray: |
| 1746 |
""" |
| 1747 |
Voltages at external ports |
| 1748 |
|
| 1749 |
Parameters |
| 1750 |
---------- |
| 1751 |
power : list or array |
| 1752 |
Input power at external ports in Watts [W] |
| 1753 |
phase : list or array |
| 1754 |
Input phase at external ports in radian [rad] |
| 1755 |
|
| 1756 |
Returns |
| 1757 |
------- |
| 1758 |
V : complex array of shape (nfreqs, nports) |
| 1759 |
Voltages in Volt [V] (peak) at ports |
| 1760 |
|
| 1761 |
""" |
| 1762 |
a = self._a(self._a_external(power, phase)) |
| 1763 |
b = self._b(a) |
| 1764 |
z0s = self.z0 |
| 1765 |
Vs = [] |
| 1766 |
for port_idx in self.port_indexes: |
| 1767 |
Vs.append((a[port_idx] + b[:,port_idx])*np.sqrt(z0s[:,port_idx])) |
| 1768 |
return np.array(Vs).T |
| 1769 |
|
| 1770 |
def plot_graph(self, **kwargs): |
| 1771 |
""" |
| 1772 |
Plot the graph of the circuit using networkx drawing capabilities. |
| 1773 |
|
| 1774 |
Customisation options with default values:: |
| 1775 |
|
| 1776 |
'network_shape': 's' |
| 1777 |
'network_color': 'gray' |
| 1778 |
'network_size', 300 |
| 1779 |
'network_fontsize': 7 |
| 1780 |
'inter_shape': 'o' |
| 1781 |
'inter_color': 'lightblue' |
| 1782 |
'inter_size', 300 |
| 1783 |
'port_shape': '>' |
| 1784 |
'port_color': 'red' |
| 1785 |
'port_size', 300 |
| 1786 |
'port_fontsize': 7 |
| 1787 |
'edges_fontsize': 5 |
| 1788 |
'network_labels': False |
| 1789 |
'edge_labels': False |
| 1790 |
'inter_labels': False |
| 1791 |
'port_labels': False |
| 1792 |
'label_shift_x': 0 |
| 1793 |
'label_shift_y': 0 |
| 1794 |
|
| 1795 |
""" |
| 1796 |
|
| 1797 |
nx = self._get_nx() |
| 1798 |
G = self.G |
| 1799 |
|
| 1800 |
|
| 1801 |
network_labels = kwargs.pop('network_labels', False) |
| 1802 |
network_shape = kwargs.pop('network_shape', 's') |
| 1803 |
network_color = kwargs.pop('network_color', 'gray') |
| 1804 |
network_fontsize = kwargs.pop('network_fontsize', 7) |
| 1805 |
network_size = kwargs.pop('network_size', 300) |
| 1806 |
inter_labels = kwargs.pop('inter_labels', False) |
| 1807 |
inter_shape = kwargs.pop('inter_shape', 'o') |
| 1808 |
inter_color = kwargs.pop('inter_color', 'lightblue') |
| 1809 |
inter_size = kwargs.pop('inter_size', 300) |
| 1810 |
port_labels = kwargs.pop('port_labels', False) |
| 1811 |
port_shape = kwargs.pop('port_shape', '>') |
| 1812 |
port_color = kwargs.pop('port_color', 'red') |
| 1813 |
port_size = kwargs.pop('port_size', 300) |
| 1814 |
port_fontsize = kwargs.pop('port_fontsize', 7) |
| 1815 |
edge_labels = kwargs.pop('edge_labels', False) |
| 1816 |
edge_fontsize = kwargs.pop('edge_fontsize', 5) |
| 1817 |
label_shift_x = kwargs.pop('label_shift_x', 0) |
| 1818 |
label_shift_y = kwargs.pop('label_shift_y', 0) |
| 1819 |
|
| 1820 |
|
| 1821 |
|
| 1822 |
all_ntw_names = [ntw.name for ntw in self.networks_list()] |
| 1823 |
port_names = [ntw_name for ntw_name in all_ntw_names if 'port' in ntw_name] |
| 1824 |
ntw_names = [ntw_name for ntw_name in all_ntw_names if 'port' not in ntw_name] |
| 1825 |
|
| 1826 |
int_names = ['X'+str(k) for k in range(self.connections_nb)] |
| 1827 |
|
| 1828 |
fig, ax = subplots(figsize=(10,8)) |
| 1829 |
|
| 1830 |
pos = nx.spring_layout(G) |
| 1831 |
|
| 1832 |
|
| 1833 |
nx.draw_networkx_nodes(G, pos, port_names, ax=ax, |
| 1834 |
node_size=port_size, |
| 1835 |
node_color=port_color, node_shape=port_shape) |
| 1836 |
nx.draw_networkx_nodes(G, pos, ntw_names, ax=ax, |
| 1837 |
node_size=network_size, |
| 1838 |
node_color=network_color, node_shape=network_shape) |
| 1839 |
|
| 1840 |
nx.draw_networkx_nodes(G, pos, int_names, ax=ax, |
| 1841 |
node_size=inter_size, |
| 1842 |
node_color=inter_color, node_shape=inter_shape) |
| 1843 |
|
| 1844 |
pos_labels = {} |
| 1845 |
for node, coords in pos.items(): |
| 1846 |
pos_labels[node] = (coords[0] + label_shift_x, |
| 1847 |
coords[1] + label_shift_y) |
| 1848 |
|
| 1849 |
|
| 1850 |
if network_labels: |
| 1851 |
network_labels = {lab:lab for lab in ntw_names} |
| 1852 |
|
| 1853 |
nx.draw_networkx_labels(G, pos_labels, labels=network_labels, |
| 1854 |
font_size=network_fontsize, ax=ax) |
| 1855 |
|
| 1856 |
|
| 1857 |
if inter_labels: |
| 1858 |
inter_labels = {'X'+str(k):'X'+str(k) for k in range(self.connections_nb)} |
| 1859 |
|
| 1860 |
nx.draw_networkx_labels(G, pos_labels, labels=inter_labels, |
| 1861 |
font_size=network_fontsize, ax=ax) |
| 1862 |
|
| 1863 |
|
| 1864 |
if port_labels: |
| 1865 |
port_labels = {lab:lab for lab in port_names} |
| 1866 |
|
| 1867 |
nx.draw_networkx_labels(G, pos_labels, labels=port_labels, |
| 1868 |
font_size=port_fontsize, ax=ax) |
| 1869 |
|
| 1870 |
|
| 1871 |
nx.draw_networkx_edges(G, pos, ax=ax) |
| 1872 |
if edge_labels: |
| 1873 |
edge_labels = self.edge_labels |
| 1874 |
nx.draw_networkx_edge_labels(G, pos, |
| 1875 |
edge_labels=edge_labels, label_pos=0.5, |
| 1876 |
font_size=edge_fontsize, ax=ax) |
| 1877 |
|
| 1878 |
ax.axis('off') |
| 1879 |
fig.tight_layout() |
| 1880 |
|
| 1881 |
|
| 1882 |
def reduce_circuit(connections: list[list[tuple[Network, int]]], |
| 1883 |
check_duplication: bool = True, |
| 1884 |
split_ground: bool = True, |
| 1885 |
split_multi: bool = False, |
| 1886 |
max_nports: int = 20, |
| 1887 |
dynamic_networks: Sequence[Network] = tuple()) -> list[list[tuple[Network, int]]]: |
| 1888 |
""" |
| 1889 |
Return a reduced equivalent circuit connections with fewer components. |
| 1890 |
|
| 1891 |
The reduced equivalent circuit connections allows faster calculation of the circuit network. |
| 1892 |
|
| 1893 |
|
| 1894 |
Parameters |
| 1895 |
---------- |
| 1896 |
connections : list[list[tuple[Network, int]]]. |
| 1897 |
The connection list to reduce. |
| 1898 |
check_duplication : bool, optional. |
| 1899 |
If True, check if the connections have duplicate names. Default is True. |
| 1900 |
split_ground : bool, optional. |
| 1901 |
If True, split the global ground connection to independent ground connections. Default is True. |
| 1902 |
split_multi : bool, optional. |
| 1903 |
If True, use a splitter to handle connections involving more than two components. This approach |
| 1904 |
increases the computational load for individual computations. However, it proves advantageous for |
| 1905 |
batch processing by enabling a more comprehensive reduction of circuits, leading to more efficiency |
| 1906 |
in batch computations. Default is False. |
| 1907 |
max_nports : int, optional. |
| 1908 |
The maximum number of ports of a Network that can be reduced in circuit. If a Network in the |
| 1909 |
circuit has a number of ports (nports), using the Network.connect() method to reduce the circuit's |
| 1910 |
dimensions becomes less efficient compared to directly calculating it with Circuit.s_external. |
| 1911 |
This value depends on the performance of the computer and the scale of the circuit. Default is 20. |
| 1912 |
dynamic_networks : Sequence[Network], optional. |
| 1913 |
A sequence of Networks to ignore in the reduction process. Default is an empty tuple. |
| 1914 |
|
| 1915 |
|
| 1916 |
Returns |
| 1917 |
------- |
| 1918 |
reduced_cnxs : list. |
| 1919 |
The reduced connections. |
| 1920 |
|
| 1921 |
|
| 1922 |
Examples |
| 1923 |
-------- |
| 1924 |
>>> import skrf as rf |
| 1925 |
>>> import numpy as np |
| 1926 |
>>> circuit = rf.Circuit(connections) |
| 1927 |
>>> reduced_cnxs = rf.reduce_circuit(connections) |
| 1928 |
>>> reduced_circuit = rf.Circuit(reduced_cnxs) |
| 1929 |
>>> ntwkA = circuit.network |
| 1930 |
>>> ntwkB = reduced_circuit.network |
| 1931 |
>>> np.allclose(ntwkA.s, ntwkB.s) |
| 1932 |
True |
| 1933 |
""" |
| 1934 |
|
| 1935 |
ignore_ntwk_names: set[str] = set(ntw.name for ntw in dynamic_networks) |
| 1936 |
|
| 1937 |
def invalide_to_reduce(cnx: list[tuple[Network, int]]) -> bool: |
| 1938 |
return ( |
| 1939 |
any( |
| 1940 |
( |
| 1941 |
Circuit._is_port(ntwk) |
| 1942 |
or ntwk.nports > max_nports |
| 1943 |
or ntwk.name in ignore_ntwk_names |
| 1944 |
) |
| 1945 |
for ntwk, _ in cnx |
| 1946 |
) |
| 1947 |
or len(cnx) != 2 |
| 1948 |
) |
| 1949 |
|
| 1950 |
if split_ground: |
| 1951 |
tmp_cnxs = [] |
| 1952 |
for cnx in connections: |
| 1953 |
ground_ntwk = next((ntwk for ntwk, _ in cnx if Circuit._is_ground(ntwk)), None) |
| 1954 |
|
| 1955 |
|
| 1956 |
if not ground_ntwk or len(cnx) == 2: |
| 1957 |
tmp_cnxs.append(cnx) |
| 1958 |
continue |
| 1959 |
|
| 1960 |
|
| 1961 |
for ntwk, port in cnx: |
| 1962 |
if Circuit._is_ground(ntwk): |
| 1963 |
continue |
| 1964 |
tmp_gnd = Circuit.Ground(frequency=ground_ntwk.frequency, |
| 1965 |
name=f'G_{ntwk.name}_{port}') |
| 1966 |
tmp_gnd.z0 = ground_ntwk.z0 |
| 1967 |
tmp_cnxs.append([(ntwk, port), (tmp_gnd, 0)]) |
| 1968 |
|
| 1969 |
connections = tmp_cnxs |
| 1970 |
|
| 1971 |
if split_multi: |
| 1972 |
tmp_cnxs = [] |
| 1973 |
|
| 1974 |
for cnx in connections: |
| 1975 |
|
| 1976 |
if len(cnx) <= 2: |
| 1977 |
tmp_cnxs.append(cnx) |
| 1978 |
continue |
| 1979 |
|
| 1980 |
|
| 1981 |
_media = media.DefinedGammaZ0(cnx[0][0].frequency) |
| 1982 |
splitter = _media.splitter( |
| 1983 |
name=f"Splt_{'&'.join(ntwk.name for ntwk, _ in cnx)}", |
| 1984 |
nports=len(cnx), |
| 1985 |
z0=np.array([ntwk.z0[:, p] for ntwk, p in cnx]).T |
| 1986 |
) |
| 1987 |
|
| 1988 |
|
| 1989 |
for (idx, (ntwk, port)) in enumerate(cnx): |
| 1990 |
tmp_cnxs.append([(splitter, idx), (ntwk, port)]) |
| 1991 |
|
| 1992 |
connections = tmp_cnxs |
| 1993 |
|
| 1994 |
|
| 1995 |
processed_network_names: set[str] = set() |
| 1996 |
|
| 1997 |
|
| 1998 |
def calculate_ports(cnx: list[tuple[Network, int]]) -> int: |
| 1999 |
if invalide_to_reduce(cnx): |
| 2000 |
return -1 |
| 2001 |
|
| 2002 |
name_list = sorted(ntwk.name for ntwk, _ in cnx) |
| 2003 |
ntwks_str: str = ''.join(name_list) |
| 2004 |
|
| 2005 |
unique_networks = len(set(name_list)) |
| 2006 |
total_ports = sum(ntwk.nports for ntwk, _ in cnx) - 2 |
| 2007 |
|
| 2008 |
|
| 2009 |
ports = total_ports if unique_networks == 2 else total_ports // 2 - 1 |
| 2010 |
|
| 2011 |
|
| 2012 |
|
| 2013 |
|
| 2014 |
if ntwks_str in processed_network_names: |
| 2015 |
ports -= 1 |
| 2016 |
else: |
| 2017 |
processed_network_names.add(ntwks_str) |
| 2018 |
|
| 2019 |
return ports |
| 2020 |
|
| 2021 |
|
| 2022 |
cnx_ports_list = [(idx, calculate_ports(cnx)) for idx, cnx in enumerate(connections)] |
| 2023 |
reorder_indices = [idx for idx, _ in sorted(cnx_ports_list, key=lambda x: x[1])] |
| 2024 |
|
| 2025 |
|
| 2026 |
connections = [connections[i] for i in reorder_indices] |
| 2027 |
|
| 2028 |
|
| 2029 |
if check_duplication: |
| 2030 |
connections_list = [conn for conn in enumerate(chain.from_iterable(connections))] |
| 2031 |
Circuit.check_duplicate_names(connections_list) |
| 2032 |
|
| 2033 |
|
| 2034 |
gen = ( |
| 2035 |
(idx, cnx) |
| 2036 |
for idx, cnx in enumerate(connections) |
| 2037 |
if not invalide_to_reduce(cnx) |
| 2038 |
) |
| 2039 |
|
| 2040 |
|
| 2041 |
skip_idx, cnx_to_reduce = next(gen, (-1, [(Network(), -1)] * 2)) |
| 2042 |
|
| 2043 |
|
| 2044 |
if skip_idx == -1: |
| 2045 |
return connections |
| 2046 |
|
| 2047 |
|
| 2048 |
(ntwkA, k), (ntwkB, l) = cnx_to_reduce |
| 2049 |
ntwks_name = (ntwkA.name, ntwkB.name) |
| 2050 |
|
| 2051 |
|
| 2052 |
name_cnt, name_a, name_b = "", str(ntwkA.name), str(ntwkB.name) |
| 2053 |
|
| 2054 |
|
| 2055 |
if ntwkA.name == ntwkB.name: |
| 2056 |
ntwk_cnt = innerconnect(ntwkA=ntwkA, k=k, l=l) |
| 2057 |
name_cnt = f"<{name_a}>" |
| 2058 |
else: |
| 2059 |
ntwk_cnt = connect(ntwkA=ntwkA, k=k, ntwkB=ntwkB, l=l) |
| 2060 |
name_cnt = f"({name_a}**{name_b})" |
| 2061 |
|
| 2062 |
|
| 2063 |
ntwk_cnt.name = name_cnt |
| 2064 |
|
| 2065 |
|
| 2066 |
|
| 2067 |
port_idx = tuple() |
| 2068 |
if ntwkA.name == ntwkB.name: |
| 2069 |
port_cnt = list(range(ntwk_cnt.nports)) |
| 2070 |
port_cnt.insert(min(k, l), -1) |
| 2071 |
port_cnt.insert(max(k, l), -1) |
| 2072 |
port_idx = (tuple(port_cnt), tuple(port_cnt)) |
| 2073 |
elif ntwkB.nports == 2 and ntwkA.nports > 2: |
| 2074 |
|
| 2075 |
port_idx = ( |
| 2076 |
tuple([(i if i != k else -1) for i in range(ntwkA.nports)]), |
| 2077 |
((-1, k) if l == 0 else (k, -1)), |
| 2078 |
) |
| 2079 |
else: |
| 2080 |
portA = list(range(ntwkA.nports - 1)) |
| 2081 |
portA.insert(k, -1) |
| 2082 |
portB = [i + ntwkA.nports - 1 for i in range(ntwkB.nports - 1)] |
| 2083 |
portB.insert(l, -1) |
| 2084 |
|
| 2085 |
port_idx = (tuple(portA), tuple(portB)) |
| 2086 |
|
| 2087 |
|
| 2088 |
|
| 2089 |
reduced_cnxs = [] |
| 2090 |
for idx, cnx in enumerate(connections): |
| 2091 |
|
| 2092 |
if idx == skip_idx: |
| 2093 |
continue |
| 2094 |
|
| 2095 |
tmp_cnx = [] |
| 2096 |
for ntwk, port in cnx: |
| 2097 |
name = ntwk.name |
| 2098 |
ntwk_changed = name in ntwks_name |
| 2099 |
|
| 2100 |
ntwk_tmp = ntwk |
| 2101 |
port_tmp = port |
| 2102 |
|
| 2103 |
|
| 2104 |
if ntwk_changed: |
| 2105 |
ntwk_tmp = ntwk_cnt |
| 2106 |
port_tmp = port_idx[ntwks_name.index(name)][port] |
| 2107 |
|
| 2108 |
tmp_cnx.append((ntwk_tmp, port_tmp)) |
| 2109 |
|
| 2110 |
reduced_cnxs.append(tmp_cnx) |
| 2111 |
|
| 2112 |
return reduce_circuit( |
| 2113 |
connections=reduced_cnxs, |
| 2114 |
check_duplication=False, |
| 2115 |
split_ground=False, |
| 2116 |
split_multi=False, |
| 2117 |
max_nports=max_nports, |
| 2118 |
dynamic_networks=dynamic_networks, |
| 2119 |
) |