Skip to content

components ¤

Reusable electronic, photonic and fitted circuit models.

Modules:

Name Description
base_component

Base class and decorators for defining JAX-compatible circuit components.

characteristic_line

Uniform transmission lines realized by their characteristic admittance and exact delay.

electronic

Electronic components.

filters

Buffered continuous-time voltage filters for driver and behavioral models.

hybrid_laser

Netlist assemblies for reconfigurable gain and passive-feedback laser cavities.

laser_mirrors

Passive single-pole spectral reflection and electrically loaded thermal tuning.

laser_modes

Longitudinal threshold conditions for the native thermally tuned laser.

laser_sections

Composable bidirectional sections for reconfigurable semiconductor laser circuits.

phase_shifter

Electro-optic phase shifters built from designer-supplied physics.

photonic

Photonic components for optical circuit simulation.

rational

Factory functions for creating Circulax components from rational fitting models.

soa

Forward diode coupled to a single-pass, integrated optical gain state.

transmission_line

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

traveling_wave_laser

Electrically pumped, bidirectional delayed-gain laser circuit component.

va_component

Backward-compatibility shim — re-exports va_component from bosdi.circulax.

Classes:

Name Description
HybridSettings

Passive-feedback settings: comb spacings Hz, lengths m, phase rad/K, loss dB.

JunctionModel

Electrical junction model per metre of length, usable on its own.

RLGCTransmissionLine

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

Functions:

Name Description
Bessel3

Unity-DC-gain third-order Bessel low-pass, normalized at -3 dB.

BidirectionalWaveguide

Reflection-free reciprocal propagation with real flight time and loss.

Biquad

Unity-DC-gain second-order low-pass with -3 dB frequency and quality factor.

CoupledInductors

Two magnetically coupled inductors with M = k * sqrt(L1 * L2).

DifferentialAdapter

Lossless bidirectional differential/common to conductor adapter.

IdealTransformer

Ideal transformer with turns ratio n = N1 / N2 (n > 0).

LowPass1

Unity-DC-gain first-order low-pass; f3db is the -3 dB frequency.

MatchedOpticalLoad

Absorb a wave at unit reference impedance; no incident optical field.

MatchedOpticalPulse

Matched coherent pulse source: prescribed incoming wave, absorbs return.

OpticalDelayLine

Waveguide modelled as an explicit time-of-flight delay line (real group delay).

OpticalDirectionalCoupler

Reciprocal unitary four-port coupler, suitable for connecting ring loops.

OpticalInterface

Reciprocal optical interface; r=i*rho, t=sqrt(1-rho²), common excess loss.

SemiconductorOpticalAmplifier

Diode injection, gain depletion/recovery, and carrier-induced phase.

ThermoOpticPhaseShifter

Reciprocal delayed phase section, uniform arrival-time temperature.

TransmissionLine

Matched bidirectional transmission line with exact fixed delay.

TravelingWaveGainCell

One retarded-gain cell; both delayed incident powers share one reservoir.

add_drop_ring

Bidirectional add/drop ring assembled from two couplers and two arms.

characteristic_rlgc_transmission_line

Create a fast uniform line from RLGC versus Hz, with its delay de-embedded.

charge_from_capacitance_table

Integrate a C(V) table, in F/m, into a junction charge function in C/m.

delay_line_fdomain

Frequency-domain delay line for AC and harmonic-balance analysis.

delta_neff_from_vpil

Integrate a small-signal VπL table into delta_neff(v).

depletion_charge

Depletion charge per metre with SPICE forward-bias linearisation.

diode_current

Diode current per metre: Shockley equation plus a dark-current shunt.

hybrid_laser_netlist

Editable cavity netlist and model map, without drives or terminations.

junction_model

Build a junction model from functions of voltage, per metre of length.

mode_transmission_line

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

phase_shifter_factory

Build an electro-optic phase shifter component from functions of voltage.

pn_diode

PN diode per metre: :func:diode_current plus :func:depletion_charge.

reduced_rlgc_transmission_line

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

ring_reflector

Ring drop port followed by a mirror: a replaceable spectral reflector.

rlgc_transmission_line

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

sampled_bragg_grating

Lossless thin-patch sampled-grating approximation with causal gap delays.

tabulated

Return a piecewise-linear function of voltage from a sampled table.

HybridSettings ¤

Bases: NamedTuple

Passive-feedback settings: comb spacings Hz, lengths m, phase rad/K, loss dB.

samples is a physical number of identical thin grating patches. Each grating's length is (samples-1)c/(2n_g*FSR). Loss is per optical interface.

JunctionModel ¤

JunctionModel(
    current_fn: VoltageFunction | None,
    current_params: list[Parameter],
    charge_fn: VoltageFunction | None,
    charge_params: list[Parameter],
)

Electrical junction model per metre of length, usable on its own.

Create one with :func:junction_model or :func:pn_diode. Evaluate it directly with :meth:current, :meth:charge and :meth:capacitance (arrays and parameter overrides are accepted), build a two-terminal circuit component with :meth:component, or pass it to :func:phase_shifter_factory as junction.

Methods:

Name Description
capacitance

Small-signal capacitance per metre, d charge / dv, in F/m.

charge

Stored charge per metre in C/m, zero at 0 V for the built-in models.

charge_per_m

Junction charge in C/m for already-resolved parameters (traced use).

component

Return a two-terminal component with ports anode and cathode.

current

DC current per metre, anode to cathode, in A/m.

current_per_m

Junction current in A/m for already-resolved parameters (traced use).

Attributes:

Name Type Description
defaults dict[str, float]

Default value of every runtime parameter.

Source code in circulax/components/phase_shifter.py
def __init__(
    self,
    current_fn: VoltageFunction | None,
    current_params: list[inspect.Parameter],
    charge_fn: VoltageFunction | None,
    charge_params: list[inspect.Parameter],
) -> None:
    """Store the per-metre current and charge functions and their parameters."""
    self._current_fn, self._current_params = current_fn, tuple(current_params)
    self._charge_fn, self._charge_params = charge_fn, tuple(charge_params)
    self.parameters = tuple(_merge(current_params, charge_params).values())

defaults property ¤

defaults: dict[str, float]

Default value of every runtime parameter.

capacitance ¤

capacitance(v: ArrayLike, **overrides: Any) -> Any

Small-signal capacitance per metre, d charge / dv, in F/m.

Source code in circulax/components/phase_shifter.py
def capacitance(self, v: ArrayLike, **overrides: Any) -> Any:
    """Small-signal capacitance per metre, ``d charge / dv``, in F/m."""
    kw = self._resolve(overrides)
    return jnp.vectorize(jax.grad(lambda x: self.charge_per_m(x, kw)))(jnp.asarray(v, dtype=float))

charge ¤

charge(v: ArrayLike, **overrides: Any) -> Any

Stored charge per metre in C/m, zero at 0 V for the built-in models.

Source code in circulax/components/phase_shifter.py
def charge(self, v: ArrayLike, **overrides: Any) -> Any:
    """Stored charge per metre in C/m, zero at 0 V for the built-in models."""
    kw = self._resolve(overrides)
    return jnp.vectorize(lambda x: self.charge_per_m(x, kw))(jnp.asarray(v, dtype=float))

charge_per_m ¤

charge_per_m(v: Any, kw: dict[str, Any]) -> Any

Junction charge in C/m for already-resolved parameters (traced use).

Source code in circulax/components/phase_shifter.py
def charge_per_m(self, v: Any, kw: dict[str, Any]) -> Any:
    """Junction charge in C/m for already-resolved parameters (traced use)."""
    if self._charge_fn is None:
        return jnp.zeros_like(v)
    return self._charge_fn(v, **_keywords(self._charge_params, kw))

component ¤

component(name: str = 'Junction') -> type[CircuitComponent]

Return a two-terminal component with ports anode and cathode.

Its runtime parameters are length_um plus :attr:defaults; the component carries length * current(v) and stores length * charge(v).

Source code in circulax/components/phase_shifter.py
def component(self, name: str = "Junction") -> type[CircuitComponent]:
    """Return a two-terminal component with ports ``anode`` and ``cathode``.

    Its runtime parameters are ``length_um`` plus :attr:`defaults`; the
    component carries ``length * current(v)`` and stores ``length * charge(v)``.
    """
    junction = self

    def physics(signals: Signals, **kw: Any) -> PhysicsReturn:
        v = jnp.real(signals.anode - signals.cathode)
        length_m = kw["length_um"] * 1e-6
        current = length_m * junction.current_per_m(v, kw)
        charge = length_m * junction.charge_per_m(v, kw)
        return {"anode": current, "cathode": -current}, {"anode": charge, "cathode": -charge}

    _set_signature(physics, name, {"length_um": _RUNTIME_DEFAULTS["length_um"]}, self.parameters)
    return component(ports=("anode", "cathode"))(physics)

current ¤

current(v: ArrayLike, **overrides: Any) -> Any

DC current per metre, anode to cathode, in A/m.

Source code in circulax/components/phase_shifter.py
def current(self, v: ArrayLike, **overrides: Any) -> Any:
    """DC current per metre, anode to cathode, in A/m."""
    kw = self._resolve(overrides)
    return jnp.vectorize(lambda x: self.current_per_m(x, kw))(jnp.asarray(v, dtype=float))

current_per_m ¤

current_per_m(v: Any, kw: dict[str, Any]) -> Any

Junction current in A/m for already-resolved parameters (traced use).

Source code in circulax/components/phase_shifter.py
def current_per_m(self, v: Any, kw: dict[str, Any]) -> Any:
    """Junction current in A/m for already-resolved parameters (traced use)."""
    if self._current_fn is None:
        return jnp.zeros_like(v)
    return self._current_fn(v, **_keywords(self._current_params, kw))

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}

Bessel3 ¤

Bessel3(signals: Signals, f3db: float = 35000000000.0) -> PhysicsReturn

Unity-DC-gain third-order Bessel low-pass, normalized at -3 dB.

The delay-normalized prototype is 15/(p**3+6*p**2+15*p+15). Its -3 dB angular frequency is 1.7556723686812106; scaling by it makes f3db the voltage magnitude cutoff. The DC group delay is 1.7556723686812106/(2*pi*f3db). This buffered block includes that filter delay; add physical flight time separately when needed.

Source code in circulax/components/filters.py
@component(ports=("inp", "out"), states=("i_out", "x", "z"), holomorphic=True)
def Bessel3(signals: Signals, f3db: float = 35e9) -> PhysicsReturn:
    """Unity-DC-gain third-order Bessel low-pass, normalized at -3 dB.

    The delay-normalized prototype is ``15/(p**3+6*p**2+15*p+15)``.
    Its -3 dB angular frequency is 1.7556723686812106; scaling by it makes
    ``f3db`` the voltage magnitude cutoff. The DC group delay is
    ``1.7556723686812106/(2*pi*f3db)``. This buffered block includes that
    filter delay; add physical flight time separately when needed.
    """
    r3db = 1.7556723686812106
    w = 2.0 * jnp.pi * f3db / r3db
    return {
        "inp": 0.0 * signals.inp,
        "out": signals.i_out,
        "i_out": w * (15 * signals.out + 15 * signals.x + 6 * signals.z - 15 * signals.inp),
        "x": -w * signals.x,
        "z": -w * signals.z,
    }, {"i_out": signals.z, "x": signals.out, "z": signals.x}

BidirectionalWaveguide ¤

BidirectionalWaveguide(
    signals: Signals,
    length_m: float = 5e-05,
    group_index: float = 4.0,
    loss_m1: float = 0.0,
    phase_rad: float = 0.0,
    frame_offset_rad_s: float = 0.0,
) -> PhysicsReturn

Reflection-free reciprocal propagation with real flight time and loss.

phase_rad is the phase at the fixed optical reference, not a recomputed carrier phase when changing envelope coordinates. loss_m1 is power loss.

Source code in circulax/components/laser_sections.py
@component(ports=("p1", "p2"), states=("a1", "a2"), holomorphic=True)
def BidirectionalWaveguide(
    signals: Signals,
    length_m: float = 50e-6,
    group_index: float = 4.0,
    loss_m1: float = 0.0,
    phase_rad: float = 0.0,
    frame_offset_rad_s: float = 0.0,
) -> PhysicsReturn:
    """Reflection-free reciprocal propagation with real flight time and loss.

    phase_rad is the phase at the fixed optical reference, not a recomputed
    carrier phase when changing envelope coordinates. loss_m1 is power loss.
    """
    tau = length_m * group_index / LIGHT_SPEED
    past = signals.at_delay(tau)
    transmission = jnp.exp(-loss_m1 * length_m / 2 + 1j * (phase_rad - frame_offset_rad_s * tau))
    return _waves(signals, transmission * past.a2, transmission * past.a1), {}

Biquad ¤

Biquad(
    signals: Signals, f3db: float = 10000000000.0, Q: float = 0.5773502692
) -> PhysicsReturn

Unity-DC-gain second-order low-pass with -3 dB frequency and quality factor.

H(s)=w0**2/(s**2+w0*s/Q+w0**2). w0 is computed so the magnitude is 1/sqrt(2) at f3db for every positive Q. For Q>1/sqrt(2), the response has peaking. This is an ideal buffered voltage block.

Source code in circulax/components/filters.py
@component(ports=("inp", "out"), states=("i_out", "x"), holomorphic=True)
def Biquad(signals: Signals, f3db: float = 10e9, Q: float = 0.5773502692) -> PhysicsReturn:
    """Unity-DC-gain second-order low-pass with -3 dB frequency and quality factor.

    ``H(s)=w0**2/(s**2+w0*s/Q+w0**2)``. ``w0`` is computed so the magnitude
    is 1/sqrt(2) at ``f3db`` for every positive Q. For Q>1/sqrt(2), the
    response has peaking. This is an ideal buffered voltage block.
    """
    b = 1.0 / Q**2 - 2.0
    # Positive root of u**2 + b*u - 1 = 0, without cancellation at small Q.
    u = 2.0 / (b + jnp.sqrt(b**2 + 4.0))
    w0 = 2.0 * jnp.pi * f3db / jnp.sqrt(u)
    return {
        "inp": 0.0 * signals.inp,
        "out": signals.i_out,
        "i_out": w0 * (signals.out + signals.x / Q - signals.inp),
        "x": -w0 * signals.x,
    }, {"i_out": signals.x, "x": signals.out}

CoupledInductors ¤

CoupledInductors(
    signals: Signals, L1: float = 1e-09, L2: float = 1e-09, k: float = 0.5
) -> PhysicsReturn

Two magnetically coupled inductors with M = k * sqrt(L1 * L2).

Dots are on p1 and s1; currents are positive into the dotted terminals. The parameters should satisfy L1, L2 > 0 and |k| <= 1. At k = 0 the windings are independent. For |k| = 1 the inductance matrix is singular.

Source code in circulax/components/electronic.py
@component(
    ports=("p1", "p2", "s1", "s2"),
    states=("i1", "i2"),
    port_aliases={"p1": "P1", "p2": "P2", "s1": "S1", "s2": "S2"},
    holomorphic=True,
)
def CoupledInductors(signals: Signals, L1: float = 1e-9, L2: float = 1e-9, k: float = 0.5) -> PhysicsReturn:
    """Two magnetically coupled inductors with ``M = k * sqrt(L1 * L2)``.

    Dots are on ``p1`` and ``s1``; currents are positive into the dotted
    terminals. The parameters should satisfy ``L1, L2 > 0`` and ``|k| <= 1``.
    At ``k = 0`` the windings are independent. For ``|k| = 1`` the inductance
    matrix is singular.
    """
    m = k * jnp.sqrt(L1 * L2)
    v1 = signals.p1 - signals.p2
    v2 = signals.s1 - signals.s2
    return (
        {"p1": signals.i1, "p2": -signals.i1, "s1": signals.i2, "s2": -signals.i2, "i1": v1, "i2": v2},
        {"i1": -(L1 * signals.i1 + m * signals.i2), "i2": -(m * signals.i1 + L2 * signals.i2)},
    )

DifferentialAdapter ¤

DifferentialAdapter(signals: Signals) -> PhysicsReturn

Lossless bidirectional differential/common to conductor adapter.

Va=Vc+Vd/2, Vb=Vc-Vd/2. Currents are positive into this component at all four ports, so Id=-(Ia-Ib)/2 and Ic=-(Ia+Ib). The resulting instantaneous sum of port powers is zero. Modal impedances use the full differential/common convention (2*Zodd and Zeven/2).

Source code in circulax/components/electronic.py
@component(ports=("d", "c", "a", "b"), states=("ia", "ib"), holomorphic=True)
def DifferentialAdapter(signals: Signals) -> PhysicsReturn:
    """Lossless bidirectional differential/common to conductor adapter.

    ``Va=Vc+Vd/2``, ``Vb=Vc-Vd/2``. Currents are positive into this
    component at all four ports, so ``Id=-(Ia-Ib)/2`` and ``Ic=-(Ia+Ib)``.
    The resulting instantaneous sum of port powers is zero. Modal impedances
    use the full differential/common convention (2*Zodd and Zeven/2).
    """
    return {
        "d": -(signals.ia - signals.ib) / 2,
        "c": -(signals.ia + signals.ib),
        "a": signals.ia,
        "b": signals.ib,
        "ia": signals.a - signals.c - signals.d / 2,
        "ib": signals.b - signals.c + signals.d / 2,
    }, {}

IdealTransformer ¤

IdealTransformer(signals: Signals, n: float = 1.0) -> PhysicsReturn

Ideal transformer with turns ratio n = N1 / N2 (n > 0).

Dots are on p1 and s1. It passes DC; add a magnetizing inductor across the primary to model low-frequency roll-off.

Source code in circulax/components/electronic.py
@component(
    ports=("p1", "p2", "s1", "s2"),
    states=("i_p",),
    port_aliases={"p1": "P1", "p2": "P2", "s1": "S1", "s2": "S2"},
    holomorphic=True,
)
def IdealTransformer(signals: Signals, n: float = 1.0) -> PhysicsReturn:
    """Ideal transformer with turns ratio ``n = N1 / N2`` (``n > 0``).

    Dots are on ``p1`` and ``s1``. It passes DC; add a magnetizing inductor
    across the primary to model low-frequency roll-off.
    """
    v1 = signals.p1 - signals.p2
    v2 = signals.s1 - signals.s2
    return {
        "p1": signals.i_p,
        "p2": -signals.i_p,
        "s1": -n * signals.i_p,
        "s2": n * signals.i_p,
        "i_p": v1 - n * v2,
    }, {}

LowPass1 ¤

LowPass1(signals: Signals, f3db: float = 10000000000.0) -> PhysicsReturn

Unity-DC-gain first-order low-pass; f3db is the -3 dB frequency.

H(s)=1/(1+s*tau), tau=1/(2*pi*f3db). Input current is zero; the output voltage is independent of the connected load.

Source code in circulax/components/filters.py
@component(ports=("inp", "out"), states=("i_out",), holomorphic=True)
def LowPass1(signals: Signals, f3db: float = 10e9) -> PhysicsReturn:
    """Unity-DC-gain first-order low-pass; ``f3db`` is the -3 dB frequency.

    ``H(s)=1/(1+s*tau)``, ``tau=1/(2*pi*f3db)``. Input current is zero;
    the output voltage is independent of the connected load.
    """
    tau = 1.0 / (2.0 * jnp.pi * f3db)
    return {
        "inp": 0.0 * signals.inp,
        "out": signals.i_out,
        "i_out": signals.out - signals.inp,
    }, {"i_out": tau * signals.out}

MatchedOpticalLoad ¤

MatchedOpticalLoad(signals: Signals) -> PhysicsReturn

Absorb a wave at unit reference impedance; no incident optical field.

Source code in circulax/components/laser_sections.py
@component(ports=("p1",), holomorphic=True)
def MatchedOpticalLoad(signals: Signals) -> PhysicsReturn:
    """Absorb a wave at unit reference impedance; no incident optical field."""
    return {"p1": signals.p1}, {}

