---
title: "Network toolkit lab: conversions, cascades and matching"
heading: Converting between S and ABCD parameters, building and cascading networks, and designing single-stub matches in Python
eyebrow: S6 · Lesson 48 · Network toolkit lab
xp: 60
---

::: hook
Every calculation in this course's first half reduces to a few operations: convert a two-port between representations, multiply chains of ABCD matrices, and solve for the lines and stubs that make a load look like 50 Ω. Circuit simulators do these things internally. In this lab you'll write them yourself, in about forty lines of NumPy, and the tests will hold your code to the lessons' own results: the attenuator from lesson 1, the Butterworth filter from lesson 21, the Kuroda filter from lesson 22 and Pozar's single-stub example from lesson 9.
:::

::: predict
## A filter built from stubs and unit elements by Kuroda's identities is compared with its Richards prototype, at many frequencies. How closely should their |S₂₁| agree?

- [ ] Within about 0.5 dB, since the identities are approximations
- [ ] Only near the cutoff frequency
- [x] Exactly, to rounding error, at every frequency
- [ ] Only below half the cutoff

::: reveal
Exactly. Kuroda's identities are matrix identities between two-ports that share the same Richards variable, so they hold at every frequency, not just near the design point. Your cascade function will show the two networks agreeing to about 10⁻¹² dB, a good test that each building block is right.
:::
:::

::: nameit
## Converting between S and ABCD

In a $Z_0$ system, with $\Delta = A + B/Z_0 + CZ_0 + D$:

$$S_{11} = \frac{A + B/Z_0 - CZ_0 - D}{\Delta}, \quad S_{12} = \frac{2(AD - BC)}{\Delta}, \quad S_{21} = \frac{2}{\Delta}, \quad S_{22} = \frac{-A + B/Z_0 - CZ_0 + D}{\Delta}$$

and in the other direction

$$A = \frac{(1 + S_{11})(1 - S_{22}) + S_{12}S_{21}}{2S_{21}}, \quad B = Z_0\frac{(1 + S_{11})(1 + S_{22}) - S_{12}S_{21}}{2S_{21}}$$

$$C = \frac{(1 - S_{11})(1 - S_{22}) - S_{12}S_{21}}{2S_{21}Z_0}, \quad D = \frac{(1 - S_{11})(1 + S_{22}) + S_{12}S_{21}}{2S_{21}}$$

## Building blocks

Series impedance [[1, z], [0, 1]], shunt admittance [[1, 0], [y, 1]], and a lossless line [[cos θ, jz sin θ], [j sin θ/z, cos θ]]. In NumPy, `A @ B` multiplies matrices and `dtype=complex` keeps them complex.

## Single-stub tuning

Lesson 9's closed form: $t = \tan\beta d = \frac{X_L \pm \sqrt{R_L[(Z_0 - R_L)^2 + X_L^2]/Z_0}}{R_L - Z_0}$, the susceptance B there, and a short stub of $\frac{1}{2\pi}\arctan\frac{Y_0}{B}$, with λ/2 added to any negative length or distance.
:::

::: example
## Check the first step by hand: what S-parameters does a series 25 Ω resistor have in 50 Ω, and in 75 Ω?

::: solution
1. **ABCD matrix.**
   $$\begin{bmatrix}1 & 25\\0 & 1\end{bmatrix}$$
2. **In 50 Ω.**
   $$\begin{aligned} \Delta &= 1 + 0.5 + 0 + 1 \\ &= 2.5 \\ S_{11} &= 0.5/2.5 \\ &= 0.2 \\ S_{21} &= 2/2.5 \\ &= 0.8 \end{aligned}$$
   as $R/(R + 2Z_0)$ and $2Z_0/(R + 2Z_0)$ say.
3. **In 75 Ω.**
   $$\begin{aligned} \Delta &= 2.333 \\ S_{11} &= 25/175 \\ &= 0.143 \\ S_{21} &= 0.857 \end{aligned}$$

**Answer:** in 50 Ω, $S_{11}$ = 0.2 and $S_{21}$ = 0.8; in 75 Ω, $S_{11}$ = 0.143 and $S_{21}$ = 0.857.
:::
:::

::: example
## Why does the second step's test of the Kuroda filter also check `tline`?

::: solution
1. **What differs between the two.** The distributed filter contains two 217.4 Ω unit elements, and the prototype contains none.
2. **What a bug would do.** If `tline` had a wrong sign or a misplaced z, the two responses would differ.
3. **What agreement proves.** They agree only if the line's matrix is exactly [[cos θ, jz sin θ], [j sin θ/z, cos θ]] and the stubs' susceptances use the same tan θ.

