Skip to content

models

MEEP simulation models.

Modules:

  • api –

    Declarative API models for MEEP photonic simulation.

  • config –

    Configuration models for MEEP photonic simulation.

  • results –

    Result models for MEEP simulation output.

Classes:

  • AccuracyConfig –

    Controls MEEP subpixel averaging and polygon simplification.

  • CrossSectionBlock –

    One rectangular block in a 2D cross-section MEEP cell.

  • CrossSectionGeometry –

    Pre-computed 2D cross-section cell geometry.

  • DiagnosticsConfig –

    Controls diagnostic outputs from the MEEP runner.

  • DielectricEntry –

    One dielectric slab entry for the mode solver config.

  • Domain –

    Computational domain sizing: absolute bounds, PML, and symmetries.

  • DomainConfig –

    Resolved simulation domain sizing and PML thickness.

  • FDTD –

    Solver numerics: resolution, stopping, subpixel, diagnostics.

  • Geometry –

    Physical layout: component + layer stack.

  • LayerStackEntry –

    One layer in the stack config sent to the cloud runner.

  • Material –

    EM material properties for MEEP simulation overrides.

  • MaterialData –

    Optical material data for config JSON.

  • ModeResult –

    Eigenmode solution from standalone mode solving.

  • ModeSolver –

    Eigenmode solver configuration for waveguide cross-section analysis.

  • ModeSolverConfig –

    Serializable config for cloud eigenmode solving.

  • ModeSource –

    Mode source excitation and spectral measurement window.

  • PortData –

    Serializable port data for the config JSON.

  • PortVerticalOverride –

    Explicit vertical placement for one waveguide port.

  • ResolutionConfig –

    MEEP grid resolution configuration.

  • SParameterResult –

    S-parameter results from MEEP simulation.

  • SimConfig –

    Complete serializable simulation config written as JSON.

  • SourceConfig –

    Source excitation configuration.

  • StoppingConfig –

    Controls when the MEEP simulation stops.

  • Symmetry –

    Mirror symmetry plane.

  • SymmetryEntry –

    One MEEP mirror symmetry plane.

  • WavelengthConfig –

    Wavelength and frequency settings for MEEP FDTD simulation.

AccuracyConfig

Bases: BaseModel

Controls MEEP subpixel averaging and polygon simplification.

eps_averaging toggles MEEP's subpixel smoothing (expensive for complex polygons). subpixel_maxeval / subpixel_tol tune the integration that implements it. simplify_tol applies Shapely polygon simplification before extrusion, dramatically reducing vertex counts on dense GDS curves.

CrossSectionBlock

Bases: BaseModel

One rectangular block in a 2D cross-section MEEP cell.

CrossSectionGeometry

Bases: BaseModel

Pre-computed 2D cross-section cell geometry.

Serialised so the cloud runner can build the MEEP cell from simple blocks without needing gdsfactory or KLayout installed.

DiagnosticsConfig

Bases: BaseModel

Controls diagnostic outputs from the MEEP runner.

DielectricEntry

Bases: BaseModel

One dielectric slab entry for the mode solver config.

Describes a uniform horizontal layer (infinite in x, y) with a material name and vertical extent.

Domain

Bases: BaseModel

Computational domain sizing: absolute bounds, PML, and symmetries.

x_bounds, y_bounds, and z_bounds control the PML-inner interval on each active axis. "auto" keeps automatic sizing; a numeric pair specifies the exact interval in absolute micrometers, with PML outside it.

Automatic X/Y sizing fits the component bounding box plus margin_x or margin_y. An explicit bound cannot be combined with an explicitly set margin on the same axis.

z_ref and margin_z remain temporarily as input-compatibility fields for existing code. They are deprecated and translated to concrete bounds by :meth:gsim.meep.Simulation.build_config.

Methods:

legacy_z_fields_used

legacy_z_fields_used() -> tuple[str, ...]

Return deprecated vertical fields explicitly set by the caller.

resolved_margin_x

resolved_margin_x() -> tuple[float, float]

Return XY margin as (-x side, +x side).

resolved_margin_y

resolved_margin_y() -> tuple[float, float]

Return XY margin as (-y side, +y side).

resolved_margin_z

resolved_margin_z() -> tuple[float, float]

Return vertical margin as (below, above).

DomainConfig

Bases: BaseModel

Resolved simulation domain sizing and PML thickness.

Concrete *_bounds fields are authoritative PML-inner intervals. None retains legacy geometry-bbox plus margin sizing on that axis. The legacy margin_z_low / margin_z_high fields remain readable for old generated configs and are omitted when concrete bounds are serialized. Along automatic X/Y axes the margins are the per-side gaps between the geometry bounding box and the PML inner edge.

Cell size formula

cell_x = x_inner_extent + 2dpml cell_y = y_inner_extent + 2dpml cell_z = z_extent + 2*dpml (z-margins baked into z_extent)

Explicit axes are centered on their interval midpoint. Automatic axes are shifted by (margin_high - margin_low)/2 so asymmetric margins place more room on the intended side.

FDTD

Bases: BaseModel

Solver numerics: resolution, stopping, subpixel, diagnostics.

Methods:

resolved_cut

resolved_cut() -> float | str | None

Value of the active cut ('auto', a float, or None in 3D).

resolved_is_3d

resolved_is_3d() -> bool

Whether this solves a full 3D simulation.

resolved_plane

resolved_plane() -> Literal['xy', 'xz'] | None

Internal 2D plane name implied by the active cut ('xz'|'xy'|None).

stop_after_sources

stop_after_sources(time: float) -> FDTD

Run for a fixed sim-time after sources turn off.

Parameters:

  • time (float) –

    Run time after sources in MEEP time units (um/c).

Returns:

  • FDTD –

    self (for fluent chaining).

stop_after_walltime

stop_after_walltime(seconds: float) -> FDTD

Set a wall-clock time limit (safety net).

This is orthogonal to the sim-time stopping mode — it caps how long the FDTD run is allowed to take in real (wall) seconds. Combine with any other stopping method.

Parameters:

  • seconds (float) –

    Maximum wall-clock seconds for the FDTD run.

Returns:

  • FDTD –

    self (for fluent chaining).

stop_when_dft_decayed

stop_when_dft_decayed(tol: float = 0.001, min_time: float = 100.0) -> FDTD

Stop when all DFT monitors converge.

Parameters:

  • tol (float, default: 0.001 ) –

    DFT convergence tolerance.

  • min_time (float, default: 100.0 ) –

    Minimum absolute sim time before checking convergence.

Returns:

  • FDTD –

    self (for fluent chaining).

stop_when_energy_decayed

stop_when_energy_decayed(dt: float = 20.0, decay_by: float = 0.01) -> FDTD

Stop when total field energy in the cell decays (recommended).

Monitors total electromagnetic energy and stops when it has decayed by decay_by from its peak value. More robust than dft_decay for devices where DFTs can falsely converge on near-zero fields.

Parameters:

  • dt (float, default: 20.0 ) –

    Time window between energy checks (MEEP time units).

  • decay_by (float, default: 0.01 ) –

    Fractional energy decay threshold (e.g. 0.01 = 1%).

Returns:

  • FDTD –

    self (for fluent chaining).

stop_when_fields_decayed

stop_when_fields_decayed(
    dt: float = 50.0,
    component: str = "Ey",
    decay_by: float = 0.05,
    monitor_port: str | None = None,
) -> FDTD

Stop when a field component decays at a point (recommended).

Matches the standard MEEP tutorial stopping condition. Monitors |component|² at a point and stops when it decays by decay_by from its peak value.

Parameters:

  • dt (float, default: 50.0 ) –

    Decay measurement time window.

  • component (str, default: 'Ey' ) –

    Field component name (e.g. "Ey", "Hz").

  • decay_by (float, default: 0.05 ) –

    Fractional decay threshold (e.g. 0.05 = 5%).

  • monitor_port (str | None, default: None ) –

    Port to monitor (None = first non-source port).

Returns:

  • FDTD –

    self (for fluent chaining).

Geometry

Bases: BaseModel

Physical layout: component + layer stack.

The vertical crop reference lives on Domain.z_ref and the 2D cut plane lives on FDTD (solver.y_cut / z_cut).

LayerStackEntry

Bases: BaseModel

One layer in the stack config sent to the cloud runner.

The cloud runner reads these entries alongside layout.gds to extract polygons per layer and extrude them to 3D prisms.

Material

Bases: BaseModel

EM material properties for MEEP simulation overrides.

Initialize via exactly one of:

  • refractive_index (+ optional extinction_coeff) — converted to permittivity internally.
  • permittivity — used directly.

Use loss_tangent for dielectric loss (converted to conductivity at the simulation frequency).

MaterialData

Bases: BaseModel

Optical material data for config JSON.

Uses epsilon_diag as the primary permittivity representation. Supports anisotropic tensors and dispersive susceptibility poles for the MEEP runner.

ModeResult

Bases: BaseModel

Eigenmode solution from standalone mode solving.

Returned by :func:solve_slab_mode and :func:solve_cross_section_mode. Contains the effective index, field profiles over the cross-section, the dominant wavevector, and metadata about the mode.

Attributes:

  • n_eff (float) –

    Effective index (real part of propagation constant / k0).

  • wavelength (float) –

    Free-space wavelength in µm.

  • frequency (float) –

    Frequency in MEEP units (1/µm = 1/wavelength).

  • fields (dict[str, ndarray]) –

    Complex field arrays keyed by component name (e.g. {"Ex": array, "Ey": array, "Ez": array, ...}).

  • kdom (list[float]) –

    Dominant wavevector [kx, ky, kz] in MPB k-units (k*a/(2*pi), equivalent to n_eff/lambda in 1/um). The true propagation constant is beta = 2*pi*|kdom| rad/um; n_eff = |kdom|*lambda.

  • n_group (float | None) –

    Group index, if computable.

  • band_num (int) –

    Mode band index (1 = fundamental).

  • parity (str) –

    Parity of the mode ("NO_PARITY", "EVEN_Y", etc.).

  • x_grid (ndarray | None) –

    X-axis grid coordinates in µm (absolute frame). Populated for XZ cross-section modes. None when unavailable.

  • y_grid (ndarray | None) –

    Y-axis grid coordinates in µm (absolute frame). Populated for YZ cross-section modes. None when unavailable.

  • z_grid (ndarray | None) –

    Z-axis grid coordinates in µm (absolute frame). Populated for both slab and cross-section modes. None when unavailable.

  • stack (Any | None) –

    :class:LayerStack used for mode solving. Provides material boundary context for index profile reconstruction. None when unavailable.

  • component (Any | None) –

    GDSFactory :class:Component for cross-section modes. None for slab modes.

  • port_or_position (str | tuple[float, float] | None) –

    Port name (str) or position (x, y) used for cross-section mode extraction. None for slab modes.

  • cross_section_plane (str | None) –

    "xz" or "yz" for cross-section modes. None for slab modes.

Methods:

  • plot_index –

    Plot the refractive index profile from stored context.

  • plot_mode –

    Plot eigenmode field profiles.

plot_index

plot_index(
    *,
    ax: Any | None = None,
    figsize: tuple[float, float] = (7, 5),
    cmap: str = "RdYlBu",
    show: bool = True,
    **kwargs: Any,
) -> tuple[Any, Any]

Plot the refractive index profile from stored context.

Zero-argument when grid and stack fields are populated. Auto-detects 1D vs 2D from the available grid arrays.

Parameters:

  • ax (Any | None, default: None ) –

    Existing matplotlib Axes (optional).

  • figsize (tuple[float, float], default: (7, 5) ) –

    (width, height) in inches.

  • cmap (str, default: 'RdYlBu' ) –

    Colormap name for 2D pcolormesh (default "RdYlBu").

  • show (bool, default: True ) –

    Call plt.show() (default True).

  • **kwargs (Any, default: {} ) –

    Forwarded to ax.plot (1D) or ax.pcolormesh (2D).

Returns:

Raises:

  • ValueError –

    If stack, wavelength, or z_grid are missing.

plot_mode

plot_mode(
    components: str | list[str] = "auto",
    *,
    norm: str = "abs",
    index: bool = False,
    geometry: bool = False,
    geom_kwargs: dict[str, Any] | None = None,
    ax: Any | None = None,
    figsize: tuple[float, float] = (8, 6),
    cmap: str | None = None,
    aspect: str = "equal",
    title: str | None = "auto",
    suptitle: str | None = "auto",
    show: bool = True,
    shared_colorbar: bool = False,
    **kwargs: Any,
) -> tuple[Any, Any]

Plot eigenmode field profiles.

Parameters:

  • components (str | list[str], default: 'auto' ) –

    "auto" (dominant), "all" (every field), or list of component names e.g. ["Ey", "Hx"].

  • norm (str, default: 'abs' ) –

    "abs" (magnitude), "real", "imag", or "phase" (angle in radians).

  • index (bool, default: False ) –

    Overlay refractive index profile (twin-axis for 1D, greyscale underlay for 2D).

  • geometry (bool, default: False ) –

    Overlay structural geometry boundaries (material interfaces). 1D: horizontal lines at dielectric z-interfaces. 2D: prism outline rectangles at the cross-section plane. Requires stack (and component + domain_config for 2D).

  • geom_kwargs (dict[str, Any] | None, default: None ) –

    Forwarded to the geometry overlay's matplotlib artist. Defaults: color="white", linestyle="-", linewidth=1.0, zorder=50. User values override defaults. Only used when geometry=True.

  • ax (Any | None, default: None ) –

    Existing matplotlib Axes. Only valid when components resolves to a single component.

  • figsize (tuple[float, float], default: (8, 6) ) –

    (width, height) tuple in inches.

  • cmap (str | None, default: None ) –

    Matplotlib colormap name for field data. When None (default), auto-selected: "inferno" for abs, "RdBu_r" for real/imag, "twilight" for "phase".

  • aspect (str, default: 'equal' ) –

    "equal" or "auto" for pcolormesh subplots.

  • title (str | None, default: 'auto' ) –

    Per-subplot title. "auto" generates |comp| n_eff=... for single-component, component name only for multi-component. None suppresses.

  • suptitle (str | None, default: 'auto' ) –

    Figure-level suptitle. "auto" generates descriptive text for multi-component. None suppresses.

  • show (bool, default: True ) –

    Call plt.show() (default True). Set False for customisation before display.

  • shared_colorbar (bool, default: False ) –

    Use a single colour bar for all subplots instead of per-subplot colour bars.

  • **kwargs (Any, default: {} ) –

    Forwarded to the underlying matplotlib call (ax.plot for 1D, ax.pcolormesh for 2D).

Returns:

  • Any –

    (fig, ax) for single-component, (fig, axes) for

  • Any –

    multi-component.

Raises:

  • ValueError –

    If fields is empty, ax is passed with multi-component, norm is invalid, or horizontal axis is ambiguous.

ModeSolver

Bases: BaseModel

Eigenmode solver configuration for waveguide cross-section analysis.

Configure mode-solving parameters declaratively, then solve via sim.solve_modes().

Example::

sim.mode_solver(wavelengths=[1.55], num_bands=3)
sim.mode_solver.first(3).at_port("o1")
results = sim.solve_modes()

Methods:

  • at_cross_section –

    Set solver mode to cross-section (2D transverse).

  • at_port –

    Set the port name for cross-section mode solving.

  • at_slab –

    Set solver mode to slab (1D vertical).

  • first –

    Solve the first n bands (num_bands=n, band=None).

  • fundamental –

    Solve only the fundamental mode (num_bands=1, band=None).

  • sweep_wavelength –

    Populate wavelengths from a linear sweep (start, stop, num).

at_cross_section

at_cross_section() -> ModeSolver

Set solver mode to cross-section (2D transverse).

at_port

at_port(name: str) -> ModeSolver

Set the port name for cross-section mode solving.

at_slab

at_slab() -> ModeSolver

Set solver mode to slab (1D vertical).

first

first(n: int) -> ModeSolver

Solve the first n bands (num_bands=n, band=None).

fundamental

fundamental() -> ModeSolver

Solve only the fundamental mode (num_bands=1, band=None).

sweep_wavelength

sweep_wavelength(start: float, stop: float, num: int) -> ModeSolver

Populate wavelengths from a linear sweep (start, stop, num).

ModeSolverConfig

Bases: BaseModel

Serializable config for cloud eigenmode solving.

Slab mode: the runner builds a 1D cell from layer_stack. Cross-section mode: cross_section_geometry is pre-computed by the client so the runner can build the 2D cell from blocks without GDS processing.

Methods:

  • to_json –

    Write config to JSON file.

to_json

to_json(path: str | Path) -> Path

Write config to JSON file.

Parameters:

  • path (str | Path) –

    Output file path

Returns:

  • Path –

    Path to the written file

ModeSource

Bases: BaseModel

Mode source excitation and spectral measurement window.

PortData

Bases: BaseModel

Serializable port data for the config JSON.

PortVerticalOverride

Bases: BaseModel

Explicit vertical placement for one waveguide port.

Either field may be provided. Fields left unset continue to use automatic layer inference, so callers can override only an ambiguous center or span.

ResolutionConfig

Bases: BaseModel

MEEP grid resolution configuration.

Methods:

  • coarse –

    Coarse resolution (16 pixels/um) for quick tests.

  • default –

    Default resolution (32 pixels/um).

  • fine –

    Fine resolution (64 pixels/um) for production runs.

coarse classmethod

coarse() -> ResolutionConfig

Coarse resolution (16 pixels/um) for quick tests.

default classmethod

default() -> ResolutionConfig

Default resolution (32 pixels/um).

fine classmethod

fine() -> ResolutionConfig

Fine resolution (64 pixels/um) for production runs.

SParameterResult

Bases: BaseModel

S-parameter results from MEEP simulation.

Parses CSV output from the cloud runner and provides visualization via matplotlib.

Methods:

  • from_csv –

    Parse S-parameter results from CSV file.

  • from_directory –

    Load from directory — handles preview-only with no CSV.

  • plot –

    Plot S-parameters vs wavelength.

  • plot_interactive –

    Plot S-parameters with interactive legend toggling.

  • plot_plotly –

    Plot S-parameters with Plotly (interactive).

  • show_animation –

    Display field animation MP4 in Jupyter.

  • show_diagnostics –

    Display diagnostic images in Jupyter.

from_csv classmethod

from_csv(path: str | Path) -> SParameterResult

Parse S-parameter results from CSV file.

Expected CSV format

wavelength,S11_mag,S11_phase,S21_mag,S21_phase,... 1.5, 0.1, -30.0, 0.9, 45.0, ...

Automatically loads meep_debug.json from the same directory if it exists, populating the debug_info field.

Parameters:

  • path (str | Path) –

    Path to CSV file

Returns:

from_directory classmethod

from_directory(directory: str | Path) -> SParameterResult

Load from directory — handles preview-only with no CSV.

If s_parameters.csv exists, delegates to from_csv(). Otherwise loads only debug info and diagnostic images (preview mode).

Parameters:

  • directory (str | Path) –

    Path to results directory

Returns:

plot

plot(db: bool = True, keys: list[str] | None = None, **kwargs: Any) -> Any

Plot S-parameters vs wavelength.

Parameters:

  • db (bool, default: True ) –

    If True, plot in dB scale

  • keys (list[str] | None, default: None ) –

    S-parameter names to plot (e.g. ["s21", "s31"]). Plots all if None.

  • **kwargs (Any, default: {} ) –

    Passed to matplotlib plot()

Returns:

  • Any –

    matplotlib Figure

plot_interactive

plot_interactive(phase: bool = False) -> Any

Plot S-parameters with interactive legend toggling.

Parameters:

  • phase (bool, default: False ) –

    If True, plot phase (deg). Default is magnitude (dB).

Returns:

  • Any –

    plotly Figure

plot_plotly

plot_plotly(keys: list[str] | None = None) -> Any

Plot S-parameters with Plotly (interactive).

Returns a plotly.graph_objects.Figure with magnitude (dB) and phase subplots.

Parameters:

  • keys (list[str] | None, default: None ) –

    S-parameter names to plot (e.g. ["s21", "s31"]). Plots all if None.

Returns:

  • Any –

    plotly Figure

show_animation

show_animation() -> None

Display field animation MP4 in Jupyter.

show_diagnostics

show_diagnostics() -> None

Display diagnostic images in Jupyter.

SimConfig

Bases: BaseModel

Complete serializable simulation config written as JSON.

This is the top-level config that the cloud MEEP runner reads. The geometry is NOT included here — it's in the GDS file. The layer_stack tells the runner how to extrude each GDS layer.

Methods:

  • to_json –

    Write config to JSON file.

to_json

to_json(path: str | Path) -> Path

Write config to JSON file.

Parameters:

  • path (str | Path) –

    Output file path

Returns:

  • Path –

    Path to the written file

SourceConfig

Bases: BaseModel

Source excitation configuration.

Controls the Gaussian source bandwidth and which port is excited. When bandwidth is None (auto), compute_fwidth returns a bandwidth ~3x wider than the monitor frequency span (matching gplugins' dfcen=0.2 convention) so edge frequencies receive adequate spectral power.

Methods:

  • compute_fwidth –

    Compute Gaussian source fwidth in frequency units.

compute_fwidth

compute_fwidth(fcen: float, monitor_df: float) -> float

Compute Gaussian source fwidth in frequency units.

When auto (bandwidth=None), returns max(3 * monitor_df, 0.2 * fcen) to ensure edge frequencies have enough spectral power.

Parameters:

  • fcen (float) –

    Center frequency (1/um).

  • monitor_df (float) –

    Monitor frequency span (1/um).

Returns:

  • float –

    Source fwidth in frequency units (1/um).

StoppingConfig

Bases: BaseModel

Controls when the MEEP simulation stops.

field_decay mode (recommended, matches MEEP tutorials) monitors a field component at a point and stops when |component|² decays by threshold from its peak, with max_time as a numeric time cap (whichever fires first).

energy_decay mode monitors total electromagnetic energy in the cell and stops when it decays by threshold from its peak.

dft_decay mode monitors convergence of all DFT monitors and stops when they stabilize. dft_min_run_time is an absolute sim time (not time-after-sources) — with a broadband source turning off at ~t=78, a min_run_time=100 starts checking at t=100, only ~22 time units after the source ends.

fixed mode runs for a fixed time after sources turn off.

Symmetry

Bases: BaseModel

Mirror symmetry plane.

SymmetryEntry

Bases: BaseModel

One MEEP mirror symmetry plane.

WavelengthConfig

Bases: BaseModel

Wavelength and frequency settings for MEEP FDTD simulation.

MEEP uses normalized units where c = 1 and lengths are in um. Frequency f = 1/wavelength (in 1/um).

Attributes:

  • df (float) –

    Frequency width in MEEP units.

  • fcen (float) –

    Center frequency in MEEP units (1/um, since c=1).

df property

df: float

Frequency width in MEEP units.

fcen property

fcen: float

Center frequency in MEEP units (1/um, since c=1).