MatchedOpticalPulse ¤

MatchedOpticalPulse(
    signals: Signals,
    t: float,
    power_w: float = 1e-12,
    start_s: float = 1e-11,
    duration_s: float = 3e-11,
) -> PhysicsReturn

Matched coherent pulse source: prescribed incoming wave, absorbs return.

Compact sin² FIELD, sin⁴ power; exactly zero outside its support. This is deterministic startup, not spontaneous emission. p2 is optical reference.

Source code in circulax/components/laser_sections.py
@source(ports=("p1", "p2"), states=("branch",), holomorphic=True, ac_source_stamp={"branch": 2.0})
def MatchedOpticalPulse(
    signals: Signals, t: float, power_w: float = 1e-12, start_s: float = 10e-12, duration_s: float = 30e-12
) -> PhysicsReturn:
    """Matched coherent pulse source: prescribed incoming wave, absorbs return.

    Compact sin² FIELD, sin⁴ power; exactly zero outside its support. This is
    deterministic startup, not spontaneous emission. p2 is optical reference.
    """
    x = jnp.clip((t - start_s) / duration_s, 0.0, 1.0)
    field = jnp.where((t > start_s) & (t < start_s + duration_s), jnp.sqrt(power_w) * jnp.sin(jnp.pi * x) ** 2, 0.0)
    return {"p1": signals.branch, "p2": -signals.branch, "branch": signals.p1 - signals.p2 - 2 * field - signals.branch}, {}

OpticalDelayLine ¤

OpticalDelayLine(
    signals: Signals,
    length_um: float = 100.0,
    loss_dB_cm: float = 1.0,
    neff: float = 2.4,
    n_group: float = 4.0,
    wavelength_nm: float = 1310.0,
) -> PhysicsReturn

Waveguide modelled as an explicit time-of-flight delay line (real group delay).

Unlike :func:OpticalWaveguide -- which is a steady-state S-matrix stamp only valid for CW/frequency-domain analysis -- this component enforces the actual transient envelope delay: the output field at p2 is the input field at p1 from tau = length_um * n_group / c seconds ago, attenuated and phase-shifted, via a VCVS-style constraint (same pattern as :func:TunableBeamSplitter). p1 carries no self-stamp and must be driven by a connected source/component, matching that same convention.

See circulax.solvers.assembly for how the delayed local state is computed -- a fixed-size accepted-step history buffer read via jnp.interp, vmapped per-instance since tau may vary across instances of different length. Adaptive and fixed step-size controllers may take steps longer than tau; interpolation against the current Newton trial supplies the required delay Jacobian in that regime.

Parameters:

Name Type Description Default
signals Signals

Current and delayed component-local fields and branch state.

required
length_um float

Waveguide length in micrometres. Defaults to 100.0.

100.0
loss_dB_cm float

Propagation loss in dB/cm. Defaults to 1.0.

1.0
neff float

Effective refractive index, used for the carrier phase shift over the delay. Defaults to 2.4.

2.4
n_group float

Group refractive index; sets the propagation delay via tau = length_um * n_group / c. Defaults to 4.0.

4.0
wavelength_nm float

Operating wavelength in nm. Defaults to 1310.0.

1310.0
Source code in circulax/components/photonic.py
@component(ports=("p1", "p2"), states=("i_p2",))
def OpticalDelayLine(
    signals: Signals,
    length_um: float = 100.0,
    loss_dB_cm: float = 1.0,
    neff: float = 2.4,
    n_group: float = 4.0,
    wavelength_nm: float = 1310.0,
) -> PhysicsReturn:
    """Waveguide modelled as an explicit time-of-flight delay line (real group delay).

    Unlike :func:`OpticalWaveguide` -- which is a steady-state S-matrix stamp
    only valid for CW/frequency-domain analysis -- this component enforces
    the actual transient envelope delay: the output field at ``p2`` is the
    input field at ``p1`` from ``tau = length_um * n_group / c`` seconds ago,
    attenuated and phase-shifted, via a VCVS-style constraint (same pattern as
    :func:`TunableBeamSplitter`). ``p1`` carries no self-stamp and must be
    driven by a connected source/component, matching that same convention.

    See ``circulax.solvers.assembly`` for how the delayed local state is
    computed -- a fixed-size accepted-step history buffer read via
    ``jnp.interp``, vmapped per-instance since ``tau`` may vary across
    instances of different length. Adaptive and fixed step-size controllers
    may take steps longer than ``tau``; interpolation against the current
    Newton trial supplies the required delay Jacobian in that regime.

    Args:
        signals: Current and delayed component-local fields and branch state.
        length_um: Waveguide length in micrometres. Defaults to ``100.0``.
        loss_dB_cm: Propagation loss in dB/cm. Defaults to ``1.0``.
        neff: Effective refractive index, used for the carrier phase shift
            over the delay. Defaults to ``2.4``.
        n_group: Group refractive index; sets the propagation delay via
            ``tau = length_um * n_group / c``. Defaults to ``4.0``.
        wavelength_nm: Operating wavelength in nm. Defaults to ``1310.0``.

    """
    phi = 2.0 * jnp.pi * neff * (length_um / wavelength_nm) * 1000.0
    loss_val = loss_dB_cm * (length_um / 10000.0)
    T_mag = 10.0 ** (-loss_val / 20.0)
    T = T_mag * jnp.exp(-1j * phi)

    c_um_per_s = 2.99792458e14
    delay = (length_um * n_group) / c_um_per_s
    constraint = signals.p2 - T * signals.at_delay(delay).p1

    return {"p1": 0.0, "p2": signals.i_p2, "i_p2": constraint}, {}

OpticalDirectionalCoupler ¤

OpticalDirectionalCoupler(
    signals: Signals, power_coupling: float = 0.2
) -> PhysicsReturn

Reciprocal unitary four-port coupler, suitable for connecting ring loops.

Forward inputs p1,p2 exit at p3,p4; reverse paths follow reciprocity. Cross coupling has +i phase. The physical ring delay belongs in waveguides.

Source code in circulax/components/laser_sections.py
@component(ports=("p1", "p2", "p3", "p4"), states=("a1", "a2", "a3", "a4"), holomorphic=True)
def OpticalDirectionalCoupler(signals: Signals, power_coupling: float = 0.2) -> PhysicsReturn:
    """Reciprocal unitary four-port coupler, suitable for connecting ring loops.

    Forward inputs p1,p2 exit at p3,p4; reverse paths follow reciprocity.
    Cross coupling has +i phase. The physical ring delay belongs in waveguides.
    """
    t = jnp.sqrt(1 - power_coupling)
    k = 1j * jnp.sqrt(power_coupling)
    a = [getattr(signals, f"a{j}") for j in range(1, 5)]
    b = [t * a[2] + k * a[3], k * a[2] + t * a[3], t * a[0] + k * a[1], k * a[0] + t * a[1]]
    return {
        **{f"p{j}": a[j - 1] - b[j - 1] for j in range(1, 5)},
        **{f"a{j}": a[j - 1] + b[j - 1] - getattr(signals, f"p{j}") for j in range(1, 5)},
    }, {}

OpticalInterface ¤

OpticalInterface(
    signals: Signals, amplitude_reflection: float = 0.0, power_loss_db: float = 0.0
) -> PhysicsReturn

Reciprocal optical interface; r=i*rho, t=sqrt(1-rho²), common excess loss.

rho is a real amplitude magnitude in [-1,1], not power reflectance. This also supplies a frequency-flat mirror when excess loss is zero.

Source code in circulax/components/laser_sections.py
@component(ports=("p1", "p2"), states=("a1", "a2"), holomorphic=True)
def OpticalInterface(signals: Signals, amplitude_reflection: float = 0.0, power_loss_db: float = 0.0) -> PhysicsReturn:
    """Reciprocal optical interface; r=i*rho, t=sqrt(1-rho²), common excess loss.

    rho is a real amplitude magnitude in [-1,1], not power reflectance.
    This also supplies a frequency-flat mirror when excess loss is zero.
    """
    amplitude = 10 ** (-power_loss_db / 20)
    r = 1j * amplitude_reflection * amplitude
    t = jnp.sqrt(1 - amplitude_reflection**2) * amplitude
    return _waves(signals, r * signals.a1 + t * signals.a2, t * signals.a1 + r * signals.a2), {}

SemiconductorOpticalAmplifier ¤

SemiconductorOpticalAmplifier(
    signals: Signals,
    length_um: float = 600.0,
    width_um: float = 2.0,
    thickness_um: float = 0.1,
    lifetime_s: float = 2.8e-10,
    confinement: float = 0.3,
    differential_gain_m2: float = 6e-20,
    transparency_m3: float = 5.5e23,
    injection_efficiency: float = 0.8,
    wavelength_nm: float = 1540.0,
    alpha_h: float = 3.5,
    loss_db_per_cm: float = 0.0,
    saturation: float = 1.0,
    saturation_current_a: float = 1e-12,
    ideality: float = 1.8,
    thermal_voltage_v: float = 0.02585,
    resistance_ohm: float = 5.0,
    capacitance_f: float = 1.5e-13,
) -> PhysicsReturn

Diode injection, gain depletion/recovery, and carrier-induced phase.

h is the integral of modal gain over length. Its storage term yields taudh/dt = h0(I_D)-h-saturationPin*expm1(h)/Psat for zero passive loss. Set saturation=0 for a linear amplifier, and alpha_h=0 for no chirp. The junction's displacement current is excluded from carrier injection. Diode Is and C scale with contact area; vertical series R scales inversely. ASE is sampled separately with :func:ase_field, never inside Newton. Uniform passive loss is approximated with constant gain per segment. Subdivide the device to resolve loss with longitudinal depletion. The model neglects thermal effects and ASE depletion. Time follows the optical envelope; propagation delay is not included.

