Skip to content

transmission_line ¤

Passive, causal RLC transmission-line factories from sampled RLGC data.

Classes:

Name Description
FosterFit

Positive-real response constant + s*linear + sum(weights*s/(s+poles)).

RLGCTransmissionLine

Reusable fitted line; call with a length in metres to create a Circuit.

Functions:

Name Description
mode_transmission_line

Generate a passive RLC line factory from uniform-mode propagation data.

reduced_rlgc_transmission_line

Create a compact, transient-capable uniform line from RLGC versus Hz.

rlgc_transmission_line

Fit frequency-dependent RLGC per metre and return a line factory.

FosterFit dataclass ¤

FosterFit(
    constant: float,
    linear: float,
    weights: ndarray,
    poles: ndarray,
    normalized_rmse: float,
    maximum_relative_error: float,
)

Positive-real response constant + s*linear + sum(weights*s/(s+poles)).

poles are positive rates in rad/s, not signed Laplace poles. The actual branch poles are -poles. Coefficients are per metre for a line fit.

Methods:

Name Description
evaluate

Evaluate the fitted impedance or admittance per metre, in Hz.

evaluate ¤

evaluate(frequencies: ArrayLike) -> ndarray

Evaluate the fitted impedance or admittance per metre, in Hz.

Source code in circulax/components/transmission_line.py
def evaluate(self, frequencies: ArrayLike) -> np.ndarray:
    """Evaluate the fitted impedance or admittance per metre, in Hz."""
    s = 2j * np.pi * np.asarray(frequencies, dtype=float)
    return self.constant + s * self.linear + np.sum(self.weights * s[..., None] / (s[..., None] + self.poles), axis=-1)

RLGCTransmissionLine dataclass ¤

RLGCTransmissionLine(
    series: FosterFit, shunt: FosterFit, frequency_range: tuple[float, float]
)

Reusable fitted line; call with a length in metres to create a Circuit.

Both fits use nonnegative RLC values, ensuring a passive, causal finite ladder. This does not certify that the supplied sampled data is causal, nor that the approximation is accurate outside frequency_range.

Methods:

Name Description
netlist

Build an unterminated symmetric-T ladder from R, L and C primitives.

netlist ¤

netlist(*, length: float, n_sections: int = 1) -> dict

Build an unterminated symmetric-T ladder from R, L and C primitives.

Ports p1 and p2 are single-ended relative to the internal common ground. tap_0 ... tap_{n_sections-1} expose section midpoints for junction loading. No source, termination, optical model or delay is added. Increasing n_sections reduces the spatial discretization error.

Source code in circulax/components/transmission_line.py
def netlist(self, *, length: float, n_sections: int = 1) -> dict:  # noqa: C901, PLR0915 -- local RLC branch builders
    """Build an unterminated symmetric-T ladder from R, L and C primitives.

    Ports ``p1`` and ``p2`` are single-ended relative to the internal common
    ground. ``tap_0`` ... ``tap_{n_sections-1}`` expose section midpoints for
    junction loading. No source, termination, optical model or delay is added.
    Increasing ``n_sections`` reduces the spatial discretization error.
    """
    if not np.isfinite(length) or length <= 0:
        msg = "length must be finite and positive, in metres"
        raise ValueError(msg)
    if isinstance(n_sections, bool) or not isinstance(n_sections, Integral) or n_sections < 1:
        msg = "n_sections must be a positive integer"
        raise ValueError(msg)
    instances = {"GND": {"component": "ground"}}
    connections: dict[str, str] = {}
    ports = {}
    serial = 0

    def put(kind: str, value: float, start: str | None, end: str | None = None) -> tuple[str, str]:
        nonlocal serial
        serial += 1
        name = f"{kind}{serial}"
        instances[name] = {"component": kind, "settings": {kind: float(value)}}
        p1, p2 = f"{name},p1", f"{name},p2"
        if start is not None:
            connections[p1] = start
        if end is not None:
            connections[p2] = end
        return p1, p2

    def series(start: str | None, distance: float) -> str:
        tip = start
        first = None
        if self.series.constant > 0:
            first, tip = put("R", self.series.constant * distance, tip)
        if self.series.linear > 0:
            begin, tip = put("L", self.series.linear * distance, tip)
            first = first or begin
        for w, p in zip(self.series.weights, self.series.poles, strict=True):
            begin, end = put("R", w * distance, tip)
            put("L", w * distance / p, begin, end)
            first, tip = first or begin, end
        if tip is None:
            msg = "The line must have nonzero series impedance"
            raise ValueError(msg)
        if "p1" not in ports:
            ports["p1"] = first
        return tip

    def shunt(node: str, distance: float) -> None:
        if self.shunt.constant > 0:
            put("R", 1 / (self.shunt.constant * distance), node, "GND,p1")
        if self.shunt.linear > 0:
            put("C", self.shunt.linear * distance, node, "GND,p1")
        for w, p in zip(self.shunt.weights, self.shunt.poles, strict=True):
            _, tip = put("R", 1 / (w * distance), node)
            put("C", w * distance / p, tip, "GND,p1")

    last = None
    d = length / n_sections
    for k in range(n_sections):
        midpoint = series(last, d / 2)
        shunt(midpoint, d)
        ports[f"tap_{k}"] = midpoint
        last = series(midpoint, d / 2)
    ports["p2"] = last
    return {"instances": instances, "connections": connections, "ports": ports}

