def forward_simulation(design_params,
                       mon_type,
                       frequencies=None,
                       mat2=silicon):
    matgrid = mp.MaterialGrid(mp.Vector3(Nx, Ny),
                              mp.air,
                              mat2,
                              weights=design_params.reshape(Nx, Ny))

    matgrid_geometry = [
        mp.Block(center=mp.Vector3(),
                 size=mp.Vector3(design_region_size.x, design_region_size.y,
                                 0),
                 material=matgrid)
    ]

    geometry = waveguide_geometry + matgrid_geometry

    sim = mp.Simulation(resolution=resolution,
                        cell_size=cell_size,
                        boundary_layers=pml_xy,
                        sources=wvg_source,
                        geometry=geometry)

    if not frequencies:
        frequencies = [fcen]

    if mon_type.name == 'EIGENMODE':
        mode = sim.add_mode_monitor(
            frequencies,
            mp.ModeRegion(center=mp.Vector3(0.5 * sxy - dpml - 0.1),
                          size=mp.Vector3(0, sxy - 2 * dpml, 0)),
            yee_grid=True,
            eig_parity=eig_parity)
    elif mon_type.name == 'DFT':
        mode = sim.add_dft_fields([mp.Ez],
                                  frequencies,
                                  center=mp.Vector3(1.25),
                                  size=mp.Vector3(0.25, 1, 0),
                                  yee_grid=False)

    sim.run(until_after_sources=mp.stop_when_dft_decayed())

    if mon_type.name == 'EIGENMODE':
        coeff = sim.get_eigenmode_coefficients(mode, [1],
                                               eig_parity).alpha[0, :, 0]
        S12 = np.power(np.abs(coeff), 2)
    elif mon_type.name == 'DFT':
        Ez2 = []
        for f in range(len(frequencies)):
            Ez_dft = sim.get_dft_array(mode, mp.Ez, f)
            Ez2.append(np.power(np.abs(Ez_dft[4, 10]), 2))
        Ez2 = np.array(Ez2)

    sim.reset_meep()

    if mon_type.name == 'EIGENMODE':
        return S12
    elif mon_type.name == 'DFT':
        return Ez2
Beispiel #2
0
 def register_monitors(self, frequencies):
     self._frequencies = np.asarray(frequencies)
     self._monitor = self.sim.add_mode_monitor(
         frequencies,
         mp.ModeRegion(center=self.volume.center, size=self.volume.size),
         yee_grid=True,
         decimation_factor=self.decimation_factor,
     )
     return self._monitor
Beispiel #3
0
 def register_monitors(self, frequencies):
     self.frequencies = np.asarray(frequencies)
     self.monitor = self.sim.add_mode_monitor(frequencies,
                                              mp.ModeRegion(
                                                  center=self.volume.center,
                                                  size=self.volume.size),
                                              yee_grid=True)
     self.normal_direction = self.monitor.normal_direction
     return self.monitor
Beispiel #4
0
def forward_simulation(design_params,mon_type):
    matgrid = mp.MaterialGrid(mp.Vector3(Nx,Ny),
                              mp.air,
                              silicon,
                              design_parameters=design_params.reshape(Nx,Ny),
                              grid_type='U_SUM')
            
    matgrid_geometry = [mp.Block(center=mp.Vector3(),
                                 size=mp.Vector3(design_shape.x,design_shape.y,0),
                                 material=matgrid)]

    geometry = waveguide_geometry + matgrid_geometry

    sim = mp.Simulation(resolution=resolution,
                        cell_size=cell_size,
                        boundary_layers=boundary_layers,
                        sources=sources,
                        geometry=geometry)

    if mon_type.name == 'EIGENMODE':
        mode = sim.add_mode_monitor(fcen,
                                    0,
                                    1,
                                    mp.ModeRegion(center=mp.Vector3(0.5*sxy-dpml),size=mp.Vector3(0,sxy,0)),
                                    yee_grid=True)

    elif mon_type.name == 'DFT':
        mode = sim.add_dft_fields([mp.Ez],
                                  fcen,
                                  0,
                                  1,
                                  center=mp.Vector3(0.5*sxy-dpml),
                                  size=mp.Vector3(0,sxy),
                                  yee_grid=False)

    sim.run(until_after_sources=20)

    if mon_type.name == 'EIGENMODE':
        coeff = sim.get_eigenmode_coefficients(mode,[1],eig_parity).alpha[0,0,0]
        S12 = abs(coeff)**2

    elif mon_type.name == 'DFT':
        Ez_dft = sim.get_dft_array(mode, mp.Ez, 0)
        Ez2 = abs(Ez_dft[63])**2

    sim.reset_meep()

    if mon_type.name == 'EIGENMODE':
        return S12
    elif mon_type.name == 'DFT':
        return Ez2
Beispiel #5
0
        def forward_simulation(design_params):
            matgrid = mp.MaterialGrid(mp.Vector3(Nx, Ny),
                                      mp.air,
                                      silicon,
                                      design_parameters=design_params.reshape(
                                          Nx, Ny),
                                      grid_type='U_SUM')

            matgrid_geometry = [
                mp.Block(center=mp.Vector3(),
                         size=mp.Vector3(design_shape.x, design_shape.y, 0),
                         material=matgrid)
            ]

            geometry = waveguide_geometry + matgrid_geometry

            sim = mp.Simulation(resolution=resolution,
                                cell_size=cell_size,
                                boundary_layers=boundary_layers,
                                sources=sources,
                                geometry=geometry)

            mode = sim.add_mode_monitor(
                fcen,
                0,
                1,
                mp.ModeRegion(center=mp.Vector3(0.5 * sxy - dpml),
                              size=mp.Vector3(0, sxy, 0)),
                yee_grid=True)

            sim.run(until_after_sources=20)

            # mode coefficients
            coeff = sim.get_eigenmode_coefficients(mode, [1],
                                                   eig_parity).alpha[0, 0, 0]

            # S parameters
            S12 = abs(coeff)**2

            sim.reset_meep()

            return S12
def forward_simulation_damping(design_params, frequencies=None, mat2=silicon):
    matgrid = mp.MaterialGrid(mp.Vector3(Nx, Ny),
                              mp.air,
                              mat2,
                              weights=design_params.reshape(Nx, Ny),
                              damping=3.14 * fcen)

    matgrid_geometry = [
        mp.Block(center=mp.Vector3(),
                 size=mp.Vector3(design_region_size.x, design_region_size.y,
                                 0),
                 material=matgrid)
    ]

    geometry = waveguide_geometry + matgrid_geometry

    sim = mp.Simulation(resolution=resolution,
                        cell_size=cell_size,
                        boundary_layers=pml_xy,
                        sources=wvg_source,
                        geometry=geometry)

    if not frequencies:
        frequencies = [fcen]

    mode = sim.add_mode_monitor(frequencies,
                                mp.ModeRegion(
                                    center=mp.Vector3(0.5 * sxy - dpml - 0.1),
                                    size=mp.Vector3(0, sxy - 2 * dpml, 0)),
                                yee_grid=True,
                                eig_parity=eig_parity)

    sim.run(until_after_sources=mp.stop_when_dft_decayed())

    coeff = sim.get_eigenmode_coefficients(mode, [1], eig_parity).alpha[0, :,
                                                                        0]
    S12 = np.power(np.abs(coeff), 2)
    sim.reset_meep()
    return S12
Beispiel #7
0
def main(args):
    cell_zmax = 0.5 * cell_thickness if args.three_d else 0
    cell_zmin = -0.5 * cell_thickness if args.three_d else 0
    si_zmax = t_Si if args.three_d else 0

    # read cell size, volumes for source region and flux monitors,
    # and coupler geometry from GDSII file
    upper_branch = mp.get_GDSII_prisms(silicon, gdsII_file, UPPER_BRANCH_LAYER,
                                       si_zmin, si_zmax)
    lower_branch = mp.get_GDSII_prisms(silicon, gdsII_file, LOWER_BRANCH_LAYER,
                                       si_zmin, si_zmax)

    cell = mp.GDSII_vol(gdsII_file, CELL_LAYER, cell_zmin, cell_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)
    src_vol = mp.GDSII_vol(gdsII_file, SOURCE_LAYER, si_zmin, si_zmax)

    # displace upper and lower branches of coupler (as well as source and flux regions)
    if args.d != default_d:
        delta_y = 0.5 * (args.d - default_d)
        delta = mp.Vector3(y=delta_y)
        p1.center += delta
        p2.center -= delta
        p3.center += delta
        p4.center -= delta
        src_vol.center += delta
        cell.size += 2 * delta
        for np in range(len(lower_branch)):
            lower_branch[np].center -= delta
            for nv in range(len(lower_branch[np].vertices)):
                lower_branch[np].vertices[nv] -= delta
        for np in range(len(upper_branch)):
            upper_branch[np].center += delta
            for nv in range(len(upper_branch[np].vertices)):
                upper_branch[np].vertices[nv] += delta

    geometry = upper_branch + lower_branch

    if args.three_d:
        oxide_center = mp.Vector3(z=-0.5 * t_oxide)
        oxide_size = mp.Vector3(cell.size.x, cell.size.y, t_oxide)
        oxide_layer = [
            mp.Block(material=oxide, center=oxide_center, size=oxide_size)
        ]
        geometry = geometry + oxide_layer

    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(fcen, fwidth=df),
            volume=src_vol,
            eig_band=1,
            eig_parity=mp.NO_PARITY if args.three_d else mp.EVEN_Y + mp.ODD_Z,
            eig_match_freq=True)
    ]

    sim = mp.Simulation(resolution=args.res,
                        cell_size=cell.size,
                        boundary_layers=[mp.PML(dpml)],
                        sources=sources,
                        geometry=geometry)

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

    sim.run(until_after_sources=100)

    # S parameters
    p1_coeff = sim.get_eigenmode_coefficients(
        mode1, [1],
        eig_parity=mp.NO_PARITY if args.three_d else mp.EVEN_Y +
        mp.ODD_Z).alpha[0, 0, 0]
    p2_coeff = sim.get_eigenmode_coefficients(
        mode2, [1],
        eig_parity=mp.NO_PARITY if args.three_d else mp.EVEN_Y +
        mp.ODD_Z).alpha[0, 0, 1]
    p3_coeff = sim.get_eigenmode_coefficients(
        mode3, [1],
        eig_parity=mp.NO_PARITY if args.three_d else mp.EVEN_Y +
        mp.ODD_Z).alpha[0, 0, 0]
    p4_coeff = sim.get_eigenmode_coefficients(
        mode4, [1],
        eig_parity=mp.NO_PARITY if args.three_d else mp.EVEN_Y +
        mp.ODD_Z).alpha[0, 0, 0]

    # transmittance
    p2_trans = abs(p2_coeff)**2 / abs(p1_coeff)**2
    p3_trans = abs(p3_coeff)**2 / abs(p1_coeff)**2
    p4_trans = abs(p4_coeff)**2 / abs(p1_coeff)**2

    print("trans:, {:.2f}, {:.6f}, {:.6f}, {:.6f}".format(
        args.d, p2_trans, p3_trans, p4_trans))
Beispiel #8
0
def get_simulation(
    component: Component,
    extend_ports_length: Optional[float] = 4.0,
    layer_stack: LayerStack = LAYER_STACK,
    res: int = 20,
    t_clad_top: float = 1.0,
    t_clad_bot: float = 1.0,
    tpml: float = 1.0,
    clad_material: str = "SiO2",
    is_3d: bool = False,
    wl_min: float = 1.5,
    wl_max: float = 1.6,
    wl_steps: int = 50,
    dfcen: float = 0.2,
    port_source_name: str = 1,
    port_field_monitor_name: str = 2,
    port_margin: float = 0.5,
    distance_source_to_monitors: float = 0.2,
) -> Dict[str, Any]:
    """Returns Simulation dict from gdsfactory.component

    based on meep directional coupler example
    https://meep.readthedocs.io/en/latest/Python_Tutorials/GDSII_Import/

    https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction

    Args:
        component: gf.Component
        extend_ports_function: function to extend the ports for a component to ensure it goes beyond the PML
        layer_to_thickness: Dict of layer number (int, int) to thickness (um)
        res: resolution (pixels/um) For example: (10: 100nm step size)
        t_clad_top: thickness for cladding above core
        t_clad_bot: thickness for cladding below core
        tpml: PML thickness (um)
        clad_material: material for cladding
        is_3d: if True runs in 3D
        wavelengths: iterable of wavelengths to simulate
        dfcen: delta frequency
        sidewall_angle: in degrees
        port_source_name: input port name
        port_field_monitor_name:
        port_margin: margin on each side of the port
        distance_source_to_monitors: in (um) source goes before

    Returns:
        sim: simulation object

    Make sure you visualize the simulation region with gf.before you simulate a component

    .. code::

        import gdsfactory as gf
        import gmeep as gm

        c = gf.components.bend_circular()
        margin = 2
        cm = gm.add_monitors(c)
        gf.show(cm)

    """
    layer_to_thickness = layer_stack.get_layer_to_thickness()
    layer_to_material = layer_stack.get_layer_to_material()
    layer_to_zmin = layer_stack.get_layer_to_zmin()
    layer_to_sidewall_angle = layer_stack.get_layer_to_sidewall_angle()

    wavelengths = np.linspace(wl_min, wl_max, wl_steps)
    if port_source_name not in component.ports:
        warnings.warn(
            f"port_source_name={port_source_name} not in {component.ports.keys()}"
        )
        port_source = component.get_ports_list()[0]
        port_source_name = port_source.name
        warnings.warn(f"Selecting port_source_name={port_source_name} instead.")

    if port_field_monitor_name not in component.ports:
        warnings.warn(
            f"port_field_monitor_name={port_field_monitor_name} not in {component.ports.keys()}"
        )
        port_field_monitor = (
            component.get_ports_list()[0]
            if len(component.ports) < 2
            else component.get_ports_list()[1]
        )
        port_field_monitor_name = port_field_monitor.name
        warnings.warn(
            f"Selecting port_field_monitor_name={port_field_monitor_name} instead."
        )

    assert isinstance(
        component, Component
    ), f"component needs to be a gf.Component, got Type {type(component)}"

    component_extended = (
        gf.components.extension.extend_ports(
            component=component, length=extend_ports_length, centered=True
        )
        if extend_ports_length
        else component
    )

    component = component.ref()
    component.x = 0
    component.y = 0

    gf.show(component_extended)

    component_extended.flatten()
    component_extended = component_extended.ref()

    # geometry_center = [component_extended.x, component_extended.y]
    # geometry_center = [0, 0]
    # print(geometry_center)

    layers_thickness = [
        layer_to_thickness[layer]
        for layer in component.get_layers()
        if layer in layer_to_thickness
    ]

    t_core = max(layers_thickness)
    cell_thickness = tpml + t_clad_bot + t_core + t_clad_top + tpml if is_3d else 0

    cell_size = mp.Vector3(
        component.xsize + 2 * tpml,
        component.ysize + 2 * tpml,
        cell_thickness,
    )

    geometry = []
    layer_to_polygons = component_extended.get_polygons(by_spec=True)
    for layer, polygons in layer_to_polygons.items():
        if layer in layer_to_thickness and layer in layer_to_material:
            height = layer_to_thickness[layer] if is_3d else mp.inf
            zmin_um = layer_to_zmin[layer] if is_3d else 0
            # center = mp.Vector3(0, 0, (zmin_um + height) / 2)

            for polygon in polygons:
                vertices = [mp.Vector3(p[0], p[1], zmin_um) for p in polygon]
                material_name = layer_to_material[layer]
                material = get_material(name=material_name)
                geometry.append(
                    mp.Prism(
                        vertices=vertices,
                        height=height,
                        sidewall_angle=layer_to_sidewall_angle[layer],
                        material=material,
                        # center=center
                    )
                )

    freqs = 1 / wavelengths
    fcen = np.mean(freqs)
    frequency_width = dfcen * fcen

    # Add source
    port = component.ports[port_source_name]
    angle = port.orientation
    width = port.width + 2 * port_margin
    size_x = width * abs(np.sin(angle * np.pi / 180))
    size_y = width * abs(np.cos(angle * np.pi / 180))
    size_x = 0 if size_x < 0.001 else size_x
    size_y = 0 if size_y < 0.001 else size_y
    size_z = cell_thickness - 2 * tpml if is_3d else 20
    size = [size_x, size_y, size_z]
    center = port.center.tolist() + [0]  # (x, y, z=0)

    field_monitor_port = component.ports[port_field_monitor_name]
    field_monitor_point = field_monitor_port.center.tolist() + [0]  # (x, y, z=0)

    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(fcen, fwidth=frequency_width),
            size=size,
            center=center,
            eig_band=1,
            eig_parity=mp.NO_PARITY if is_3d else mp.EVEN_Y + mp.ODD_Z,
            eig_match_freq=True,
        )
    ]

    sim = mp.Simulation(
        resolution=res,
        cell_size=cell_size,
        boundary_layers=[mp.PML(tpml)],
        sources=sources,
        geometry=geometry,
        default_material=get_material(name=clad_material),
        # geometry_center=geometry_center,
    )

    # Add port monitors dict
    monitors = {}
    for port_name in component.ports.keys():
        port = component.ports[port_name]
        angle = port.orientation
        width = port.width + 2 * port_margin
        size_x = width * abs(np.sin(angle * np.pi / 180))
        size_y = width * abs(np.cos(angle * np.pi / 180))
        size_x = 0 if size_x < 0.001 else size_x
        size_y = 0 if size_y < 0.001 else size_y
        size = mp.Vector3(size_x, size_y, size_z)
        size = [size_x, size_y, size_z]

        # if monitor has a source move monitor inwards
        length = -distance_source_to_monitors if port_name == port_source_name else 0
        xy_shifted = move_polar_rad_copy(
            np.array(port.center), angle=angle * np.pi / 180, length=length
        )
        center = xy_shifted.tolist() + [0]  # (x, y, z=0)
        m = sim.add_mode_monitor(freqs, mp.ModeRegion(center=center, size=size))
        m.z = 0
        monitors[port_name] = m
    return dict(
        sim=sim,
        cell_size=cell_size,
        freqs=freqs,
        monitors=monitors,
        sources=sources,
        field_monitor_point=field_monitor_point,
        port_source_name=port_source_name,
    )
Beispiel #9
0
    def run_mode_coeffs(self, mode_num, kpoint_func, nf=1, resolution=15):

        w = 1  # width of waveguide
        L = 10  # length of waveguide

        Si = mp.Medium(epsilon=12.0)

        dair = 3.0
        dpml = 3.0

        sx = dpml + L + dpml
        sy = dpml + dair + w + dair + dpml
        cell_size = mp.Vector3(sx, sy, 0)

        prism_x = sx + 1
        prism_y = w / 2
        vertices = [
            mp.Vector3(-prism_x, prism_y),
            mp.Vector3(prism_x, prism_y),
            mp.Vector3(prism_x, -prism_y),
            mp.Vector3(-prism_x, -prism_y)
        ]

        geometry = [mp.Prism(vertices, height=mp.inf, material=Si)]

        boundary_layers = [mp.PML(dpml)]

        # mode frequency
        fcen = 0.20  # > 0.5/sqrt(11) to have at least 2 modes
        df = 0.5 * fcen

        source = mp.EigenModeSource(src=mp.GaussianSource(fcen, fwidth=df),
                                    eig_band=mode_num,
                                    size=mp.Vector3(0, sy - 2 * dpml, 0),
                                    center=mp.Vector3(-0.5 * sx + dpml, 0, 0),
                                    eig_match_freq=True,
                                    eig_resolution=2 * resolution)

        sim = mp.Simulation(
            resolution=resolution,
            cell_size=cell_size,
            boundary_layers=boundary_layers,
            geometry=geometry,
            sources=[source],
            symmetries=[mp.Mirror(mp.Y, phase=1 if mode_num % 2 == 1 else -1)])

        xm = 0.5 * sx - dpml  # x-coordinate of monitor
        mflux = sim.add_mode_monitor(
            fcen, df, nf,
            mp.ModeRegion(center=mp.Vector3(xm, 0),
                          size=mp.Vector3(0, sy - 2 * dpml)))
        mode_flux = sim.add_flux(
            fcen, df, nf,
            mp.FluxRegion(center=mp.Vector3(xm, 0),
                          size=mp.Vector3(0, sy - 2 * dpml)))

        # sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, mp.Vector3(-0.5*sx+dpml,0), 1e-10))
        sim.run(until_after_sources=100)

        ##################################################
        # If the number of analysis frequencies is >1, we
        # are testing the unit-power normalization
        # of the eigenmode source: we observe the total
        # power flux through the mode_flux monitor (which
        # equals the total power emitted by the source as
        # there is no scattering in this ideal waveguide)
        # and check that it agrees with the prediction
        # of the eig_power() class method in EigenmodeSource.
        ##################################################
        if nf > 1:
            power_observed = mp.get_fluxes(mode_flux)
            freqs = mp.get_flux_freqs(mode_flux)
            power_expected = [source.eig_power(f) for f in freqs]
            return freqs, power_expected, power_observed

        modes_to_check = [
            1, 2
        ]  # indices of modes for which to compute expansion coefficients
        res = sim.get_eigenmode_coefficients(mflux,
                                             modes_to_check,
                                             kpoint_func=kpoint_func)

        self.assertTrue(res.kpoints[0].close(mp.Vector3(0.604301, 0, 0)))
        self.assertTrue(res.kpoints[1].close(mp.Vector3(0.494353, 0, 0),
                                             tol=1e-2))
        self.assertTrue(res.kdom[0].close(mp.Vector3(0.604301, 0, 0)))
        self.assertTrue(res.kdom[1].close(mp.Vector3(0.494353, 0, 0),
                                          tol=1e-2))
        self.assertAlmostEqual(res.cscale[0], 0.50000977, places=5)
        self.assertAlmostEqual(res.cscale[1], 0.50096888, places=5)
        mode_power = mp.get_fluxes(mode_flux)[0]

        TestPassed = True
        TOLERANCE = 5.0e-3
        c0 = res.alpha[
            mode_num - 1, 0,
            0]  # coefficient of forward-traveling wave for mode #mode_num
        for nm in range(1, len(modes_to_check) + 1):
            if nm != mode_num:
                cfrel = np.abs(res.alpha[nm - 1, 0, 0]) / np.abs(c0)
                cbrel = np.abs(res.alpha[nm - 1, 0, 1]) / np.abs(c0)
                if cfrel > TOLERANCE or cbrel > TOLERANCE:
                    TestPassed = False

        self.sim = sim

        # test 1: coefficient of excited mode >> coeffs of all other modes
        self.assertTrue(TestPassed,
                        msg="cfrel: {}, cbrel: {}".format(cfrel, cbrel))
        # test 2: |mode coeff|^2 = power
        self.assertAlmostEqual(mode_power / abs(c0**2), 1.0, places=1)

        return res
Beispiel #10
0
def get_simulation(
    component: Component,
    resolution: int = 20,
    extend_ports_length: Optional[float] = 10.0,
    layer_stack: LayerStack = LAYER_STACK,
    zmargin_top: float = 3.0,
    zmargin_bot: float = 3.0,
    tpml: float = 1.5,
    clad_material: str = "SiO2",
    is_3d: bool = False,
    wl_min: float = 1.5,
    wl_max: float = 1.6,
    wl_steps: int = 50,
    dfcen: float = 0.2,
    port_source_name: str = "o1",
    port_field_monitor_name: str = "o2",
    port_margin: float = 3,
    distance_source_to_monitors: float = 0.2,
    port_source_offset: float = 0,
    port_monitor_offset: float = 0,
    dispersive: bool = False,
    **settings,
) -> Dict[str, Any]:
    r"""Returns Simulation dict from gdsfactory Component

    based on meep directional coupler example
    https://meep.readthedocs.io/en/latest/Python_Tutorials/GDSII_Import/

    https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction

    .. code::

         top view
              ________________________________
             |                               |
             | xmargin_left                  | port_extension
             |<------>          port_margin ||<-->
          ___|___________          _________||___
             |           \        /          |
             |            \      /           |
             |             ======            |
             |            /      \           |
          ___|___________/        \__________|___
             |   |                 <-------->|
             |   |ymargin_bot   xmargin_right|
             |   |                           |
             |___|___________________________|

        side view
              ________________________________
             |                     |         |
             |                     |         |
             |                   zmargin_top |
             |ymargin              |         |
             |<---> _____         _|___      |
             |     |     |       |     |     |
             |     |     |       |     |     |
             |     |_____|       |_____|     |
             |       |                       |
             |       |                       |
             |       |zmargin_bot            |
             |       |                       |
             |_______|_______________________|


    Args:
        component: gf.Component
        resolution: in pixels/um (20: for coarse, 120: for fine)
        extend_ports_length: to extend ports beyond the PML
        layer_stack: Dict of layer number (int, int) to thickness (um)
        zmargin_top: thickness for cladding above core
        zmargin_bot: thickness for cladding below core
        tpml: PML thickness (um)
        clad_material: material for cladding
        is_3d: if True runs in 3D
        wl_min: wavelength min (um)
        wl_max: wavelength max (um)
        wl_steps: wavelength steps
        dfcen: delta frequency
        port_source_name: input port name
        port_field_monitor_name:
        port_margin: margin on each side of the port
        distance_source_to_monitors: in (um) source goes before
        port_source_offset: offset between source GDS port and source MEEP port
        port_monitor_offset: offset between monitor GDS port and monitor MEEP port
        dispersive: use dispersive material models (requires higher resolution)

    Keyword Args:
        settings: other parameters for sim object (resolution, symmetries, etc.)

    Returns:
        simulation dict: sim, monitors, sources

    Make sure you review the simulation before you simulate a component

    .. code::

        import gdsfactory as gf
        import gdsfactory.simulation.meep as gm

        c = gf.components.bend_circular()
        gm.write_sparameters_meep(c, run=False)

    """

    layer_to_thickness = layer_stack.get_layer_to_thickness()
    layer_to_material = layer_stack.get_layer_to_material()
    layer_to_zmin = layer_stack.get_layer_to_zmin()
    layer_to_sidewall_angle = layer_stack.get_layer_to_sidewall_angle()

    component_ref = component.ref()
    component_ref.x = 0
    component_ref.y = 0

    wavelengths = np.linspace(wl_min, wl_max, wl_steps)
    port_names = list(component_ref.ports.keys())

    if port_source_name not in port_names:
        warnings.warn(f"port_source_name={port_source_name!r} not in {port_names}")
        port_source = component_ref.get_ports_list()[0]
        port_source_name = port_source.name
        warnings.warn(f"Selecting port_source_name={port_source_name!r} instead.")

    if port_field_monitor_name not in component_ref.ports:
        warnings.warn(
            f"port_field_monitor_name={port_field_monitor_name!r} not in {port_names}"
        )
        port_field_monitor = (
            component_ref.get_ports_list()[0]
            if len(component.ports) < 2
            else component.get_ports_list()[1]
        )
        port_field_monitor_name = port_field_monitor.name
        warnings.warn(
            f"Selecting port_field_monitor_name={port_field_monitor_name!r} instead."
        )

    assert isinstance(
        component, Component
    ), f"component needs to be a gf.Component, got Type {type(component)}"

    component_extended = (
        gf.components.extension.extend_ports(
            component=component, length=extend_ports_length, centered=True
        )
        if extend_ports_length
        else component
    )
    gf.show(component_extended)

    component_extended.flatten()
    component_extended = component_extended.ref()

    # geometry_center = [component_extended.x, component_extended.y]
    # geometry_center = [0, 0]
    # print(geometry_center)

    layers_thickness = [
        layer_to_thickness[layer]
        for layer in component.layers
        if layer in layer_to_thickness
    ]

    t_core = max(layers_thickness)
    cell_thickness = tpml + zmargin_bot + t_core + zmargin_top + tpml if is_3d else 0

    cell_size = mp.Vector3(
        component.xsize + 2 * tpml,
        component.ysize + 2 * tpml,
        cell_thickness,
    )

    geometry = []
    layer_to_polygons = component_extended.get_polygons(by_spec=True)
    for layer, polygons in layer_to_polygons.items():
        if layer in layer_to_thickness and layer in layer_to_material:
            height = layer_to_thickness[layer] if is_3d else mp.inf
            zmin_um = layer_to_zmin[layer] if is_3d else 0
            # center = mp.Vector3(0, 0, (zmin_um + height) / 2)

            for polygon in polygons:
                vertices = [mp.Vector3(p[0], p[1], zmin_um) for p in polygon]
                material_name = layer_to_material[layer]
                material = get_material(name=material_name, dispersive=dispersive)
                geometry.append(
                    mp.Prism(
                        vertices=vertices,
                        height=height,
                        sidewall_angle=layer_to_sidewall_angle[layer],
                        material=material,
                        # center=center
                    )
                )

    freqs = 1 / wavelengths
    fcen = np.mean(freqs)
    frequency_width = dfcen * fcen

    # Add source
    port = component_ref.ports[port_source_name]
    angle_rad = np.radians(port.orientation)
    width = port.width + 2 * port_margin
    size_x = width * abs(np.sin(angle_rad))
    size_y = width * abs(np.cos(angle_rad))
    size_x = 0 if size_x < 0.001 else size_x
    size_y = 0 if size_y < 0.001 else size_y
    size_z = cell_thickness - 2 * tpml if is_3d else 20
    size = [size_x, size_y, size_z]
    xy_shifted = move_polar_rad_copy(
        np.array(port.center), angle=angle_rad, length=port_source_offset
    )
    center = xy_shifted.tolist() + [0]  # (x, y, z=0)

    field_monitor_port = component_ref.ports[port_field_monitor_name]
    field_monitor_point = field_monitor_port.center.tolist() + [0]  # (x, y, z=0)

    if np.isclose(port.orientation, 0):
        direction = mp.X
    elif np.isclose(port.orientation, 90):
        direction = mp.Y
    elif np.isclose(port.orientation, 180):
        direction = mp.X
    elif np.isclose(port.orientation, 270):
        direction = mp.Y
    else:
        ValueError(f"Port angle {port.orientation} not 0, 90, 180, or 270 degrees!")

    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(fcen, fwidth=frequency_width),
            size=size,
            center=center,
            eig_band=1,
            eig_parity=mp.NO_PARITY if is_3d else mp.EVEN_Y + mp.ODD_Z,
            eig_match_freq=True,
            eig_kpoint=-1 * mp.Vector3(x=1).rotate(mp.Vector3(z=1), angle_rad),
            direction=direction,
        )
    ]

    sim = mp.Simulation(
        cell_size=cell_size,
        boundary_layers=[mp.PML(tpml)],
        sources=sources,
        geometry=geometry,
        default_material=get_material(name=clad_material),
        resolution=resolution,
        **settings,
    )

    # Add port monitors dict
    monitors = {}
    for port_name in component_ref.ports.keys():
        port = component_ref.ports[port_name]
        angle_rad = np.radians(port.orientation)
        width = port.width + 2 * port_margin
        size_x = width * abs(np.sin(angle_rad))
        size_y = width * abs(np.cos(angle_rad))
        size_x = 0 if size_x < 0.001 else size_x
        size_y = 0 if size_y < 0.001 else size_y
        size = mp.Vector3(size_x, size_y, size_z)
        size = [size_x, size_y, size_z]

        # if monitor has a source move monitor inwards
        length = (
            -distance_source_to_monitors + port_source_offset
            if port_name == port_source_name
            else port_monitor_offset
        )
        xy_shifted = move_polar_rad_copy(
            np.array(port.center), angle=angle_rad, length=length
        )
        center = xy_shifted.tolist() + [0]  # (x, y, z=0)
        m = sim.add_mode_monitor(freqs, mp.ModeRegion(center=center, size=size))
        m.z = 0
        monitors[port_name] = m
    return dict(
        sim=sim,
        cell_size=cell_size,
        freqs=freqs,
        monitors=monitors,
        sources=sources,
        field_monitor_point=field_monitor_point,
        port_source_name=port_source_name,
        initialized=False,
    )
def get_transmission_2ports(
    component: Component,
    extend_ports_length: Optional[float] = 4.0,
    layer_core: int = 1,
    layer_source: int = 110,
    layer_monitor1: int = 101,
    layer_monitor2: int = 102,
    layer_simulation_region: int = 2,
    res: int = 20,
    t_clad_bot: float = 1.0,
    t_core: float = 0.22,
    t_clad_top: float = 1.0,
    dpml: int = 1,
    clad_material: Medium = mp.Medium(epsilon=2.25),
    core_material: Medium = mp.Medium(epsilon=12),
    is_3d: bool = False,
    run: bool = True,
    wavelengths: ndarray = np.linspace(1.5, 1.6, 50),
    field_monitor_point: Tuple[int, int, int] = (0, 0, 0),
    dfcen: float = 0.2,
) -> Dict[str, Any]:
    """Returns dict with Sparameters for a 2port gf.component

    requires source and  port monitors in the GDS

    based on meep directional coupler example
    https://meep.readthedocs.io/en/latest/Python_Tutorials/GDSII_Import/

    https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction

    Args:
        component: gf.Component
        extend_ports_function: function to extend the ports for a component to ensure it goes beyond the PML
        layer_core: GDS layer for the Component material
        layer_source: for the source monitor
        layer_monitor1: monitor layer for port 1
        layer_monitor2: monitor layer for port 2
        layer_simulation_region: for simulation region
        res: resolution (pixels/um) For example: (10: 100nm step size)
        t_clad_bot: thickness for cladding below core
        t_core: thickness of the core material
        t_clad_top: thickness for cladding above core
        dpml: PML thickness (um)
        clad_material: material for cladding
        core_material: material for core
        is_3d: if True runs in 3D
        run: if True runs simulation, False only build simulation
        wavelengths: iterable of wavelengths to simulate
        field_monitor_point: monitors the field and stops simulation after field decays by 1e-9
        dfcen: delta frequency

    Returns:
        Dict:
            sim: simulation object

    Make sure you visualize the simulation region with gf.before you simulate a component

    .. code::

        import gdsfactory as gf
        import gmeep as gm

        component = gf.components.bend_circular()
        margin = 2
        cm = gm.add_monitors(component)
        cm.show()

    """
    assert isinstance(
        component, Component
    ), f"component needs to be a Component, got Type {type(component)}"
    if extend_ports_length:
        component = gf.components.extension.extend_ports(
            component=component, length=extend_ports_length, centered=True
        )
    component.flatten()
    gdspath = component.write_gds()
    gdspath = str(gdspath)

    freqs = 1 / wavelengths
    fcen = np.mean(freqs)
    frequency_width = dfcen * fcen
    cell_thickness = dpml + t_clad_bot + t_core + t_clad_top + dpml

    cell_zmax = 0.5 * cell_thickness if is_3d else 0
    cell_zmin = -0.5 * cell_thickness if is_3d else 0

    core_zmax = 0.5 * t_core if is_3d else 10
    core_zmin = -0.5 * t_core if is_3d else -10

    geometry = mp.get_GDSII_prisms(
        core_material, gdspath, layer_core, core_zmin, core_zmax
    )
    cell = mp.GDSII_vol(gdspath, layer_core, cell_zmin, cell_zmax)
    sim_region = mp.GDSII_vol(gdspath, layer_simulation_region, cell_zmin, cell_zmax)

    cell.size = mp.Vector3(
        sim_region.size[0] + 2 * dpml, sim_region.size[1] + 2 * dpml, sim_region.size[2]
    )
    cell_size = cell.size

    zsim = t_core + t_clad_top + t_clad_bot + 2 * dpml
    m_zmin = -zsim / 2
    m_zmax = +zsim / 2
    src_vol = mp.GDSII_vol(gdspath, layer_source, m_zmin, m_zmax)

    sources = [
        mp.EigenModeSource(
            src=mp.GaussianSource(fcen, fwidth=frequency_width),
            size=src_vol.size,
            center=src_vol.center,
            eig_band=1,
            eig_parity=mp.NO_PARITY if is_3d else mp.EVEN_Y + mp.ODD_Z,
            eig_match_freq=True,
        )
    ]

    sim = mp.Simulation(
        resolution=res,
        cell_size=cell_size,
        boundary_layers=[mp.PML(dpml)],
        sources=sources,
        geometry=geometry,
        default_material=clad_material,
    )
    sim_settings = dict(
        resolution=res,
        cell_size=cell_size,
        fcen=fcen,
        field_monitor_point=field_monitor_point,
        layer_core=layer_core,
        t_clad_bot=t_clad_bot,
        t_core=t_core,
        t_clad_top=t_clad_top,
        is_3d=is_3d,
        dmp=dpml,
    )

    m1_vol = mp.GDSII_vol(gdspath, layer_monitor1, m_zmin, m_zmax)
    m2_vol = mp.GDSII_vol(gdspath, layer_monitor2, m_zmin, m_zmax)
    m1 = sim.add_mode_monitor(
        freqs,
        mp.ModeRegion(center=m1_vol.center, size=m1_vol.size),
    )
    m1.z = 0
    m2 = sim.add_mode_monitor(
        freqs,
        mp.ModeRegion(center=m2_vol.center, size=m2_vol.size),
    )
    m2.z = 0

    # if 0:
    #     ''' Useful for debugging.  '''
    #     sim.run(until=50)
    #     sim.plot2D(fields=mp.Ez)
    #     plt.show()
    #     quit()

    r = dict(sim=sim, cell_size=cell_size, sim_settings=sim_settings)

    if run:
        sim.run(
            until_after_sources=mp.stop_when_fields_decayed(
                dt=50, c=mp.Ez, pt=field_monitor_point, decay_by=1e-9
            )
        )

        # call this function every 50 time spes
        # look at simulation and measure component that we want to measure (Ez component)
        # when field_monitor_point decays below a certain 1e-9 field threshold

        # Calculate the mode overlaps
        m1_results = sim.get_eigenmode_coefficients(m1, [1]).alpha
        m2_results = sim.get_eigenmode_coefficients(m2, [1]).alpha

        # Parse out the overlaps
        a1 = m1_results[:, :, 0]  # forward wave
        b1 = m1_results[:, :, 1]  # backward wave
        a2 = m2_results[:, :, 0]  # forward wave
        # b2 = m2_results[:, :, 1]  # backward wave

        # Calculate the actual scattering parameters from the overlaps
        s11 = np.squeeze(b1 / a1)
        s12 = np.squeeze(a2 / a1)
        s22 = s11.copy()
        s21 = s12.copy()

        # s22 and s21 requires another simulation, with the source on the other port
        # Luckily, if the device is symmetric, we can assume that s22=s11 and s21=s12.

        # visualize results
        plt.figure()
        plt.plot(
            wavelengths,
            10 * np.log10(np.abs(s11) ** 2),
            "-o",
            label="Reflection",
        )
        plt.plot(
            wavelengths,
            10 * np.log10(np.abs(s12) ** 2),
            "-o",
            label="Transmission",
        )
        plt.ylabel("Power (dB)")
        plt.xlabel(r"Wavelength ($\mu$m)")
        plt.legend()
        plt.grid(True)

        r.update(dict(s11=s11, s12=s12, s21=s21, s22=s22, wavelengths=wavelengths))
        keys = [key for key in r.keys() if key.startswith("S")]
        s = {f"{key}a": list(np.unwrap(np.angle(r[key].flatten()))) for key in keys}
        s_mod = {f"{key}m": list(np.abs(r[key].flatten())) for key in keys}
        s.update(**s_mod)
        s = pd.DataFrame(s)
    return r
Beispiel #12
0
    def test_grating_3d(self):
        """Unit test for mode decomposition in 3d.

        Verifies that the reflectance and transmittance in the z
        direction at a single wavelength for a unit cell of a
        3d grating using a normally incident planewave is equivalent
        to the sum of the Poynting flux (normalized by the flux
        of the input source) for all the individual reflected
        and transmitted diffracted orders.
        """
        resolution = 25  # pixels/μm

        nSi = 3.45
        Si = mp.Medium(index=nSi)
        nSiO2 = 1.45
        SiO2 = mp.Medium(index=nSiO2)

        wvl = 0.5  # wavelength
        fcen = 1 / wvl

        dpml = 1.0  # PML thickness
        dsub = 3.0  # substrate thickness
        dair = 3.0  # air padding
        hcyl = 0.5  # cylinder height
        rcyl = 0.2  # cylinder radius

        sx = 1.1
        sy = 0.8
        sz = dpml + dsub + hcyl + dair + dpml

        cell_size = mp.Vector3(sx, sy, sz)

        boundary_layers = [mp.PML(thickness=dpml, direction=mp.Z)]

        # periodic boundary conditions
        k_point = mp.Vector3()

        src_cmpt = mp.Ex
        sources = [
            mp.Source(src=mp.GaussianSource(fcen, fwidth=0.2 * fcen),
                      size=mp.Vector3(sx, sy, 0),
                      center=mp.Vector3(0, 0, -0.5 * sz + dpml),
                      component=src_cmpt)
        ]

        symmetries = [
            mp.Mirror(direction=mp.X, phase=-1),
            mp.Mirror(direction=mp.Y, phase=+1)
        ]

        sim = mp.Simulation(resolution=resolution,
                            cell_size=cell_size,
                            sources=sources,
                            default_material=SiO2,
                            boundary_layers=boundary_layers,
                            k_point=k_point,
                            symmetries=symmetries)

        refl_pt = mp.Vector3(0, 0, -0.5 * sz + dpml + 0.5 * dsub)
        refl_flux = sim.add_mode_monitor(
            fcen, 0, 1,
            mp.ModeRegion(center=refl_pt, size=mp.Vector3(sx, sy, 0)))

        stop_cond = mp.stop_when_energy_decayed(20, 1e-6)
        sim.run(until_after_sources=stop_cond)

        input_flux = mp.get_fluxes(refl_flux)
        input_flux_data = sim.get_flux_data(refl_flux)

        sim.reset_meep()

        geometry = [
            mp.Block(size=mp.Vector3(mp.inf, mp.inf, dpml + dsub),
                     center=mp.Vector3(0, 0, -0.5 * sz + 0.5 * (dpml + dsub)),
                     material=SiO2),
            mp.Cylinder(height=hcyl,
                        radius=rcyl,
                        center=mp.Vector3(0, 0, -0.5 * sz + dpml + dsub +
                                          0.5 * hcyl),
                        material=Si)
        ]

        sim = mp.Simulation(resolution=resolution,
                            cell_size=cell_size,
                            sources=sources,
                            geometry=geometry,
                            boundary_layers=boundary_layers,
                            k_point=k_point,
                            symmetries=symmetries)

        refl_flux = sim.add_mode_monitor(
            fcen, 0, 1,
            mp.ModeRegion(center=refl_pt, size=mp.Vector3(sx, sy, 0)))
        sim.load_minus_flux_data(refl_flux, input_flux_data)

        tran_flux = sim.add_mode_monitor(
            fcen, 0, 1,
            mp.ModeRegion(center=mp.Vector3(0, 0, 0.5 * sz - dpml),
                          size=mp.Vector3(sx, sy, 0)))

        sim.run(until_after_sources=stop_cond)

        # sum the Poynting flux in z direction for all reflected orders
        Rsum = 0

        # number of reflected modes/orders in SiO2 in x and y directions (upper bound)
        nm_x = int(fcen * nSiO2 * sx) + 1
        nm_y = int(fcen * nSiO2 * sy) + 1
        for m_x in range(nm_x):
            for m_y in range(nm_y):
                for S_pol in [False, True]:
                    res = sim.get_eigenmode_coefficients(
                        refl_flux,
                        mp.DiffractedPlanewave([m_x, m_y, 0],
                                               mp.Vector3(1, 0, 0),
                                               1 if S_pol else 0,
                                               0 if S_pol else 1))
                    r_coeffs = res.alpha
                    Rmode = abs(r_coeffs[0, 0, 1])**2 / input_flux[0]
                    print("refl-order:, {}, {}, {}, {:.6f}".format(
                        "s" if S_pol else "p", m_x, m_y, Rmode))
                    if m_x == 0 and m_y == 0:
                        Rsum += Rmode
                    elif (m_x != 0 and m_y == 0) or (m_x == 0 and m_y != 0):
                        Rsum += 2 * Rmode
                    else:
                        Rsum += 4 * Rmode

        # sum the Poynting flux in z direction for all transmitted orders
        Tsum = 0

        # number of transmitted modes/orders in air in x and y directions (upper bound)
        nm_x = int(fcen * sx) + 1
        nm_y = int(fcen * sy) + 1
        for m_x in range(nm_x):
            for m_y in range(nm_y):
                for S_pol in [False, True]:
                    res = sim.get_eigenmode_coefficients(
                        tran_flux,
                        mp.DiffractedPlanewave([m_x, m_y, 0],
                                               mp.Vector3(1, 0, 0),
                                               1 if S_pol else 0,
                                               0 if S_pol else 1))
                    t_coeffs = res.alpha
                    Tmode = abs(t_coeffs[0, 0, 0])**2 / input_flux[0]
                    print("tran-order:, {}, {}, {}, {:.6f}".format(
                        "s" if S_pol else "p", m_x, m_y, Tmode))
                    if m_x == 0 and m_y == 0:
                        Tsum += Tmode
                    elif (m_x != 0 and m_y == 0) or (m_x == 0 and m_y != 0):
                        Tsum += 2 * Tmode
                    else:
                        Tsum += 4 * Tmode

        r_flux = mp.get_fluxes(refl_flux)
        t_flux = mp.get_fluxes(tran_flux)
        Rflux = -r_flux[0] / input_flux[0]
        Tflux = t_flux[0] / input_flux[0]

        print("refl:, {}, {}".format(Rsum, Rflux))
        print("tran:, {}, {}".format(Tsum, Tflux))
        print("sum:,  {}, {}".format(Rsum + Tsum, Rflux + Tflux))

        ## to obtain agreement for two decimal digits,
        ## the resolution must be increased to 200
        self.assertAlmostEqual(Rsum, Rflux, places=1)
        self.assertAlmostEqual(Tsum, Tflux, places=2)
        self.assertAlmostEqual(Rsum + Tsum, 1.00, places=1)
