コード例 #1
0
    def test_animation_output(self):
        # ------------------------- #
        # Check over 2D domain
        # ------------------------- #

        sim = setup_sim() # generate 2D simulation
        
        Animate = mp.Animate2D(sim,fields=mp.Ez, realtime=False, normalize=False) # Check without normalization
        Animate_norm = mp.Animate2D(sim,mp.Ez,realtime=False,normalize=True) # Check with normalization

        # test both animation objects during same run
        sim.run(
            mp.at_every(1,Animate),
            mp.at_every(1,Animate_norm),
            until=5)
        
        # Test outputs
        Animate.to_mp4(5,'test_2D.mp4') # Check mp4 output
        Animate.to_gif(150,'test_2D.gif') # Check gif output
        Animate.to_jshtml(10) # Check jshtml output
        Animate_norm.to_mp4(5,'test_2D_norm.mp4') # Check mp4 output
        Animate_norm.to_gif(150,'test_2D_norm.gif') # Check gif output
        Animate_norm.to_jshtml(10) # Check jshtml output

        # ------------------------- #
        # Check over 3D domain
        # ------------------------- #
        sim = setup_sim(5) # generate 2D simulation
        
        Animate_xy = mp.Animate2D(sim,fields=mp.Ey, realtime=False, normalize=True) # Check without normalization
        Animate_xz = mp.Animate2D(sim,mp.Ey,realtime=False,normalize=True) # Check with normalization

        # test both animation objects during same run
        sim.run(
            mp.at_every(1,mp.in_volume(mp.Volume(center=mp.Vector3(),size=mp.Vector3(sim.cell_size.x,sim.cell_size.y)),Animate_xy)),
            mp.at_every(1,mp.in_volume(mp.Volume(center=mp.Vector3(),size=mp.Vector3(sim.cell_size.x,0,sim.cell_size.z)),Animate_xz)),
            until=5)
        
        # Test outputs
        Animate_xy.to_mp4(5,'test_3D_xy.mp4') # Check mp4 output
        Animate_xy.to_gif(150,'test_3D_xy.gif') # Check gif output
        Animate_xy.to_jshtml(10) # Check jshtml output
        Animate_xz.to_mp4(5,'test_3D_xz.mp4') # Check mp4 output
        Animate_xz.to_gif(150,'test_3D_xz.gif') # Check gif output
        Animate_xz.to_jshtml(10) # Check jshtml output
コード例 #2
0
    def test_animation_output(self):
        # Check without normalization
        sim = setup_sim()
        Animate = mp.Animate2D(sim,
                               fields=mp.Ez,
                               realtime=False,
                               normalize=False)
        sim.run(mp.at_every(1, Animate), until=5)

        # Check with normalization
        animation = mp.Animate2D(sim, mp.Ez, realtime=False, normalize=True)
        sim.run(mp.at_every(1), until=25)

        # Check mp4 output
        Animate.to_mp4(10, 'test.mp4')

        # Check gif output
        Animate.to_gif(10, 'test.gif')

        # Check jshtml output
        Animate.to_jshtml(10)
コード例 #3
0
                    subpixel_tol=1,
                    cell_size=cell.size,
                    boundary_layers=[mp.PML(dpml)],
                    sources=sources,
                    geometry=final_geometry,
                    geometry_center=mp.Vector3(ring_radius / 2,
                                               -ring_radius / 2))

# Could add monitors at many frequencies by looping over fcen
# Means one FDTD for many results!
mode1 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p1))
mode2 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p2))
mode3 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p3))
mode4 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p4))

# Setup and run the simulation
f = plt.figure(dpi=100)
animate = mp.Animate2D(sim, mp.Ez, f=f, normalize=True)
sim.run(mp.at_every(1, animate), until_after_sources=100)
#sim.run(until_after_sources=100)
plt.close()

# Do the analysis we want
# S parameters
print(sim.get_eigenmode_coefficients(mode1, [1], eig_parity=mp.NO_PARITY))
print(sim.get_eigenmode_coefficients(mode2, [1], eig_parity=mp.NO_PARITY))

# Save a video
filename = 'media/coupler.mp4'
animate.to_mp4(10, filename)
コード例 #4
0
ファイル: straight-waveguide.py プロジェクト: davito0203/MEEP
sim.run(until=200)

eps_data = sim.get_array(center=mp.Vector3(),
                         size=cell,
                         component=mp.Dielectric)
plt.figure(dpi=100)
sim.plot2D()
#plt.show()
plt.savefig('PLM-Box.png')

ez_data = sim.get_array(center=mp.Vector3(), size=cell, component=mp.Ez)
plt.figure(dpi=100)
sim.plot2D(fields=mp.Ez)
#plt.show()
plt.savefig('EzComponent.png')

#sim.reset_meep()
f = plt.figure(dpi=100)
Animate = mp.Animate2D(sim, fields=mp.Ez, f=f, realtime=False, normalize=True)
plt.close()

sim.run(mp.at_every(1, Animate), until=100)
plt.close()

filename = "straight_waveguide.mp4"
Animate.to_mp4(20, filename)

