Photonic crystal slab band structure calculation#

In this notebook, we simulate a photonic crystal slab consisting of a square lattice of air holes in a dielectric slab. Our goal is to compute the band structure of this photonic crystal slab, as found in:

Shanhui Fan and J. D. Joannopoulos, “Analysis of guided resonances in photonic crystal slabs,” Phys. Rev. B 65, 235112 (2002).

To this end, we excite the structure with several PointDipole sources, and we measure the response with several FieldTimeMonitor monitors. We excite modes with a fixed Bloch wavevector by using Bloch boundary conditions. We then use the ResonanceFinder to find the resonant frequencies. By sweeping the Bloch wavevector, we obtain the full band structure of the photonic crystal slab.

See also the api reference for ResonanceFinder here.

[1]:
# standard python imports
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr

import tidy3d as td
from tidy3d import web
from tidy3d.plugins import ResonanceFinder

[23:01:47] 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

We will randomly position our sources and monitors. Here, we seed the random number generator to guarantee reproducible results.

[2]:
rng = np.random.default_rng(12345)

Now we define the parameters for the simulation, structure, sources, and monitors.

We take the dipole polarization to be Hz and the symmetry to be (0,0,1) in order to excite only modes which are even with respect to the xy mirror plane.

[3]:
# Simulation parameters
runtime_fwidth = 200.0  # in units of 1/frequency bandwidth of the source
t_start_fwidth = 5.0  # time to start monitoring after source has decayed, units of 1/frequency bandwidth
dPML = 1.0  # space between PhC slabs and PML, in unit of longest wavelength of interest

# Structure parameters (um)
a_lattice = 1  # lattice constant "a"
r_hole = 0.2 * a_lattice  # radius of the air holes
t_slab = 0.5 * a_lattice  # slab thickness
ep_slab = 12  # dielectric constant of the slab
ep_hole = 1  # dielectric constant of the holes

# Frequency range of interest (Hz)
freq_range_unitless = np.array((0.1, 0.43))  # in units of c/a
freq_scale = (
    td.constants.C_0 / a_lattice
)  # frequency scale determined by the lattice constant
freq_range = freq_range_unitless * freq_scale
lambda_range = (td.constants.C_0 / freq_range[1], td.constants.C_0 / freq_range[0])

# Gaussian pulse parameters
freq0 = np.sum(freq_range) / 2  # central frequency
freqw = 0.3 * (freq_range[1] - freq_range[0])  # pulse width

# Runtime
run_time = runtime_fwidth / freqw
print(f"Total runtime = {(run_time*1e12):.2f} ps")
t_start = t_start_fwidth / freqw

# Simulation size
spacing = dPML * lambda_range[-1]  # space between PhC slabs and PML
sim_size = Lx, Ly, Lz = (a_lattice, a_lattice, 2 * spacing + t_slab)

# Number of k values to sample, per edge of the irreducible Brillouin zone
Nk = 4

# Number of dipoles and monitors
num_dipoles = 7
num_monitors = 2

# Dipole polarization and symmetry
polarization = "Hz"
symmetry = (0, 0, 1)

Total runtime = 6.74 ps

We define the materials and structures in terms of the above parameters. We take the photonic crystal slab to be lying in the xy plane. Because the photonic crystal slab is periodic in the x and y directions, we only need to simulate a single unit cell, containing the dielectric slab and a single air hole.

[4]:
mat_slab = td.Medium(permittivity=ep_slab, name="mat_slab")
mat_hole = td.Medium(permittivity=ep_hole, name="mat_hole")

slab = td.Structure(
    geometry=td.Box(
        center=(0, 0, 0),
        size=(td.inf, td.inf, t_slab),
    ),
    medium=mat_slab,
    name="slab",
)

hole = td.Structure(
    geometry=td.Cylinder(
        center=(0, 0, 0),
        axis=2,
        radius=r_hole,
        length=t_slab,
    ),
    medium=mat_hole,
    name="hole",
)

structures = [slab, hole]

We will excite the photonic crystal slab with several PointDipole sources. Each dipole will have a random position and phase.

[5]:
dipole_positions = rng.uniform(
    [-Lx / 2, -Ly / 2, 0], [Lx / 2, Ly / 2, 0], [num_dipoles, 3]
)

dipole_phases = rng.uniform(0, 2 * np.pi, num_dipoles)

pulses = []
dipoles = []
for i in range(num_dipoles):
    pulse = td.GaussianPulse(freq0=freq0, fwidth=freqw, phase=dipole_phases[i])
    pulses.append(pulse)
    dipoles.append(
        td.PointDipole(
            source_time=pulse,
            center=tuple(dipole_positions[i]),
            polarization=polarization,
            name="dipole_" + str(i),
        )
    )

We create FieldTimeMonitors to record the field as a function of time at several random locations within the photonic crystal slab. Crucially, we start the monitors after the source pulse has decayed.

[6]:
monitor_positions = rng.uniform(
    [-Lx / 2, -Ly / 2, 0], [Lx / 2, Ly / 2, 0], [num_monitors, 3]
)

monitors_time = []
for i in range(num_monitors):
    monitors_time.append(
        td.FieldTimeMonitor(
            fields=["Hz"],
            center=tuple(monitor_positions[i]),
            size=(0, 0, 0),
            start=t_start,
            name="monitor_time_" + str(i),
        )
    )

We will perform 3*Nk different simulations, each with different Bloch boundary conditions, as we sweep the Bloch wavevector over the boundary of the irreducible Brillouin zone. We sweep over three lines, namely \(\Gamma X\), \(XM\), and \(M\Gamma\). We use a PML in the z direction.

Here, we simply define all of the boundary conditions we will use and put them into a single array.

[7]:
bspecs_gammax = []
bspecs_xm = []
bspecs_mgamma = []
for i in range(Nk):
    bspecs_gammax.append(
        td.BoundarySpec(
            x=td.Boundary.bloch((1 / 2) * i / Nk),
            y=td.Boundary.periodic(),
            z=td.Boundary.pml(),
        )
    )
    bspecs_xm.append(
        td.BoundarySpec(
            x=td.Boundary.bloch(1 / 2),
            y=td.Boundary.bloch((1 / 2) * i / Nk),
            z=td.Boundary.pml(),
        )
    )
    bspecs_mgamma.append(
        td.BoundarySpec(
            x=td.Boundary.bloch((1 / 2) * (1 - i / Nk)),
            y=td.Boundary.bloch((1 / 2) * (1 - i / Nk)),
            z=td.Boundary.pml(),
        )
    )
bspecs = bspecs_gammax + bspecs_xm + bspecs_mgamma

Now we define the simulations we want to run.

[8]:
sims = {}
for i in range(3 * Nk):
    sims[f"sim_{i}"] = td.Simulation(
        center=(0, 0, 0),
        size=sim_size,
        grid_spec=td.GridSpec.auto(),
        structures=structures,
        sources=dipoles,
        monitors=monitors_time,
        run_time=run_time,
        shutoff=0,
        boundary_spec=bspecs[i],
        normalize_index=None,
        symmetry=symmetry,
    )

Let’s check that the structure and source look correct. The source spectrum must fill the entire frequency range of interest.

[9]:
fig, ax = plt.subplots(1, 2, tight_layout=True, figsize=(10, 4))
sims["sim_0"].plot(z=0.0, ax=ax[0])
sims["sim_0"].plot(x=0, freq=freq0, ax=ax[1])
plt.show()

f, (ax1, ax2) = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))
plot_time = 5 / freqw
ax1 = (
    sims["sim_0"]
    .sources[0]
    .source_time.plot(times=np.linspace(0, plot_time, 1001), ax=ax1)
)
ax1.lines.pop(0)
ax1.lines.pop(1)
ax1.set_xlim(0, plot_time)
ax1.legend(("source amplitude",))
ax2 = (
    sims["sim_0"]
    .sources[0]
    .source_time.plot_spectrum(
        times=np.linspace(0, sims["sim_0"].run_time, 10001), ax=ax2
    )
)
ax2.lines.pop(0)
ax2.lines.pop(0)
ax2.hlines(0, freq_range[0], freq_range[1], linewidth=10, color="g", alpha=0.4)
ax2.legend(("source spectrum", "measurement"))
ax2.set_ylim(-1e-16)
plt.show()

[23:01:48] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
../_images/notebooks_Bandstructure_17_1.png
../_images/notebooks_Bandstructure_17_2.png

Now we run the simulations as a Batch. We save

[10]:
# initialize a batch and run them all
batch = td.web.Batch(simulations=sims)

# run the batch and store all of the data in the `data/` dir.
batch_data = batch.run(path_dir="data")

[23:01:49] INFO     Created task 'sim_0' with task_id '425fbe84-a204-43ca-a331-08a2bd603db7'.         webapi.py:120
[23:01:50] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_1' with task_id '524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2'.         webapi.py:120
[23:01:51] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
[23:01:52] INFO     Created task 'sim_2' with task_id '8b30587b-3c92-40dd-9025-bba6f1aaddac'.         webapi.py:120
[23:01:53] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_3' with task_id '719b283b-13c3-44e0-8b76-fa952db89bbf'.         webapi.py:120
[23:01:54] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_4' with task_id '2059db83-e7cb-4486-81f5-dcc111ee48a1'.         webapi.py:120
[23:01:55] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_5' with task_id '0f5ed6f3-cc9c-43e3-b3d5-dc83d60e194f'.         webapi.py:120
[23:01:56] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
[23:01:57] INFO     Created task 'sim_6' with task_id 'e74e7171-af37-47ac-b584-8e92cbfa37ca'.         webapi.py:120
[23:01:58] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_7' with task_id 'a941d525-dced-4a28-b46c-a1be17570ff8'.         webapi.py:120
[23:01:59] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
           INFO     Created task 'sim_8' with task_id 'feb89d62-370a-4b44-b7ff-c506d4249796'.         webapi.py:120
[23:02:00] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
[23:02:01] INFO     Created task 'sim_9' with task_id '4a0fcb9a-a192-4b3b-bfbd-365b6e26881d'.         webapi.py:120
           INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
[23:02:02] INFO     Created task 'sim_10' with task_id '6c6dc262-ecd4-4b4b-abc3-d1b4899fb3e1'.        webapi.py:120
[23:02:03] INFO     Auto meshing using wavelength 3.7736 defined from sources.                     grid_spec.py:510
[23:02:04] INFO     Created task 'sim_11' with task_id '0898cac9-d357-4895-bd29-e0da91946906'.        webapi.py:120
[23:02:10] Started working on Batch.                                                               container.py:361
[23:03:16] Batch complete.                                                                         container.py:382

Now that the simulations are complete, we can analyze the data. Let’s first look at one of the FieldTimeMonitors to make sure the source has decayed.

[11]:
plt.plot(
    batch_data["sim_1"].monitor_data["monitor_time_0"].Hz.t,
    np.real(batch_data["sim_1"].monitor_data["monitor_time_0"].Hz.squeeze()),
)
plt.title("FieldTimeMonitor data")
plt.xlabel("t")
plt.ylabel("Hz")

[23:03:17] INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5"                                               
[23:03:19] INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
           INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
[11]:
Text(0, 0.5, 'Hz')
../_images/notebooks_Bandstructure_21_7.png

We see that the source has mostly decayed by the time we switch on the monitors, and the remaining data shows decay and oscillation due to the resonances inside the system.

Looking at the Fourier transform of this data, we can see resonances at the band frequencies.

[12]:
df = 1 / np.amax(batch_data["sim_1"].monitor_data["monitor_time_0"].Hz.t)
minn = int(freq_range[0] / df)
maxn = int(freq_range[1] / df)
spectrum = np.fft.fft(batch_data["sim_1"].monitor_data["monitor_time_0"].Hz.squeeze())
plt.plot(
    np.linspace(freq_range[0], freq_range[1], maxn - minn),
    np.abs(spectrum[::-1][minn:maxn]),
)
plt.title("Spectrum at single wavevector")
plt.xlabel("Frequency (Hz)")
plt.ylabel("Amplitude")

           INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
           INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
[12]:
Text(0, 0.5, 'Amplitude')
../_images/notebooks_Bandstructure_23_3.png

We use the ResonanceFinder plugin to find the band frequencies.

We first construct a ResonanceFinder object storing our parameters, and then call run() on our list of FieldTimeData objects. This will add up the signals from all of the monitors before searching for resonances. The ResonanceFinder class has additional methods in case the signal takes another form; see the api reference here.

The run() method returns an xr.Dataset containing the decay rate, Q factor, amplitude, phase, and estimation error for each resonance as a function of frequency.

[13]:
resonance_finder = ResonanceFinder(freq_window=tuple(freq_range))
resonance_data = resonance_finder.run(signals=batch_data["sim_1"].data)
resonance_data.to_dataframe()

           INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:20] INFO             Completed ResonanceFinder (nfreqs = 5)                                 resonance.py:201
[13]:
decay Q amplitude phase error
freq
9.788253e+13 7.430813e+11 413.826865 0.008332 1.656388 0.000041
1.061235e+14 9.529783e+10 3498.472629 0.037352 3.054479 0.000009
1.131265e+14 2.128035e+12 167.007322 0.038965 1.695435 0.000051
1.191562e+14 1.150597e+12 325.344332 0.022350 -2.133775 0.000034
1.372927e+14 1.121520e+12 384.583068 0.031599 -0.707254 0.000053

We see the four resonances from the previous figure. All four have reasonable Q factors, amplitudes, and errors, so they are likely to represent physical resonances. Note that in order to accurately obtain the Q factor for high-Q modes, it may be necessary to run the simulation for a longer time.

Now we are ready to compute the band structure. We run the resonance finder at every Bloch wavevector.

[14]:
resonance_finder = ResonanceFinder(freq_window=tuple(freq_range))
resonance_datas = []
plt.figure(figsize=(10, 8))
for i in range(3 * Nk):
    sim_data = batch_data[f"sim_{i}"]
    resonance_datas.append(resonance_finder.run(signals=sim_data.data))

           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/425fbe84-a204-43ca-a331-08a2bd603db7.hdf5"                                               
[23:03:22] INFO     loading SimulationData from data/425fbe84-a204-43ca-a331-08a2bd603db7.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
           INFO             Iterated ResonanceFinder (nfreqs = 3)                                  resonance.py:203
           INFO             Completed ResonanceFinder (nfreqs = 3)                                 resonance.py:201
           INFO     loading SimulationData from data/524d39cf-9f84-4f05-9d5c-f8d13bd6b5c2.hdf5        webapi.py:415
[23:03:23] INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
           INFO             Completed ResonanceFinder (nfreqs = 5)                                 resonance.py:201
[23:03:24] INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/8b30587b-3c92-40dd-9025-bba6f1aaddac.hdf5"                                               
[23:03:25] INFO     loading SimulationData from data/8b30587b-3c92-40dd-9025-bba6f1aaddac.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:26] INFO             Completed ResonanceFinder (nfreqs = 6)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/719b283b-13c3-44e0-8b76-fa952db89bbf.hdf5"                                               
[23:03:28] INFO     loading SimulationData from data/719b283b-13c3-44e0-8b76-fa952db89bbf.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:29] INFO             Completed ResonanceFinder (nfreqs = 6)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/2059db83-e7cb-4486-81f5-dcc111ee48a1.hdf5"                                               
[23:03:30] INFO     loading SimulationData from data/2059db83-e7cb-4486-81f5-dcc111ee48a1.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:31] INFO             Completed ResonanceFinder (nfreqs = 6)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/0f5ed6f3-cc9c-43e3-b3d5-dc83d60e194f.hdf5"                                               
[23:03:33] INFO     loading SimulationData from data/0f5ed6f3-cc9c-43e3-b3d5-dc83d60e194f.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:34] INFO             Iterated ResonanceFinder (nfreqs = 5)                                  resonance.py:203
           INFO             Completed ResonanceFinder (nfreqs = 5)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/e74e7171-af37-47ac-b584-8e92cbfa37ca.hdf5"                                               
[23:03:36] INFO     loading SimulationData from data/e74e7171-af37-47ac-b584-8e92cbfa37ca.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:37] INFO             Iterated ResonanceFinder (nfreqs = 4)                                  resonance.py:203
           INFO             Completed ResonanceFinder (nfreqs = 4)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/a941d525-dced-4a28-b46c-a1be17570ff8.hdf5"                                               
[23:03:39] INFO     loading SimulationData from data/a941d525-dced-4a28-b46c-a1be17570ff8.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
           INFO             Completed ResonanceFinder (nfreqs = 4)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/feb89d62-370a-4b44-b7ff-c506d4249796.hdf5"                                               
[23:03:41] INFO     loading SimulationData from data/feb89d62-370a-4b44-b7ff-c506d4249796.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:42] INFO             Completed ResonanceFinder (nfreqs = 3)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/4a0fcb9a-a192-4b3b-bfbd-365b6e26881d.hdf5"                                               
[23:03:44] INFO     loading SimulationData from data/4a0fcb9a-a192-4b3b-bfbd-365b6e26881d.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:45] INFO             Completed ResonanceFinder (nfreqs = 5)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/6c6dc262-ecd4-4b4b-abc3-d1b4899fb3e1.hdf5"                                               
[23:03:46] INFO     loading SimulationData from data/6c6dc262-ecd4-4b4b-abc3-d1b4899fb3e1.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:47] INFO             Completed ResonanceFinder (nfreqs = 6)                                 resonance.py:201
           INFO     downloading file "output/monitor_data.hdf5" to                                    webapi.py:593
                    "data/0898cac9-d357-4895-bd29-e0da91946906.hdf5"                                               
[23:03:49] INFO     loading SimulationData from data/0898cac9-d357-4895-bd29-e0da91946906.hdf5        webapi.py:415
           INFO             Running ResonanceFinder (nfreqs = 200)                                 resonance.py:187
[23:03:50] INFO             Completed ResonanceFinder (nfreqs = 6)                                 resonance.py:201
<Figure size 1000x800 with 0 Axes>

We define a function to filter resonances based on their Q, amplitude, and error.

[15]:
def filter_resonances(resonance_data, minQ, minamp, maxerr):
    resonance_data = resonance_data.where(abs(resonance_data.Q) > minQ, drop=True)
    resonance_data = resonance_data.where(resonance_data.amplitude > minamp, drop=True)
    resonance_data = resonance_data.where(resonance_data.error < maxerr, drop=True)
    return resonance_data

We plot the band structure with the light line overlaid.

[16]:
for i in range(3 * Nk):
    resonance_data = resonance_datas[i]
    resonance_data = filter_resonances(
        resonance_data=resonance_data, minQ=0, minamp=0.001, maxerr=100
    )
    freqs = resonance_data.freq.to_numpy()
    Qs = resonance_data.Q.to_numpy()
    plt.scatter(np.full(len(freqs), (1 / 2) * i / Nk), freqs / 3e14, color="blue")

lightx = np.linspace(0, 0.5, 100)
lighty1 = lightx
lighty3 = (0.5 - lightx) * np.sqrt(2)

plt.plot(lightx, lighty1, color="blue", alpha=0.2)
plt.plot(1 + lightx, lighty3, color="blue", alpha=0.2)

plt.ylim(0, freq_range_unitless[1])

plt.title("Band diagram")
plt.ylabel("Frequency (c/a)")
plt.xlabel("Wavevector")
plt.xticks([0, 0.5, 1, 1.5], ["$\Gamma$", "X", "M", "$\Gamma$"])
plt.xlim(0, 1.5)
plt.show()

../_images/notebooks_Bandstructure_31_0.png

The bandstructure we obtained matches the expected result from the paper. If we were seeing too many resonances, we could change the parameters to our filter_resonances function to eliminate the spurious ones. If we were seeing too few resonances even before filtering, we might have to change the parameters of the ResonanceFinder, for example decreasing rcond or increasing init_num_freqs. If the ResonanceFinder takes too long, we can decrease init_num_freqs. There can also be resonances on the light line associated with Wood’s anomaly; we filter those out here based on their small amplitude.