Beispiel #13
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])
                                   ])
Beispiel #14
0
                       eig_match_freq=True)
]

geometry = [board, trace]

pml_layers = [mp.PML(pmlThickness)]
sim = mp.Simulation(resolution=resolution,
                    cell_size=cell,
                    boundary_layers=pml_layers,
                    sources=sources,
                    geometry=geometry)

plane1 = mp.Block(planeSize, center=mp.Vector3(-twidth / 2, 0, 0))
plane2 = mp.Block(planeSize, center=mp.Vector3(twidth / 2, 0, 0))
mode1 = sim.add_mode_monitor(f, df, nfreq,
                             mp.ModeRegion(volume=plane1, direction=mp.X))
mode2 = sim.add_mode_monitor(f, df, nfreq,
                             mp.ModeRegion(volume=plane2, direction=mp.X))

sim.run(until_after_sources=tau)

S11 = []
S12 = []
S21 = []
S22 = []
ff = []

S1 = sim.get_eigenmode_coefficients(mode1, [1],
                                    eig_parity=mp.EVEN_Y + mp.ODD_Z)
S2 = sim.get_eigenmode_coefficients(mode2, [1],
                                    eig_parity=mp.EVEN_Y + mp.ODD_Z)
Beispiel #15
0
    def run_mode_coeffs(self, mode_num, kpoint_func):

        resolution = 15

        w = 1   # width of waveguide
        L = 10  # length of waveguide

        Si = mp.Medium(epsilon=12.0)

        dair = 3.0
        dpml = 3.0

        sx = dpml + L + dpml
        sy = dpml + dair + w + dair + dpml
        cell_size = mp.Vector3(sx, sy, 0)

        prism_x = sx + 1
        prism_y = w / 2
        vertices = [mp.Vector3(-prism_x, prism_y),
                    mp.Vector3(prism_x, prism_y),
                    mp.Vector3(prism_x, -prism_y),
                    mp.Vector3(-prism_x, -prism_y)]

        geometry = [mp.Prism(vertices, height=mp.inf, material=Si)]

        boundary_layers = [mp.PML(dpml)]

        # mode frequency
        fcen = 0.20  # > 0.5/sqrt(11) to have at least 2 modes

        sources = [mp.EigenModeSource(src=mp.GaussianSource(fcen, fwidth=0.5*fcen),
                                      eig_band=mode_num,
                                      size=mp.Vector3(0,sy-2*dpml,0),
                                      center=mp.Vector3(-0.5*sx+dpml,0,0),
                                      eig_match_freq=True,
                                      eig_resolution=32) ]

        sim = mp.Simulation(resolution=resolution,
                            cell_size=cell_size,
                            boundary_layers=boundary_layers,
                            geometry=geometry,
                            sources=sources,
                            symmetries=[mp.Mirror(mp.Y, phase=1 if mode_num % 2 == 1 else -1)])

        xm = 0.5*sx - dpml  # x-coordinate of monitor
        mflux = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(center=mp.Vector3(xm,0), size=mp.Vector3(0,sy-2*dpml)))
        mode_flux = sim.add_flux(fcen, 0, 1, mp.FluxRegion(center=mp.Vector3(xm,0), size=mp.Vector3(0,sy-2*dpml)))

        # sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, mp.Vector3(-0.5*sx+dpml,0), 1e-10))
        sim.run(until_after_sources=100)

        modes_to_check = [1, 2]  # indices of modes for which to compute expansion coefficients
        res = sim.get_eigenmode_coefficients(mflux, modes_to_check, kpoint_func=kpoint_func)

        self.assertTrue(res.kpoints[0].close(mp.Vector3(0.604301, 0, 0)))
        self.assertTrue(res.kpoints[1].close(mp.Vector3(0.494353, 0, 0), tol=1e-2))
        self.assertTrue(res.kdom[0].close(mp.Vector3(0.604301, 0, 0)))
        self.assertTrue(res.kdom[1].close(mp.Vector3(0.494353, 0, 0), tol=1e-2))

        mode_power = mp.get_fluxes(mode_flux)[0]

        TestPassed = True
        TOLERANCE = 5.0e-3
        c0 = res.alpha[mode_num - 1, 0, 0] # coefficient of forward-traveling wave for mode #mode_num
        for nm in range(1, len(modes_to_check)+1):
            if nm != mode_num:
                cfrel = np.abs(res.alpha[nm - 1, 0, 0]) / np.abs(c0)
                cbrel = np.abs(res.alpha[nm - 1, 0, 1]) / np.abs(c0)
                if cfrel > TOLERANCE or cbrel > TOLERANCE:
                    TestPassed = False

        self.sim = sim

        # test 1: coefficient of excited mode >> coeffs of all other modes
        self.assertTrue(TestPassed, msg="cfrel: {}, cbrel: {}".format(cfrel, cbrel))
        # test 2: |mode coeff|^2 = power
        self.assertAlmostEqual(mode_power / abs(c0**2), 1.0, places=1)

        return res
]

# Display simulation object
sim = mp.Simulation(resolution=res,
                    default_material=oxide,
                    eps_averaging=False,
                    subpixel_maxeval=1,
                    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))

mode1 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p1))
mode2 = sim.add_mode_monitor(fcen, 0, 1, mp.ModeRegion(volume=p2))

# Setup and run the simulation
sim.run(until_after_sources=100)

# Do the analysis we want
# S parameters
# I am computing 3 bands to choose the right coefficients
print(sim.get_eigenmode_coefficients(mode1, [1, 2, 3],
                                     eig_parity=mp.NO_PARITY))
print(sim.get_eigenmode_coefficients(mode2, [1, 2, 3],
                                     eig_parity=mp.NO_PARITY))

# Save a video
#filename = 'media/bend.mp4'
Beispiel #17
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])
            ])