from IPython.display import Video
Video(filename)
コード例 #5
0
    def sparameter_calculation(
        n,
        component: Component,
        port_symmetries: Optional[PortSymmetries] = port_symmetries,
        monitor_indices: Tuple = monitor_indices,
        wl_min: float = wl_min,
        wl_max: float = wl_max,
        wl_steps: int = wl_steps,
        dirpath: Path = dirpath,
        animate: bool = animate,
        dispersive: bool = dispersive,
        **settings,
    ) -> Dict:

        sim_dict = get_simulation(
            component=component,
            port_source_name=f"o{monitor_indices[n]}",
            resolution=resolution,
            wl_min=wl_min,
            wl_max=wl_max,
            wl_steps=wl_steps,
            port_margin=port_margin,
            port_monitor_offset=port_monitor_offset,
            port_source_offset=port_source_offset,
            dispersive=dispersive,
            **settings,
        )

        sim = sim_dict["sim"]
        monitors = sim_dict["monitors"]
        # freqs = sim_dict["freqs"]
        # wavelengths = 1 / freqs
        # print(sim.resolution)

        # Make termination when field decayed enough across ALL monitors
        termination = []
        for monitor_name in monitors:
            termination.append(
                mp.stop_when_fields_decayed(
                    dt=50,
                    c=mp.Ez,
                    pt=monitors[monitor_name].regions[0].center,
                    decay_by=1e-9,
                ))

        if animate:
            sim.use_output_directory()
            animate = mp.Animate2D(
                sim,
                fields=mp.Ez,
                realtime=True,
                field_parameters={
                    "alpha": 0.8,
                    "cmap": "RdBu",
                    "interpolation": "none",
                },
                eps_parameters={"contour": True},
                normalize=True,
            )
            sim.run(mp.at_every(1, animate), until_after_sources=termination)
            animate.to_mp4(30, monitor_indices[n] + ".mp4")
        else:
            sim.run(until_after_sources=termination)
        # call this function every 50 time spes
        # look at simulation and measure Ez component
        # when field_monitor_point decays below a certain 1e-9 field threshold

        # Calculate mode overlaps
        # Get source monitor results
        component_ref = component.ref()
        source_entering, source_exiting = parse_port_eigenmode_coeff(
            monitor_indices[n], component_ref.ports, sim_dict)
        # Get coefficients
        for monitor_index in monitor_indices:
            j = monitor_indices[n]
            i = monitor_index
            if monitor_index == monitor_indices[n]:
                sii = source_exiting / source_entering
                siia = np.unwrap(np.angle(sii))
                siim = np.abs(sii)
                sp[f"s{i}{i}a"] = siia
                sp[f"s{i}{i}m"] = siim
            else:
                monitor_entering, monitor_exiting = parse_port_eigenmode_coeff(
                    monitor_index, component_ref.ports, sim_dict)
                sij = monitor_exiting / source_entering
                sija = np.unwrap(np.angle(sij))
                sijm = np.abs(sij)
                sp[f"s{i}{j}a"] = sija
                sp[f"s{i}{j}m"] = sijm
                sij = monitor_entering / source_entering
                sija = np.unwrap(np.angle(sij))
                sijm = np.abs(sij)

        if bool(port_symmetries) is True:
            for key in port_symmetries[f"o{monitor_indices[n]}"].keys():
                values = port_symmetries[f"o{monitor_indices[n]}"][key]
                for value in values:
                    sp[f"{value}m"] = sp[f"{key}m"]
                    sp[f"{value}a"] = sp[f"{key}a"]

        return sp
コード例 #6
0
                    )
   
## Scattering monitor ref
box_x1 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(x=-lxm/2),size=mp.Vector3(0,2*lym/2,2*lzm/2)))
box_x2 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(x=+lxm/2),size=mp.Vector3(0,2*lym/2,2*lzm/2)))
box_y1 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(y=-lym/2),size=mp.Vector3(2*lxm/2,0,2*lzm/2)))
box_y2 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(y=+lym/2),size=mp.Vector3(2*lxm/2,0,2*lzm/2)))
box_z1 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(z=-lzm/2),size=mp.Vector3(2*lxm/2,2*lym/2,0)))
box_z2 = sim.add_flux(frq_cen, dfrq, nfrq, mp.FluxRegion(center=mp.Vector3(z=+lzm/2),size=mp.Vector3(2*lxm/2,2*lym/2,0)))
                                
### Run simulation-------------1.2

## Field movie settings
volume=mp.Block(size=vid_dim, center=mp.Vector3())
f = plt.figure(dpi=100)
Animate_ref = mp.Animate2D(sim, fields=mon_cmpt, f=f,output_plane=volume, realtime=False, normalize=True)
plt.close()

# Run 
sim.run(mp.at_every(vid_t,Animate_ref),until_after_sources=mp.stop_when_fields_decayed(2,src_cmpt,pt,field_min))    
plt.close()

## Scattering monitor Fourier-transformed fields in ram
freqs = mp.get_flux_freqs(box_x1)
box_x1_data = sim.get_flux_data(box_x1)
box_x2_data = sim.get_flux_data(box_x2)
box_y1_data = sim.get_flux_data(box_y1)
box_y2_data = sim.get_flux_data(box_y2)
box_z1_data = sim.get_flux_data(box_z1)
box_z2_data = sim.get_flux_data(box_z2)
box_z1_flux0 = mp.get_fluxes(box_z1)
コード例 #7
0
def main(args):

    SIM_CELL = pya.LayerInfo(0, 0)
    Si = pya.LayerInfo(1, 0)
    MEEP_SOURCE = pya.LayerInfo(10, 0)
    MEEP_PORT1 = pya.LayerInfo(20, 0)
    MEEP_PORT2 = pya.LayerInfo(21, 0)
    MEEP_PORT3 = pya.LayerInfo(22, 0)
    MEEP_PORT4 = pya.LayerInfo(23, 0)


    # ## Simulation Parameters

    # In[3]:


    ring_radius = 8 # um
    ring_width = 0.5 # um
    pml_width = 1.0 # um
    gap = args.gap # um
    src_port_gap = 0.2 # um
    straight_wg_length = pml_width + 1 # um

    # Simulation resolution
    res = 100        # pixels/μm


    # ## Step 1. Drawing a waveguide coupler and saving into a temporary .gds file

    # In[4]:


    from zeropdk.layout import layout_arc, layout_waveguide, layout_path, layout_box
    from tempfile import NamedTemporaryFile
    from math import sqrt

    # Create a temporary filename
    temp_file = NamedTemporaryFile(delete=False, suffix='.gds')
    filename = temp_file.name
    # temp_file = None
    # filename = "test.gds"

    # Instantiate a layout and a top cell
    layout = pya.Layout()
    layout.dbu = 0.001
    TOP = layout.create_cell("TOP")

    sqrt2 = sqrt(2)

    # Unit vectors
    ex = pya.DVector(1, 0)
    ey = pya.DVector(0, 1)
    e45 = (ex + ey) / sqrt2
    e135 = (-ex + ey) / sqrt2

    # Draw circular bend
    layout_arc(TOP, Si, - ring_radius*ey, ring_radius, ring_width, 0, np.pi/2)

    # Extend the bend to avoid discontinuities
    layout_waveguide(TOP, Si, [0*ex, - straight_wg_length*ex], ring_width)
    layout_waveguide(TOP, Si, [-1*ring_radius*ey + ring_radius*ex, 
                               -straight_wg_length * ey - ring_radius*ey + ring_radius*ex], ring_width)

    # Add the ports as 0-width paths
    port_size = ring_width * 4.0


    # Draw add/drop waveguide

    coupling_point = (ring_radius + gap + ring_width) * e45 - ring_radius * ey
    add_drop_length = (ring_radius + gap + ring_width) * sqrt2
    layout_waveguide(TOP, Si, [coupling_point + (add_drop_length + 0.4) * e135,
                               coupling_point - (add_drop_length + 0.4) * e135],
                    ring_width)


    # Source at port 1
    layout_path(TOP, MEEP_SOURCE, [coupling_point - port_size/2*ex + (add_drop_length / 2 + src_port_gap) * e135, 
                                   coupling_point + port_size/2*ex + (add_drop_length / 2 + src_port_gap) * e135], 0)

    # Source at port 2 (alternative)
    # layout_path(TOP, MEEP_SOURCE, [-port_size/2*ey - src_port_gap*ex, port_size/2*ey - 0.2*ex], 0)

    # Port 1
    layout_path(TOP, MEEP_PORT1,   [coupling_point - port_size/2*ex + (add_drop_length / 2) * e135, 
                                    coupling_point + port_size/2*ex  + (add_drop_length / 2) * e135], 0)

    # Port 2
    layout_path(TOP, MEEP_PORT2,   [-port_size/2*ey, port_size/2*ey], 0)

    # Port 3
    layout_path(TOP, MEEP_PORT3,   [coupling_point - port_size/2*ey - (add_drop_length / 2) * e135, 
                                    coupling_point + port_size/2*ey - (add_drop_length / 2) * e135], 0)
    # Port 4
    layout_path(TOP, MEEP_PORT4,   [-1*ring_radius*ey + ring_radius*ex - port_size/2*ex, 
                                    -1*ring_radius*ey + ring_radius*ex + port_size/2*ex], 0)

    # Draw simulation region
    layout_box(TOP, SIM_CELL, 
               -1.0*ring_radius*ey - (pml_width + src_port_gap) * (ex + ey), # Bottom left point 
               coupling_point + (add_drop_length / 2 + src_port_gap) * e45 + pml_width * (ex + ey),  # Top right point
               ex)

    # Write to file
    layout.write(filename)
    print(f"Produced file {filename}.")


    # ## Step 2. Load gds file into meep
    # 
    # ### Visualization and simulation
    # 
    # If you choose a normal filename (not temporary), you can download the GDSII file from the cluster (see Files in MyAdroit dashboard) to see it with your local Klayout. Otherwise, let's get simulating:

    # In[5]:


    def round_vector(vector, decimal_places=3):
        x = round(vector.x, decimal_places)
        y = round(vector.y, decimal_places)
        z = round(vector.z, decimal_places)
        return mp.Vector3(x, y, z)


    # In[6]:


    gdsII_file = filename
    CELL_LAYER = 0
    SOURCE_LAYER = 10
    Si_LAYER = 1
    PORT1_LAYER = 20
    PORT2_LAYER = 21
    PORT3_LAYER = 22
    PORT4_LAYER = 23

    t_oxide = 1.0
    t_Si = 0.22
    t_SiO2 = 0.78

    oxide = mp.Medium(epsilon=2.25)
    silicon=mp.Medium(epsilon=12)

    lcen = 1.55
    fcen = 1/lcen
    df = 0.2*fcen
    nfreq = 25

    cell_zmax =  0
    cell_zmin =  0
    si_zmax = 10
    si_zmin = -10

    # read cell size, volumes for source region and flux monitors,
    # and coupler geometry from GDSII file
    # WARNING: Once the file is loaded, the prism contents is cached and cannot be reloaded.
    # SOLUTION: Use a different filename or restart the kernel

    si_layer = mp.get_GDSII_prisms(silicon, gdsII_file, Si_LAYER, si_zmin, si_zmax)

    cell = mp.GDSII_vol(gdsII_file, CELL_LAYER, cell_zmin, cell_zmax)
    src_vol = mp.GDSII_vol(gdsII_file, SOURCE_LAYER, si_zmin, si_zmax)
    p1 = mp.GDSII_vol(gdsII_file, PORT1_LAYER, si_zmin, si_zmax)
    p2 = mp.GDSII_vol(gdsII_file, PORT2_LAYER, si_zmin, si_zmax)
    p3 = mp.GDSII_vol(gdsII_file, PORT3_LAYER, si_zmin, si_zmax)
    p4 = mp.GDSII_vol(gdsII_file, PORT4_LAYER, si_zmin, si_zmax)


    sources = [mp.EigenModeSource(src=mp.GaussianSource(fcen,fwidth=df),
                                  size=round_vector(src_vol.size),
                                  center=round_vector(src_vol.center),
                                  direction=mp.NO_DIRECTION,
                                  eig_kpoint=mp.Vector3(1, -1, 0), # -45 degree angle
                                  eig_band=1,
                                  eig_parity=mp.NO_PARITY,
                                  eig_match_freq=True)]

    # Display simulation object
    sim = mp.Simulation(resolution=res,
                        default_material=oxide,
                        eps_averaging=False,
                        cell_size=cell.size,
                        geometry_center=round_vector(cell.center,2),
                        boundary_layers=[mp.PML(pml_width)],
                        sources=sources,
                        geometry=si_layer)

    # Delete file created in previous cell

    import os
    if temp_file:
        temp_file.close()
        os.unlink(filename)


    # ## Step 3. Setup simulation environment
    # 
    # This will load the python-defined parameters from the previous cell and instantiate a fast, C++ based, simulation environment using meep. It will also compute the eigenmode of the source, in preparation for the FDTD simulation.

    # In[7]:


    sim.reset_meep()

    # Could add monitors at many frequencies by looping over fcen
    # Means one FDTD for many results!
    mode1 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p1))
    mode2 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p2))
    mode3 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p3))
    mode4 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p4))

    # Let's store the frequencies that were generated by this mode monitor
    mode1_freqs = np.array(mp.get_eigenmode_freqs(mode1))
    mode2_freqs = np.array(mp.get_eigenmode_freqs(mode2))
    mode3_freqs = np.array(mp.get_eigenmode_freqs(mode3))
    mode4_freqs = np.array(mp.get_eigenmode_freqs(mode4))

    sim.init_sim()


    # ### Verify if there are numerical errors.
    # - You should see a clean black and white plot.
    # - If there are other weird structures, try increasing the resolution.

    # In[8]:


    eps_data = sim.get_array(center=cell.center, size=cell.size, component=mp.Dielectric)
    plt.figure(dpi=res)
    plt.imshow(eps_data.transpose(), interpolation='none', cmap='binary', origin='lower')
    plt.colorbar()
    plt.show()


    # ### Verify that the structure makes sense.
    # 
    # Things to check:
    # - Are the sources and ports outside the PML?
    # - Are dimensions correct?
    # - Is the simulation region unnecessarily large?

    # In[9]:


    # If there is a warning that reads "The specified user volume
    # is larger than the simulation domain and has been truncated",
    # It has to do with some numerical errors between python and meep.
    # Ignore.
    # sim.init_sim()

    f = plt.figure(dpi=100)
    sim.plot2D(ax=f.gca())
    plt.show()


    # Looks pretty good. Simulations at the high enough resolution required to avoid spurious reflections in the bend are very slow! This can be sped up quite a bit by running the code in parallel from the terminal. Later, we will put this notebook's code into a script and run it in parallel.

    # ## Step 4. Simulate FDTD and Animate results
    # 
    # More detailed meep documentation available [here](https://meep.readthedocs.io/en/latest/Python_Tutorials/Basics/#transmittance-spectrum-of-a-waveguide-bend).

    # In[10]:


    # Set to true to compute animation (may take a lot of memory)
    # Turn this off if you don't need to visualize.
    compute_animation = False


    # In[11]:


    # Setup and run the simulation

    # The following line defines a stopping condition depending on the square
    # of the amplitude of the Ez field at the port 2.
    print(f"Stop condition: decay to 0.1% of peak value in the last {2.0/df:.1f} time units.")
    stop_condition = mp.stop_when_fields_decayed(2.0/df,mp.Ez,p3.center,1e-3)
    if compute_animation:
        f = plt.figure(dpi=100)
        animate = mp.Animate2D(sim,mp.Ez,f=f,normalize=True)
        sim.run(mp.at_every(1,animate), until_after_sources=stop_condition)
        plt.close()
        animate.to_mp4(10, 'media/coupler1.mp4')
    else:
        sim.run(until_after_sources=stop_condition)


    # ### Visualize results
    # 
    # Things to check:
    # - Was the simulation time long enough for the pulse to travel through the output port in its entirety? Given the automatic stop condition, this should be the case.

    # In[12]:


    from IPython.display import Video, display
    if compute_animation:
        display(Video('media/coupler1.mp4'))

    # ## Step 5. Compute S parameters of the coupler

    # In[13]:


    # Every mode monitor measures the power flowing through it in either the forward or backward direction

    # This time, the monitor is at an oblique angle to the waveguide. This is because meep
    # can only compute fluxes in either the x, y, or z planes. In order to correctly measure
    # the flux, we need to provide a k-vector at an angle. 
    # So we compute a unit vector at a -45 angle like so:
    kpoint135 = mp.Vector3(x=1).rotate(mp.Vector3(z=1), np.radians(-45))

    # In this simulation, the ports 1 and 3 are on an angled waveguide, and
    # 2 and 4 are perpendicular to the waveguide.
    eig_mode1 = sim.get_eigenmode_coefficients(mode1, [1], eig_parity=mp.NO_PARITY, 
                                               direction=mp.NO_DIRECTION, kpoint_func=lambda f,n: kpoint135)

    eig_mode2 = sim.get_eigenmode_coefficients(mode2, [1], eig_parity=mp.NO_PARITY)

    eig_mode3 = sim.get_eigenmode_coefficients(mode3, [1], eig_parity=mp.NO_PARITY, 
                                               direction=mp.NO_DIRECTION, kpoint_func=lambda f,n: kpoint135)

    eig_mode4 = sim.get_eigenmode_coefficients(mode4, [1], eig_parity=mp.NO_PARITY)

    # We proceed like last time.

    # First, we need to figure out which direction the "dominant planewave" k-vector is
    # We can pick the first frequency (0) for that, assuming that for all simulated frequencies,
    # The dominant k-vector will point in the same direction.
    k1 = eig_mode1.kdom[0]
    k2 = eig_mode2.kdom[0]
    k3 = eig_mode3.kdom[0]
    k4 = eig_mode4.kdom[0]

    # eig_mode.alpha[0,0,0] corresponds to the forward direction, whereas
    # eig_mode.alpha[0,0,1] corresponds to the backward direction

    # For port 1, we are interested in the -y direction, so if k1.y is positive, select 1, otherwise 0
    idx = (k1.y > 0) * 1
    p1_thru_coeff = eig_mode1.alpha[0,:,idx]
    p1_reflected_coeff = eig_mode1.alpha[0,:,1-idx]

    # For port 3, we are interestred in the +x direction
    idx = (k3.x < 0) * 1
    p3_thru_coeff = eig_mode3.alpha[0,:,idx]
    p3_reflected_coeff = eig_mode3.alpha[0,:,1-idx]

    # For port 2, we are interested in the -x direction
    idx = (k2.x > 0) * 1
    p2_thru_coeff = eig_mode2.alpha[0,:,idx]
    p2_reflected_coeff = eig_mode2.alpha[0,:,1-idx]

    # For port 4, we are interested in the -y direction
    idx = (k4.y > 0) * 1
    p4_thru_coeff = eig_mode4.alpha[0,:,idx]
    p4_reflected_coeff = eig_mode4.alpha[0,:,1-idx]


    # transmittance
    S41 = p4_thru_coeff/p1_thru_coeff
    S31 = p3_thru_coeff/p1_thru_coeff
    S21 = p2_thru_coeff/p1_thru_coeff
    S11 = p1_reflected_coeff/p1_thru_coeff

    print("----------------------------------")
    print(f"Parameters: radius={ring_radius:.1f}")
    print(f"Frequencies: {mode1_freqs}")


    # In[20]:


    #Write to csv file
    import csv
    with open(f'sparams1.gap{gap:.2f}um.csv', mode='w') as sparams_file:
        sparam_writer = csv.writer(sparams_file, delimiter=',')
        sparam_writer.writerow(['f(Hz)',
                                'real(S11)','imag(S11)',
                                'real(S21)','imag(S21)',
                                'real(S31)','imag(S31)',
                                'real(S41)','imag(S41)'
                               ])
        for i in range(len(mode1_freqs)):
            sparam_writer.writerow([mode1_freqs[i] * 3e14,
                                    np.real(S11[i]),np.imag(S11[i]),
                                    np.real(S21[i]),np.imag(S21[i]),
                                    np.real(S31[i]),np.imag(S31[i]),
                                    np.real(S41[i]),np.imag(S41[i])
                                   ])
コード例 #8
0
ファイル: simulation.py プロジェクト: marco-butz/simFrame
def simulation(plotMe,
               plotDir='simulationData/',
               jobSpecifier='direct-',
               mat=None):
    if os.getenv("X_USE_MPI") != "1":
        jobName = jobSpecifier + randomString()
    else:
        jobName = jobSpecifier
    start = time.time()

    if str(plotMe) == '1':
        os.makedirs(plotDir)
        import matplotlib
        #matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        print('will plot')
    else:
        mp.quiet(True)
    __author__ = 'Marco Butz'

    pixelSize = mat['pixelSize']

    spectralWidth = 300 / mat['wavelength']
    modeFrequencyResolution = 1
    normOffset = pixelSize / 1000 * 10
    if mat['dims'][2] == 1:
        cell = mp.Vector3(mat['dims'][0]*pixelSize/1000, \
        mat['dims'][1]*pixelSize/1000, 0)
    else:
        cell = mp.Vector3(mat['dims'][0]*pixelSize/1000, \
        mat['dims'][1]*pixelSize/1000, mat['dims'][2]*pixelSize/1000)

    #generate hdf5 epsilon file
    if mp.am_master():
        h5f = h5py.File(jobName + '_eps.h5', 'a')
        h5f.create_dataset('epsilon', data=mat['epsilon'])
        h5f.close()

    sourceCenter = [
        (mat['modeSourcePos'][0][0] + mat['modeSourcePos'][1][0]) / 2,
        (mat['modeSourcePos'][0][1] + mat['modeSourcePos'][1][1]) / 2,
        (mat['modeSourcePos'][0][2] + mat['modeSourcePos'][1][2]) / 2
    ]
    sourceSize = [(mat['modeSourcePos'][1][0] - mat['modeSourcePos'][0][0]),
                  (mat['modeSourcePos'][1][1] - mat['modeSourcePos'][0][1]),
                  (mat['modeSourcePos'][1][2] - mat['modeSourcePos'][0][2])]

    modeNumModesToMeasure = []
    posModesToMeasure = []
    if not isinstance(mat['modeNumModesToMeasure'], Iterable):
        #this wraps stuff into an array if it has been squeezed before
        posModesToMeasure = [mat['posModesToMeasure']]
        modeNumModesToMeasure = [mat['modeNumModesToMeasure']]
        print('transformed')
    else:
        posModesToMeasure = mat['posModesToMeasure']
        modeNumModesToMeasure = mat['modeNumModesToMeasure']

    outputsModeNum = []
    outputsCenter = []
    outputsSize = []
    for i in range(0, mat['numModesToMeasure']):
        outputsCenter.append([
            (posModesToMeasure[i][0][0] + posModesToMeasure[i][1][0]) / 2,
            (posModesToMeasure[i][0][1] + posModesToMeasure[i][1][1]) / 2,
            (posModesToMeasure[i][0][2] + posModesToMeasure[i][1][2]) / 2
        ])
        outputsSize.append([
            (posModesToMeasure[i][1][0] - posModesToMeasure[i][0][0]),
            (posModesToMeasure[i][1][1] - posModesToMeasure[i][0][1]),
            (posModesToMeasure[i][1][2] - posModesToMeasure[i][0][2])
        ])
        outputsModeNum.append(modeNumModesToMeasure[i])

    for i in range(0, len(sourceCenter)):
        sourceCenter[i] = sourceCenter[i] * pixelSize / 1000 - cell[i] / 2
        sourceSize[i] = sourceSize[i] * pixelSize / 1000
    for i in range(0, len(outputsCenter)):
        for j in range(0, len(outputsCenter[i])):
            outputsCenter[i][
                j] = outputsCenter[i][j] * pixelSize / 1000 - cell[j] / 2
            outputsSize[i][j] = outputsSize[i][j] * pixelSize / 1000

    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(wavelength=mat['wavelength'] / 1000,
                                  fwidth=spectralWidth),
            eig_band=mat['modeSourceNum'] + 1,
            center=mp.Vector3(sourceCenter[0], sourceCenter[1],
                              sourceCenter[2]),
            size=mp.Vector3(sourceSize[0], sourceSize[1], sourceSize[2]))
    ]
    """
    sources = [mp.EigenModeSource(src=mp.ContinuousSource(wavelength=mat['wavelength']/1000),
                                    eig_band=mat['modeSourceNum']+1,
                                    center=mp.Vector3(sourceCenter[0],sourceCenter[1],sourceCenter[2]),
                                    size=mp.Vector3(sourceSize[0],sourceSize[1],sourceSize[2]))]
    """

    resolution = 1000 / pixelSize  #pixels per micrometer

    pmlLayers = [mp.PML(pixelSize * 10 / 1000)]

    sim = mp.Simulation(cell_size=cell,
                        boundary_layers=pmlLayers,
                        geometry=[],
                        epsilon_input_file=jobName + '_eps.h5',
                        sources=sources,
                        resolution=resolution)
    #force_complex_fields=True) #needed for fdfd solver

    transmissionFluxes = []
    transmissionModes = []
    normFluxRegion = mp.FluxRegion(
        center=mp.Vector3(sourceCenter[0] + normOffset, sourceCenter[1],
                          sourceCenter[2]),
        size=mp.Vector3(sourceSize[0], sourceSize[1], sourceSize[2]),
        direction=mp.X)
    normMode = sim.add_mode_monitor(1000 / mat['wavelength'], spectralWidth,
                                    modeFrequencyResolution, normFluxRegion)
    normFlux = sim.add_flux(1000 / mat['wavelength'], spectralWidth,
                            modeFrequencyResolution, normFluxRegion)

    for i in range(0, len(outputsCenter)):
        transmissionFluxRegion = mp.FluxRegion(
            center=mp.Vector3(outputsCenter[i][0], outputsCenter[i][1],
                              outputsCenter[i][2]),
            size=mp.Vector3(outputsSize[i][0], outputsSize[i][1],
                            outputsSize[i][2]),
            direction=mp.X)
        transmissionFluxes.append(
            sim.add_flux(1000 / mat['wavelength'], spectralWidth,
                         modeFrequencyResolution, transmissionFluxRegion))
        transmissionModes.append(
            sim.add_mode_monitor(1000 / mat['wavelength'], spectralWidth,
                                 modeFrequencyResolution,
                                 transmissionFluxRegion))
    if str(plotMe) == '1':
        animation = mp.Animate2D(sim,
                                 fields=mp.Ey,
                                 realtime=False,
                                 normalize=True,
                                 field_parameters={
                                     'alpha': 0.8,
                                     'cmap': 'RdBu',
                                     'interpolation': 'none'
                                 },
                                 boundary_parameters={
                                     'hatch': 'o',
                                     'linewidth': 1.5,
                                     'facecolor': 'y',
                                     'edgecolor': 'b',
                                     'alpha': 0.3
                                 })
        sim.run(mp.at_every(0.5,mp.in_volume(mp.Volume(center=mp.Vector3(),size=mp.Vector3(sim.cell_size.x,sim.cell_size.y)),animation)), \
            until_after_sources=mp.stop_when_fields_decayed(20,mp.Ey,mp.Vector3(outputsCenter[0][0],outputsCenter[0][1],outputsCenter[0][2]),1e-5))
        #sim.init_sim()
        #sim.solve_cw(tol=10**-5,L=20)
        print('saving animation to ' +
              str(os.path.join(plotDir + 'animation.gif')))
        animation.to_gif(
            10,
            os.path.join(plotDir + 'inputMode_' + str(mat['modeSourceNum']) +
                         '_' + 'animation.gif'))
    else:
        sim.run(until_after_sources=mp.stop_when_fields_decayed(
            20, mp.Ey,
            mp.Vector3(outputsCenter[0][0], outputsCenter[0][1],
                       outputsCenter[0][2]), 1e-5))

    normModeCoefficients = sim.get_eigenmode_coefficients(
        normMode, [mat['modeSourceNum'] + 1], direction=mp.X)
    #print('input norm coefficients TE00: ', numpy.abs(sim.get_eigenmode_coefficients(normMode, [1], direction=mp.X).alpha[0][0][0])**2)
    #print('input norm coefficients TE10: ', numpy.abs(sim.get_eigenmode_coefficients(normMode, [3], direction=mp.X).alpha[0][0][0])**2)
    #print('input norm coefficients TE20: ', numpy.abs(sim.get_eigenmode_coefficients(normMode, [5], direction=mp.X).alpha[0][0][0])**2)
    #normFluxes = sim.get
    resultingModes = []
    resultingOverlaps = []
    for i in range(0, len(outputsCenter)):
        resultingModes.append(
            sim.get_eigenmode_coefficients(transmissionModes[i],
                                           [outputsModeNum[i] + 1],
                                           direction=mp.X))
        resultingOverlaps.append([
            numpy.abs(resultingModes[i].alpha[0][j][0])**2 /
            numpy.abs(normModeCoefficients.alpha[0][j][0])**2
            for j in range(modeFrequencyResolution)
        ])
        #resultingFluxes.append(sim.get_flux_data(transmissionFluxes[i]) / inputFlux)

    if str(plotMe) == '1':
        eps_data = sim.get_array(center=mp.Vector3(),
                                 size=cell,
                                 component=mp.Dielectric)

        plt.figure()
        for i in range(0, len(resultingModes)):
            frequencys = numpy.linspace(
                1000 / mat['wavelength'] - spectralWidth / 2,
                1000 / mat['wavelength'] + spectralWidth / 2,
                modeFrequencyResolution)
            plt.plot(1000 / frequencys,
                     resultingOverlaps[i],
                     label='Transmission TE' +
                     str(int(outputsModeNum[i] / 2)) + '0')
            print('mode coefficients: ' + str(resultingOverlaps[i]) +
                  ' for mode number ' + str(outputsModeNum[i]))
            print('mode coefficients: ' + str(resultingModes[i].alpha[0]) +
                  ' for mode number ' + str(outputsModeNum[i]))
        plt.legend()
        plt.xlabel('Wavelength [nm]')
        plt.savefig(
            os.path.join(plotDir + 'inputMode_' + str(mat['modeSourceNum']) +
                         '_' + 'mode_coefficients.png'))
        plt.close()

        if mat['dims'][2] == 1:
            plt.figure()
            plt.imshow(eps_data.transpose(),
                       interpolation='spline36',
                       cmap='binary')
            plt.axis('off')
            plt.savefig(
                os.path.join(plotDir + 'inputMode_' +
                             str(mat['modeSourceNum']) + '_' +
                             'debug_structure.png'))
            plt.close()

            inputFourier = [
                sources[0].src.fourier_transform(1000 / f)
                for f in range(1, 1000)
            ]
            plt.figure()
            plt.plot(inputFourier)
            plt.savefig(
                os.path.join(plotDir + 'inputMode_' +
                             str(mat['modeSourceNum']) + '_' +
                             'debug_input_fourier.png'))
            plt.close()

            ez_data = numpy.real(
                sim.get_array(center=mp.Vector3(), size=cell, component=mp.Ez))
            plt.figure()
            plt.imshow(eps_data.transpose(),
                       interpolation='spline36',
                       cmap='binary')
            plt.imshow(ez_data.transpose(),
                       interpolation='spline36',
                       cmap='RdBu',
                       alpha=0.9)
            plt.axis('off')
            plt.savefig(
                os.path.join(plotDir + 'inputMode_' +
                             str(mat['modeSourceNum']) + '_' +
                             'debug_overlay.png'))
            plt.close()

    #it might be possible to just reset the structure. will result in speedup
    mp.all_wait()
    sim.reset_meep()
    end = time.time()
    if mp.am_master():
        os.remove(jobName + '_eps.h5')
        print('simulation took ' + str(end - start))

    if __name__ == "__main__":
        jobNameWithoutPath = jobName.split('/')[len(jobName.split('/')) - 1]
        sio.savemat(
            "results_" + jobNameWithoutPath, {
                'pos': posModesToMeasure,
                'modeNum': modeNumModesToMeasure,
                'overlap': resultingOverlaps,
                'inputModeNum': mat['modeSourceNum'],
                'inputModePos': mat['modeSourcePos']
            })
    else:
        return {
            'pos': posModesToMeasure,
            'modeNum': modeNumModesToMeasure,
            'overlap': resultingOverlaps,
            'inputModeNum': mat['modeSourceNum'],
            'inputModePos': mat['modeSourcePos']
        }
