Web API#

Run this notebook in your browser using Binder.

This notebook is a tutorial of the API used for submitting simulations to our servers.

[1]:
import tidy3d as td

Setup#

Let’s set up a simple simulation to get started.

[2]:
# set up parameters of simulation
dl = 0.05
pml = td.PML()
sim_size = [4, 4, 4]
freq0 = 3e14
fwidth = 1e13
run_time = 1/fwidth

# create structure
dielectric = td.Medium.from_nk(n=2, k=0, freq=freq0)
square = td.Structure(
    geometry=td.Box(center=[0, 0, 0], size=[1.5, 1.5, 1.5]),
    medium=dielectric)

# create source
source = td.UniformCurrentSource(
    center=(-1.5, 0, 0),
    size=(0, 0.4, 0.4),
    source_time = td.GaussianPulse(
        freq0=freq0,
        fwidth=fwidth),
    polarization='Ex')

# create monitor
monitor = td.FieldMonitor(
    fields=['Ex', 'Ey', 'Ez'],
    center=(0, 0, 0),
    size=(td.inf, td.inf, 0),
    freqs=[freq0],
    name='field')

# Initialize simulation
sim = td.Simulation(
    size=sim_size,
    grid_spec=td.GridSpec.uniform(dl),
    structures=[square],
    sources=[source],
    monitors=[monitor],
    run_time=run_time,
    boundary_spec=td.BoundarySpec.all_sides(boundary=pml),
)

Running simulation manually#

For the most control, you can run the simulation through the Tidy3D web API. Each simulation running on the server is identified by a task_id, which must be specified in the web API. Let’s walk through submitting a simulation this way.

[3]:
import tidy3d.web as web

# upload the simulation to our servers
task_id = web.upload(sim, task_name='webAPI')

# start the simulation running
web.start(task_id)

# monitor the simulation, dont move on to next line until completed.
web.monitor(task_id)

# download the results and load into a simulation data object for plotting, post processing etc.
sim_data = web.load(task_id, path='data/sim.hdf5')
[22:30:41] INFO     Using Tidy3D credentials from stored file                                            auth.py:74
[22:30:44] INFO     Uploaded task 'webAPI' with task_id 'f94362d8-796b-4c35-ab56-94c8cd3c2111'.       webapi.py:117
[22:30:49] INFO     status = queued                                                                   webapi.py:258
[22:30:55] INFO     status = preprocess                                                               webapi.py:270
[22:30:57] INFO     Maximum flex unit cost: 0.10                                                      webapi.py:249
[22:31:03] INFO     starting up solver                                                                webapi.py:274
[22:31:10] INFO     running solver                                                                    webapi.py:280
[22:31:12] INFO     status = postprocess                                                              webapi.py:303
[22:31:17] INFO     status = success                                                                  webapi.py:303
[22:31:18] INFO     downloading file "output/monitor_data.hdf5" to "data/sim.hdf5"                    webapi.py:575
[22:31:24] INFO     loading SimulationData from data/sim.hdf5                                         webapi.py:397
           WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            

While we broke down each of the individual steps above, one can also perform the entire process in one line by calling the web.run() function as follows.

sim_data = web.run(sim, task_name='webAPI', path='data/sim.hdf5')

(We won’t run it again in this notebook to save time).

Sometimes this is more convenient, but other times it can be helpful to have the steps broken down one by one, for example if the simulation is long, you may want to web.start and then exit the session and load the results at a later time using web.load.

Job Container#

The web.Job interface provides a more convenient way to manage single simuations, mainly because it eliminates the need for keeping track of the task_id and original Simulation.

While Job has methods with names identical to the web API functions above, which give some more granular control, it is often most convenient to call [.run()] so we will do that now.

[4]:
# set the logging level to warning to reduce downloading messages.
td.config.logging_level = 'warning'

# initializes job, puts task on server (but doesnt run it)
job = web.Job(simulation=sim, task_name='job')

# start job, monitor, and load results
sim_data = job.run(path='data/sim.hdf5')
[22:32:01] WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            

Another convenient thing about Job objects is that they can be saved and loaded just like other Tidy3d components.

This is convenient if you want to save and load up the results of a job that has already finished, without needing to know the task_id.

[5]:
# saves the job metadata to a single file
job.to_file('data/job.json')

# can exit session, break here, or continue in new session.

# load the job metadata from file
job_loaded = web.Job.from_file('data/job.json')

# download the data from the server and load it into a SimulationData object.
sim_data = job_loaded.load(path='data/sim.hdf5')
[22:32:04] WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            

Batch Processing#

Commonly one needs to submit a batch of Simulations. One way to approach this using the web API is to upload, start, monitor, and load a series of tasks one by one, but this is clumsy and you can lose your data if the session gets interrupted.

A better way is to use the built-in Batch object. The batch object is like a Job, but stores task metadata for a series of simulations.

[6]:
# make a dictionary of  {task name : simulation} for demonstration
sims = {f'sim_{i}': sim for i in range(3)}

# initialize a batch and run them all
batch = web.Batch(simulations=sims)

# run the batch and store all of the data in the `data/` dir.
batch_results = batch.run(path_dir='data')
[22:32:18] Started working on Batch.                                                               container.py:353
[22:32:51] Batch complete.                                                                         container.py:374

When the batch is completed, the output is not a SimulationData but rather a BatchData. The data within this BatchData object can either be indexed directly batch_results[task_name] or can be looped through batch_results.items() to get the SimulationData for each task.

This was chosen to reduce the memory strain from loading all SimulationData objects at once.

Alternatively, the batch can be looped through (several times) using the .items() method, similar to a dictionary.

[7]:
# grab the sum of intensities in the simulation one by one (to save memory)
intensities = {}
for task_name, sim_data in batch_results.items():
    field_data = sim_data.at_centers('field').sel(f=freq0)
    intensity = abs(field_data.Ex)**2 + abs(field_data.Ey)**2 + abs(field_data.Ez)**2
    sum_intensity = float(intensity.sum(('x', 'y')).values)
    intensities[task_name] = sum_intensity

print(intensities)
[22:32:57] WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            
[22:33:02] WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            
[22:33:06] WARNING  Simulation final field decay value of 0.336 is greater than the simulation        webapi.py:403
                    shutoff threshold of 1e-05. Consider simulation again with large run_time                      
                    duration for more accurate results.                                                            
{'sim_0': 12829601.474178102, 'sim_1': 12829601.474178102, 'sim_2': 12829601.474178102}