Parameter scan#


Run this notebook in your browser using Binder.

In this notebook, we will show an example of using tidy3d to evaluate device performance over a set of many design parameters.

This example will also provide a walkthrough of Tidy3D’s Job and Batch features for managing both individual simulations and sets of simulations.

For demonstration, we look at the splitting ratio of a directional coupler as we vary the coupling length between two waveguides. The sidewall of the waveguides is slanted, deviating from the vertical direction by sidewall_angle.

# standard python imports
import numpy as np
import matplotlib.pyplot as plt
import os
import gdspy

# tidy3D imports
import tidy3d as td
from tidy3d import web

# set tidy3d to only print error information to reduce verbosity


First we set up some global parameters

# wavelength / frequency
lambda0 = 1.550                     # all length scales in microns
freq0 = td.constants.C_0 / lambda0
fwidth = freq0 / 10

# Permittivity of waveguide and substrate
wg_n = 3.48
sub_n = 1.45
mat_wg = td.Medium(permittivity=wg_n**2)
mat_sub = td.Medium(permittivity=sub_n**2)

# Waveguide dimensions

# Waveguide height
wg_height = 0.22
# Waveguide width
wg_width = 0.45
# Waveguide separation in the beginning/end
wg_spacing_in = 8
# Angle of the sidewall deviating from the vertical ones, positive values for the base larger than the top
sidewall_angle = np.pi/6
# Total device length along propagation direction
device_length = 100
# Length of the bend region
bend_length = 16
# space between waveguide and PML
pml_spacing = 1
# resolution control: minimum number of grid cells per wavelength in each material
grid_cells_per_wvl = 16

Define waveguide bends and coupler#

Here is where we define our directional coupler shape programmatically in terms of the geometric parameters

def bend_pts(bend_length, width, npts=10):
    """ Set of points describing a tanh bend from (0, 0) to (length, width)"""
    x = np.linspace(0, bend_length, npts)
    y = width*(1 + np.tanh(6*(x/bend_length - 0.5)))/2
    return np.stack((x, y), axis=1)

def arm_pts(length, width, coup_length, bend_length, npts_bend=30):
    """ Set of points defining one arm of an integrated coupler """
    ### Make the right half of the coupler arm first
    # Make bend and offset by coup_length/2
    bend = bend_pts(bend_length, width, npts_bend)
    bend[:, 0] += coup_length / 2
    # Add starting point as (0, 0)
    right_half = np.concatenate(([[0, 0]], bend))
    # Add an extra point to make sure waveguide is straight past the bend
    right_half = np.concatenate((right_half, [[right_half[-1, 0] + 0.1, width]]))
    # Add end point as (length/2, width)
    right_half = np.concatenate((right_half, [[length/2, width]]))

    # Make the left half by reflecting and omitting the (0, 0) point
    left_half = np.copy(right_half)[1:, :]
    left_half[:, 0] = -left_half[::-1, 0]
    left_half[:, 1] = left_half[::-1, 1]

    return np.concatenate((left_half, right_half), axis=0)