mode_transmission_line ¤

mode_transmission_line(
    frequencies: ArrayLike,
    *,
    attenuation_db_per_m: ArrayLike | Callable[[ndarray], ArrayLike],
    n_eff: ArrayLike | Callable[[ndarray], ArrayLike],
    impedance: ArrayLike | Callable[[ndarray], ArrayLike],
    n_poles: int = 12,
    poles: ArrayLike | None = None,
    tolerance: float = 0.01
) -> RLGCTransmissionLine

Generate a passive RLC line factory from uniform-mode propagation data.

Each input may be a scalar, a sampled array, or a function of frequency in Hz returning either. attenuation_db_per_m is nonnegative loss in dB/metre. n_eff is the positive real RF phase effective index, not group index. impedance is the modal characteristic impedance in ohms and may be complex/frequency dependent, with positive real part.

Converts gamma = log(10)/20 * attenuation + 1j*2*pi*f*n_eff/c and Z'=gamma*impedance, Y'=gamma/impedance to per-metre RLGC. The generated model and all fit settings follow :func:rlgc_transmission_line. Loss, phase and impedance data must describe a mutually consistent mode; an independent choice of arbitrary curves need not admit this passive, causal Foster realization. Errors exceeding tolerance raise ValueError.

Group velocity is c/(n_eff + f*dn_eff/df). When designing a MZM, compare the RF phase index of the loaded electrode at each modulation frequency with the optical group index: the walk-off phase is 2*pi*f*L*(n_rf(f) - n_g_opt)/c. Avoid adding a junction R/C twice if it is already included in mode data. No additional loads are included by this factory.

Source code in circulax/components/transmission_line.py
def mode_transmission_line(
    frequencies: ArrayLike,
    *,
    attenuation_db_per_m: ArrayLike | Callable[[np.ndarray], ArrayLike],
    n_eff: ArrayLike | Callable[[np.ndarray], ArrayLike],
    impedance: ArrayLike | Callable[[np.ndarray], ArrayLike],
    n_poles: int = 12,
    poles: ArrayLike | None = None,
    tolerance: float = 0.01,
) -> RLGCTransmissionLine:
    """Generate a passive RLC line factory from uniform-mode propagation data.

    Each input may be a scalar, a sampled array, or a function of frequency
    in Hz returning either. ``attenuation_db_per_m`` is nonnegative loss in
    dB/metre. ``n_eff`` is the positive real RF *phase* effective index, not
    group index. ``impedance`` is the modal characteristic impedance in ohms
    and may be complex/frequency dependent, with positive real part.

    Converts ``gamma = log(10)/20 * attenuation + 1j*2*pi*f*n_eff/c`` and
    ``Z'=gamma*impedance``, ``Y'=gamma/impedance`` to per-metre RLGC. The
    generated model and all fit settings follow :func:`rlgc_transmission_line`.
    Loss, phase and impedance data must describe a mutually consistent mode;
    an independent choice of arbitrary curves need not admit this passive,
    causal Foster realization. Errors exceeding ``tolerance`` raise ValueError.

    Group velocity is ``c/(n_eff + f*dn_eff/df)``. When designing a MZM,
    compare the RF *phase* index of the *loaded* electrode at each modulation
    frequency with the optical group index: the walk-off phase is
    ``2*pi*f*L*(n_rf(f) - n_g_opt)/c``.
    Avoid adding a junction R/C twice if it is already included in mode data.
    No additional loads are included by this factory.
    """
    f = np.asarray(frequencies)
    if np.iscomplexobj(f) or f.ndim != 1 or len(f) < 2:
        msg = "frequencies must be a real 1-D array with at least two samples"
        raise ValueError(msg)
    f = f.astype(float)
    if not np.all(np.isfinite(f)) or f[0] < 0 or np.any(np.diff(f) <= 0):
        msg = "frequencies must be finite, nonnegative and strictly increasing"
        raise ValueError(msg)

    def sample(value: ArrayLike | Callable[[np.ndarray], ArrayLike], label: str, *, complex_ok: bool = False) -> np.ndarray:
        raw = np.asarray(value(f.copy()) if callable(value) else value)
        if raw.shape not in ((), f.shape) or (np.iscomplexobj(raw) and not complex_ok):
            msg = f"{label} must be a scalar or frequency-matched array" + ("" if complex_ok else " of real values")
            raise ValueError(msg)
        array = np.broadcast_to(raw.astype(complex if complex_ok else float), f.shape)
        if not np.all(np.isfinite(array)):
            msg = f"{label} must be finite"
            raise ValueError(msg)
        return array

    attenuation = sample(attenuation_db_per_m, "attenuation_db_per_m")
    index = sample(n_eff, "n_eff")
    z0 = sample(impedance, "impedance", complex_ok=True)
    if np.any(attenuation < 0) or np.any(index <= 0) or np.any(z0.real <= 0):
        msg = "attenuation must be nonnegative; n_eff and the real part of impedance must be positive"
        raise ValueError(msg)
    if f[0] == 0 and abs(z0[0].imag) > 1e-12 * abs(z0[0]):
        msg = "impedance must be real at DC for a real-valued transient model"
        raise ValueError(msg)
    omega = 2 * np.pi * f
    gamma = np.log(10) / 20 * attenuation + 1j * omega * index / 299_792_458.0
    z_per_m, y_per_m = gamma * z0, gamma / z0
    # At DC only Re(Z') and Re(Y') enter; the L/C placeholders do not affect fitting.
    inductance = np.divide(z_per_m.imag, omega, out=np.zeros_like(f), where=omega > 0)
    capacitance = np.divide(y_per_m.imag, omega, out=np.zeros_like(f), where=omega > 0)
    return rlgc_transmission_line(
        f,
        R=z_per_m.real,
        L=inductance,
        G=y_per_m.real,
        C=capacitance,
        n_poles=n_poles,
        poles=poles,
        tolerance=tolerance,
    )

reduced_rlgc_transmission_line ¤

reduced_rlgc_transmission_line(
    frequencies: ArrayLike,
    *,
    R: ArrayLike | Callable[[ndarray], ArrayLike],
    L: ArrayLike | Callable[[ndarray], ArrayLike],
    G: ArrayLike | Callable[[ndarray], ArrayLike],
    C: ArrayLike | Callable[[ndarray], ArrayLike],
    length: float,
    z0: float = 50.0,
    options: ModelFitOptions | None = None
) -> Circuit

Create a compact, transient-capable uniform line from RLGC versus Hz.

Fit the distributed two-port, rather than discretizing it into RLC sections. The default fit enforces sampled passivity; stable proper poles and nonnegative optional port delays make the realization causal. Invalid or insufficiently accurate fits raise instead of returning an unchecked model. Passivity is sampled, not globally certified; input causality is not certified.

Ports p1 and p2 are single-ended to ground. There are no internal taps: use :func:rlgc_transmission_line when distributed loading is needed. Fitting depends on length; refit for a different length. Use circulax.fitting.fit_rlgc to inspect, evaluate or save the coefficients. For electrically long lines, :func:characteristic_rlgc_transmission_line removes the propagation delay exactly and needs far fewer poles.

Source code in circulax/components/transmission_line.py
def reduced_rlgc_transmission_line(
    frequencies: ArrayLike,
    *,
    R: ArrayLike | Callable[[np.ndarray], ArrayLike],
    L: ArrayLike | Callable[[np.ndarray], ArrayLike],
    G: ArrayLike | Callable[[np.ndarray], ArrayLike],
    C: ArrayLike | Callable[[np.ndarray], ArrayLike],
    length: float,
    z0: float = 50.0,
    options: ModelFitOptions | None = None,
) -> Circuit:
    """Create a compact, transient-capable uniform line from RLGC versus Hz.

    Fit the distributed two-port, rather than discretizing it into RLC sections.
    The default fit enforces sampled passivity; stable proper poles and
    nonnegative optional port delays make the realization causal. Invalid or
    insufficiently accurate fits raise instead of returning an unchecked model.
    Passivity is sampled, not globally certified; input causality is not certified.

    Ports ``p1`` and ``p2`` are single-ended to ground. There are no internal
    taps: use :func:`rlgc_transmission_line` when distributed loading is needed.
    Fitting depends on length; refit for a different length. Use
    ``circulax.fitting.fit_rlgc`` to inspect, evaluate or save the coefficients.
    For electrically long lines, :func:`characteristic_rlgc_transmission_line`
    removes the propagation delay exactly and needs far fewer poles.
    """
    from circulax.fitting import circuit_from_coefficients, fit_rlgc

    fitted = fit_rlgc(frequencies, R=R, L=L, G=G, C=C, length=length, z0=z0, options=options)
    return circuit_from_coefficients(fitted, name="ReducedTransmissionLine")

rlgc_transmission_line ¤