**Answer:** the distributed filter's two unit elements go through `tline` and the prototype has none, so the two responses agree only if `tline` is exactly right.
:::
:::

::: check
kind: python

## Step 1. Write `abcd_to_s(M, z0)` and `s_to_abcd(S, z0)`: conversions between ABCD and S-parameters for any two-port.

```python starter
import numpy as np

def abcd_to_s(M, z0=50.0):
    # M: 2x2 complex ABCD matrix. Return the 2x2 S-matrix in a z0 system.
    return np.zeros((2, 2), dtype=complex)

def s_to_abcd(S, z0=50.0):
    # S: 2x2 complex S-matrix. Return the 2x2 ABCD matrix.
    return np.eye(2, dtype=complex)

print(abcd_to_s(np.array([[1, 25], [0, 1]], dtype=complex)))
```

```python solution
import numpy as np

def abcd_to_s(M, z0=50.0):
    A, B, C, D = M[0, 0], M[0, 1], M[1, 0], M[1, 1]
    den = A + B/z0 + C*z0 + D
    return np.array([[(A + B/z0 - C*z0 - D)/den, 2*(A*D - B*C)/den],
                     [2/den, (-A + B/z0 - C*z0 + D)/den]], dtype=complex)

def s_to_abcd(S, z0=50.0):
    S11, S12, S21, S22 = S[0, 0], S[0, 1], S[1, 0], S[1, 1]
    A = ((1 + S11)*(1 - S22) + S12*S21)/(2*S21)
    B = z0*((1 + S11)*(1 + S22) - S12*S21)/(2*S21)
    C = ((1 - S11)*(1 - S22) - S12*S21)/(2*S21*z0)
    D = ((1 - S11)*(1 + S22) + S12*S21)/(2*S21)
    return np.array([[A, B], [C, D]], dtype=complex)

print(abcd_to_s(np.array([[1, 25], [0, 1]], dtype=complex)))
```

```python tests
import numpy as np
S = abcd_to_s(np.array([[1, 25], [0, 1]], dtype=complex))
assert np.shape(S) == (2, 2), "Return a 2x2 matrix."
assert abs(S[0, 0] - 0.2) < 1e-12 and abs(S[1, 0] - 0.8) < 1e-12, f"A series 25 Ω resistor has S11 = 0.2 and S21 = 0.8 in 50 Ω; got {S[0, 0]:.4f} and {S[1, 0]:.4f}."
ser = lambda z: np.array([[1, z], [0, 1]], dtype=complex)
sh = lambda y: np.array([[1, 0], [y, 1]], dtype=complex)
T = ser(8.6) @ sh(1/141.8) @ ser(8.6)
s21 = abs(abcd_to_s(T)[1, 0])
assert abs(s21 - 0.70713) < 2e-5, f"The 8.6/141.8/8.6 Ω attenuator has |S21| = 0.70713 (3.01 dB); got {s21:.5f}."
S75 = abcd_to_s(ser(25), 75.0)
assert abs(S75[0, 0] - 25/175) < 1e-12, f"In a 75 Ω system the series 25 Ω resistor has S11 = 25/175; got {S75[0, 0]:.4f}. Use z0."
rng = np.random.default_rng(7)
for k in range(20):
    Sr = (rng.normal(size=(2, 2)) + 1j*rng.normal(size=(2, 2)))*0.4
    back = abcd_to_s(s_to_abcd(Sr, 50.0), 50.0)
    assert np.max(np.abs(back - Sr)) < 1e-10, f"Converting S to ABCD and back should return the same S (including non-reciprocal ones); the error was {np.max(np.abs(back - Sr)):.2e}."
M = s_to_abcd(abcd_to_s(T))
assert np.max(np.abs(M - T)) < 1e-10, "s_to_abcd should recover the attenuator's ABCD matrix."
```

::: right
Right. Both directions work for any two-port, reciprocal or not, and they reproduce lesson 2's series resistor and lesson 1's attenuator.
:::
:::

::: check
kind: python

## Step 2. Write the building blocks `series`, `shunt` and `tline`, and `cascade`, which multiplies ABCD matrices in order.

```python starter
import numpy as np

def series(z):
    # ABCD matrix of a series impedance z.
    return np.eye(2, dtype=complex)

def shunt(y):
    # ABCD matrix of a shunt admittance y.
    return np.eye(2, dtype=complex)

def tline(z, theta):
    # ABCD matrix of a lossless line of impedance z and electrical length theta (radians).
    return np.eye(2, dtype=complex)

def cascade(*mats):
    # Product of the ABCD matrices, input to output.
    return np.eye(2, dtype=complex)

def s21_db(M, z0=50.0):
    A, B, C, D = M[0, 0], M[0, 1], M[1, 0], M[1, 1]
    return 20*np.log10(abs(2/(A + B/z0 + C*z0 + D)))

def zin(M, zl):
    A, B, C, D = M[0, 0], M[0, 1], M[1, 0], M[1, 1]
    return (A*zl + B)/(C*zl + D)

print(zin(tline(70.71, np.pi/2), 100.0))
```

```python solution
import numpy as np

def series(z):
    return np.array([[1, z], [0, 1]], dtype=complex)

def shunt(y):
    return np.array([[1, 0], [y, 1]], dtype=complex)

def tline(z, theta):
    c, s = np.cos(theta), np.sin(theta)
    return np.array([[c, 1j*z*s], [1j*s/z, c]], dtype=complex)

def cascade(*mats):
    M = np.eye(2, dtype=complex)
    for m in mats:
        M = M @ m
    return M

def s21_db(M, z0=50.0):
    A, B, C, D = M[0, 0], M[0, 1], M[1, 0], M[1, 1]
    return 20*np.log10(abs(2/(A + B/z0 + C*z0 + D)))

def zin(M, zl):
    A, B, C, D = M[0, 0], M[0, 1], M[1, 0], M[1, 1]
    return (A*zl + B)/(C*zl + D)

print(zin(tline(70.71, np.pi/2), 100.0))
```

```python tests
import numpy as np
z = zin(tline(50*np.sqrt(2), np.pi/2), 100.0)
assert abs(z - 50) < 1e-9, f"A quarter-wave 70.7 Ω line turns 100 Ω into 50 Ω; got {z:.4f}."
z = zin(tline(50.0, np.pi), 30 + 20j)
assert abs(z - (30 + 20j)) < 1e-9, f"A half-wave line repeats its load; got {z:.4f}."
w = 2*np.pi*1e9
L = 50/w; C = 2/(50*w)
T = cascade(series(1j*w*L), shunt(1j*w*C), series(1j*w*L))
assert abs(s21_db(T) + 10*np.log10(2)) < 1e-9, f"The N = 3 Butterworth T (7.96 nH, 6.37 pF, 7.96 nH) is 3.0103 dB down at its 1 GHz cutoff; got {s21_db(T):.4f}."
w2 = 2*w
T2 = cascade(series(1j*w2*L), shunt(1j*w2*C), series(1j*w2*L))
assert abs(s21_db(T2) + 10*np.log10(65)) < 1e-9, f"At 2 GHz it's 10 log(1 + 2^6) = 18.13 dB down; got {s21_db(T2):.4f}."
assert np.max(np.abs(cascade(series(10), shunt(0.01)) - np.array([[1.1, 10], [0.01, 1]]))) < 1e-12, "cascade must multiply in order, input to output: series 10 Ω then shunt 0.01 S has A = 1.1."
g1, g2 = 3.3487, 0.7117
n2 = 1 + g1
for r in (0.3, 0.8, 1.0, 1.4, 2.7):
    th = np.pi/4*r; W = np.tan(th)
    proto = cascade(series(1j*W*g1*50), shunt(1j*W*g2/50), series(1j*W*g1*50))
    dist = cascade(shunt(1j*W/(n2/g1*50)), tline(n2*50, th), shunt(1j*W*g2/50), tline(n2*50, th), shunt(1j*W/(n2/g1*50)))
    assert abs(s21_db(proto) - s21_db(dist)) < 1e-9, f"Lesson 22's Kuroda-transformed filter must match its Richards prototype exactly; at {r} f_c they differ by {abs(s21_db(proto) - s21_db(dist)):.2e} dB."
```

::: right
Right. Four small functions reproduce the quarter-wave inverter, the Butterworth T's −3.01 dB at cutoff and lesson 22's Kuroda filter to every digit.
:::
:::

::: check
kind: python

## Step 3. Write `single_stub(zl, z0)`: both shunt short-stub solutions for any load, as (d, ℓ) pairs in wavelengths.

```python starter
import numpy as np

def single_stub(zl, z0=50.0):
    # Shunt short-circuited single-stub match for the load zl (complex, real part not equal to z0).
    # Return a list of (d, ell) pairs in wavelengths, both in [0, 0.5), sorted by d:
    # d = distance from the load to the stub, ell = stub length.
    return []

print(single_stub(60 - 80j))
```