def make_coupler(
    """ Make an integrated coupler using the gdspy FlexPath object. """

    # Compute one arm of the coupler
    arm_width = (wg_spacing_in - wg_width - wg_spacing_coup)/2
    arm = arm_pts(length, arm_width, coup_length, bend_length, npts_bend)
    # Reflect and offset bottom arm
    coup_bot = np.copy(arm)
    coup_bot[:, 1] = -coup_bot[::-1, 1] - wg_width/2 - wg_spacing_coup/2
    # Offset top arm
    coup_top = np.copy(arm)
    coup_top[:, 1] += wg_width/2 + wg_spacing_coup/2

    # Create waveguides as GDS paths
    path_bot = gdspy.FlexPath(coup_bot, wg_width, layer=1, datatype=0)
    path_top = gdspy.FlexPath(coup_top, wg_width, layer=1, datatype=1)

    return [path_bot, path_top]

Create Simulation and Submit Job#

The following function creates a tidy3d simulation object for a set of design parameters.

Note that the simulation has not been run yet, just created.

def make_sim(coup_length, wg_spacing_coup, domain_field=False):
    """ Make a simulation with a given length of the coupling region and
    distance between the waveguides in that region. If ``domain_field``
    is True, a 2D in-plane field monitor will be added.

    gdspy.current_library = gdspy.GdsLibrary()
    lib = gdspy.GdsLibrary()

    # Geometry must be placed in GDS cells to import into Tidy3D
    coup_cell = lib.new_cell('Coupler')

    substrate = gdspy.Rectangle(
        (-device_length/2, -wg_spacing_in/2-10),
        (device_length/2, wg_spacing_in/2+10),

    # Add the coupler to a gdspy cell
    gds_coup = make_coupler(

    # Substrate
    [oxide_geo] = td.PolySlab.from_gds(
        slab_bounds=(-10, 0),

    oxide = td.Structure(

    # Waveguides (import all datatypes if gds_dtype not specified)
    coupler1_geo, coupler2_geo = td.PolySlab.from_gds(
        slab_bounds=(0, wg_height),

    coupler1 = td.Structure(

    coupler2 = td.Structure(

    # Simulation size along propagation direction
    sim_length = 2 + 2*bend_length + coup_length

    # Spacing between waveguides and PML
    sim_size = [
        wg_spacing_in + wg_width + 2*pml_spacing,
        wg_height + 2*pml_spacing]

    # source
    src_pos = -sim_length/2 + 0.5
    msource = td.ModeSource(
        center=[src_pos , wg_spacing_in / 2 , wg_height / 2],
        size=[0, 3, 2],
        source_time = td.GaussianPulse(

    mon_in = td.ModeMonitor(
        center=[(src_pos + 0.5), wg_spacing_in / 2, wg_height / 2],
        size=[0, 3, 2],
    mon_ref_bot = td.ModeMonitor(
        center=[(src_pos + 0.5), -wg_spacing_in / 2, wg_height / 2],
        size=[0, 3, 2],
    mon_top = td.ModeMonitor(
        center=[-(src_pos + 0.5), wg_spacing_in / 2, wg_height / 2],
        size=[0, 3, 2],
    mon_bot = td.ModeMonitor(
        center=[-(src_pos + 0.5), -wg_spacing_in / 2, wg_height / 2],
        size=[0, 3, 2],
    monitors = [mon_in, mon_ref_bot, mon_top, mon_bot]

    if domain_field == True:
        domain_monitor = td.FieldMonitor(
            center = [0,0,wg_height/2],
            size = [td.inf, td.inf, 0],
            freqs = [freq0],

    # initialize the simulation
    sim = td.Simulation(
        grid_spec =,
        structures=[oxide, coupler1, coupler2],

    return sim

Inspect Simulation#

Let’s create and inspect a single simulation to make sure it was defined correctly before doing the full scan. The sidewalls of the waveguides deviate from the vertical direction by 30 degree. We also add an in-plane field monitor to have a look at the fields evolution in this one simulation. We will not use such a monitor in the batch to avoid storing unnecesarrily large amounts of data.

# Length of the coupling region
coup_length = 10

# Waveguide separation in the coupling region
wg_spacing_coup = 0.10

sim = make_sim(coup_length, wg_spacing_coup, domain_field=True)
# visualize geometry
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 4))
sim.plot(z=wg_height/2+0.01, ax=ax1);
sim.plot(x=0.1, ax=ax2);
ax2.set_xlim([-3, 3])
<Figure size 1008x288 with 2 Axes>

Create and Submit Job#

The Job object provides an interface for managing simulations.

job = Job(simulation) will create a job and upload the simulation to our server to run.

Then, one may call various methods of job to monitor progress, download results, and get information.

For more information, refer to the API reference.

# create job, upload sim to server to begin running
job = web.Job(simulation=sim, task_name='CouplerVerify')

# download the results and load them into a simulation
sim_data ='data/sim_data.hdf5')


The following function takes a completed simulation (with data loaded into it) and computes the quantities of interest.

For this case, we measure both the total transmission in the right ports and also the ratio of power between the top and bottom ports.

def measure_transmission(sim_data):
    """ Constructs a "row" of the scattering matrix when sourced from top left port """

    input_amp = sim_data['in'].amps.sel(direction='+')

    amps = np.zeros(4, dtype=complex)
    directions = ('-', '-', '+', '+')
    for i, (monitor, direction) in enumerate(zip(sim_data.simulation.monitors[:4], directions)):
        amp = sim_data[].amps.sel(direction=direction)
        amp_normalized = amp / input_amp
        amps[i] = np.squeeze(amp_normalized.values)

    return amps
# monitor and test out the measure_transmission function the results of the single run
amps_arms = measure_transmission(sim_data)
print('mode amplitudes in each port: \n')
for amp, monitor in zip(amps_arms, sim_data.simulation.monitors[:-1]):
    print(f'\tmonitor     = "{}"')
    print(f'\tamplitude^2 = {abs(amp)**2:.2f}')
    print(f'\tphase       = {(np.angle(amp)):.2f} (rad)\n')
mode amplitudes in each port:

        monitor     = "in"
        amplitude^2 = 0.00
        phase       = -1.12 (rad)

        monitor     = "refect_bottom"
        amplitude^2 = 0.00
        phase       = 0.78 (rad)

        monitor     = "top"
        amplitude^2 = 0.97
        phase       = 0.32 (rad)

        monitor     = "bottom"
        amplitude^2 = 0.02
        phase       = 1.89 (rad)

fig, ax = plt.subplots(1, 1, figsize=(16, 3))
# sim_data['field'].Ey.real.interp(z=0).plot()
sim_data.plot_field('field', 'Ey', z=wg_height/2, freq=freq0, ax=ax)
<Figure size 1152x216 with 2 Axes>

1D Parameter Scan#

Now we will scan through the coupling length parameter to see the effect on splitting ratio.

To do this, we will create a list of simulations corresponding to each parameter combination.

We will use this list to create a Batch object, which has similar functionality to Job but allows one to manage a set of jobs.

First, we create arrays to store the input and output values.

# create variables to store parameters, simulation information, results
Nl = 11

ls = np.linspace(5, 12, Nl)
split_ratios = np.zeros(Nl)
efficiencies = np.zeros(Nl)

Create Batch#

We now create our list of simulations and use them to initialize a Batch.

For more information, refer to the API reference.

# submit all jobs
sims = {f'l={l:.2f}' : make_sim(l, wg_spacing_coup) for l in ls}
batch = web.Batch(simulations=sims)

Monitor Batch#

Here we can perform real-time monitoring of how many of the jobs in the batch have completed.

batch_results ='data')
[16:25:21] Started working on Batch.                               
[16:40:46] Batch complete.                                         

Load and visualize Reults#

Finally, we can compute the output quantities and load them into the arrays we created initally.

Then we may plot the results.

amps_batch = []
for task_name, sim_data in batch_results.items():
    amps_arms_i = np.array(measure_transmission(sim_data))
amps_batch = np.stack(amps_batch, axis=1)
print(amps_batch.shape) # (4, num_freqs)
(4, 11)
[[ 1.18382672e-02-2.04873540e-02j  6.06200628e-03-1.90360822e-02j
   1.04302320e-02-2.16651006e-02j  1.71161918e-02-1.42609694e-02j
   1.19803181e-02-2.60690029e-02j  7.94478913e-03-1.02238803e-02j
   2.34377016e-02-2.30585080e-02j  4.94122162e-04-2.11650775e-02j
   1.60262481e-02-1.03149647e-02j  1.21988534e-02-2.55425273e-02j
 [ 7.62878664e-03+3.16861453e-03j  9.14585920e-04-8.40127560e-03j
  -2.13963729e-03+1.39599917e-02j  6.74595887e-03-6.21571269e-03j
  -7.61138393e-03+1.91425097e-03j  9.13429864e-03+5.44624199e-03j
  -4.12639842e-03+1.62042779e-03j  1.22217378e-03-9.16074091e-04j
   1.22934069e-03+2.64548921e-03j  4.32269893e-03+1.32600815e-05j
 [-3.39532261e-01+4.79388365e-01j  4.22786416e-01+5.59005767e-01j
   7.52464732e-01-2.68144178e-01j -3.47555954e-02-8.77998349e-01j
  -9.06973844e-01-2.42912365e-01j -5.20832584e-01+8.27463396e-01j
   6.34991781e-01+7.65015851e-01j  9.14774206e-01-3.72186710e-01j
  -7.47372022e-02-9.55338761e-01j -8.84829650e-01-1.98340170e-01j
 [ 6.52465723e-01+4.64905931e-01j  5.61980278e-01-4.23264859e-01j
  -1.97028034e-01-5.56229331e-01j -4.63392735e-01+1.75976168e-02j
  -8.48484012e-02+3.15272953e-01j  1.53561422e-01+9.66980209e-02j
   2.44169415e-02-2.04218452e-02j  4.44920840e-02+1.10167880e-01j
   2.65748494e-01-2.06604601e-02j  8.90194527e-02-3.97862554e-01j
powers = abs(amps_batch)**2
power_top = powers[2]
power_bot = powers[3]
power_out = power_top + power_bot
plt.plot(ls, 100*power_top, label='% in top port')
plt.plot(ls, 100*power_bot, label='% in bottom port')
plt.plot(ls, 100*power_out, label='% power transmitted to output ports')
plt.plot(ls, 100*np.ones_like(ls), '--', label='unity (100%)')
plt.xlabel('coupling length (um)')
plt.ylabel('splitting ratio (%)')
plt.ylim(0, 110)
<Figure size 432x288 with 1 Axes>

Final Remarks#

Batches provide some other convenient functionality for managing large numbers of jobs.

For example, one can save the batch information to file and load the batch at a later time, if needing to disconnect from the service while the jobs are running.

# save batch metadata

# load batch metadata into a new batch
loaded_batch = web.Batch.from_file('data/batch_data.json')

For more reference, refer to our documentation.

[ ]: