Tidy3D first walkthrough#

Run this notebook in your browser using Binder.

Our first tutorial focuses on illustrating the basic setup, run, and analysis of a Tidy3D simulation. In this example, we will simulate a plane wave impinging on dielectric slab with a triangular pillar made of a lossy dielectric sitting on top. First, we import everything needed.

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

# tidy3d imports
import tidy3d as td
from tidy3d import web

First, we initialize some general simulation parameters. We note that the PML layers extend beyond the simulation domain, making the total simulation size larger - as opposed to some solvers in which the PML is covering part of the user-defined simulation domain.

# Simulation domain size (in micron)
sim_size = [4, 4, 4]

# Central frequency and bandwidth of pulsed excitation, in Hz
freq0 = 2e14
fwidth = 1e13

# pad the z direction (out of plane) with PML but leave it off x and y for periodic boundary conditions.
pml_layers = (None, None, td.PML())

The run time of a simulation depends a lot on whether there are any long-lived resonances. In our example here, there is no strong resonance. Thus, we do not need to run the simulation much longer than after the sources have decayed. We thus set the run time based on the source bandwidth.

# Total time to run in seconds
run_time = 2/fwidth

Structures and materials#

Next, we initialize the simulated structure. The structure consists of two Structure objects. Each object consists of a Geometry and a Medium to define the spatial extent and material properties, respectively. Note that the size of any object (structure, source, or monitor) can extend beyond the simulation domain, and is truncated at the edges of that domain.

Note: For best results, structures that intersect with the PML or simulation edges should extend extend all the way through. In many such cases, an “infinite” size td.inf can be used to define the size along that dimension.

# Lossless dielectric specified directly using relative permittivity
material1 = td.Medium(permittivity=6.)

# Lossy dielectric defined from the real and imaginary part of the refractive index
material2 = td.Medium.from_nk(n=1.5, k=0.0, freq=freq0)
# material2 = td.Medium(permittivity=2.)

# Rectangular slab, extending infinitely in x and y with medium `material1`
box = td.Structure(
    geometry=td.Box(center=[0, 0, 0], size=[td.inf, td.inf, 1]),

# Triangle in the xy-plane with a finite extent in z
equi_tri_verts = [[-1/2, -1/4],
                  [1/2, -1/4],
                  [0, np.sqrt(3)/2 - 1/4]]

poly = td.Structure(
        # vertices=equi_tri_verts,
        slab_bounds=(.5, 1.0),


Next, we define a source injecting a normal-incidence plane-wave from above. The time dependence of the source is a Gaussian pulse. A source can be added to multiple simulations. After we add the source to a specific simulation, such that the total run time is known, we can use in-built plotting tools to visualize its time- and frequency-dependence, which we will show below.

psource = td.PlaneWave(
    size=(td.inf, td.inf, 0),
    source_time = td.GaussianPulse(


Finally, we can also add some monitors that will record the fields that we request during the simulation run.

The two monitor types for measuring fields are FieldMonitor and FieldTimeMonitor, which record the frequency-domain and time-domain fields, respectively.

FieldMonitor objects operate by running a discrete Fourier transform of the fields at a given set of frequencies to perform the calculation “in-place” with the time stepping. FieldMonitor objects are useful for investigating the steady-state field distribution in 2D or even 3D regions of the simulation.

FieldMonitor objects are best used to monitor the time dependence of the fields at a single point, but they can also be used to create “animations” of the field pattern evolution. Because spatially large FieldMonitor objects can lead to a very large amount of data that needs to be stored, an optional start and stop time can be supplied, as well as an interval specifying the amount of time steps between each measurement (default of 1).

# measure time domain fields at center location, measure every 5 time steps
time_mnt = td.FieldTimeMonitor(center=[0, 0, 0], size=[0, 0, 0], interval=5, name='field_time')

# measure the steady state fields at central frequency in the xy plane and the xz plane.
freq_mnt1 = td.FieldMonitor(center=[0, 0, -1], size=[20, 20, 0], freqs=[freq0], name='field1')
freq_mnt2 = td.FieldMonitor(center=[0, 0, 0], size=[20, 0, 20], freqs=[freq0], name='field2')


Now we can initialize the Simulation with all the elements defined above. A nonuniform simulation grid is generated automatically based on a given minimum number of cells per wavelength in each material (10 by default), using the frequencies defined in the source.

# Initialize simulation
sim = td.Simulation(size=sim_size,
                    grid_spec = td.GridSpec.auto(min_steps_per_wvl=20),
                    structures=[box, poly],
                    monitors=[time_mnt, freq_mnt1, freq_mnt2],

We can check the simulation monitors just to make sure everything looks right.

for m in sim.monitors:
╭────────────────── <class 'tidy3d.components.monitor.FieldTimeMonitor'> ───────────────────╮
 :class:`Monitor` that records electromagnetic fields in the time domain.                  
  FieldTimeMonitor(center=(0.0, 0.0, 0.0), type='FieldTimeMonitor', size=(0.0, 0.0,      
  0.0), name='field_time', start=0.0, stop=None, interval=5, fields=['Ex', 'Ey', 'Ez',   
  'Hx', 'Hy', 'Hz'])                                                                     
 bounding_box = Box(center=(0.0, 0.0, 0.0), type='Box', size=(0.0, 0.0, 0.0))              
       bounds = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))                                         
       center = (0.0, 0.0, 0.0)                                                            
       fields = ['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz']                                       
     geometry = Box(center=(0.0, 0.0, 0.0), type='Box', size=(0.0, 0.0, 0.0))              
     interval = 5                                                                          
         name = 'field_time'                                                               
  plot_params = PlotParams(alpha=0.4, edgecolor='orange', facecolor='orange', fill=True,   
                hatch=None, linewidth=3.0, type='PlotParams')                              
         size = (0.0, 0.0, 0.0)                                                            
        start = 0.0                                                                        
         stop = None                                                                       
         type = 'FieldTimeMonitor'                                                         
╭──────────────────── <class 'tidy3d.components.monitor.FieldMonitor'> ─────────────────────╮
 :class:`Monitor` that records electromagnetic fields in the frequency domain.             
  FieldMonitor(center=(0.0, 0.0, -1.0), type='FieldMonitor', size=(20.0, 20.0, 0.0),     
  name='field1', freqs=[200000000000000.0], fields=['Ex', 'Ey', 'Ez', 'Hx', 'Hy',        
 bounding_box = Box(center=(0.0, 0.0, -1.0), type='Box', size=(20.0, 20.0, 0.0))           
       bounds = ((-10.0, -10.0, -1.0), (10.0, 10.0, -1.0))                                 
       center = (0.0, 0.0, -1.0)                                                           
       fields = ['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz']                                       
        freqs = [200000000000000.0]                                                        
     geometry = Box(center=(0.0, 0.0, -1.0), type='Box', size=(20.0, 20.0, 0.0))           
         name = 'field1'                                                                   
  plot_params = PlotParams(alpha=0.4, edgecolor='orange', facecolor='orange', fill=True,   
                hatch=None, linewidth=3.0, type='PlotParams')                              
         size = (20.0, 20.0, 0.0)                                                          
         type = 'FieldMonitor'                                                             
╭──────────────────── <class 'tidy3d.components.monitor.FieldMonitor'> ─────────────────────╮
 :class:`Monitor` that records electromagnetic fields in the frequency domain.             
  FieldMonitor(center=(0.0, 0.0, 0.0), type='FieldMonitor', size=(20.0, 0.0, 20.0),      
  name='field2', freqs=[200000000000000.0], fields=['Ex', 'Ey', 'Ez', 'Hx', 'Hy',        
 bounding_box = Box(center=(0.0, 0.0, 0.0), type='Box', size=(20.0, 0.0, 20.0))            
       bounds = ((-10.0, 0.0, -10.0), (10.0, 0.0, 10.0))                                   
       center = (0.0, 0.0, 0.0)                                                            
       fields = ['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz']                                       
        freqs = [200000000000000.0]                                                        
     geometry = Box(center=(0.0, 0.0, 0.0), type='Box', size=(20.0, 0.0, 20.0))            
         name = 'field2'                                                                   
  plot_params = PlotParams(alpha=0.4, edgecolor='orange', facecolor='orange', fill=True,   
                hatch=None, linewidth=3.0, type='PlotParams')                              
         size = (20.0, 0.0, 20.0)                                                          
         type = 'FieldMonitor'                                                             

Visualization functions#

We can now use the some in-built plotting functions to make sure that we have set up the simulation as we desire.

First, let’s take a look at the source time dependence.

# Visualize source
psource.source_time.plot(np.linspace(0, run_time, 1001))
<Figure size 432x288 with 1 Axes>

And now let’s visualize the simulation.

For this, we will plot three cross sections at z=0.75, y=0, and x=0, respectively.

The relative permittivity of objects is plotted in greyscale.

By default, sources are overlayed in green, monitors in yellow, and PML boundaries in grey.

fig, ax = plt.subplots(1, 3, figsize=(13, 4))
sim.plot_eps(z=0.75, freq=freq0, ax=ax[0]);
sim.plot_eps(y=0.01, freq=freq0, ax=ax[1]);
sim.plot_eps(x=0, freq=freq0, ax=ax[2]);
[16:10:28] INFO     Auto meshing using wavelength 1.4990 defined from        grid_spec.py:466
<Figure size 936x288 with 6 Axes>

Alternatively, we can also plot the structures with a fake color based on the material they are made of.

fig, ax = plt.subplots(1, 3, figsize=(12, 3))
sim.plot(z=0.75, ax=ax[0]);
sim.plot(y=0.01, ax=ax[1]);
sim.plot(x=0, ax=ax[2]);
<Figure size 864x216 with 3 Axes>

Running through the web API#

Now that the simulation is constructed, we can run it using the web API of Tidy3D. First, we submit the project. Note that we can give it a custom name.

task_id = web.upload(sim, task_name='Simulation')
[16:10:29] INFO     Using Tidy3D credentials from stored file                      auth.py:74
[16:10:31] INFO     Uploaded task 'Simulation' with task_id                     webapi.py:120

We can continously monitor the status of the current project, and wait until the run is successful. The monitor function will keep running until either a 'success' or 'error' status is returned.

[16:10:35] INFO     Maximum flex unit cost: 0.20                                webapi.py:253
           INFO     status = queued                                             webapi.py:262
[16:10:46] INFO     status = preprocess                                         webapi.py:274
[16:11:01] INFO     starting up solver                                          webapi.py:278
[16:11:26] INFO     running solver                                              webapi.py:284
           INFO     status = postprocess                                        webapi.py:301
[16:11:40] INFO     status = success                                            webapi.py:307

Loading and analyzing data#

After a successful run, we can download the results and load them into our simulation model. We use the download_results function from our web API, which downloads a single hdf5 file containing all the monitor data, a log file, and a json file defining the original simulation (same as what you’ll get if you run sim.to_json() on the current object). Optionally, you can provide a folder in which to store the files. In the example below, the results are stored in the data/ folder.

sim_data = web.load(task_id, path='data/sim_data.hdf5')

# Show the output of the log file
[16:11:42] INFO     downloading file "monitor_data.hdf5" to                     webapi.py:537
[16:11:43] INFO     loading SimulationData from data/sim_data.hdf5              webapi.py:369
Simulation domain Nx, Ny, Nz: [156, 157, 104]
Applied symmetries: (0, 0, 0)
Number of computational grid points: 2.5472e+06.
Using subpixel averaging: True
Number of time steps: 3.8430e+03
Automatic shutoff factor: 1.00e-05
Time step (s): 5.2068e-17

Compute source modes time (s):     0.0132
Compute monitor modes time (s):    0.0190
Rest of setup time (s):            3.0609

Starting solver...
- Time step    153 / time 7.97e-15s (  4 % done), field decay: 1.00e+00
- Time step    307 / time 1.60e-14s (  8 % done), field decay: 1.00e+00
- Time step    461 / time 2.40e-14s ( 12 % done), field decay: 1.00e+00
- Time step    614 / time 3.20e-14s ( 16 % done), field decay: 1.00e+00
- Time step    768 / time 4.00e-14s ( 20 % done), field decay: 1.00e+00
- Time step    922 / time 4.80e-14s ( 24 % done), field decay: 1.00e+00
- Time step   1076 / time 5.60e-14s ( 28 % done), field decay: 1.00e+00
- Time step   1229 / time 6.40e-14s ( 32 % done), field decay: 1.00e+00
- Time step   1383 / time 7.20e-14s ( 36 % done), field decay: 1.00e+00
- Time step   1528 / time 7.96e-14s ( 39 % done), field decay: 1.00e+00
- Time step   1537 / time 8.00e-14s ( 40 % done), field decay: 1.00e+00
- Time step   1690 / time 8.80e-14s ( 44 % done), field decay: 1.00e+00
- Time step   1844 / time 9.60e-14s ( 48 % done), field decay: 7.18e-01
- Time step   1998 / time 1.04e-13s ( 52 % done), field decay: 2.58e-01
- Time step   2152 / time 1.12e-13s ( 56 % done), field decay: 1.12e-01
- Time step   2305 / time 1.20e-13s ( 60 % done), field decay: 4.16e-02
- Time step   2459 / time 1.28e-13s ( 64 % done), field decay: 9.96e-03
- Time step   2613 / time 1.36e-13s ( 68 % done), field decay: 2.08e-03
- Time step   2766 / time 1.44e-13s ( 72 % done), field decay: 4.92e-04
- Time step   2920 / time 1.52e-13s ( 76 % done), field decay: 1.17e-04
- Time step   3074 / time 1.60e-13s ( 80 % done), field decay: 2.51e-05
- Time step   3228 / time 1.68e-13s ( 84 % done), field decay: 4.93e-06
Field decay smaller than shutoff factor, exiting solver.

Solver time (s):                   1.4008
Post-processing time (s):          0.0679

Visualization functions#

Finally, we can now use the in-built visualization tools to examine the results. Below, we plot the y-component of the field recorded by the two frequency monitors (this is the dominant component since the source is y-polarized).

fig, ax = plt.subplots(1, 2, figsize=(10, 4))
sim_data.plot_field('field1', 'Ey', z=-1.0, ax=ax[0], freq=freq0, val='real');
sim_data.plot_field('field2', 'Ey', y=0.025, ax=ax[1], freq=freq0, val='real');
<Figure size 720x288 with 4 Axes>

Monitor data#

The raw field data can be accessed through indexing by monitor name directly.

For plenty of discussion on accessing and manipulating data, refer to the data visualization tutorial.

mon1_data = sim_data['field1']
<xarray.Tidy3dDataArray (x: 158, y: 159, z: 3, f: 1)>
array([[[[ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j]],

        [[ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j]],

        [[ 3.76341104e-07+1.37481008e-07j],
         [ 2.98652386e-07+8.58909077e-08j],
         [ 2.55527254e-07+1.10070138e-07j]],


        [[ 3.65468090e-07+3.04554500e-09j],
         [ 3.43471661e-07-3.49294274e-08j],
         [ 2.30893499e-07-6.35356279e-08j]],

         [ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j]],

        [[ 2.38725528e-09-9.49622846e-08j],
         [ 1.45188561e-08+5.62374597e-08j],



        [[ 8.94926715e-09+8.48070051e-08j],
         [ 9.77314793e-09-1.98321927e-08j]],

        [[ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j],
         [ 0.00000000e+00+0.00000000e+00j]]]])
  * x        (x) float64 -2.379 -2.348 -2.318 -2.288 ... 2.288 2.318 2.348 2.379
  * y        (y) float64 -2.39 -2.36 -2.33 -2.3 ... 2.266 2.295 2.325 2.354
  * z        (z) float64 -1.108 -1.034 -0.9598
  * f        (f) float64 2e+14
ax = mon1_data.Ez.interp(z=-1).real.plot()
<Figure size 432x288 with 2 Axes>

We can use this raw data for example to also plot the time-domain fields recorded in the FieldTimeMonitor, which look largely like a delayed version of the source input, indicating that no resonant features were excited.

time_data = sim_data['field_time']
fig, ax = plt.subplots(1)
time_data.Ey.interp(x=0, y=0, z=0).plot()
ax.set_ylabel('$E_y(t)$ [V/m]')
<Figure size 432x288 with 1 Axes>

Permittivity data#

We can also query the relative permittivity in the simulation within a volume parameterized by a td.Box. The method Simulation.epsilon(box, coord_key) returns the permittivity within the specified volume.

The coord_key specifies at what locations in the yee cell to evaluate the permittivity at (eg. 'centers', 'Ey', 'Hz', etc.).

volume = td.Box(center=(0,0,0.75), size=(5, 5, 0))

# at Yee cell centers
eps_centers = sim.epsilon(

# at Ex locations in the yee cell
eps_Ex = sim.epsilon(

Return an xarray DataArray containing the complex-valued permittivity values at the Yee cell centers and the “Ex” within the box.

We can then plot or post-process this data as we wish.

f, (ax1, ax2) = plt.subplots(1, 2, tight_layout=True, figsize=(10, 4))

eps_centers.real.plot(x='x', y='y', cmap='Greys', ax=ax1)
eps_Ex.real.plot(x='x', y='y', cmap='Greys', ax=ax2)
ax1.set_title('epsilon_r at centers')
ax2.set_title('epsilon_r at Ex locations')

<Figure size 720x288 with 4 Axes>
[ ]: