### Install gdsfactory with all plugins Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs gdsfactory and all its associated plugins. Use this for a complete setup. ```bash pip install "gdsfactory[full]" --upgrade ``` -------------------------------- ### Install Ray Tune and Hyperopt Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/ray_optimiser.ipynb Install Ray Tune with necessary extras and the Hyperopt library for optimization. ```bash pip install "ray[tune,air]" hyperopt ``` -------------------------------- ### Setup for Si waveguide mode solver Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/femwell_01_modes.ipynb Initializes parameters for simulating a Silicon (Si) waveguide, including refractive indices, dimensions, and meshing resolutions. This setup is for a single width calculation. ```python wavelength = 1.55 # wavelength of the light ncore = 3.47 # refractive index of the core (Si) nclad = 1.444 # refractive index of the cladding (SiO2) num_modes = 6 widths = np.array([0.5]) wg_thickness = 0.22 sidewall_angle = 0 # sidewall angle of the waveguide (in degrees) slab_thickness = 0 default_resolution_max = 0.08 core_resolution = 0.02 core_distance = 1 buffer_size = 1.0 all_neffs = np.zeros((widths.shape[0], num_modes)) all_te_fracs = np.zeros((widths.shape[0], num_modes)) for i, width in enumerate(tqdm(widths)): top_width = width bottom_width = 2 * np.tan(np.deg2rad(sidewall_angle)) + width total_slab_width = 4 + bottom_width if slab_thickness > 0: core = Polygon( [ (-total_slab_width / 2, 0), (+total_slab_width / 2, 0), (+total_slab_width / 2, slab_thickness), (+bottom_width / 2, slab_thickness), (+top_width / 2, wg_thickness), (-top_width / 2, wg_thickness), (-bottom_width / 2, slab_thickness), (-total_slab_width / 2, slab_thickness), (-total_slab_width / 2, 0), ] ) else: core = Polygon( [ (-bottom_width / 2, 0), (+bottom_width / 2, 0), (+top_width / 2, wg_thickness), (-top_width / 2, wg_thickness), (-bottom_width / 2, 0), ] ) polygons = OrderedDict( ``` -------------------------------- ### Install PySwarms Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/pso.ipynb Install PySwarms using pip. This is a prerequisite for running the optimization examples. ```console pip install pyswarms ``` -------------------------------- ### Install gplugins with specific plugins Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs gplugins along with a selected set of plugins. Useful for a tailored installation. ```bash pip install "gplugins[devsim,femwell,gmsh,schematic,meow,meshwell,sax,tidy3d]" --upgrade ``` -------------------------------- ### Get and plot tidy3d simulation modeler setup Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Initializes a `ComponentModeler` for the tidy3d component and plots the simulation setup along the x and z axes. ```python # initialize the tidy3d ComponentModeler modeler = c.get_component_modeler( center_z="core", port_size_mult=(6, 4), sim_size_z=3.0 ) # we can plot the tidy3d simulation setup fig, ax = plt.subplots(2, 1) modeler.plot_sim(z=c.get_layer_center("core")[2], ax=ax[0]) modeler.plot_sim(x=c.ports[0].dcenter[0], ax=ax[1]) fig.tight_layout() plt.show() ``` -------------------------------- ### Install gplugins with a minimal set of plugins Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs gplugins with only the specified plugins. Ideal for users who need a subset of functionalities. ```bash pip install "gplugins[schematic,femwell,meow,sax,tidy3d]" --upgrade ``` -------------------------------- ### Install gplugins with SAX Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Installs the gplugins library with SAX support. Ensure you follow the SAX installation instructions for specific requirements. ```bash ! pip install gplugins[sax] ``` -------------------------------- ### Install gplugins and dependencies with uv Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs gplugins and its development dependencies using the uv package manager. This is part of the recommended contributor setup. ```bash uv venv --python 3.12 uv sync --extra docs --extra dev # --extra tidy3d --extra femwell ... ``` -------------------------------- ### Get help for run_capacitive_simulation_palace Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/palace_01_electrostatic.ipynb Displays the help documentation for the `run_capacitive_simulation_palace` function, providing details on its parameters and usage. ```python help(run_capacitive_simulation_palace) ``` -------------------------------- ### Install uv package manager on Windows Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs the uv package manager using PowerShell. This is the recommended method for contributors on Windows. ```powershell # On Windows. powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Setup Simulation with Continuous Source Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Configures a Meep simulation using gplugins with a continuous source and complex fields enabled. Requires the component definition from the previous step. ```python component = gf.add_padding_container( c, default=0, top=3.2, bottom=3.2, ) sim_dict = get_simulation( component, is_3d=False, port_source_offset=-0.1, extend_ports_length=3, continuous_source=True, force_complex_fields=True, ) sim = sim_dict["sim"] sim.plot2D() ``` -------------------------------- ### PSO Optimization Setup Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/pso.ipynb Sets up the loss function, trainable simulation function, bounds, and PSO optimizer for optimizing a gdsfactory MMI1x2 component. ```python from functools import partial import gdsfactory as gf import numpy as np from gdsfactory.config import PATH try: import pyswarms as ps except ImportError: print("Please install pyswarms and gmeep to run this example") try: import gplugins.gmeep as gm except ImportError: print("Please install meep to run this example") # Create a working directory for the PSO optimization wrk_dir = PATH.cwd / "extra" wrk_dir.mkdir(exist_ok=True) # ## Define the loss function used in the PSO optimization def loss_S21_L1(x, target): r"""Loss function. Returns :math:`$\\|sum_i L_1(x_i)\\|$` and :math:`$x$` as a tuple.""" return np.abs(target - x), x # ## Define the trainable function for the PSO optimization def trainable_simulations(x, loss=lambda x: x): """Training step, or `trainable`, function for Ray Tune to run simulations and return results.""" loss_arr = [] use_mpi = False for xi in x: # Component to optimize component = gf.components.mmi1x2(length_mmi=xi[0], width_mmi=xi[1]) # Simulate and get output meep_params = dict( component=component, run=True, dirpath=wrk_dir, wavelength_start=1.5, wavelength_points=1, is_3d=False, ) if use_mpi: # change this to false if no MPI support s_params = gm.write_sparameters_meep_mpi( cores=2, **meep_params, # set this to be the same as in `tune.Tuner` ) s_params = np.load( s_params ) # parallel version returns the filepath to npz instead else: s_params = gm.write_sparameters_meep(**meep_params) s_params_abs = np.abs(s_params["o2@0,o1@0"]) ** 2 loss_x, x = loss(s_params_abs) if not np.isscalar(x): # for many wavelengths, consider sum and mean loss_x, x = -loss_x.sum(), x.mean() loss_arr.append(loss_x) return np.asarray(loss_arr) # Define the target value for the loss function loss = partial(loss_S21_L1, target=0.5) func = partial(trainable_simulations, loss=loss) # Create bounds for the optimization max_bound = np.array([0.05, 0.05]) min_bound = np.array([2, 2]) bounds = (min_bound, max_bound) # Set options for the PSO optimizer options = {"c1": 0.5, "c2": 0.3, "w": 0.9} try: # Create an instance of the PSO optimizer optimizer = ps.single.GlobalBestPSO( n_particles=10, dimensions=2, options=options, bounds=bounds ) except NameError: print("Please install pyswarms to run this example") ``` -------------------------------- ### Waveguide Mode Solver Setup Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_1_mzi.ipynb Sets up a Waveguide object for mode solving. Specifies material properties, dimensions, and wavelength. The group_index_step is used for group index calculation. ```python import matplotlib.pyplot as plt import numpy as np import gplugins.tidy3d as gt nm = 1e-3 strip = gt.modes.Waveguide( wavelength=1.55, core_width=0.5, core_thickness=0.22, slab_thickness=0.0, core_material="si", clad_material="sio2", group_index_step=10 * nm, ) ``` -------------------------------- ### Install uv package manager on macOS and Linux Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs the uv package manager using a curl script. This is the recommended method for contributors on Unix-like systems. ```bash # On macOS and Linux. curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Initialize and Run Tuner Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/ray_optimiser.ipynb Instantiate a `tune.Tuner` with a trainable function, resource allocation, parameter space, and run configuration. Call `tuner.fit()` to start the optimization. Ensure `local_dir` is set for saving results. ```python tuner = tune.Tuner( tune.with_resources( trainable_simulations, {"cpu": 2} ), # maximum resources given to a worker, it also supports 'gpu' param_space=search_config, tune_config=tune_config, run_config=ray.air.RunConfig( local_dir=tmp / "ray_results", checkpoint_config=ray.air.CheckpointConfig(checkpoint_frequency=1), log_to_file=True, verbose=2, # Intermediate results in Jupyter ), ) # Previous simulations can be restored with, see https://docs.ray.io/en/latest/tune/tutorials/tune-stopping.html # tuner = Tuner.restore(path=tmp / "ray_results/my_experiment") results = tuner.fit() ``` -------------------------------- ### Install Meep and MPB using Conda Source: https://github.com/gdsfactory/gplugins/blob/main/README.md Installs Meep and MPB using conda or mamba, required for MacOS, Linux, or Windows WSL. Ensure MPI is configured. ```bash conda install pymeep=*=mpi_mpich_* -c conda-forge -y ``` -------------------------------- ### SAX Circuit Simulation Setup Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Prepares for SAX simulation by extracting placements and creating a SAX circuit object from the gdsfactory netlist. The `recursive=True` option ensures all sub-components are included. ```python placements = compact_mzi1.get_netlist()["placements"] mzi3, _ = sax.circuit(compact_mzi1.get_netlist(recursive=True), models=models) mzi3() ``` -------------------------------- ### Install Palace via Singularity/Apptainer Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/palace_01_electrostatic.ipynb This script allows running the Palace solver using a Singularity container. Ensure the `palace.sif` file is in the specified path. ```bash #!/bin/bash singularity exec ~/palace.sif /opt/palace/bin/palace "$@" ``` -------------------------------- ### Create and Pad a Straight Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Defines a straight component and adds padding using gplugins. This is a prerequisite for simulation setup. ```python c = gf.components.straight(length=10) component = gf.add_padding_container( c, default=0, top=3.2, bottom=3.2, ) component.plot() ``` -------------------------------- ### Setup gdsfactory and LayerStack for Thermal Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/femwell_02_heater.ipynb Initializes gdsfactory and configures the LayerStack with thermal properties for simulation. Ensure the PDK is activated and layer thicknesses/z-coordinates are set. ```python import gdsfactory as gf import meshio from gdsfactory.generic_tech import get_generic_pdk from gdsfactory.technology import LayerStack from skfem.io import from_meshio PDK = get_generic_pdk() PDK.activate() LAYER_STACK = PDK.layer_stack LAYER_STACK.layers["heater"].thickness = 0.13 LAYER_STACK.layers["heater"].zmin = 2.2 heater = gf.components.straight_heater_metal(length=50) heater.plot() ``` -------------------------------- ### Initialize Lumerical INTERCONNECT Session Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/lumerical_2_interconnect.ipynb Imports necessary libraries and initializes a Lumerical INTERCONNECT session. Requires installation of gdsfactory, ubcpdk, and lumapi. ```python from collections import OrderedDict import gdsfactory as gf import matplotlib.pyplot as plt import numpy as np import ubcpdk.components as pdk from gdsfactory.get_netlist import get_instance_name_from_alias as get_instance_name from gdsfactory.routing import route_single from gplugins.lumerical.interconnect import plot_wavelength_sweep, run_wavelength_sweep gf.config.rich_output() import lumapi session = lumapi.INTERCONNECT() ``` -------------------------------- ### Define and Simulate an MZI Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/lumerical_2_interconnect.ipynb Creates an MZI component and runs a wavelength sweep simulation on it. This example demonstrates simulating a more complex component and setting `is_top_level` to True. ```python mzi = pdk.mzi() mzi ``` ```python # If the ports are in the top-level cell, use a dictionary like this and # set is_top_level to True in the call to run_wavelength_sweep ports_in = {"o1": "o1"} ports_out = {"o2": "o2"} simulation_settings = OrderedDict( [ ("MC_uniformity_thickness", np.array([200, 200])), ("MC_uniformity_width", np.array([200, 200])), ("MC_non_uniform", 0), ("MC_grid", 1e-5), ("MC_resolution_x", 200), ("MC_resolution_y", 0), ] ) results = run_wavelength_sweep( session=session, component=mzi, ports_in=ports_in, ports_out=ports_out, results=("transmission",), component_distance_scaling=50, simulation_settings=simulation_settings, setup_mc=True, is_top_level=True, ) ``` -------------------------------- ### Setup tidy3d component with material mapping and padding Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Defines a material mapping for tidy3d and sets up a `Tidy3DComponent` with specified padding and extension for a gdsfactory component. ```python # define a mapping of pdk material names to tidy3d medium objects mapping = { "si": td.Medium(name="Si", permittivity=3.47**2), "sio2": td.Medium(name="SiO2", permittivity=1.47**2), } # setup the tidy3d component c = gt.Tidy3DComponent( component=component, layer_stack=LAYER_STACK, material_mapping=mapping, pad_xy_inner=2.0, pad_xy_outer=2.0, pad_z_inner=0, pad_z_outer=0, extend_ports=2.0, ) # plot the component and the layerstack fig = plt.figure(constrained_layout=True) gs = fig.add_gridspec(ncols=2, nrows=3, width_ratios=(3, 1)) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[1, 0]) ax2 = fig.add_subplot(gs[2, 0]) axl = fig.add_subplot(gs[1, 1]) c.plot_slice(x="core", ax=ax0) c.plot_slice(y="core", ax=ax1) c.plot_slice(z="core", ax=ax2) axl.legend(*ax0.get_legend_handles_labels(), loc="center") axl.axis("off") plt.show() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Imports essential libraries for gdsfactory, MEEP, and plotting. Ensure these are installed before running. ```python import gdsfactory as gf import matplotlib.pyplot as plt import meep as mp import numpy as np from gdsfactory.generic_tech import get_generic_pdk from meep import MaterialGrid, Medium, Vector3, Volume from meep.adjoint import ( DesignRegion, get_conic_radius_from_eta_e, ) import gplugins import gplugins.gmeep as gm from gplugins.gmeep.get_simulation import get_simulation gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() ``` -------------------------------- ### Get Help for Batch Meep Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Displays the help message for the 'write_sparameters_meep_batch' function, useful for understanding its parameters and usage for batch simulations. ```python help(gm.write_sparameters_meep_batch) ``` -------------------------------- ### Simulate and Plot Grating Coupler (Repeat) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Re-simulates and plots a grating coupler with identical parameters as a previous example. This might be for comparison or to ensure reproducibility. ```python sim = gt.get_simulation_grating_coupler( c, is_3d=False, fiber_angle_deg=fiber_angle_deg, fiber_xoffset=0 ) f = gt.plot_simulation(sim) ``` -------------------------------- ### Write Grating S-parameters with Plotting Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_02_gratings.ipynb Computes grating coupler S-parameters and plots the simulation results for review. Ensure the simulation setup is correct. ```python sp = gm.write_sparameters_grating(plot=True) ``` -------------------------------- ### Write S-parameters for a straight component (multimode, no run) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Generates S-parameters for a straight component, configured for multimode simulation, without running the actual MEEP simulation. This allows for setup verification. ```python c = gf.components.straight(length=5, width=2) sp = gm.write_sparameters_meep( c, run=False, ymargin_top=3, ymargin_bot=3, is_3d=False, resolution=20, ) ``` -------------------------------- ### Write S-parameters for a straight component (no run) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Generates S-parameters for a straight component using MEEP without running the simulation. Useful for verifying setup. `ymargin_top` and `ymargin_bot` ensure adequate distance to PML boundaries. ```python sp = gm.write_sparameters_meep(c, run=False, ymargin_top=3, ymargin_bot=3, is_3d=False) ``` -------------------------------- ### Instantiate and Visualize Compact MZI Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Creates an instance of the compact MZI component and displays it. This is a basic step before simulation. ```python compact_mzi1 = compact_mzi() compact_mzi1 ``` -------------------------------- ### Prepare and Write Batch Simulations Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Prepares a list of simulation jobs for grating couplers with varying fiber angles and writes them to disk for parallel execution. Ensure the PATH object is correctly configured. ```python c = gf.components.grating_coupler_elliptical_lumerical() fiber_angles = [3, 5, 7] jobs = [ dict( component=c, is_3d=False, fiber_angle_deg=fiber_angle_deg, filepath=PATH.sparameters_repo / f"gc_angle{fiber_angle_deg}", ) for fiber_angle_deg in fiber_angles ] sps = gt.write_sparameters_grating_coupler_batch(jobs) ``` -------------------------------- ### Get Netlist Keys Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_3_cascaded_mzi.ipynb Retrieves the top-level keys of a netlist dictionary. ```python netlist.keys() ``` -------------------------------- ### Get Optimized Delta Length Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Retrieves the optimized delta_length value after the training process. ```python delta_length = params_fn(state) delta_length ``` -------------------------------- ### Get and print netlist keys Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/11_get_netlist.ipynb Extracts the netlist of a component and prints its top-level keys. ```python c = gf.components.mzi() n = c.get_netlist() print(c.get_netlist().keys()) ``` -------------------------------- ### Instantiate and Display a Simple MZI Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Creates and displays a simple Mach-Zehnder Interferometer (MZI) circuit using predefined models. ```python mzi = simple_mzi() mzi ``` -------------------------------- ### Dilation Calculation Example Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Illustrates a calculation related to dilation, showing a multiplication operation. ```python 0.5 * 0.8 ``` -------------------------------- ### Get Effective Refractive Index Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mode_solver_fdfd.ipynb Retrieves the effective refractive index (n_eff) of the waveguide modes. ```python strip.n_eff ``` -------------------------------- ### Create and plot a component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/11_get_netlist.ipynb Creates a Mach-Zehnder Interferometer (MZI) component and plots it. ```python c = gf.components.mzi() c.plot() ``` -------------------------------- ### Get Instance Keys from Netlist Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_3_cascaded_mzi.ipynb Retrieves the keys (instance names) from the 'instances' dictionary within a netlist. ```python netlist["instances"].keys() ``` -------------------------------- ### Initialize gdsfactory and PDK Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_1_mzi.ipynb Imports necessary libraries and activates the generic PDK for gdsfactory. ```python import gdsfactory as gf import numpy as np from gdsfactory.generic_tech import get_generic_pdk gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() ``` -------------------------------- ### Get Group Index from Waveguide Mode Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_1_mzi.ipynb Retrieves the group index (ng) of the fundamental mode from the Waveguide object. ```python ng = strip.n_group[0] ng ``` -------------------------------- ### Get component netlist Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/11_get_netlist.ipynb Extracts the netlist of a component. The netlist is a dictionary representing the component's structure and connections. ```python n = c.get_netlist() ``` -------------------------------- ### Dilation Erosion Calculation Example Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Illustrates a calculation related to negative dilation (erosion), showing a multiplication operation. ```python 0.2 * 0.5 ``` -------------------------------- ### Initialize and Solve Continuous Wave Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Initializes the Meep simulation and solves for a continuous wave at a specific frequency. Ensure the simulation object `sim` is properly initialized. ```python sim.init_sim() sim.solve_cw(1e-6, 10000, 10) ``` -------------------------------- ### Plot electric field for a non-guided mode Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mpb_001_mpb_waveguide.ipynb Visualizes the electric field for a mode that is not guided (its neff is below the cladding index). ```python m3.plot_e() ``` -------------------------------- ### Create and plot a sample circuit Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/vlsir_netlist.ipynb Generates a sample circuit using `pads_correct` and displays it. This is a prerequisite for netlist extraction. ```python c = pads_correct() c.plot() ``` -------------------------------- ### Get Grating Coupler Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Retrieves simulation data for an out-of-plane grating coupler. Supports both 2D and 3D simulations. ```python help(gt.get_simulation_grating_coupler) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mpb_001_mpb_waveguide.ipynb Imports matplotlib, meep, numpy, and gplugins.modes for waveguide mode analysis. ```python import matplotlib.pyplot as plt import meep as mp import numpy as np import gplugins.modes as gm ``` -------------------------------- ### Get Help for Coupler Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Use this function to display the help message for the coupler component, detailing its parameters and usage. ```python help(gf.components.coupler) ``` -------------------------------- ### Import gplugins and Meep for Grating Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_02_gratings.ipynb Imports necessary libraries for gdsfactory and gplugins simulations, including the generic PDK. Activate the PDK before running simulations. ```python import gdsfactory as gf from gdsfactory.generic_tech import get_generic_pdk import gplugins as sim import gplugins.gmeep as gm gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() ``` -------------------------------- ### Get recursive netlist for MZI lattice Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/11_get_netlist.ipynb Extracts a recursive netlist for the MZI lattice component, including nested connections. ```python n_recursive = c.get_netlist(recursive=True) ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_1_mzi.ipynb Imports essential libraries for gdsfactory, JAX, Matplotlib, NumPy, SAX, and gplugins. Ensure these are installed before running. ```python import gdsfactory as gf import jax.numpy as jnp import matplotlib.pyplot as plt import numpy as np import sax import gplugins.sax as gsax ``` -------------------------------- ### Define a PINWaveguide cross-section for simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/devsim_01_pin_waveguide.ipynb Initializes a PINWaveguide object with specified dimensions and then sets up the DEVSIM solver. This prepares the simulation environment for the waveguide geometry. ```python nm = 1e-9 c = get_simulation_xsection.PINWaveguide( core_width=500 * nm, core_thickness=220 * nm, slab_thickness=90 * nm, ) # Initialize mesh and solver c.ddsolver() ``` -------------------------------- ### Import necessary libraries for path-length analysis Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/path_length_analysis.ipynb Imports required libraries for GDS analysis, plotting, and text formatting. Ensure these are installed. ```python from IPython.display import display import gdsfactory as gf import matplotlib.pyplot as plt import textwrap from gplugins.path_length_analysis.path_length_analysis_from_gds import ( extract_paths, get_min_radius_and_length_path_dict, plot_curvature, ) ``` -------------------------------- ### Create and Plot a Coupler Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Instantiates a coupler component with specified length and gap, then visualizes it. Ensure the 'gf' and plotting libraries are imported. ```python c = gf.components.coupler(length=8, gap=0.13) c.plot() ``` -------------------------------- ### Import necessary libraries for SAX Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Imports essential libraries for gdsfactory, JAX, SAX, and plotting. This setup is required for most SAX-related operations. ```python import json import logging import os import sys from functools import partial import gdsfactory as gf import jax import jax.example_libraries.optimizers as opt import jax.numpy as jnp import matplotlib.pyplot as plt import meow as mw import numpy as np import sax from gdsfactory.generic_tech import get_generic_pdk from numpy.fft import fft2, fftfreq, fftshift, ifft2 from rich.logging import RichHandler from sklearn.linear_model import LinearRegression from tqdm.notebook import tqdm, trange import gplugins.sax as gs import gplugins.tidy3d as gt from gplugins.common.config import PATH gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() logger = logging.getLogger() logger.removeHandler(sys.stderr) logging.basicConfig(level="WARNING", datefmt="[%X]", handlers=[RichHandler()]) ``` -------------------------------- ### Configure and Run Wavelength Sweep Simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/lumerical_2_interconnect.ipynb Sets up simulation parameters and executes a wavelength sweep using `run_wavelength_sweep`. This function requires the component, Lumerical session, input/output ports, and simulation settings. ```python simulation_settings = OrderedDict( [ ("MC_uniformity_thickness", np.array([200, 200])), ("MC_uniformity_width", np.array([200, 200])), ("MC_non_uniform", 0), ("MC_grid", 1e-5), ("MC_resolution_x", 200), ("MC_resolution_y", 0), ] ) results = run_wavelength_sweep( component=circuit, session=session, ports_in=ports_in, ports_out=ports_out, simulation_settings=simulation_settings, results=("transmission",), component_distance_scaling=10, setup_mc=True, ) ``` -------------------------------- ### Generate and write sample layout Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/11_get_netlist_spice.ipynb Creates a sample layout using pads_correct and writes it to a GDS file. Use this to generate a GDS file for netlist extraction. ```python c = pads_correct() gdspath = c.write_gds() c.show() c.plot() ``` -------------------------------- ### Setup tidy3d component without substrate layer Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Configures a `Tidy3DComponent` after removing the 'substrate' layer from the `LAYER_STACK`, then plots the component slices. ```python LAYER_STACK.layers.pop("substrate", None) # setup the tidy3d component c = gt.Tidy3DComponent( component=component, layer_stack=LAYER_STACK, material_mapping=mapping, pad_xy_inner=2.0, pad_xy_outer=2.0, pad_z_inner=0, pad_z_outer=0, extend_ports=2.0, ) # plot the component and the layerstack fig = plt.figure(constrained_layout=True) gs = fig.add_gridspec(ncols=2, nrows=3, width_ratios=(3, 1)) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[1, 0]) ax2 = fig.add_subplot(gs[2, 0]) axl = fig.add_subplot(gs[1, 1]) c.plot_slice(x="core", ax=ax0) c.plot_slice(y="core", ax=ax1) c.plot_slice(z="core", ax=ax2) axl.legend(*ax0.get_legend_handles_labels(), loc="center") axl.axis("off") plt.show() ``` -------------------------------- ### Initialize and Plot Waveguide Coupler Index Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mode_solver_fdfd.ipynb Creates a WaveguideCoupler object and plots its effective indices. Requires specifying core widths, gap, and material properties. ```python gap = 200 * nm c = gt.modes.WaveguideCoupler( wavelength=wavelength, core_width=(wg_width, wg_width), gap=gap, core_thickness=core_thickness, slab_thickness=slab_thickness, core_material="si", clad_material="sio2", ) c.plot_index() ``` -------------------------------- ### Write S-parameters for a taper component (no run) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Generates S-parameters for a taper component without running the simulation. This allows for setup verification. ```python sp = gm.write_sparameters_meep(c, run=False, ymargin_top=3, ymargin_bot=3) ``` -------------------------------- ### Get help for dispersion calculation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mpb_001_mpb_waveguide.ipynb Displays the help message for the `find_mode_dispersion` function, providing information on its parameters and usage for dispersion calculations. ```python help(gm.find_mode_dispersion) ``` -------------------------------- ### Initialize gdsfactory and MEOW Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meow_01.ipynb Sets up the gdsfactory environment and PDK, then defines a component and a filtered LayerStack for MEOW simulation. Ensure your LayerStack includes material information for all relevant layers. ```python import gdsfactory as gf import matplotlib.pyplot as plt import numpy as np from gdsfactory.generic_tech import get_generic_pdk from gplugins.meow import MEOW gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() LAYER_STACK = PDK.layer_stack c = gf.components.taper_cross_section_sine() c.plot() ``` ```python layer_stack = LAYER_STACK filtered_layer_stack = gf.technology.LayerStack( layers={ k: layer_stack.layers[k] for k in ( "slab90", "core", "box", "clad", ) } ) ``` ```python eme = MEOW( component=c, layer_stack=filtered_layer_stack, wavelength=1.55, overwrite=True ) ``` -------------------------------- ### Get Results DataFrame Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/ray_optimiser.ipynb Retrieve the optimization results as a pandas DataFrame for easy analysis and manipulation. This is useful for inspecting all simulation outcomes. ```python df = results.get_dataframe() df ``` -------------------------------- ### Run Batch Meep Simulations for 1x1 Components Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Launches a batch of Meep simulations for 1x1 components using MPI. Configure the number of cores per run, total cores, and parallelism strategy. The function returns a list of filepaths for the saved S-parameters. ```python c1_dict = {"component": c, "ymargin": 3} jobs = [ c1_dict, ] filepaths = gm.write_sparameters_meep_batch_1x1( jobs=jobs, cores_per_run=4, total_cores=8, lazy_parallelism=True, is_3d=False, filepath='data/meep_straight3.npz' ) sp = np.load(filepaths[0]) gplugins.plot.plot_sparameters(sp) ``` -------------------------------- ### Import DRC Functions from gplugins Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/klayout_drc.ipynb Imports essential functions for writing DRC rules and generating Klayout decks. Ensure gplugins is installed. ```python import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.generic_tech import LAYER from gdsfactory.typings import Float2, Layer from gplugins.klayout.drc.write_drc import ( check_area, check_density, check_enclosing, check_separation, check_space, check_width, write_drc_deck_macro, ) ``` -------------------------------- ### 3D Simulation with Filepath Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Runs a 3D simulation, specifying the output filepath and sim_size_z. Assumes 'c' is a defined component. ```python c = gf.components.straight(length=2) sp = gt.write_sparameters( c, filepath=PATH.sparameters_repo / "straight_3d.npz", sim_size_z=4 ) gp.plot.plot_sparameters(sp) ``` -------------------------------- ### MEOW Simulation with Specific cell_length Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meow_01.ipynb Instantiates and simulates a component using a specific `cell_length` value. This snippet is part of the convergence test setup. ```python eme = MEOW( component=c, layer_stack=filtered_layer_layer_stack, wavelength=1.55, overwrite=True, spacing_y=-3, cell_length=0.25, ) ``` -------------------------------- ### 2D Simulation with Filepath Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Runs a 2D simulation, specifying the output filepath, sim_size_z, and center_z. Assumes 'component' is defined. ```python component = gf.components.straight() sp = gt.write_sparameters( component, filepath=PATH.sparameters_repo / "straight_2d.npz", sim_size_z=0, center_z="core", ) ``` -------------------------------- ### Import necessary libraries and initialize PDK Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/palace_01_electrostatic.ipynb Imports required gdsfactory, pyvista, and gplugins modules. Activates the generic PDK for use in simulations. ```python import os from math import inf from pathlib import Path import gdsfactory as gf import pyvista as pv from gdsfactory.components.analog.interdigital_capacitor import ( interdigital_capacitor, ) from gdsfactory.generic_tech import LAYER, get_generic_pdk from gdsfactory.technology import LayerStack from gdsfactory.technology.layer_stack import LayerLevel from IPython.display import display from gplugins.common.types import RFMaterialSpec from gplugins.palace import run_capacitive_simulation_palace gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() ``` -------------------------------- ### Create a Straight Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Instantiates a straight waveguide component with a specified length. This component can be used as input for simulation jobs. ```python c = gf.components.straight(length=3.1) ``` -------------------------------- ### Get effective refractive index (neff) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mpb_001_mpb_waveguide.ipynb Retrieves the effective refractive index of a calculated mode. This value is crucial for understanding mode propagation. ```python m1.neff ``` -------------------------------- ### Create and plot a generic gdsfactory component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tidy3d_00_tidy3d.ipynb Initializes a generic PDK and creates a `coupler_ring` component from gdsfactory, then plots it. ```python from gdsfactory.generic_tech import LAYER_STACK, get_generic_pdk pdk = get_generic_pdk() pdk.activate() component = gf.components.coupler_ring() component.plot() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/ray_optimiser.ipynb Import required libraries for gdsfactory, Ray Tune, and MEEP simulations. ```python from functools import partial import gdsfactory as gf import numpy as np import ray import ray.air import ray.air.session from gdsfactory.config import PATH from gdsfactory.generic_tech import get_generic_pdk from ray import tune from ray.tune.search.hyperopt import HyperOptSearch import gplugins.gmeep as gm gf.config.rich_output() PDK = get_generic_pdk() PDK.activate() tmp = PATH.optimiser tmp.mkdir(exist_ok=True) ``` -------------------------------- ### Print LayerStack Keys Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/femwell_02_heater.ipynb Prints the available layer names within the current LayerStack configuration. Useful for verifying layer names before simulation setup. ```python print(LAYER_STACK.layers.keys()) ``` -------------------------------- ### Display help for run_capacitive_simulation_elmer Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/elmer_01_electrostatic.ipynb Prints the help message for the `run_capacitive_simulation_elmer` function, providing details on its parameters and usage. ```python help(run_capacitive_simulation_elmer) ``` -------------------------------- ### Visualize and Sample Wafer Maps Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Visualizes generated wafer maps and prepares them for sampling. Requires matplotlib for plotting. ```python import matplotlib.pyplot as plt placements = mzi.get_netlist()["placements"] xm, ym, wmaps = create_wafermaps( placements, correlation_length=100, mean=0.5, std=0.002, num_maps=100, seed=42, ) for i, wmap in enumerate(wmaps): if i > 1: break plt.imshow(wmap, cmap="RdBu") plt.show() ``` -------------------------------- ### Run Optical Simulation with Lumi Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/luminescent.ipynb Executes the optical simulation using the Lumi plugin. Configure simulation parameters like PML depths, time limits, and field decay thresholds for accuracy and speed. GPU acceleration can be enabled. ```python lumi.make( path=path, component=c, wavelengths=wavelengths, sources=sources, modes=modes, # limits zmin=-zmargin, zmax=th + zmargin, # materials and layers materials_library=materials_library, layer_stack=layer_stack, # accuracy and speed settings gpu="CUDA", # use GPU acceleration nres=8, # number of grid points per wavelength in material (not vacuum) relative_courant=0.95, # relative to maximum theoretical Courant number at relative_pml_depths=[1, 1, 0.3], # relative PML depth Tsim=500, # max time [periods] field_decay_threshold=0.01, # field energy decay threshold for stopping simulation # visualization saveat=50, # save and plot field every n periods views=[lumi.View("Hz", z="halfway", y=0, x=0)], ) lumi.solve(path) ``` -------------------------------- ### Create and Plot MZI Phase Shifter Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Generates a basic MZI phase shifter component and visualizes it. This is a starting point for defining voltage-dependent behavior. ```python delta_length = 10 mzi_component = gf.components.mzi_phase_shifter(delta_length=delta_length) mzi_component.plot() ``` -------------------------------- ### Create and Plot MZI Component Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_1_mzi.ipynb Generates a Mach-Zehnder interferometer (MZI) component with a specified delta_length and plots it. This is a preliminary step before circuit simulation. ```python mzi10 = gf.components.mzi(splitter=c, delta_length=10) mzi10.plot() ``` -------------------------------- ### Import necessary libraries for FEM mode solver Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/femwell_01_modes.ipynb Imports essential libraries for FEM calculations, meshing, plotting, and mode computation. Ensure these are installed before running. ```python from collections import OrderedDict import matplotlib.pyplot as plt import numpy as np from femwell.maxwell.waveguide import compute_modes from femwell.mesh import mesh_from_OrderedDict from shapely.geometry import Polygon, box from shapely.ops import clip_by_rect from skfem import Basis, ElementTriP0 from skfem.io.meshio import from_meshio from tqdm import tqdm ``` -------------------------------- ### Simulate MZI Circuit with SAX Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Creates a SAX circuit from a netlist and defined models, then simulates its response at a specific wavelength. The output is a dictionary of S-parameters. ```python mzi_circuit, _ = sax.circuit(netlist=netlist, models=models, backend="filipsson_gunnar") S = mzi_circuit(wl=1.55) {k: v for k, v in S.items() if abs(v) > 1e-5} ``` -------------------------------- ### Import necessary libraries for DEVSIM simulation Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/devsim_01_pin_waveguide.ipynb Imports gdsfactory, matplotlib, numpy, and specific DEVSIM simulation modules. Ensure gplugins is installed with devsim support. ```python import gdsfactory as gf import matplotlib.pyplot as plt import numpy as np from gplugins.devsim import get_simulation_xsection from gplugins.devsim.get_simulation_xsection import k_to_alpha gf.config.rich_output() ``` -------------------------------- ### Get group index (ng) Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/mpb_001_mpb_waveguide.ipynb Retrieves the group index (ng) of a calculated mode. The group index is essential for understanding group velocity and dispersion effects. ```python m.ng ``` -------------------------------- ### Display help for write_sparameters_meep Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/meep_01_sparameters.ipynb Shows the documentation for the `write_sparameters_meep` function, detailing its parameters and usage. ```python help(gm.write_sparameters_meep) ``` -------------------------------- ### Automated S-parameter Simulation for Components Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/lumerical_1_fdtd_sparameters.ipynb Iterates through a predefined list of gdsfactory components, runs `write_sparameters_lumerical` with `run=False` to set up the simulation, and prompts the user to confirm if the simulation looks good. Components requiring review are collected. ```python import lumapi s = lumapi.FDTD() gf.components.cells.keys() components = [ "bend_euler", "bend_s", "coupler", "coupler_ring", "crossing", "mmi1x2", "mmi2x2", "taper", "straight", ] need_review = [] for component_name in components: component = gf.components.cells[component_name]() sim.write_sparameters_lumerical(component, run=False, session=s) response = input(f"does the simulation for {component_name} look good? (y/n)") if response.upper()[0] == "N": need_review.append(component_name) ``` -------------------------------- ### Simulate Couplers and Plot Results Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/workflow_3_cascaded_mzi.ipynb Generates simulation jobs for couplers with calculated lengths, writes them to files, and then simulates them. It plots the thru, drop, and loss ratios against wavelength and calculates the fitting error for each coupler. ```python jobs = [ dict( component=coupler_sc(gap=gap, length=length), filepath=PATH.sparameters_repo / f"dc_{length}.npz", layer_stack=layer_stack, ) for length in lengths ] sims = gt.write_sparameters_batch(jobs) s_params_list = [sim.result() for sim in sims] fig, ax = plt.subplots(1, 3, figsize=(12, 3)) errors = [] i = wavelengths.size // 2 for pr, sp in zip(power_ratios, s_params_list): drop = np.abs(sp["o3@0,o1@0"]) ** 2 thru = np.abs(sp["o4@0,o1@0"]) ** 2 assert lda_c == wavelengths[i] errors.append(drop[i] / (thru[i] + drop[i]) - pr) ax[0].plot(wavelengths, thru, label=f"{1 - pr}") ax[1].plot(wavelengths, drop, label=f"{pr}") ax[2].plot(wavelengths, 1 - thru - drop) ax[0].set_ylabel("Thru ratio") ax[1].set_ylabel("Drop ratio") ax[2].set_ylabel("Loss") ax[0].set_ylim(0, 1) ax[1].set_ylim(0, 1) ax[0].legend() ax[1].legend() fig.tight_layout() print(errors) ``` -------------------------------- ### Import necessary modules Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/tcad_03_numerical_implantation.ipynb Import Path and rmtree for file system operations. ```python from pathlib import Path from shutil import rmtree ``` -------------------------------- ### Display Help for write_drc_deck_macro Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/klayout_drc.ipynb Displays the help documentation for the `write_drc_deck_macro` function, useful for understanding its parameters and usage. ```python help(write_drc_deck_macro) ``` -------------------------------- ### Get Group Index from Waveguide Model Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Retrieves the group index (n_group) for the first mode of a previously defined waveguide model. Assumes `strip` object is already created. ```python ng = strip.n_group[0] print(ng) ``` -------------------------------- ### Get Effective Index from Waveguide Model Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Retrieves the effective index (n_eff) for the first mode of a previously defined waveguide model. Assumes `strip` object is already created. ```python neff = strip.n_eff[0] print(neff) ``` -------------------------------- ### Define and Configure Optical Sources Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/luminescent.ipynb Defines optical sources with specific port margins, wavelengths, and bandwidths. Ensure `source_port_margin` and `wavelength` are appropriately set. ```python sources = [ lumi.Source( "o1", source_port_margin=source_port_margin, wavelength=wavelength, bandwidth=wavelength/5, ) ] ``` -------------------------------- ### Initialize JAX Optimizer and State Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/sax_01_sax.ipynb Initializes the Adam optimizer and its state for optimizing the delta_length parameter of the MZI. ```python initial_delta_length = 21.0 init_fn, update_fn, params_fn = opt.adam(step_size=0.1) state = init_fn(initial_delta_length) ``` -------------------------------- ### Get Best Result Parameters Source: https://github.com/gdsfactory/gplugins/blob/main/notebooks/ray_optimiser.ipynb Extract the best performing result based on a specified metric and mode (e.g., minimizing 'loss'). This returns the metrics and configuration of the best trial. ```python best_params = results.get_best_result(metric="loss", mode="min").metrics best_params["loss"], best_params["config"] ```