Source code in circulax/components/soa.py
@component(ports=("anode", "cathode", "optical_in", "optical_out"), states=("v_j", "h", "i_out"), holomorphic=False)
def SemiconductorOpticalAmplifier(  # noqa: PLR0917 -- component parameters are declared as model fields
    signals: Signals,
    length_um: float = 600.0,
    width_um: float = 2.0,
    thickness_um: float = 0.1,
    lifetime_s: float = 280e-12,
    confinement: float = 0.3,
    differential_gain_m2: float = 6e-20,
    transparency_m3: float = 5.5e23,
    injection_efficiency: float = 0.8,
    wavelength_nm: float = 1540.0,
    alpha_h: float = 3.5,
    loss_db_per_cm: float = 0.0,
    saturation: float = 1.0,
    saturation_current_a: float = 1e-12,
    ideality: float = 1.8,
    thermal_voltage_v: float = 0.02585,
    resistance_ohm: float = 5.0,
    capacitance_f: float = 150e-15,
) -> PhysicsReturn:
    """Diode injection, gain depletion/recovery, and carrier-induced phase.

    ``h`` is the integral of modal gain over length. Its storage term yields
    tau*dh/dt = h0(I_D)-h-saturation*Pin*expm1(h)/Psat for zero passive loss.
    Set saturation=0 for a linear amplifier, and alpha_h=0 for no chirp.
    The junction's displacement current is excluded from carrier injection.
    Diode Is and C scale with contact area; vertical series R scales inversely.
    ASE is sampled separately with :func:`ase_field`, never inside Newton.
    Uniform passive loss is approximated with constant gain per segment.
    Subdivide the device to resolve loss with longitudinal depletion. The model
    neglects thermal effects and ASE depletion. Time follows the optical envelope;
    propagation delay is not included.
    """
    contact_scale = length_um * width_um / (600.0 * 2.0)
    vj = signals.v_j
    diode_current = saturation_current_a * contact_scale * jnp.expm1(vj / (ideality * thermal_voltage_v))
    terminal_current = (signals.anode - signals.cathode - vj) / (resistance_ohm / contact_scale)
    h0 = unsaturated_gain(
        jnp.real(diode_current),
        length_um=length_um,
        width_um=width_um,
        thickness_um=thickness_um,
        lifetime_s=lifetime_s,
        confinement=confinement,
        differential_gain_m2=differential_gain_m2,
        transparency_m3=transparency_m3,
        injection_efficiency=injection_efficiency,
    )
    _, _, energy = soa_scales(
        length_um=length_um,
        width_um=width_um,
        thickness_um=thickness_um,
        confinement=confinement,
        differential_gain_m2=differential_gain_m2,
        wavelength_nm=wavelength_nm,
    )
    h_real = jnp.real(signals.h)
    pin = jnp.abs(signals.optical_in) ** 2
    loss = loss_db_per_cm * length_um / 10000.0 * jnp.log(10.0) / 10.0
    depletion = saturation * lifetime_s * stimulated_power(h_real, loss, pin) / energy
    output = signals.optical_in * jnp.exp(0.5 * ((1 - 1j * alpha_h) * h_real - loss))
    return {
        "anode": terminal_current,
        "cathode": -terminal_current,
        "v_j": (diode_current - terminal_current) / 0.1,
        "h": signals.h - h0 + depletion,
        "optical_in": signals.optical_in,
        "optical_out": signals.i_out,
        "i_out": signals.optical_out - output,
    }, {"v_j": capacitance_f * contact_scale * vj / 0.1, "h": lifetime_s * signals.h}

ThermoOpticPhaseShifter ¤

ThermoOpticPhaseShifter(
    signals: Signals,
    length_m: float = 0.0001,
    group_index: float = 4.0,
    loss_m1: float = 0.0,
    phase_rad: float = 0.0,
    phase_per_k: float = 0.15,
    frame_offset_rad_s: float = 0.0,
    heater_resistance_ohm: float = 100.0,
    thermal_resistance_k_per_w: float = 200.0,
    thermal_tau_s: float = 1e-06,
) -> PhysicsReturn

Reciprocal delayed phase section, uniform arrival-time temperature.

temperature is the rise above ambient (K); phase_per_k is one-pass rad/K. Thermal variation during a flight is neglected (flight << thermal time).

Source code in circulax/components/laser_sections.py
@component(ports=("p1", "p2", "heater", "heater_return"), states=("a1", "a2", "temperature"), holomorphic=False)
def ThermoOpticPhaseShifter(
    signals: Signals,
    length_m: float = 100e-6,
    group_index: float = 4.0,
    loss_m1: float = 0.0,
    phase_rad: float = 0.0,
    phase_per_k: float = 0.15,
    frame_offset_rad_s: float = 0.0,
    heater_resistance_ohm: float = 100.0,
    thermal_resistance_k_per_w: float = 200.0,
    thermal_tau_s: float = 1e-6,
) -> PhysicsReturn:
    """Reciprocal delayed phase section, uniform arrival-time temperature.

    temperature is the rise above ambient (K); phase_per_k is one-pass rad/K.
    Thermal variation during a flight is neglected (flight << thermal time).
    """
    tau = length_m * group_index / LIGHT_SPEED
    past = signals.at_delay(tau)
    phase = phase_rad + phase_per_k * jnp.real(signals.temperature) - frame_offset_rad_s * tau
    transmission = jnp.exp(-loss_m1 * length_m / 2 + 1j * phase)
    f = _waves(signals, transmission * past.a2, transmission * past.a1)
    current, ft, qt = thermal_terms(
        signals.heater - signals.heater_return,
        signals.temperature,
        heater_resistance_ohm,
        thermal_resistance_k_per_w,
        thermal_tau_s,
    )
    f.update(heater=current, heater_return=-current, temperature=ft)
    return f, {"temperature": qt}

TransmissionLine ¤

TransmissionLine(
    signals: Signals, tau: float = 1e-09, z0: float = 50.0, attenuation: float = 1.0
) -> PhysicsReturn

Matched bidirectional transmission line with exact fixed delay.

a1 and a2 are the incident power-wave amplitudes at the two reference planes. The outgoing waves are the delayed incident wave from the opposite end. This stamp stays finite for an exactly lossless line and therefore avoids the singular S -> Y conversion of an ideal through connection.

The same equations are interpreted by DC, transient, AC, and HB.

Source code in circulax/components/electronic.py
@component(
    ports=("p1", "p2"),
    states=("a1", "a2"),
    port_aliases=_PN_ALIASES,
    holomorphic=True,
)
def TransmissionLine(
    signals: Signals,
    tau: float = 1e-9,
    z0: float = 50.0,
    attenuation: float = 1.0,
) -> PhysicsReturn:
    """Matched bidirectional transmission line with exact fixed delay.

    ``a1`` and ``a2`` are the incident power-wave amplitudes at the two
    reference planes. The outgoing waves are the delayed incident wave from
    the opposite end. This stamp stays finite for an exactly lossless line
    and therefore avoids the singular ``S -> Y`` conversion of an ideal
    through connection.

    The same equations are interpreted by DC, transient, AC, and HB.
    """
    past = signals.at_delay(tau)
    b1 = attenuation * past.a2
    b2 = attenuation * past.a1
    i1 = (signals.a1 - b1) / z0
    i2 = (signals.a2 - b2) / z0
    return {
        "p1": i1,
        "p2": i2,
        "a1": signals.p1 - signals.a1 - b1,
        "a2": signals.p2 - signals.a2 - b2,
    }, {}

TravelingWaveGainCell ¤

TravelingWaveGainCell(
    signals: Signals,
    length_m: float = 7.5e-05,
    width_m: float = 2e-06,
    thickness_m: float = 1e-07,
    group_index: float = 3.6,
    lifetime_s: float = 2.8e-10,
    confinement: float = 0.3,
    differential_gain_m2: float = 6e-20,
    transparency_m3: float = 5.5e23,
    injection_efficiency: float = 0.8,
    wavelength_m: float = 1.54e-06,
    alpha_h: float = 3.5,
    loss_m1: float = 1000.0,
    detuning_rad_s: float = 0.0,
    frame_offset_rad_s: float = 0.0,
    saturation: float = 1.0,
    saturation_current_a: float = 1e-12,
    ideality: float = 1.8,
    thermal_voltage_v: float = 0.02585,
    resistance_ohm: float = 5.0,
    capacitance_f: float = 1.5e-13,
) -> PhysicsReturn

One retarded-gain cell; both delayed incident powers share one reservoir.

Connect cells in optical series and their diode terminals in electrical parallel for a uniformly contacted gain region. Diode area scales with cell length. Frozen arrival-time gain is first order in cell length. Interference is averaged; carrier gratings, gain dispersion and spontaneous noise omitted.

Source code in circulax/components/laser_sections.py
@component(ports=("p1", "p2", "anode", "cathode"), states=("a1", "a2", "v_j", "h"), holomorphic=False)
def TravelingWaveGainCell(
    signals: Signals,
    length_m: float = 75e-6,
    width_m: float = 2e-6,
    thickness_m: float = 0.1e-6,
    group_index: float = 3.6,
    lifetime_s: float = 280e-12,
    confinement: float = 0.3,
    differential_gain_m2: float = 6e-20,
    transparency_m3: float = 5.5e23,
    injection_efficiency: float = 0.8,
    wavelength_m: float = 1540e-9,
    alpha_h: float = 3.5,
    loss_m1: float = 1000.0,
    detuning_rad_s: float = 0.0,
    frame_offset_rad_s: float = 0.0,
    saturation: float = 1.0,
    saturation_current_a: float = 1e-12,
    ideality: float = 1.8,
    thermal_voltage_v: float = 0.02585,
    resistance_ohm: float = 5.0,
    capacitance_f: float = 150e-15,
) -> PhysicsReturn:
    """One retarded-gain cell; both delayed incident powers share one reservoir.

    Connect cells in optical series and their diode terminals in electrical
    parallel for a uniformly contacted gain region. Diode area scales with cell length.
    Frozen arrival-time gain is first order in cell length. Interference is
    averaged; carrier gratings, gain dispersion and spontaneous noise omitted.
    """
    scale = length_m * width_m / (600e-6 * 2e-6)
    diode = saturation_current_a * scale * jnp.expm1(signals.v_j / (ideality * thermal_voltage_v))
    current = (signals.anode - signals.cathode - signals.v_j) * scale / resistance_ohm
    settings = {
        "length_um": length_m * 1e6,
        "width_um": width_m * 1e6,
        "thickness_um": thickness_m * 1e6,
        "confinement": confinement,
        "differential_gain_m2": differential_gain_m2,
    }
    h0 = unsaturated_gain(
        jnp.real(diode),
        lifetime_s=lifetime_s,
        transparency_m3=transparency_m3,
        injection_efficiency=injection_efficiency,
        **settings,
    )
    energy = soa_scales(wavelength_nm=wavelength_m * 1e9, **settings)[2]
    tau = length_m * group_index / LIGHT_SPEED
    past = signals.at_delay(tau)
    gain = jnp.real(signals.h)
    loss = loss_m1 * length_m
    transmission = jnp.exp(((1 - 1j * alpha_h) * gain - loss) / 2 + 1j * (detuning_rad_s - frame_offset_rad_s) * tau)
    f = _waves(signals, transmission * past.a2, transmission * past.a1)
    pin = abs(past.a1) ** 2 + abs(past.a2) ** 2
    f.update(
        anode=current,
        cathode=-current,
        v_j=(diode - current) / 0.1,
        h=signals.h - h0 + saturation * lifetime_s * stimulated_power(gain, loss, pin) / energy,
    )
    return f, {"v_j": capacitance_f * scale * signals.v_j / 0.1, "h": lifetime_s * signals.h}

add_drop_ring cached ¤

add_drop_ring(
    *,
    length_m: float = 0.0004,
    group_index: float = 4.0,
    power_coupling: float = 0.2,
    loss_m1: float = 100.0
) -> Circuit

Bidirectional add/drop ring assembled from two couplers and two arms.

Ports input/through/add/drop plus heater/heater_return. One arm supplies thermal phase tuning. All unexcited optical ports must be terminated.

Source code in circulax/components/hybrid_laser.py
@lru_cache(maxsize=16)
def add_drop_ring(
    *, length_m: float = 400e-6, group_index: float = 4.0, power_coupling: float = 0.2, loss_m1: float = 100.0
) -> Circuit:
    """Bidirectional add/drop ring assembled from two couplers and two arms.

    Ports input/through/add/drop plus heater/heater_return. One arm supplies
    thermal phase tuning. All unexcited optical ports must be terminated.
    """
    from circulax import compile_circuit

    arm = {"length_m": length_m / 2, "group_index": group_index, "loss_m1": loss_m1}
    net = {
        "instances": {
            "C1": {"component": "coupler", "settings": {"power_coupling": power_coupling}},
            "C2": {"component": "coupler", "settings": {"power_coupling": power_coupling}},
            "A": {"component": "waveguide", "settings": arm.copy()},
            "B": {"component": "phase", "settings": arm.copy()},
        },
        "connections": {"C1,p4": "A,p1", "A,p2": "C2,p2", "C2,p4": "B,p1", "B,p2": "C1,p2"},
        "ports": {
            "input": "C1,p1",
            "through": "C1,p3",
            "add": "C2,p1",
            "drop": "C2,p3",
            "heater": "B,heater",
            "heater_return": "B,heater_return",
        },
    }
    return compile_circuit(
        net,
        {"coupler": OpticalDirectionalCoupler, "waveguide": BidirectionalWaveguide, "phase": ThermoOpticPhaseShifter},
        is_complex=True,
        backend="klu",
        g_leak=0,
    )

characteristic_rlgc_transmission_line ¤

characteristic_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,
    tolerance: float = 0.001,
    max_order: int = 40,
    delay_fraction: float = 0.98,
    z0: float = 50.0
) -> Circuit

Create a fast uniform line from RLGC versus Hz, with its delay de-embedded.

Use it instead of :func:~circulax.components.reduced_rlgc_transmission_line when the line is electrically long. That model fits the S-parameters and needs many poles to follow the propagation phase. This one removes the delay exactly and fits only the smooth characteristic admittance and the remaining propagation. frequencies must start at DC, and the lowest nonzero frequency must be low enough for the DC floors described in :func:~circulax.fitting.fit_rlgc_characteristic. That function also documents the admission checks; a fit failing them raises ValueError. z0 is only the reference impedance for the S error check.

Ports p1 and p2 are single-ended to ground, with no internal taps. Fitting depends on length, so refit for a different length. Use fit_rlgc_characteristic to inspect the fit and model.circuit() to realize it.

Source code in circulax/components/characteristic_line.py
def characteristic_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,
    tolerance: float = 1e-3,
    max_order: int = 40,
    delay_fraction: float = 0.98,
    z0: float = 50.0,
) -> Circuit:
    """Create a fast uniform line from RLGC versus Hz, with its delay de-embedded.

    Use it instead of :func:`~circulax.components.reduced_rlgc_transmission_line`
    when the line is electrically long. That model fits the S-parameters and
    needs many poles to follow the propagation phase. This one removes the delay
    exactly and fits only the smooth characteristic admittance and the
    remaining propagation. ``frequencies`` must start at DC, and the lowest
    nonzero frequency must be low enough for the DC floors described in
    :func:`~circulax.fitting.fit_rlgc_characteristic`. That function also
    documents the admission checks; a fit failing them raises ``ValueError``.
    ``z0`` is only the reference impedance for the S error check.

    Ports ``p1`` and ``p2`` are single-ended to ground, with no internal taps.
    Fitting depends on length, so refit for a different length. Use
    ``fit_rlgc_characteristic`` to inspect the fit and ``model.circuit()`` to
    realize it.
    """
    from circulax.fitting import fit_rlgc_characteristic

    model = fit_rlgc_characteristic(
        frequencies,
        R=R,
        L=L,
        G=G,
        C=C,
        length=length,
        tolerance=tolerance,
        max_order=max_order,
        delay_fraction=delay_fraction,
        z0=z0,
    )
    return model.circuit()

charge_from_capacitance_table ¤

charge_from_capacitance_table(
    voltages: ArrayLike,
    capacitance_F_per_m: ArrayLike,
    *,
    reference_voltage: float = 0.0
) -> VoltageFunction

Integrate a C(V) table, in F/m, into a junction charge function in C/m.

The capacitance is interpolated linearly and integrated exactly, so d charge / dv reproduces the table and stays continuous; outside the table the end capacitances are held. Pass the result as charge to :func:junction_model.

Source code in circulax/components/phase_shifter.py
def charge_from_capacitance_table(
    voltages: ArrayLike,
    capacitance_F_per_m: ArrayLike,
    *,
    reference_voltage: float = 0.0,
) -> VoltageFunction:
    """Integrate a C(V) table, in F/m, into a junction charge function in C/m.

    The capacitance is interpolated linearly and integrated exactly, so
    ``d charge / dv`` reproduces the table and stays continuous; outside the
    table the end capacitances are held. Pass the result as
    ``charge`` to :func:`junction_model`.
    """
    v, cap = _table(voltages, capacitance_F_per_m, "charge_from_capacitance_table")
    if np.any(cap < 0):
        msg = "charge_from_capacitance_table: capacitance must be nonnegative"
        raise ValueError(msg)
    return _integrated(v, cap, reference_voltage)

delay_line_fdomain ¤

delay_line_fdomain(
    f: float, length_um: float = 100.0, loss_dB_cm: float = 1.0, n_group: float = 4.0
) -> ndarray

Frequency-domain delay line for AC and harmonic-balance analysis.

Models a pure transmission-line group delay: S21 = T_mag * exp(-j 2pi f tau) where tau = length_um * n_group / c and T_mag accounts for propagation loss. The S-matrix is converted to a Y-matrix via :func:s_to_y.

This is a frequency-domain-only component (f = modulation / signal frequency, e.g. 1 GHz for an AC sweep). Carrier-phase effects (neff, wavelength_nm) belong in the wavelength-domain :func:OpticalWaveguide and are intentionally excluded here.

This component is AC/HB-only; it cannot be used in transient simulation (fdomain components raise at transient setup time).

Parameters:

Name Type Description Default
f float

Modulation frequency in Hz (supplied by the AC/HB solver).

required
length_um float

Waveguide length in micrometres. Defaults to 100.0.

100.0
loss_dB_cm float

Propagation loss in dB/cm. Defaults to 1.0.

1.0
n_group float

Group refractive index; sets the propagation delay via tau = length_um * n_group / c. Defaults to 4.0.

4.0
Source code in circulax/components/photonic.py
@fdomain_component(ports=("p1", "p2"))
def delay_line_fdomain(
    f: float,
    length_um: float = 100.0,
    loss_dB_cm: float = 1.0,
    n_group: float = 4.0,
) -> jnp.ndarray:
    """Frequency-domain delay line for AC and harmonic-balance analysis.

    Models a pure transmission-line group delay: ``S21 = T_mag * exp(-j 2pi f tau)``
    where ``tau = length_um * n_group / c`` and ``T_mag`` accounts for
    propagation loss.  The S-matrix is converted to a Y-matrix via
    :func:`s_to_y`.

    This is a frequency-domain-only component (``f`` = modulation / signal
    frequency, e.g. 1 GHz for an AC sweep).  Carrier-phase effects
    (``neff``, ``wavelength_nm``) belong in the wavelength-domain
    :func:`OpticalWaveguide` and are intentionally excluded here.

    This component is AC/HB-only; it cannot be used in transient simulation
    (fdomain components raise at transient setup time).

    Args:
        f: Modulation frequency in Hz (supplied by the AC/HB solver).
        length_um: Waveguide length in micrometres. Defaults to ``100.0``.
        loss_dB_cm: Propagation loss in dB/cm. Defaults to ``1.0``.
        n_group: Group refractive index; sets the propagation delay via
            ``tau = length_um * n_group / c``. Defaults to ``4.0``.

    """
    c_um_per_s = 2.99792458e14
    loss_val = loss_dB_cm * (length_um / 10000.0)
    T_mag = 10.0 ** (-loss_val / 20.0)
    tau = (length_um * n_group) / c_um_per_s
    T = T_mag * jnp.exp(-1j * 2.0 * jnp.pi * f * tau)
    S = jnp.array([[0.0, T], [T, 0.0]], dtype=jnp.complex128)
    return s_to_y(S)