```python solution
import numpy as np

def single_stub(zl, z0=50.0):
    RL, XL = zl.real, zl.imag
    root = np.sqrt(RL*((z0 - RL)**2 + XL**2)/z0)
    out = []
    for t in ((XL + root)/(RL - z0), (XL - root)/(RL - z0)):
        d = np.arctan(t)/(2*np.pi)
        if d < 0:
            d += 0.5
        B = (RL**2*t - (z0 - XL*t)*(XL + z0*t))/(z0*(RL**2 + (XL + z0*t)**2))
        ell = np.arctan(1/(B*z0))/(2*np.pi)
        if ell < 0:
            ell += 0.5
        out.append((d, ell))
    return sorted(out)

print(single_stub(60 - 80j))
```

```python tests
import numpy as np
sols = single_stub(60 - 80j)
assert len(sols) == 2, f"Return both solutions; got {len(sols)}."
(d1, l1), (d2, l2) = sols
assert abs(d1 - 0.1104) < 5e-4 and abs(l1 - 0.0950) < 5e-4, f"Pozar's first solution for 60 − j80 Ω is d = 0.110λ, ℓ = 0.095λ; got d = {d1:.4f}, ℓ = {l1:.4f}."
assert abs(d2 - 0.2594) < 5e-4 and abs(l2 - 0.4050) < 5e-4, f"The second is d = 0.259λ, ℓ = 0.405λ; got d = {d2:.4f}, ℓ = {l2:.4f}."
def check(zl, z0):
    s = single_stub(zl, z0)
    assert len(s) == 2, f"Two solutions expected for {zl}."
    assert s == sorted(s), "Sort the solutions by d."
    for d, ell in s:
        assert 0 <= d < 0.5 and 0 <= ell < 0.5, f"Keep d and ℓ in [0, 0.5); got {d:.4f}, {ell:.4f} for {zl}."
        t = np.tan(2*np.pi*d)
        zd = z0*(zl + 1j*z0*t)/(z0 + 1j*zl*t)
        y = 1/zd - 1j/(z0*np.tan(2*np.pi*ell))
        assert abs(y - 1/z0) < 1e-9, f"With d = {d:.4f}λ and a short stub of {ell:.4f}λ, the load {zl} Ω should be matched to {z0} Ω; the admittance is off by {abs(y - 1/z0):.2e} S."
for zl, z0 in ((60 - 80j, 50.0), (25 + 30j, 50.0), (150 + 0j, 50.0), (20 - 10j, 75.0), (300 + 200j, 75.0)):
    check(zl, z0)
```

::: right
Right. Your tuner finds Pozar's two solutions and matches every test load exactly, checked by an independent line calculation.
:::
:::

::: explain
## Why are ABCD matrices the right tool for cascading, while S-parameters are the right tool for measuring?

::: model
ABCD matrices relate the voltage and current at one port to those at the other, so connecting networks in a chain just means multiplying their matrices, which is why the toolkit cascades in ABCD form. But voltages and currents can't be measured directly at microwave frequencies, and the open and short circuits that Z and Y parameters need are hard to make and can make active devices oscillate. S-parameters are defined with matched terminations and traveling waves, which is what a network analyzer's couplers measure. So measurements arrive as S-parameters, get converted to ABCD to be combined, and are converted back to S to describe the result.
:::
:::

::: practice

::: check
given: A = 1.1 | 1.4; B = 10 | 35; C = 0.004 | 0.012; Z = 50
answer: 2/(A + B/Z + C*Z + (1 + B*C)/A)
tolerance: 0.5%

## |S₂₁| of a reciprocal two-port with A = {A}, B = {B} Ω, C = {C} S in {Z} Ω?

::: misses
- [any] D from AD − BC = 1, then $2/\Delta$.
:::
:::

::: check
given: Z = 35 | 70.7 | 100; L = 25 | 150
answer: Z^2/L
unit: Ω
tolerance: 0.5%

## Quarter-wave line of {Z} Ω, load {L} Ω: input impedance?

::: misses
- [any] $Z^2/Z_L$.
:::
:::

::: check
given: R = 20 | 60 | 150; X = -40 | 30; Z = 50
answer: (X + sqrt(R*((Z - R)^2 + X^2)/Z))/(R - Z)
tolerance: 0.5%

## Stub position: t = tan βd for {R} + j({X}) Ω on {Z} Ω, + root?

::: misses
- [any] Lesson 9's formula for t.
:::
:::
:::
