Web API#

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

[1]:
import tidy3d as td
[20:11:44] WARNING  This version of Tidy3D was pip installed from the 'tidy3d-beta' repository on   __init__.py:103
                    PyPI. Future releases will be uploaded to the 'tidy3d' repository. From now on,                
                    please use 'pip install tidy3d' instead.                                                       
           INFO     Using client version: 1.9.0rc1                                                  __init__.py:121

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

[20:11:45] INFO     Created task 'webAPI' with task_id 'dc6e200c-f012-4208-a412-2082893d8568'.        webapi.py:120
[20:11:47] INFO     Maximum FlexUnit cost: 0.025                                                      webapi.py:253
           INFO     status = queued                                                                   webapi.py:262
[20:11:50] INFO     status = preprocess                                                               webapi.py:274
[20:11:56] INFO     starting up solver                                                                webapi.py:278
[20:12:02] INFO     running solver                                                                    webapi.py:284
[20:12:04] INFO     status = postprocess                                                              webapi.py:307
[20:12:08] INFO     status = success                                                                  webapi.py:307
           INFO     Billed FlexUnit cost: 0.025                                                       webapi.py:311
           INFO     downloading file "output/monitor_data.hdf5" to "data/sim.hdf5"                    webapi.py:593
[20:12:10] INFO     loading SimulationData from data/sim.hdf5                                         webapi.py:415
           WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    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")

[20:12:34] WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    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")

[20:12:36] WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    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")

[20:12:41] Started working on Batch.                                                               container.py:361
[20:13:25] Batch complete.                                                                         container.py:382

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)

[20:13:27] WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    threshold of 1e-05. Consider simulation again with large run_time duration for                 
                    more accurate results.                                                                         
[20:13:29] WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    threshold of 1e-05. Consider simulation again with large run_time duration for                 
                    more accurate results.                                                                         
[20:13:30] WARNING  Simulation final field decay value of 0.33 is greater than the simulation shutoff webapi.py:421
                    threshold of 1e-05. Consider simulation again with large run_time duration for                 
                    more accurate results.                                                                         
{'sim_0': 13540216.497151697, 'sim_1': 13540216.497151697, 'sim_2': 13540216.497151697}