delta_neff_from_vpil ¤

delta_neff_from_vpil(
    voltages: ArrayLike,
    vpil_V_cm: ArrayLike,
    *,
    wavelength_nm: float,
    reference_voltage: float = 0.0
) -> VoltageFunction

Integrate a small-signal VπL table into delta_neff(v).

vpil_V_cm is the small-signal VπL in V·cm at each junction voltage v = V_anode - V_cathode (negative for reverse bias), measured at wavelength_nm. The slope magnitude is |dn_eff/dV| = λ / (2·VπL). Its sign follows plasma dispersion in a depletion-mode junction: reverse bias removes carriers, so n_eff increases as v decreases.

The slope is interpolated linearly between samples and integrated exactly, so delta_neff has a continuous derivative inside the table and extrapolates with the end slopes. delta_neff(reference_voltage) = 0; the factory's neff is therefore the effective index at that voltage.

Source code in circulax/components/phase_shifter.py
def delta_neff_from_vpil(
    voltages: ArrayLike,
    vpil_V_cm: ArrayLike,
    *,
    wavelength_nm: float,
    reference_voltage: float = 0.0,
) -> VoltageFunction:
    """Integrate a small-signal VπL table into ``delta_neff(v)``.

    ``vpil_V_cm`` is the small-signal VπL in V·cm at each junction voltage
    ``v = V_anode - V_cathode`` (negative for reverse bias), measured at
    ``wavelength_nm``. The slope magnitude is ``|dn_eff/dV| = λ / (2·VπL)``.
    Its sign follows plasma dispersion in a depletion-mode junction: reverse
    bias removes carriers, so ``n_eff`` *increases* as ``v`` decreases.

    The slope is interpolated linearly between samples and integrated exactly,
    so ``delta_neff`` has a continuous derivative inside the table and
    extrapolates with the end slopes. ``delta_neff(reference_voltage) = 0``;
    the factory's ``neff`` is therefore the effective index at that voltage.
    """
    v, vpil = _table(voltages, vpil_V_cm, "delta_neff_from_vpil")
    if np.any(vpil <= 0):
        msg = "delta_neff_from_vpil: VπL values must be positive"
        raise ValueError(msg)
    slope = -(wavelength_nm * 1e-9) / (2.0 * vpil * 1e-2)
    return _integrated(v, slope, reference_voltage)

depletion_charge ¤

depletion_charge(
    v: Any,
    cj0_F_per_m: float = 3e-10,
    vbi: float = 0.9,
    grading: float = 0.5,
    fc: float = 0.5,
) -> Any

Depletion charge per metre with SPICE forward-bias linearisation.

C(v) = cj0 / (1 - v/vbi)**grading for v < fc*vbi. Above that the capacitance continues linearly (the standard SPICE FC treatment), so the charge and its derivative stay finite if the junction is driven forward during Newton iterations. charge(0) = 0.

Source code in circulax/components/phase_shifter.py
def depletion_charge(
    v: Any,
    cj0_F_per_m: float = 3.0e-10,
    vbi: float = 0.9,
    grading: float = 0.5,
    fc: float = 0.5,
) -> Any:
    """Depletion charge per metre with SPICE forward-bias linearisation.

    ``C(v) = cj0 / (1 - v/vbi)**grading`` for ``v < fc*vbi``. Above that the
    capacitance continues linearly (the standard SPICE ``FC`` treatment), so
    the charge and its derivative stay finite if the junction is driven
    forward during Newton iterations. ``charge(0) = 0``.
    """
    v_fc = fc * vbi
    one_m = 1.0 - grading
    v_safe = jnp.minimum(v, v_fc)
    q_rev = cj0_F_per_m * vbi / one_m * (1.0 - (1.0 - v_safe / vbi) ** one_m)
    f1 = (1.0 - fc) ** (-1.0 - grading)
    dv = jnp.maximum(v - v_fc, 0.0)
    q_fwd = cj0_F_per_m * f1 * ((1.0 - fc * (1.0 + grading)) * dv + grading / (2.0 * vbi) * ((v_fc + dv) ** 2 - v_fc**2))
    return q_rev + q_fwd

diode_current ¤

diode_current(
    v: Any,
    *,
    is_A_per_m: float = 1e-08,
    ideality: float = 1.0,
    vt: float = 0.025852,
    v_limit: float = 0.9,
    dark_current_A_per_m: float = 0.0,
    dark_bias_V: float = -1.0
) -> Any

Diode current per metre: Shockley equation plus a dark-current shunt.

I = is*(exp(v/(ideality*vt)) - 1) - dark_current * v / dark_bias_V. The second term is an ohmic leakage sized so that it carries dark_current_A_per_m at the reverse bias dark_bias_V (negative), in addition to the saturation current. The exponential is replaced by its tangent above v_limit so the current stays finite during Newton iterations.

Source code in circulax/components/phase_shifter.py
def diode_current(
    v: Any,
    *,
    is_A_per_m: float = 1.0e-8,
    ideality: float = 1.0,
    vt: float = 0.025852,
    v_limit: float = 0.9,
    dark_current_A_per_m: float = 0.0,
    dark_bias_V: float = -1.0,
) -> Any:
    """Diode current per metre: Shockley equation plus a dark-current shunt.

    ``I = is*(exp(v/(ideality*vt)) - 1) - dark_current * v / dark_bias_V``.
    The second term is an ohmic leakage sized so that it carries
    ``dark_current_A_per_m`` at the reverse bias ``dark_bias_V`` (negative),
    in addition to the saturation current. The exponential is replaced by its
    tangent above ``v_limit`` so the current stays finite during Newton
    iterations.
    """
    n_vt = ideality * vt
    e = jnp.exp(jnp.minimum(v, v_limit) / n_vt)
    shockley = is_A_per_m * (e * (1.0 + jnp.maximum(v - v_limit, 0.0) / n_vt) - 1.0)
    return shockley - dark_current_A_per_m * v / dark_bias_V

hybrid_laser_netlist ¤

hybrid_laser_netlist(
    p: LaserParameters,
    s: HybridSettings = DEFAULT_HYBRID_SETTINGS,
    *,
    segments: int = 4,
    left_reflector: object = None,
    right_reflector: object = None
) -> tuple[dict, dict]

Editable cavity netlist and model map, without drives or terminations.

Left output--SG_L--interface--gain cells--interface--phase--SG_R--right output. All gain diodes share anode/cathode. Reflector and phase heaters are separate electrical ports. Either reflector can be a compatible component or compiled Circuit with ports p1,p2,heater,heater_return, e.g. ring_reflector(). Its settings are then caller-owned; SG threshold helpers no longer apply. A replacement uses p1 facing the cavity and p2 facing the exterior. p.r_left/r_right belong to the older integrated model and are ignored; the separate reflector components own all reflection/transmission physics.

Source code in circulax/components/hybrid_laser.py
def hybrid_laser_netlist(
    p: LaserParameters,
    s: HybridSettings = DEFAULT_HYBRID_SETTINGS,
    *,
    segments: int = 4,
    left_reflector: object = None,
    right_reflector: object = None,
) -> tuple[dict, dict]:
    """Editable cavity netlist and model map, without drives or terminations.

    Left output--SG_L--interface--gain cells--interface--phase--SG_R--right output.
    All gain diodes share anode/cathode. Reflector and phase heaters are separate
    electrical ports. Either reflector can be a compatible component or compiled
    Circuit with ports p1,p2,heater,heater_return, e.g. ring_reflector(). Its
    settings are then caller-owned; SG threshold helpers no longer apply.
    A replacement uses p1 facing the cavity and p2 facing the exterior.
    p.r_left/r_right belong to the older integrated model and are ignored;
    the separate reflector components own all reflection/transmission physics.
    """
    if not isinstance(segments, int) or segments < 1:
        msg = "segments must be a positive integer"
        raise ValueError(msg)
    gain_settings = {key: value for key, value in p._asdict().items() if key not in {"r_left", "r_right"}}
    gain_settings["length_m"] = p.length_m / segments
    instances = {
        "SG_L": {"component": "grating", "settings": grating_settings(p, s, "left")},
        "SG_R": {"component": "grating", "settings": grating_settings(p, s, "right")},
        "CHIP_L": {"component": "interface", "settings": {"power_loss_db": s.interface_loss_db}},
        "CHIP_R": {"component": "interface", "settings": {"power_loss_db": s.interface_loss_db}},
        "PHASE": {
            "component": "phase",
            "settings": {"length_m": s.phase_length_m, "group_index": s.passive_group_index, "phase_per_k": s.phase_per_k},
        },
        **{f"GAIN{j}": {"component": "gain", "settings": gain_settings.copy()} for j in range(segments)},
    }
    chain = ["SG_L", "CHIP_L", *(f"GAIN{j}" for j in range(segments)), "CHIP_R", "PHASE", "SG_R"]
    connections = {f"{a},p2": f"{b},p1" for a, b in pairwise(chain)}
    if segments > 1:
        for terminal in ("anode", "cathode"):
            connections[f"GAIN0,{terminal}"] = tuple(f"GAIN{j},{terminal}" for j in range(1, segments))
    connections["PHASE,heater_return"] = ("SG_L,heater_return", "SG_R,heater_return")
    ports = {
        "p1": "SG_L,p1",
        "p2": "SG_R,p2",
        "anode": "GAIN0,anode",
        "cathode": "GAIN0,cathode",
        "heater_left": "SG_L,heater",
        "heater_right": "SG_R,heater",
        "heater_phase": "PHASE,heater",
        "heater_return": "PHASE,heater_return",
    }
    models = {
        "grating": sampled_bragg_grating(s.samples),
        "interface": OpticalInterface,
        "phase": ThermoOpticPhaseShifter,
        "gain": TravelingWaveGainCell,
    }
    if left_reflector is not None:
        models["left_feedback"] = left_reflector
        instances["SG_L"] = {"component": "left_feedback"}
        del connections["SG_L,p2"]
        connections["SG_L,p1"] = "CHIP_L,p1"
        ports["p1"] = "SG_L,p2"
    if right_reflector is not None:
        models["right_feedback"] = right_reflector
        instances["SG_R"] = {"component": "right_feedback"}
    return {"instances": instances, "connections": connections, "ports": ports}, models