コード例 #9
0
def main(args):

    SIM_CELL = pya.LayerInfo(0, 0)
    Si = pya.LayerInfo(1, 0)
    MEEP_SOURCE1 = pya.LayerInfo(10, 0)
    MEEP_PORT1 = pya.LayerInfo(20, 0)
    MEEP_PORT2 = pya.LayerInfo(21, 0)

    # ## Simulation Parameters

    # In[3]:

    ring_radius = args.radius  # um
    ring_width = 0.5  # um
    pml_width = 1.0  # um
    straight_wg_length = pml_width + 0.2  # um

    # Simulation resolution
    res = 100  # pixels/μm

    # ## Step 1. Drawing a bent waveguide and saving into a temporary .gds file

    # In[4]:

    from zeropdk.layout import layout_arc, layout_waveguide, layout_path, layout_box
    from tempfile import NamedTemporaryFile

    # Create a temporary filename
    temp_file = NamedTemporaryFile(delete=False, suffix='.gds')
    filename = temp_file.name

    # Instantiate a layout and a top cell
    layout = pya.Layout()
    layout.dbu = 0.001
    TOP = layout.create_cell("TOP")

    # Unit vectors
    ex = pya.DVector(1, 0)
    ey = pya.DVector(0, 1)

    # Draw circular bend
    layout_arc(TOP, Si, -ring_radius * ey, ring_radius, ring_width, 0,
               np.pi / 2)

    # Extend the bend to avoid discontinuities
    layout_waveguide(TOP, Si, [0 * ex, -straight_wg_length * ex], ring_width)
    layout_waveguide(TOP, Si, [
        -1 * ring_radius * ey + ring_radius * ex,
        -straight_wg_length * ey - ring_radius * ey + ring_radius * ex
    ], ring_width)

    # Add the ports as 0-width paths
    port_size = ring_width * 4.0

    # Source port
    layout_path(
        TOP, MEEP_SOURCE1,
        [-port_size / 2 * ey - 0.2 * ex, port_size / 2 * ey - 0.2 * ex], 0)
    # Input port (immediately at the start of the bend)
    layout_path(TOP, MEEP_PORT1, [-port_size / 2 * ey, port_size / 2 * ey], 0)
    # Output port (immediately at the end of the bend)
    layout_path(TOP, MEEP_PORT2, [
        -1 * ring_radius * ey + ring_radius * ex - port_size / 2 * ex,
        -1 * ring_radius * ey + ring_radius * ex + port_size / 2 * ex
    ], 0)

    # Draw simulation region
    layout_box(
        TOP,
        SIM_CELL,
        -1.0 * ring_radius * ey - straight_wg_length *
        (ex + ey),  # Bottom left point 
        1.0 * ring_radius * ex + (straight_wg_length + port_size / 2) *
        (ex + ey),  # Top right point
        ex)

    # Write to file
    layout.write(filename)
    print(f"Produced file {filename}.")

    # ## Step 2. Load gds file into meep
    #
    # ### Visualization and simulation
    #
    # If you choose a normal filename (not temporary), you can download the GDSII file from the cluster (see Files in MyAdroit dashboard) to see it with your local Klayout. Otherwise, let's get simulating:

    # In[5]:

    gdsII_file = filename
    CELL_LAYER = 0
    SOURCE_LAYER = 10
    Si_LAYER = 1
    PORT1_LAYER = 20
    PORT2_LAYER = 21

    t_oxide = 1.0
    t_Si = 0.22
    t_SiO2 = 0.78

    oxide = mp.Medium(epsilon=2.25)
    silicon = mp.Medium(epsilon=12)

    lcen = 1.55
    fcen = 1 / lcen
    df = 0.2 * fcen
    nfreq = 25

    cell_zmax = 0
    cell_zmin = 0
    si_zmax = 10
    si_zmin = -10

    # read cell size, volumes for source region and flux monitors,
    # and coupler geometry from GDSII file
    # WARNING: Once the file is loaded, the prism contents is cached and cannot be reloaded.
    # SOLUTION: Use a different filename or restart the kernel

    si_layer = mp.get_GDSII_prisms(silicon, gdsII_file, Si_LAYER, si_zmin,
                                   si_zmax)

    cell = mp.GDSII_vol(gdsII_file, CELL_LAYER, cell_zmin, cell_zmax)
    src_vol = mp.GDSII_vol(gdsII_file, SOURCE_LAYER, si_zmin, si_zmax)
    p1 = mp.GDSII_vol(gdsII_file, PORT1_LAYER, si_zmin, si_zmax)
    p2 = mp.GDSII_vol(gdsII_file, PORT2_LAYER, si_zmin, si_zmax)

    sources = [
        mp.EigenModeSource(src=mp.GaussianSource(fcen, fwidth=df),
                           size=src_vol.size,
                           center=src_vol.center,
                           eig_band=1,
                           eig_parity=mp.NO_PARITY,
                           eig_match_freq=True)
    ]

    # Display simulation object
    sim = mp.Simulation(resolution=res,
                        default_material=oxide,
                        eps_averaging=False,
                        cell_size=cell.size,
                        boundary_layers=[mp.PML(pml_width)],
                        sources=sources,
                        geometry=si_layer,
                        geometry_center=cell.center)

    # Delete file created in previous cell

    import os
    temp_file.close()
    os.unlink(filename)

    # ## Step 3. Setup simulation environment
    #
    # This will load the python-defined parameters from the previous cell and instantiate a fast, C++ based, simulation environment using meep. It will also compute the eigenmode of the source, in preparation for the FDTD simulation.

    # In[6]:

    sim.reset_meep()

    # Could add monitors at many frequencies by looping over fcen
    # Means one FDTD for many results!
    mode1 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p1))
    mode2 = sim.add_mode_monitor(fcen, df, nfreq, mp.ModeRegion(volume=p2))

    # Let's store the frequencies that were generated by this mode monitor
    mode1_freqs = np.array(mp.get_eigenmode_freqs(mode1))
    mode2_freqs = np.array(mp.get_eigenmode_freqs(mode2))

    sim.init_sim()

    # ### Verify that the structure makes sense.
    #
    # Things to check:
    # - Are the sources and ports outside the PML?
    # - Are dimensions correct?
    # - Is the simulation region unnecessarily large?

    # In[7]:

    # If there is a warning that reads "The specified user volume
    # is larger than the simulation domain and has been truncated",
    # It has to do with some numerical errors between python and meep.
    # Ignore.

    # f = plt.figure(dpi=100)
    # sim.plot2D(ax=f.gca())
    # plt.show()

    # Looks pretty good. Simulations at the high enough resolution required to avoid spurious reflections in the bend are very slow! This can be sped up quite a bit by running the code in parallel from the terminal. Later, we will put this notebook's code into a script and run it in parallel.

    # ## Step 4. Simulate FDTD and Animate results
    #
    # More detailed meep documentation available [here](https://meep.readthedocs.io/en/latest/Python_Tutorials/Basics/#transmittance-spectrum-of-a-waveguide-bend).

    # In[8]:

    # Set to true to compute animation (may take a lot of memory)
    compute_animation = False

    # In[9]:

    # Setup and run the simulation

    # The following line defines a stopping condition depending on the square
    # of the amplitude of the Ez field at the port 2.
    print(
        f"Stop condition: decay to 0.1% of peak value in the last {2.0/df:.1f} time units."
    )
    stop_condition = mp.stop_when_fields_decayed(2.0 / df, mp.Ez, p2.center,
                                                 1e-3)
    if compute_animation:
        f = plt.figure(dpi=100)
        animate = mp.Animate2D(sim, mp.Ez, f=f, normalize=True)
        sim.run(mp.at_every(1, animate), until_after_sources=stop_condition)
        plt.close()
        # Save video as mp4
        animate.to_mp4(10, 'media/bend.mp4')
    else:
        sim.run(until_after_sources=stop_condition)

    # ### Visualize results
    #
    # Things to check:
    # - Was the simulation time long enough for the pulse to travel through port2 in its entirety? Given the automatic stop condition, this should be the case.

    # In[10]:

    from IPython.display import Video, display
    # display(Video('media/bend.mp4'))

    # ## Step 5. Compute loss and reflection of the bend

    # In[11]:

    # Every mode monitor measures the power flowing through it in either the forward or backward direction
    eig_mode1 = sim.get_eigenmode_coefficients(mode1, [1],
                                               eig_parity=mp.NO_PARITY)
    eig_mode2 = sim.get_eigenmode_coefficients(mode2, [1],
                                               eig_parity=mp.NO_PARITY)

    # First, we need to figure out which direction the "dominant planewave" k-vector is
    # We can pick the first frequency (0) for that, assuming that for all simulated frequencies,
    # The dominant k-vector will point in the same direction.
    k1 = eig_mode1.kdom[0]
    k2 = eig_mode2.kdom[0]

    # eig_mode.alpha[0,0,0] corresponds to the forward direction, whereas
    # eig_mode.alpha[0,0,1] corresponds to the backward direction

    # For port 1, we are interested in the +x direction, so if k1.x is positive, select 0, otherwise 1
    idx = (k1.x < 0) * 1
    p1_thru_coeff = eig_mode1.alpha[0, :, idx]
    p1_reflected_coeff = eig_mode1.alpha[0, :, 1 - idx]

    # For port 2, we are interestred in the -y direction
    idx = (k2.y > 0) * 1
    p2_thru_coeff = eig_mode2.alpha[0, :, idx]
    p2_reflected_coeff = eig_mode2.alpha[0, :, 1 - idx]

    # transmittance
    p2_trans = abs(p2_thru_coeff / p1_thru_coeff)**2
    p2_reflected = abs(p1_reflected_coeff / p1_thru_coeff)**2

    print("----------------------------------")
    print(f"Parameters: radius={ring_radius:.1f}")
    print(f"Frequencies: {mode1_freqs}")
    print(f"Transmitted fraction: {p2_trans}")
    print(f"Reflected fraction: {p2_reflected}")

    # In[1]:

    S21 = p2_thru_coeff / p1_thru_coeff
    S11 = p1_reflected_coeff / p1_thru_coeff

    S21_mag = np.abs(S21)
    S21_phase = np.unwrap(np.angle(S21))
    S11_mag = np.abs(S11)
    S11_phase = np.unwrap(np.angle(S11))

    # In[13]:

    #     # Plot S21
    #     f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(5, 8))
    #     ax1.plot(1/mode1_freqs, 10 * np.log10(S21_mag), '.-')
    #     ax1.set_title("S21")
    #     ax1.set_xlabel(r"$\lambda$ (um)")
    #     ax1.set_ylabel("Magnitude (dB)")
    #     ax1.set_ylim(None, 0)
    #     ax1.grid()

    #     ax2.plot(1/mode1_freqs, S21_phase, '.-')
    #     ax2.set_xlabel(r"$\lambda$ (um)")
    #     ax2.set_ylabel("Phase (rad)")
    #     ax2.grid()
    #     plt.tight_layout()

    #     # In[14]:

    #     # Plot S11
    #     f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(5, 8))
    #     ax1.plot(1/mode1_freqs, 10 * np.log10(S11_mag), '.-')
    #     ax1.set_title("S11")
    #     ax1.set_xlabel(r"$\lambda$ (um)")
    #     ax1.set_ylabel("Magnitude (dB)")
    #     ax1.set_ylim(None, 0)
    #     ax1.grid()

    #     ax2.plot(1/mode1_freqs, S11_phase, '.-')
    #     ax2.set_xlabel(r"$\lambda$ (um)")
    #     ax2.set_ylabel("Phase (rad)")
    #     ax2.grid()
    #     plt.tight_layout()

    # # Milestones
    #
    # Goal: Compute the transmission profile for bend radii between 1.5um and 10um.
    #
    # - Q: Is the reflection significant for any radius? What explain the loss?
    # - Q: What is the formula total size of the simulation region? How many pixels are there?
    # - Q: If each pixel can host 3-dimensional E-field and H-field vectors with 64bit complex float stored in each dimension, how many megabytes of data needs to be stored at each time step? Is it feasible to save all this information throughout the FDTD simulation?
    # - Bonus: Collect the simulation runtime for each radius. How does it change with different radii?
    # - Bonus: At what resolution does the accuracy of the simulation start degrading? In other words, if halving the resolution only results in a 1% relative difference in the most important target metric, it is still a good resolution.

    # In[2]:

    #Write to csv file
    import csv
    with open(f'sparams.r{ring_radius:.1f}um.csv', mode='w') as sparams_file:
        sparam_writer = csv.writer(sparams_file, delimiter=',')
        sparam_writer.writerow(
            ['f(Hz)', 'real(S11)', 'imag(S11)', 'real(S21)', 'imag(S21)'])
        for i in range(len(mode1_freqs)):
            sparam_writer.writerow([
                mode1_freqs[i] * 3e14,
                np.real(S11[i]),
                np.imag(S11[i]),
                np.real(S21[i]),
                np.imag(S21[i])
            ])