# EME: S-Bend

An S-bend moves a waveguide sideways. Here a 500 x 220 nm Si wire in SiO2 at 1550 nm is shifted by 2 um with two `bend_section`s of the same radius and opposite `sweep_angle`. The S-bend is solved at several radii, with the two bends joined and with a short straight between them, and compared with an Euler S-bend of the same minimum radius and offset.

Highlighted features: `bend_section` with a signed `sweep_angle`, `bend_section` with a `curvature` profile for an Euler bend, and `plot(view='layout')` drawing the field where the layout places each section.

A bend pushes its mode toward the outside of the curve, so the loss comes from the mode mismatch at each junction, and at the joint between the two bends the mode has to move from one side of the guide to the other. The loss falls quickly as the radius grows. At the tightest radius a short straight between the bends lowers the loss noticeably, since the mode passes through a centered straight mode on its way across. At larger radii the mode barely moves, and the straight makes little difference.

An Euler S-bend has no jump in curvature. A single `bend_section(curvature=[0, 1/R, 0, -1/R, 0], length=4*R*angle)` raises the curvature linearly from zero to 1/R and back while it turns by `angle`, then does the same the other way, and the example solves the angle that gives the same 2 um offset. EMode slices the bend along its length like a taper, each slice solved at its local radius, and the layout follows the integrated curve. Its minimum radius is the circular S-bend’s radius, so it is longer, and its mode moves across the guide gradually instead of at a junction. Here that lowers the loss at every radius: by a factor of eight at 5 um, and at 10 and 20 um to a few parts in a million of the power, the level of the solve’s own error. The gain depends on the ramps being long enough for the mode to follow: at a tight radius and a short ramp the curvature changes faster than the guide’s first-order mode beats against the fundamental, and that mode takes most of what an Euler bend loses, so an Euler bend is not lower loss in every case.

The windows have metal walls and no PML, so the power a junction scatters stays in the window’s modes and the example measures the junction loss, not radiation. A bend tight enough to radiate needs a PML on its outer wall, as in [Bend Mode Solvers](Bend_Solvers.md).

*This code example is licensed under the* [BSD 3-Clause License](../_static/LICENSE.html).

Python

```python
import sys
import time
import numpy as np
import emodeconnection as emc
from matplotlib import pyplot as plt
from scipy.integrate import cumulative_trapezoid, trapezoid
from scipy.optimize import brentq

## An S-bend that shifts a Si wire sideways by 2 um, built from two circular
## bends of opposite curvature. Its loss is compared for three radii, with and
## without a short straight between the two bends, and with an Euler S-bend
## of the same minimum radius and offset.

## Set simulation parameters
wavelength = 1550  # [nm] wavelength
dx, dy = 20, 20  # [nm] resolution
w_core = 500  # [nm] waveguide core width
h_core = 220  # [nm] waveguide core height
h_clad = 1090  # [nm] cladding below and above the core
window_width = 4000  # [nm]
window_height = h_core + 2*h_clad  # [nm]
num_modes = 32  # [-] number of modes

shift = 2000  # [nm] lateral offset of the S-bend
radii = [20000, 10000, 5000]  # [nm] bend radii (the Euler S-bend's minimum), the last is plotted
lead = 1000  # [nm] straight input and output
## The S-bends: two arcs joined, two arcs with a 1 um straight between them,
## and an Euler S-bend
kinds = {'joined arcs': 0, '1 um between': 1000, 'Euler': None}  # [nm] straight between


def euler_s_bend(radius, angle):
    """Lateral offset and z length of an Euler S-bend at minimum radius `radius`.

    Its curvature rises linearly from zero to 1/radius and back while it turns
    by `angle`, then does the same with the opposite sign, so its length is
    4*radius*angle and it has no jump in curvature anywhere.
    """
    length = 4 * radius * angle
    s = np.linspace(0, length, 40001)
    kappa = np.interp(s, np.linspace(0, length, 5), [0, 1 / radius, 0, -1 / radius, 0])
    heading = cumulative_trapezoid(kappa, s, initial=0)
    return trapezoid(np.sin(heading), s), trapezoid(np.cos(heading), s)


def solve_sbends(kind):
    """Solve one kind of S-bend at every radius."""
    straight_length = kinds[kind]
    name = {'joined arcs': 'sbend', '1 um between': 'sbend_straight', 'Euler': 'sbend_euler'}[kind]
    em = emc.EMode(emode_cmd=sys.argv[1:], simulation_name=name)
    em.settings(
        wavelength=wavelength, x_resolution=dx, y_resolution=dy,
        window_width=window_width, window_height=window_height,
        num_modes=num_modes, boundary_condition='00', background_material='SiO2')
    em.shape(name='BOX', material='SiO2', height=h_clad)
    em.shape(name='core', material='Si', height=h_core, etch_depth=h_core, mask=w_core)
    em.label_profile(name='wg')

    rows = []
    for radius in radii:
        em.straight_section(name='input', profile='wg', length=lead)
        if straight_length is None:
            ## One bend_section whose curvature goes 0, 1/R, 0, -1/R, 0 along its
            ## length, turning by `angle` and back. The angle is solved for the offset.
            angle = brentq(lambda a: euler_s_bend(radius, a)[0] - shift, 0.01, 1.5, xtol=1e-12)
            z_length = euler_s_bend(radius, angle)[1]
            em.bend_section(name='euler', profile='wg', length=4 * radius * angle,
                            curvature=[0, 1 / radius, 0, -1 / radius, 0])
        else:
            ## Two arcs of opposite sweep shift the guide by `shift`
            ## over 2*R*sin(angle) along z, plus the straight between them
            angle = np.arccos(1 - shift / (2 * radius))  # [rad]
            z_length = 2 * radius * np.sin(angle) + straight_length
            em.bend_section(name='bend_1', profile='wg', radius=radius, sweep_angle=angle)
            if straight_length > 0:
                em.straight_section(name='middle', profile='wg', length=straight_length)
            em.bend_section(name='bend_2', profile='wg', radius=radius, sweep_angle=-angle)
        em.straight_section(name='output', profile='wg', length=lead)

        start = time.time()
        S = em.EME()
        elapsed = time.time() - start

        ## Transmission of the fundamental mode, and the power that leaves
        ## through every mode of both ports (each mode weighted by its power)
        T = np.abs(S.block('right', 'left')[0, 0]) ** 2
        launched = S.block(['left', 'right'], 'left')[:, 0]
        balance = np.sum(S.mode_power * np.abs(launched) ** 2) / S.mode_power[0]
        rows.append((radius, angle, z_length, T, balance, elapsed))

    if kind != '1 um between':
        ## The field of the tightest S-bend, drawn where the layout places it
        em.plot(component='Ex', plot_function='abs', plane='z-x', view='layout',
                file_name=f'{name}_field', file_type='png')
    em.close()
    return rows


results = {kind: solve_sbends(kind) for kind in kinds}

## Print the loss of every S-bend
print(f'\n{"S-bend":<14s}{"R (um)":>8s}{"angle (rad)":>13s}{"z length (um)":>15s}'
      f'{"T":>10s}{"loss (dB)":>11s}{"power out":>11s}{"time (s)":>10s}')
for kind, rows in results.items():
    for radius, angle, z_length, T, balance, elapsed in rows:
        print(f'{kind:<14s}{radius * 1e-3:>8.1f}{angle:>13.4f}'
              f'{z_length * 1e-3:>15.3f}{T:>10.6f}{-10 * np.log10(T):>11.4f}'
              f'{balance:>11.5f}{elapsed:>10.1f}')

## Plot the loss against the bend radius
plt.figure(figsize=(6, 4.5))
for kind, rows in results.items():
    label = {'joined arcs': 'arcs joined', '1 um between': 'arcs, 1 um straight between',
             'Euler': 'Euler S-bend'}[kind]
    plt.semilogy([r[0] * 1e-3 for r in rows], [-10 * np.log10(r[3]) for r in rows],
                 marker='o', label=label)
plt.xlabel('Bend radius (μm)')
plt.ylabel('S-bend loss (dB)')
plt.title(f'S-bend with a {shift * 1e-3:.0f} μm offset')
plt.legend()
plt.grid(True, which='both', alpha=0.3)
plt.tight_layout()
plt.savefig('sbend_loss_vs_radius.png', dpi=300, bbox_inches='tight')
```

Console output:

```default
EMode3D 1.0.8 - email

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: bend_2... completed in 0.9 sec
Solving section: output... completed in 0.0 sec
 completed in 9.9 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: bend_2... completed in 0.9 sec
Solving section: output... completed in 0.0 sec
 completed in 7.7 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: bend_2... completed in 0.9 sec
Solving section: output... completed in 0.0 sec
 completed in 7.6 sec
Exited EMode
EMode3D 1.0.8 - email

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: middle... completed in 0.0 sec
Solving section: bend_2... completed in 1.0 sec
Solving section: output... completed in 0.0 sec
 completed in 9.7 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: middle... completed in 0.0 sec
Solving section: bend_2... completed in 0.9 sec
Solving section: output... completed in 0.0 sec
 completed in 7.3 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: bend_1... completed in 0.9 sec
Solving section: middle... completed in 0.0 sec
Solving section: bend_2... completed in 0.9 sec
Solving section: output... completed in 0.0 sec
 completed in 7.7 sec
Exited EMode
EMode3D 1.0.8 - email

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: euler... completed in 4 min 33.2 sec
Solving section: output... completed in 0.0 sec
 completed in 4 min 36.0 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: euler... completed in 8 min 9.9 sec
Solving section: output... completed in 0.0 sec
 completed in 8 min 12.6 sec

Solving S-matrices...
Solving section: input... completed in 0.0 sec
Solving section: euler... completed in 13 min 57.3 sec
Solving section: output... completed in 0.0 sec
 completed in 14 min 0.3 sec
Exited EMode

S-bend          R (um)  angle (rad)  z length (um)         T  loss (dB)  power out  time (s)
joined arcs       20.0       0.3176         12.490  0.999871     0.0006    1.00000      13.0
joined arcs       10.0       0.4510          8.718  0.998446     0.0068    0.99999      10.8
joined arcs        5.0       0.6435          6.000  0.997418     0.0112    0.99979      10.7
1 um between      20.0       0.3176         13.490  0.999816     0.0008    1.00000      13.3
1 um between      10.0       0.4510          9.718  0.998411     0.0069    0.99999      10.7
1 um between       5.0       0.6435          7.000  0.998150     0.0080    0.99978      11.3
Euler             20.0       0.2242         17.765  0.999994     0.0000    1.00000     277.8
Euler             10.0       0.3180         12.474  0.999998     0.0000    1.00000     494.2
Euler              5.0       0.4522          8.694  0.999684     0.0014    1.00000     842.3
```

Figures:

![image](examples/Figures/EME_SBend/sbend_loss_vs_radius.png)![image](examples/Figures/EME_SBend/sbend_field.png)![image](examples/Figures/EME_SBend/sbend_euler_field.png)