junction_model ¤

junction_model(
    *,
    current: VoltageFunction | float | None = None,
    charge: VoltageFunction | None = None,
    capacitance: VoltageFunction | float | None = None,
    defaults: dict[str, float] | None = None
) -> JunctionModel

Build a junction model from functions of voltage, per metre of length.

Parameters:

Name Type Description Default
current VoltageFunction | float | None

DC current in A/m, anode to cathode, e.g. :func:diode_current.

None
charge VoltageFunction | None

Stored charge in C/m, e.g. :func:depletion_charge or :func:charge_from_capacitance_table.

None
capacitance VoltageFunction | float | None

Alternative to charge: capacitance in F/m, integrated from 0 V with 16-point Gauss-Legendre quadrature. Must be smooth over the voltages used.

None
defaults dict[str, float] | None

Replacement defaults for keyword parameters of the functions.

None

Functions take the junction voltage v = V_anode - V_cathode first and may declare keyword parameters with numeric defaults; those become runtime parameters wherever the model is used.

Source code in circulax/components/phase_shifter.py
def junction_model(
    *,
    current: VoltageFunction | float | None = None,
    charge: VoltageFunction | None = None,
    capacitance: VoltageFunction | float | None = None,
    defaults: dict[str, float] | None = None,
) -> JunctionModel:
    """Build a junction model from functions of voltage, per metre of length.

    Args:
        current: DC current in A/m, anode to cathode, e.g. :func:`diode_current`.
        charge: Stored charge in C/m, e.g. :func:`depletion_charge` or
            :func:`charge_from_capacitance_table`.
        capacitance: Alternative to ``charge``: capacitance in F/m, integrated
            from 0 V with 16-point Gauss-Legendre quadrature. Must be smooth
            over the voltages used.
        defaults: Replacement defaults for keyword parameters of the functions.

    Functions take the junction voltage ``v = V_anode - V_cathode`` first and
    may declare keyword parameters with numeric defaults; those become
    runtime parameters wherever the model is used.

    """
    if charge is not None and capacitance is not None:
        msg = "Supply either charge or capacitance, not both"
        raise ValueError(msg)
    current_fn, current_params = _as_function(current, "current")
    if capacitance is not None:
        cap_fn, charge_params = _as_function(capacitance, "capacitance")
        gauss_x, gauss_w = jnp.asarray(_GAUSS_X), jnp.asarray(_GAUSS_W)

        def charge_fn(v: Any, **kw: Any) -> Any:
            half = 0.5 * v
            return half * jnp.sum(gauss_w * cap_fn(half * (gauss_x + 1.0), **kw))

    else:
        charge_fn, charge_params = _as_function(charge, "charge")

    if defaults:
        known = {p.name for p in (*current_params, *charge_params)}
        unknown = set(defaults) - known
        if unknown:
            msg = f"defaults: unknown parameters {sorted(unknown)}; available: {sorted(known)}"
            raise ValueError(msg)
        current_params = [p.replace(default=float(defaults.get(p.name, p.default))) for p in current_params]
        charge_params = [p.replace(default=float(defaults.get(p.name, p.default))) for p in charge_params]
    return JunctionModel(current_fn, current_params, charge_fn, charge_params)

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,
    )

phase_shifter_factory ¤

phase_shifter_factory(
    *,
    delta_neff: VoltageFunction | float,
    loss_dB_cm: VoltageFunction | float = 0.0,
    junction: JunctionModel | None = None,
    name: str = "PhaseShifter"
) -> type[CircuitComponent]

Build an electro-optic phase shifter component from functions of voltage.

The optical inputs are functions of the voltage v = Re(V_anode - V_cathode) (or constants). Functions must be JAX-traceable and may declare extra keyword parameters with numeric defaults, for example def delta_neff(v, a1=1e-4, a2=1e-5): .... Those parameters, and the junction's, become runtime parameters of the returned component, shared by name, so they can be set in netlist settings, swept or fitted.

Parameters:

Name Type Description Default
delta_neff VoltageFunction | float

Change in optical effective index, dimensionless. By convention it increases under reverse bias (v < 0) in a depletion junction, where carriers are removed. Use :func:delta_neff_from_vpil for VπL data, :func:tabulated for a Δn_eff(V) table (for example from a 2D carrier/mode solve), or any function of v.

required
loss_dB_cm VoltageFunction | float

Optical propagation loss in dB/cm.

0.0
junction JunctionModel | None

Electrical model from :func:pn_diode or :func:junction_model. None leaves the electrodes unloaded, as for a Pockels (e.g. thin-film lithium niobate) modulator with no junction, whose electrode capacitance belongs in the RF line.

None
name str

Class name of the generated component.

'PhaseShifter'

Returns:

Type Description
type[CircuitComponent]

A component class with ports ("anode", "cathode", "o1", "o2") and

type[CircuitComponent]

runtime parameters length_um, neff (index where

type[CircuitComponent]

delta_neff is zero), n_group, wavelength_nm plus the

type[CircuitComponent]

keyword parameters of the supplied functions.

Optical model: the section is a matched, reciprocal 1 Ω waveguide. Light takes length_um * n_group / c to cross it in either direction. The voltage-dependent transmission T(v) = 10**(-loss_dB_cm(v)*L_cm/20) * exp(-2j*pi*(neff + delta_neff(v))*L/λ) is applied at the section midpoint using the junction voltage half a transit earlier, which is when the light passed it. Model a long traveling-wave electrode as several short sections so the RF voltage is approximately uniform along each. Transient analysis reads each delay by interpolating accepted history; when the half-transit of a section is shorter than the time step, that error accumulates along a chain of sections, so check convergence by reducing the step.

Electrical model: the anode receives length * junction.current(v) and the junction stores length * junction.charge(v). Series resistance and electrode loading are external; connect them in the netlist.

Example, a depletion PN phase shifter from VπL and loss tables::

diode = pn_diode(cj0_F_per_m=3e-10, dark_current_A_per_m=1e-5)
diode.capacitance([-2.0, -1.0, 0.0])  # evaluate the junction alone
PN = phase_shifter_factory(
    delta_neff=delta_neff_from_vpil(v_data, vpil_data, wavelength_nm=1310.0),
    loss_dB_cm=tabulated(v_data, loss_data),
    junction=diode,
)
# The diode parameters (cj0_F_per_m, vbi, ...) are settings of every "PN" instance.
Source code in circulax/components/phase_shifter.py
def phase_shifter_factory(
    *,
    delta_neff: VoltageFunction | float,
    loss_dB_cm: VoltageFunction | float = 0.0,
    junction: JunctionModel | None = None,
    name: str = "PhaseShifter",
) -> type[CircuitComponent]:
    """Build an electro-optic phase shifter component from functions of voltage.

    The optical inputs are functions of the voltage ``v = Re(V_anode -
    V_cathode)`` (or constants). Functions must be JAX-traceable and may
    declare extra keyword parameters with numeric defaults, for example
    ``def delta_neff(v, a1=1e-4, a2=1e-5): ...``. Those parameters, and the
    junction's, become runtime parameters of the returned component, shared
    by name, so they can be set in netlist settings, swept or fitted.

    Args:
        delta_neff: Change in optical effective index, dimensionless. By
            convention it increases under reverse bias (``v < 0``) in a
            depletion junction, where carriers are removed. Use
            :func:`delta_neff_from_vpil` for VπL data, :func:`tabulated` for
            a Δn_eff(V) table (for example from a 2D carrier/mode solve), or
            any function of ``v``.
        loss_dB_cm: Optical propagation loss in dB/cm.
        junction: Electrical model from :func:`pn_diode` or
            :func:`junction_model`. ``None`` leaves the electrodes unloaded,
            as for a Pockels (e.g. thin-film lithium niobate) modulator with
            no junction, whose electrode capacitance belongs in the RF line.
        name: Class name of the generated component.

    Returns:
        A component class with ports ``("anode", "cathode", "o1", "o2")`` and
        runtime parameters ``length_um``, ``neff`` (index where
        ``delta_neff`` is zero), ``n_group``, ``wavelength_nm`` plus the
        keyword parameters of the supplied functions.

    Optical model: the section is a matched, reciprocal 1 Ω waveguide. Light
    takes ``length_um * n_group / c`` to cross it in either direction. The
    voltage-dependent transmission
    ``T(v) = 10**(-loss_dB_cm(v)*L_cm/20) * exp(-2j*pi*(neff + delta_neff(v))*L/λ)``
    is applied at the section midpoint using the junction voltage half a
    transit earlier, which is when the light passed it. Model a long
    traveling-wave electrode as several short sections so the RF voltage is
    approximately uniform along each. Transient analysis reads each delay by
    interpolating accepted history; when the half-transit of a section is
    shorter than the time step, that error accumulates along a chain of
    sections, so check convergence by reducing the step.

    Electrical model: the anode receives ``length * junction.current(v)`` and
    the junction stores ``length * junction.charge(v)``. Series resistance
    and electrode loading are external; connect them in the netlist.

    Example, a depletion PN phase shifter from VπL and loss tables::

        diode = pn_diode(cj0_F_per_m=3e-10, dark_current_A_per_m=1e-5)
        diode.capacitance([-2.0, -1.0, 0.0])  # evaluate the junction alone
        PN = phase_shifter_factory(
            delta_neff=delta_neff_from_vpil(v_data, vpil_data, wavelength_nm=1310.0),
            loss_dB_cm=tabulated(v_data, loss_data),
            junction=diode,
        )
        # The diode parameters (cj0_F_per_m, vbi, ...) are settings of every "PN" instance.

    """
    if junction is not None and not isinstance(junction, JunctionModel):
        msg = "junction must be a JunctionModel from pn_diode() or junction_model()"
        raise TypeError(msg)
    dn_fn, dn_params = _as_function(delta_neff, "delta_neff")
    loss_fn, loss_params = _as_function(loss_dB_cm, "loss_dB_cm")
    merged = _merge(dn_params, loss_params, junction.parameters if junction is not None else ())

    def physics(signals: Signals, **kw: Any) -> PhysicsReturn:
        length_um, wavelength_nm = kw["length_um"], kw["wavelength_nm"]
        past = signals.at_delay(length_um * kw["n_group"] / (2.0 * C_UM_PER_S))
        v_mid = jnp.real(past.anode - past.cathode)
        neff = kw["neff"] + dn_fn(v_mid, **_keywords(dn_params, kw))
        loss_db = loss_fn(v_mid, **_keywords(loss_params, kw)) * length_um * 1e-4
        transmission = 10.0 ** (-loss_db / 20.0) * jnp.exp(-2j * jnp.pi * neff * length_um * 1e3 / wavelength_nm)
        b1 = transmission * past.m_reverse
        b2 = transmission * past.m_forward
        f = {
            "o1": signals.a_forward - b1,
            "o2": signals.a_reverse - b2,
            "a_forward": signals.o1 - signals.a_forward - b1,
            "a_reverse": signals.o2 - signals.a_reverse - b2,
            "m_forward": signals.m_forward - past.a_forward,
            "m_reverse": signals.m_reverse - past.a_reverse,
        }
        q = {}
        if junction is not None:
            v_now = jnp.real(signals.anode - signals.cathode)
            length_m = length_um * 1e-6
            current = length_m * junction.current_per_m(v_now, kw)
            charge = length_m * junction.charge_per_m(v_now, kw)
            f["anode"], f["cathode"] = current, -current
            q["anode"], q["cathode"] = charge, -charge
        return f, q

    _set_signature(physics, name, _RUNTIME_DEFAULTS, tuple(merged.values()))
    return component(
        ports=("anode", "cathode", "o1", "o2"),
        states=("a_forward", "a_reverse", "m_forward", "m_reverse"),
    )(physics)