rlgc_transmission_line(
    frequencies: ArrayLike,
    *,
    R: ArrayLike,
    L: ArrayLike,
    G: ArrayLike,
    C: ArrayLike,
    n_poles: int = 12,
    poles: ArrayLike | None = None,
    tolerance: float = 0.01
) -> RLGCTransmissionLine

Fit frequency-dependent RLGC per metre and return a line factory.

frequencies must be increasing, nonnegative Hz with a positive maximum. R, L, G, C are real nonnegative scalars or arrays on that grid, in ohm/m, H/m, S/m and F/m. The series impedance R+sL and shunt admittance G+sC are fitted independently; constant characteristic impedance is not assumed. Skin-effect responses can be approximated over a finite band, but not every passive response belongs to this branch family.

poles optionally supplies positive branch rates in rad/s. Otherwise n_poles logarithmically spaced rates are chosen. tolerance is the maximum weighted relative RMS fitting error for each response. The relative weighting has a floor of 1% of the maximum response magnitude. Excess error raises ValueError rather than returning a poor fit silently. Inspect series and shunt for coefficients and errors. Spatial discretization is separate: verify convergence as n_sections increases.

Example::

line = rlgc_transmission_line(f, R=r, L=l, G=g, C=c)
section = line(length=200e-6, n_sections=2)
# Use section as models_map["line"] in a parent circuit.

Fitting runs once in NumPy/SciPy. Generated Circulax component values are ordinary real RLC parameters; no S-to-state-space conversion is used.

Source code in circulax/components/transmission_line.py
def rlgc_transmission_line(
    frequencies: ArrayLike,
    *,
    R: ArrayLike,
    L: ArrayLike,
    G: ArrayLike,
    C: ArrayLike,
    n_poles: int = 12,
    poles: ArrayLike | None = None,
    tolerance: float = 0.01,
) -> RLGCTransmissionLine:
    """Fit frequency-dependent RLGC per metre and return a line factory.

    ``frequencies`` must be increasing, nonnegative Hz with a positive maximum.
    ``R``, ``L``, ``G``, ``C`` are real nonnegative scalars or arrays on that grid,
    in ohm/m, H/m, S/m and F/m. The series impedance ``R+sL`` and shunt
    admittance ``G+sC`` are fitted independently; constant characteristic
    impedance is not assumed. Skin-effect responses can be approximated over
    a finite band, but not every passive response belongs to this branch family.

    ``poles`` optionally supplies positive branch rates in rad/s. Otherwise
    ``n_poles`` logarithmically spaced rates are chosen. ``tolerance`` is the
    maximum weighted relative RMS fitting error for *each* response. The
    relative weighting has a floor of 1% of the maximum response magnitude.
    Excess error raises ValueError rather than returning a poor fit silently.
    Inspect ``series`` and ``shunt`` for coefficients and errors. Spatial
    discretization is separate: verify convergence as ``n_sections`` increases.

    Example::

        line = rlgc_transmission_line(f, R=r, L=l, G=g, C=c)
        section = line(length=200e-6, n_sections=2)
        # Use section as models_map["line"] in a parent circuit.

    Fitting runs once in NumPy/SciPy. Generated Circulax component values are
    ordinary real RLC parameters; no S-to-state-space conversion is used.
    """
    f, r, l, g, cap = _sample_rlgc(frequencies, R, L, G, C)
    if not np.isfinite(tolerance) or tolerance <= 0:
        msg = "tolerance must be finite and positive"
        raise ValueError(msg)
    if not np.any(r) and not np.any(l):
        msg = "The line must have nonzero series impedance"
        raise ValueError(msg)
    if poles is None:
        if isinstance(n_poles, bool) or not isinstance(n_poles, Integral) or n_poles < 1:
            msg = "n_poles must be a positive integer"
            raise ValueError(msg)
        f_min = max(f[f > 0][0] / 10, f[-1] / 1e6)
        rates = 2 * np.pi * np.geomspace(f_min, 10 * f[-1], n_poles)
    else:
        rates = np.asarray(poles)
        if np.iscomplexobj(rates) or rates.ndim != 1 or not len(rates):
            msg = "poles must be a nonempty real 1-D array of positive rates"
            raise ValueError(msg)
        rates = rates.astype(float)
        if not np.all(np.isfinite(rates)) or np.any(rates <= 0) or np.any(np.diff(rates) <= 0):
            msg = "poles must be finite, positive and strictly increasing"
            raise ValueError(msg)
    s = 2j * np.pi * f
    return RLGCTransmissionLine(
        series=_fit_response(r + s * l, f, rates, tolerance, "Series impedance"),
        shunt=_fit_response(g + s * cap, f, rates, tolerance, "Shunt admittance"),
        frequency_range=(float(f[0]), float(f[-1])),
    )