pn_diode ¤

pn_diode(**defaults: float) -> JunctionModel

PN diode per metre: :func:diode_current plus :func:depletion_charge.

Keyword arguments replace parameter defaults, for example pn_diode(cj0_F_per_m=4e-10, vbi=0.8, dark_current_A_per_m=1e-5). Parameters: is_A_per_m, ideality, vt, v_limit, dark_current_A_per_m, dark_bias_V (negative), cj0_F_per_m, vbi, grading and fc.

Source code in circulax/components/phase_shifter.py
def pn_diode(**defaults: float) -> JunctionModel:
    """PN diode per metre: :func:`diode_current` plus :func:`depletion_charge`.

    Keyword arguments replace parameter defaults, for example
    ``pn_diode(cj0_F_per_m=4e-10, vbi=0.8, dark_current_A_per_m=1e-5)``.
    Parameters: ``is_A_per_m``, ``ideality``, ``vt``, ``v_limit``,
    ``dark_current_A_per_m``, ``dark_bias_V`` (negative), ``cj0_F_per_m``,
    ``vbi``, ``grading`` and ``fc``.
    """
    if defaults.get("dark_bias_V", -1.0) >= 0:
        msg = "dark_bias_V must be a negative (reverse) bias"
        raise ValueError(msg)
    return junction_model(current=diode_current, charge=depletion_charge, defaults=defaults)

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")

ring_reflector cached ¤

ring_reflector(*, length_m: float = 0.0004, power_coupling: float = 0.2) -> Circuit

Ring drop port followed by a mirror: a replaceable spectral reflector.

Through/add ports are matched; drop sees a frequency-flat lossless mirror. p1 faces the cavity, p2 is the transmitted mirror output. This deliberately has a different spectrum and loss budget from a sampled Bragg reflector.

Source code in circulax/components/hybrid_laser.py
@lru_cache(maxsize=16)
def ring_reflector(*, length_m: float = 400e-6, power_coupling: float = 0.2) -> Circuit:
    """Ring drop port followed by a mirror: a replaceable spectral reflector.

    Through/add ports are matched; drop sees a frequency-flat lossless mirror.
    p1 faces the cavity, p2 is the transmitted mirror output. This deliberately
    has a different spectrum and loss budget from a sampled Bragg reflector.
    """
    from circulax import compile_circuit

    ring = add_drop_ring(length_m=length_m, power_coupling=power_coupling)
    ring_model = "ring_" + sha256(repr((length_m, power_coupling)).encode()).hexdigest()[:16]
    net = {
        "instances": {
            "RING": {"component": ring_model},
            "M": {"component": "mirror", "settings": {"amplitude_reflection": 0.9}},
            "THROUGH": {"component": "ring_load"},
            "ADD": {"component": "ring_load"},
        },
        "connections": {
            "RING,drop": "M,p1",
            "RING,through": "THROUGH,p1",
            "RING,add": "ADD,p1",
        },
        "ports": {"p1": "RING,input", "p2": "M,p2", "heater": "RING,heater", "heater_return": "RING,heater_return"},
    }
    return compile_circuit(
        net,
        {ring_model: ring, "mirror": OpticalInterface, "ring_load": MatchedOpticalLoad},
        is_complex=True,
        backend="klu",
        g_leak=0,
    )

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])),
    )

sampled_bragg_grating cached ¤

sampled_bragg_grating(samples: int = 5) -> type[CircuitComponent]

Lossless thin-patch sampled-grating approximation with causal gap delays.

Identical zero-length Bragg patches have r=itanh(strength/samples), t=sech(strength/samples). Delayed gaps retain all multiple reflections. Peak power reflectance=tanh(strength)^2; comb FSR=c/(2n_g*spacing). Finite patch bandwidth/dispersion is omitted: qualify a finite wavelength window near the reference. Increasing samples changes the physical device; it is not numerical mesh refinement of the same grating.

Source code in circulax/components/laser_sections.py
@lru_cache(maxsize=16)
def sampled_bragg_grating(samples: int = 5) -> type[CircuitComponent]:
    """Lossless thin-patch sampled-grating approximation with causal gap delays.

    Identical zero-length Bragg patches have r=i*tanh(strength/samples),
    t=sech(strength/samples). Delayed gaps retain all multiple reflections.
    Peak power reflectance=tanh(strength)^2; comb FSR=c/(2*n_g*spacing).
    Finite patch bandwidth/dispersion is omitted: qualify a finite wavelength
    window near the reference. Increasing samples changes the physical device;
    it is not numerical mesh refinement of the same grating.
    """
    if not isinstance(samples, int) or samples < 2:
        msg = "samples must be an integer >= 2"
        raise ValueError(msg)
    states = ("a1", "a2", "temperature", *(f"{d}{j}" for j in range(samples) for d in ("f", "b")))

    @component(ports=("p1", "p2", "heater", "heater_return"), states=states, holomorphic=False)
    def SampledBraggGrating(
        signals: Signals,
        spacing_m: float = 187.37028625e-6,
        group_index: float = 4.0,
        strength: float = 0.9,
        center_m: float = 1540e-9,
        shift_m_per_k: float = 0.08e-9,
        reference_m: float = 1540e-9,
        frame_offset_rad_s: float = 0.0,
        heater_resistance_ohm: float = 100.0,
        thermal_resistance_k_per_w: float = 200.0,
        thermal_tau_s: float = 1e-6,
    ) -> PhysicsReturn:
        """Two optical scattering ports and a real resistive thermal control."""
        tau = spacing_m * group_index / LIGHT_SPEED
        past = signals.at_delay(tau)
        center = mirror_detuning(center_m, shift_m_per_k, jnp.real(signals.temperature), reference_m)
        gap = jnp.exp(1j * (center - frame_offset_rad_s) * tau)
        r = 1j * jnp.tanh(strength / samples)
        t = 1 / jnp.cosh(strength / samples)
        f = _waves(signals, signals.b0, getattr(signals, f"f{samples - 1}"))
        for j in range(samples):
            u = signals.a1 if j == 0 else gap * getattr(past, f"f{j - 1}")
            v = signals.a2 if j == samples - 1 else gap * getattr(past, f"b{j + 1}")
            f[f"f{j}"] = getattr(signals, f"f{j}") - (t * u + r * v)
            f[f"b{j}"] = getattr(signals, f"b{j}") - (r * u + t * v)
        current, ft, qt = thermal_terms(
            signals.heater - signals.heater_return,
            signals.temperature,
            heater_resistance_ohm,
            thermal_resistance_k_per_w,
            thermal_tau_s,
        )
        f.update(heater=current, heater_return=-current, temperature=ft)
        return f, {"temperature": qt}

    return SampledBraggGrating

tabulated ¤

tabulated(voltages: ArrayLike, values: ArrayLike) -> VoltageFunction

Return a piecewise-linear function of voltage from a sampled table.

Use it for delta_neff, loss_dB_cm or a junction current when data is tabulated. Values are held constant outside the table. For a measured capacitance table use :func:charge_from_capacitance_table instead, which integrates exactly and keeps the capacitance continuous.

Source code in circulax/components/phase_shifter.py
def tabulated(voltages: ArrayLike, values: ArrayLike) -> VoltageFunction:
    """Return a piecewise-linear function of voltage from a sampled table.

    Use it for ``delta_neff``, ``loss_dB_cm`` or a junction ``current`` when
    data is tabulated. Values are held constant outside the table. For a measured
    capacitance table use :func:`charge_from_capacitance_table` instead, which
    integrates exactly and keeps the capacitance continuous.
    """
    v, y = _table(voltages, values, "tabulated")
    v_j, y_j = jnp.asarray(v), jnp.asarray(y)

    def table(voltage: Any) -> Any:
        return jnp.interp(voltage, v_j, y_j)

    return table