# Solver and analysis

### solve

Calculate the waveguide modes with the finite-difference (FDM) or the finite-element (FEM) solver. The fields, effective indices, losses and TE fractions are saved as described under `FDM()`, whichever solver runs.

* **Parameters:**
  * **solver_method** (*str*) – ‘FDM’, ‘FEM’ or ‘bessel’ runs that solver, the same as calling `FDM()` or `FEM()` for the first two, and sets the profile’s `solver` setting to it. ‘bessel’ is the exact solver for a round step-index fiber (see `solver` under [`settings`](setup.md#settings)). ‘default’ runs the solver the `solver` setting selects, without changing it. That setting is itself ‘default’ unless changed, which is the Bessel solver for a round step-index fiber that guides `num_modes` modes with no PML set, and the FDM otherwise, default: ‘default’
  * **profile** (*str* *or* *int*) – the stored profile to solve, in place (one saved with `label_profile()`), the same one `get(profile=...)` reads. An unknown name raises an error listing the stored profiles. To save a solve under a new name, call `label_profile()` after it. With `section`, the name the solved slice is stored under. Default: ‘_default’
  * **section** (*str*) – name of an EME section to solve a slice from, instead of the profile’s own settings/shapes, default: None
  * **propagation_distance** (*float*) – [nm] where along `section` to take the cross-section, default: None
  * **include_heat** (*bool*) – whether to include the temperature change from the most recent `heat()` solve, default: True
  * **include_static** (*bool*) – whether to apply the electro-optic (Pockels) permittivity perturbation from the most recent `electrostatic()` solve, default: True
  * **verbose** (*bool*) – print progress, default: True
  * **simulation_name** (*str*) – simulation name, default: ‘emode’
* **Returns:**
  what `FDM()` or `FEM()` returns, for whichever solver ran.

#### NOTE
The FEM solver requires an EMode<sub>3D</sub> license, so `solve()` needs one whenever it runs the FEM: with `solver_method='FEM'`, or with ‘default’ when the profile’s `solver` setting is ‘FEM’. See [`FEM`](fem.md#FEM) on the Multi-Physics page.

### FDM

Calculate the waveguide modes using the finite difference method. Calling `FDM()` sets the profile’s `solver` setting to ‘FDM’, so `EME()` and `sweep()` then use the FDM too. It automatically runs `EM_mesh` as needed (generating `x`, `y`, `permittivity`, and `permeability`). After solving the mode, the effective index (`effective_index`), mode propagation loss (`loss_dB_per_m`), and field components (`Fx`, `Fy`, `Ex`, `Ey`, `Ez`, `Hx`, `Hy`, `Hz`, `Sx`, `Sy`, `Sz`) are available, where the fields are normalized to the equation below.

$$
\frac{1}{2} \mathrm{Re} \iint \left( \vec E \times \vec H^* \right) \! \cdot \! \hat{z} \, \mathrm{d}x \, \mathrm{d}y = 1 \, \mathrm{W}

$$

It also calculates the TE fraction of each mode (`TE_fraction`) with the following equation, and it saves the indices of the TE and TM modes (`TE_indices` and `TM_indices`).

$$
\mathrm{{TE_fraction}} = \frac{\iint \left| \vec E_\mathrm{x} \right|^2 \, \mathrm{d}x \, \mathrm{d}y}{\iint \left| \vec E_\mathrm{x} \right|^2 + \left| \vec E_\mathrm{y} \right|^2 \, \mathrm{d}x \, \mathrm{d}y}

$$

A multi-wavelength profile (a wavelength list in `settings()`, or a set from `create_profile_set()`) is solved at each of its wavelengths, and is saved as one solved profile per wavelength, so `get()` returns a dict keyed by wavelength and `plot()` and `EME()` use the modes at each wavelength. `FEM()` and `solve()` do the same. The direct return value then holds every wavelength’s result, keyed by wavelength (see below).

* **Parameters:**
  * **profile** (*str* *or* *int*) – the stored profile to solve, in place (one saved with `label_profile()`), the same one `get(profile=...)` reads. An unknown name raises an error listing the stored profiles. To save a solve under a new name, call `label_profile()` after it. With `section`, the name the solved slice is stored under. Default: ‘_default’
  * **section** (*str*) – name of an EME section to solve a slice from, instead of the profile’s own settings/shapes, default: None
  * **propagation_distance** (*float*) – [nm] optional propagation distance used to compute an additional propagation phase/loss, default: None
  * **mode_filter** (*str*) – choose to filter the mode list for propagation direction of ‘forward’, ‘backward’, or ‘none’. It acts in the anisotropic solver only, since the isotropic solver returns forward modes by construction. It is saved in the profile’s settings, so a later `EME()` or `sweep()` that solves this profile again uses it too. Default: ‘forward’
  * **fLanczos** (*int*) – size of the eigensolver’s Krylov subspace as a multiple of the number of modes requested, at least 1. The default, None, is automatic: 5 vectors a mode up to 10 modes, and past 10 modes 2 more vectors a mode (`2 num_modes + 31` in all), which solves many modes faster with the same effective indices. The anisotropic solver searches twice `num_modes`, so its limit starts past 5 modes. An integer is used exactly as given, so raise it if a many-mode solve does not converge. It is saved in the profile’s settings like `mode_filter`, and `FDM()` without it saves None. Default: None
  * **solve_type** (*str*) – either ‘isotropic’, ‘anisotropic’, or ‘auto’ to control whether anisotropic materials are solved with the full tensor or reduced to their isotropic diagonal, default: ‘auto’
  * **include_heat** (*bool*) – whether to include heat-related material properties when meshing, default: True
  * **include_static** (*bool*) – whether to apply the electro-optic (Pockels) permittivity perturbation from the most recent `electrostatic()` solve, default: True
  * **scattering** (*bool*) – whether to automatically calculate interfacial scattering loss for all shapes after solving. The `include_scattering` setting in [`settings`](setup.md#settings) does the same for every solve of the profile. Default: False
  * **verbose** (*bool*) – print progress, default: True
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

#### NOTE
The direct return value of this function (as called through `emodeconnection`) is a dict with keys `n_eff_tilde`, `TE_fraction`, `TE_indices`, `TM_indices` and `PML_indices`. The fields are not part of the return value, since they run to tens of MB for many modes. Use `get()` or `get_fields()` to read them and `plot()` to draw them. For a multi-wavelength profile it is a `WavelengthDict` of these dicts, one per wavelength, indexable like a `dict[float, dict]` (`result[1550]['n_eff_tilde']`). The individual field components and derived quantities described above (`effective_index`, `loss_dB_per_m`, `Ex`/`Ey`/etc.) become available afterward from the saved profile via `get()`/`get_fields()`, not as top-level keys of this return value.

### sweep

This function sweeps a calculation as a function of any available setting, shape parameter, or section parameter (EMode<sub>3D</sub> only). Run a parameter sweep of `key` over defined `values` by solving `solve_type` for each value and saving a list of parameters defined by ‘result’ that correspond to the `values`. After running a sweep, the data will be available from a parameter called `sweep_data`, which includes all of the specified parameters of this funcion and the data specified by the `result` parameter. The `result` parameter can include any parameter that is listed in the `inspect()` output (after running the desired simulation). Additionally, the `result` parameter can include ‘scattering_loss’ (a sum of all scattering losses for each mode) or ‘mode_order’ (a list of mode indices used for tracking the order of the modes).

* **Parameters:**
  * **key** (*str*) – any settings, shape, or section parameter that will have its value changed in the sweep, directly specify the key for settings parameters, specify ‘shape, SHAPE_NAME, SHAPE_KEY’ to specify the SHAPE_KEY of SHAPE_NAME in the default profile, specify ‘shape, PROFILE_NAME, SHAPE_NAME, SHAPE_KEY’ for a shape of the labeled profile PROFILE_NAME (a sweep of it runs `solve_type='EME'`, the profile reaching the result through the sections built on it), specify ‘section, SECTION_NAME, SECTION_KEY’ to specify the SECTION_KEY of SECTION_NAME. The accepted section keys are ‘length’, ‘num_modes’, ‘minimum_z_step’, ‘overlap_variation’, ‘z_slices’, ‘offset’, ‘window_width’, ‘window_height’, and ‘facet_angle’ (the tilt [degrees] of an angled facet on that section, see [`make_angled_facet_port()`](../interface.md#make_angled_facet_port)). Any other section key raises an error naming it. A shape’s `etch_depth`, `sidewall_angle` and `tone` are swept as ‘shape, SHAPE_NAME, etch_depth’ and so on.
  * **values** (*list* *or* *array*) – the values that define the `key` during the sweep
  * **solve_type** (*str*) – either ‘mesh’, ‘FDM’, or ‘EME’ to specify which solver to run at each sweep step, where ‘FDM’ means a mode solve with the solver the `solver` setting selects (the FDM or the FEM), default: automatically chosen based on the `key` and `result` selection
  * **result** (*str* *or* *list*) – the parameters to save from each iteration of the sweep.  This can be any value in the eph file.  Internally, this calls `get`, so if you can read the value with `get` you can collect it with `sweep`. Additionally, ‘scattering_loss’, ‘mode_order’ and ‘monitor_coupling’ are accepted. ‘monitor_coupling’ collects [`monitor_coupling`](eme.md#monitor_coupling) for the monitor named by `monitor` and the beam described by `beam`. With a `key` that is one of the beam’s arguments (‘angle’, ‘mode_field_diameter’, ‘center’, ‘index’ or ‘polarization’) the solved chain is reused and only the overlap is evaluated at each value, with no solve, and `sweep_data` also carries `power_through_plane` and `overlap`. Any other key needs `solve_type='EME'` and solves the chain at each value. default: ‘effective_index’
  * **seed** (*bool*) – whether to seed each solve step with the previous step’s mode list, default: True
  * **adaptive** (*bool*) – only for a wavelength sweep. `values` keeps its meaning (the wavelengths you want results at), and `adaptive` changes only *where the solver runs*: modes are matched between neighboring solves through a phase-corrected overlap, and a bisection in wavelength places further solves until the mode list stops moving by more than `tolerance`, or the gap reaches `minimum_step`. The requested wavelengths are then filled in by interpolating the solved mode lists, which is much cheaper than solving every point when the modes vary smoothly. `sweep_data` additionally carries `solved_wavelengths` (where the solver actually ran) and `unconverged` (any stretch the sampler gave up on, reported rather than raised). Default: False
  * **tolerance** (*float*) – with `adaptive`, the largest mode-list change tolerated between adjacent solves, default: 1e-3
  * **minimum_step** (*float*) – [nm] with `adaptive`, the smallest wavelength gap the sampler will bisect into, default: the spacing of `values`
  * **method** (*str*) – either ‘direct’ or ‘interpolated’. ‘interpolated’ is only for `key='wavelength'` with `result='S_matrix'` (EMode<sub>3D</sub> only): the circuit is solved and refined once at the current wavelength with [`EME`](eme.md#EME), every cross-section in it is solved at `num_nodes` wavelengths (Chebyshev-Lobatto nodes, ends included) over `wavelength_range`, and the S-matrix at each of `values` is rebuilt from the propagation constants and junctions interpolated between them, so no wavelength in `values` solves anything. It suits the hundreds of wavelengths a resonator spectrum needs. A mode that cannot be followed across the range keeps its solve at the current wavelength (its effective index and its junction coupling) at every wavelength, with a warning naming its cross-sections, so the result at the current wavelength is always the solved circuit. One node is predicted from the others: `sweep_data` additionally carries `num_nodes`, `interpolation_residual` (the largest error at that node in a slice’s propagation phase factor or in a junction’s S-matrix element) and `interpolation_residuals` (the node’s wavelength, the slice and junction errors, and the largest error of the whole circuit’s S-matrix). A warning naming the slice or junction is logged when `interpolation_residual` exceeds `interpolation_tolerance`. The whole circuit’s error is not checked, since a narrow resonance moved by a small fraction of its width changes it by order one. Default: ‘direct’
  * **num_nodes** (*int*) – with `method='interpolated'`, the number of wavelengths every cross-section is solved at, at least 4. Add nodes, or narrow the range, when `interpolation_residual` is too large, default: 8
  * **wavelength_range** (*tuple* *[**float* *,* *float* *]*) – [nm] with `method='interpolated'`, the range the nodes span, which must contain every one of `values`, default: the range of `values`
  * **interpolation_tolerance** (*float*) – with `method='interpolated'`, the largest `interpolation_residual` accepted without a warning, default: 1e-4
  * **monitor** (*str*) – with `result='monitor_coupling'`, the name of the monitor (see [`monitor`](eme.md#monitor)), default: None
  * **beam** (*dict*) – with `result='monitor_coupling'`, the keyword arguments of [`monitor_coupling`](eme.md#monitor_coupling) that describe the beam, `mode_field_diameter` at least, for example `beam=dict(mode_field_diameter=10.4e3)`. A beam `key` overrides its entry here at each value, default: None
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### converge

Find the resolution, window, PML thickness or number of modes a result needs. `converge()` varies `setting` one step at a time, solving the profile at each step, and watches one quantity of one mode, the `target`. It stops once the target has settled to within `tolerance`, prints one row per solve and returns the history. The profile’s settings change only with `apply=True`, so the table can be read first. It runs in every license tier.

Each setting is varied in its own way:

* `'resolution'`: `x_resolution` and `y_resolution` together, from 20 cells per wavelength in the highest-index material, finer by a factor of $\sqrt{2}$ a step. Each step is rounded down so a whole number of cells fills the window and, where the shapes allow, every shape edge lies on a grid line. With `solver='FEM'` it varies `fem_points_per_wavelength` from 1 in the same ratio, with `fem_max_refinements=0` so the routine and not the FEM’s own refinement sets each step.
* `'window'`: `window_width` and `window_height`, from the core (every shape bounded on all four sides) plus three decay lengths $1 / (k_0 \sqrt{n_\mathrm{eff}^2 - n_\mathrm{clad}^2})$ of the cladding, growing by one decay length on each side a step. The window stays centered on the core, and an axis folded by `boundary_condition` stays centered on its mirror plane. On a bend, the outer side starts beyond the caustic $n_\mathrm{eff} R / n_\mathrm{clad}$.
* `'pml'`: `pml_thickness` on every side with a PML, from one wavelength in the cladding, growing by half a wavelength a step. With the FEM it starts no thinner than the PML’s imaginary depth (see `pml_thickness` under [`settings`](setup.md#settings)). It needs a PML (`pml_NSEW_bool`).
* `'modes'`: `num_modes`, doubling until the watched mode is among the modes confined to the window rather than to the PML.
* `'all'`: the window on the coarsest grid, the PML (when one is on), the resolution, the number of modes, then one more check of the window at the final grid.

The rule that stops it depends on how the setting converges. The resolution converges algebraically, so each step’s error is estimated as $|\Delta_k| / (r^p - 1)$, from the change $\Delta_k$ since the previous step, the refinement ratio $r$ and the order $p$ observed over the last three steps (between 1 and 4, read correctly when the two refinements differ). The x and y resolutions each refine by a ratio of their own, so the estimate is read along each axis and the larger is kept. Three values cannot tell which axis carries the error, and the larger reading keeps the estimate from falling below it. A window and a PML converge exponentially, so the estimate is the change itself. The routine stops as `'converged'` once the estimated error is at or below the tolerance on two consecutive steps, and reports the last step’s settings. A change that flips sign between two consecutive steps stops it as `'oscillating'`, since a sequence that alternates has not converged whatever its size. The orthogonality target is the largest overlap between two modes (as [`orthogonality`](#orthogonality) computes it), which must fall below the tolerance rather than settle, and a run that stops improving it ends as `'stalled'`. `max_solves` or `max_time` running out ends a run as `'budget'`. So does a step the routine predicts it cannot afford: before each step it estimates the step’s time and memory from the solves before it (the cells grow as the step asks, and the time and the factorization’s memory grow with them as the last two solves show), and it does not start a step that would pass `max_time` or need more than `max_memory`. The run then keeps the finest settings it solved, and the result’s `message` names the budget and the step.

The watched mode is followed from one step to the next by its overlap, not by its place in the mode list, so a PML mode that moves ahead of it does not change what is watched. A step with no mode overlapping the watched one above 0.9 stops the run as `'lost mode'`. One mode of a degenerate pair (a round fiber, a square core) can come back in another polarization from one solve to the next, so fold such a window with `boundary_condition` before converging it.

* **Parameters:**
  * **setting** (*str*) – ‘resolution’, ‘window’, ‘pml’, ‘modes’ or ‘all’, default: ‘resolution’
  * **target** (*str*) – ‘effective_index’, ‘group_index’ (from [`group_index`](#group_index)), ‘loss’ (`loss_dB_per_m`, with the scattering loss when `include_scattering` is set) or ‘orthogonality’, default: ‘effective_index’
  * **tolerance** (*float*) – the largest acceptable estimated error, absolute for ‘effective_index’ (default 1e-4), ‘group_index’ (1e-3) and ‘orthogonality’ (1e-6), and relative for ‘loss’ (1e-2)
  * **apply** (*bool*) – write the chosen settings to the profile, default: False
  * **max_solves** (*int*) – the most solves to make, across every setting of ‘all’, default: 20
  * **max_time** (*float*) – [s] the most time to take, default: None (no limit)
  * **max_memory** (*float*) – [GB] the most memory one solve may need, default: three quarters of the machine’s physical memory
  * **mode** (*int*) – the mode to watch, an index into the first solve’s mode list, default: 0
  * **profile** (*str*) – the profile to converge, default: ‘_default’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’
* **Returns:**
  a `ConvergenceResult` with `status`, `chosen` (the chosen settings, as [`settings`](setup.md#settings) takes them), `history` (one row per solve: `setting`, `value`, `settings`, `quantity`, `change`, `estimated_error` and `seconds`), `stages` (one per setting varied, with its status, its chosen settings and, for the resolution, its observed `order`), `message` (why a run that did not converge stopped, empty otherwise) and `seconds`. `print(result)` prints the table again. The same result is saved on the profile as `convergence`.

The guide of the [Straight Waveguide Convergence](../examples/Straight_Convergence.md) example, a 2000 x 200 nm SiN core in SiO2 at 980 nm, has a known effective index, 1.6874538. Converging its resolution to 1e-4:

```python
em.settings(wavelength=980, window_width=7000, window_height=4200, num_modes=1,
            boundary_condition='TE', background_material='SiO2')
em.shape(name='core', material='SiN', width=2000, height=200, position=[0, 2100])
result = em.converge('resolution', 'effective_index', tolerance=1e-4)
```

```text
setting                   value         n_eff     change  est. error  time (s)
resolution             23.81 nm      1.686959          -           -       0.6
resolution             16.67 nm      1.687108    1.5e-04     7.5e-04       0.8
resolution              11.9 nm      1.687301    1.9e-04     4.8e-04       1.8
resolution             8.475 nm      1.687368    6.7e-05     8.5e-05       3.0
resolution             6.024 nm      1.687412    4.3e-05     7.9e-05       6.8
resolution             4.274 nm      1.687433    2.1e-05     2.2e-05      13.0

resolution: converged (x_resolution=4.273504273504273, y_resolution=4.166666666666667, estimated error 2.2e-05, order 2.00)
converged at 0.0001 absolute in 27.9 s
```

The x resolutions divide the 500 nm lattice of the core’s side walls and the y resolutions the 200 nm lattice of its top and bottom, so every edge lies on a grid line. Each row shows the estimate made when its grid was solved. The y resolution carries most of the error of this 200 nm thick core, and read along y the estimates are within a few percent of the true distances from the reference. The x reading is the larger at 6.0 nm, where it puts the 8.5 nm grid at 1.2e-4 (true 8.5e-5), so the run takes one more grid than the y reading alone would. The chosen 4.3 nm grid is 2.1e-5 from the reference. `em.converge('resolution', 'effective_index', tolerance=1e-4, apply=True)` would also set `x_resolution` and `y_resolution` to those values.

### confinement

Calculate confinement factor of specified shape. By default, only the area of the shape that is used to define the refractive index profile is included in the confinement factor. For instance, if another shape with a higher priority overlaps the specified shape, the overlapped area is not included. The confinement factors are also returned by this function. For a multi-wavelength profile, the return value is a dict keyed by wavelength.

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **shape_list** – name (from `shape`) or list of names of shapes to include in confinement or ‘all’ for all shapes, default: ‘all’
  * **mode_list** (*str* *or* *list*) – desired modes to calculate confinement, ‘all’, ‘TE’, ‘TM’, or a list of the desired mode indices, default: ‘all’
  * **vertices** (*list* *(**Nx2* *)*) – list of vertices that define a closed polygon, specifying this parameter will override the `shape_list` input, default: None
  * **ignore_priority** (*bool*) – toggle ignoring overlapped shapes with higher priority, default: False
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### effective_area

Calculate the effective areas for all modes. After running this function, an array called `effective_area` will become available and `report` will display the effective areas. The `effective_area` is also returned by this function and is in units of $\mu\text{m}^2$. For a multi-wavelength profile, the return value is a dict keyed by wavelength.

$$
A_\mathrm{eff} = \frac{\left( \iint \left| \vec E \right|^2 \, \mathrm{d}x \, \mathrm{d}y \right)^2}{\iint \left| \vec E \right|^4 \, \mathrm{d}x \, \mathrm{d}y} \, \mu\text{m}^2

$$

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### orthogonality

Calculate the highest value of mode overlap between modes in the mode list. After running this function, a variable called `maximum_overlap` will become available in metadata of the named (or default) profile, and the `maximum_overlap` is returned by this function. For a multi-wavelength profile, the return value is a dict keyed by wavelength. Ideally, this value is less than $10^{-3}$, indicating an accurate mode list.

* **Parameters:**
  * **profile** (*str* *or* *int*) – profile name, default: ‘_default’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### group_index

Calculate the group index for all modes. `group_index` solves the profile first if it is not solved, then finds each mode’s group index from that one solve: the frequency derivative of the mode’s propagation constant, from the mode’s fields and the frequency derivative of the solver’s operator with the materials’ dispersion, $n_g = c \, \mathrm{d}\beta / \mathrm{d}\omega$. It agrees with a difference of two more solves to about $10^{-8}$, for the FDM and the FEM. A mode whose loss is more than $10^{-3}$ of its effective index (a mode of the PML), and every mode of a transformation-optics bend, takes a second solve at 0.01 % longer wavelength instead, with a note in the log. With `method='difference'` every mode does. After running this function, an array called `group_index` will become available and `report` will display the group index. The `group_index` array is also returned by this function. For a multi-wavelength profile, the return value is a dict keyed by wavelength.

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **method** (*str*) – ‘field’ (from the one solve) or ‘difference’ (a forward difference with a second solve at 1.0001 times the wavelength), default: ‘field’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### dispersion

Calculate the group index, the group-velocity dispersion and the dispersion parameter of every mode from one solve. The GVD needs the first-order change of each mode with frequency as well, which is one linear solve with the solver’s operator, not a second mode solve. Returns a dict with:

- `'group_index'`: as [`group_index`](#group_index) returns it
- `'GVD'`: $\beta_2 = \mathrm{d}^2\beta / \mathrm{d}\omega^2$ in ps<sub>2</sub>/km
- `'D'`: $D = -\frac{2 \pi c}{\lambda^2} \beta_2$ in ps/(nm km)
- `'method'`: per mode, `'field'` for a result from the one solve, or `'difference'` for a mode whose group index took a second solve (see [`group_index`](#group_index)), whose GVD is then NaN

For a multi-wavelength profile, the return value is a dict keyed by wavelength. For the dispersion of a mode the field method does not cover, [`sweep`](#sweep) the wavelength.

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### report

Display a simulation report table with information about each mode:

- mode number
- effective index
- TE fraction
- loss (dB/m)
- a `PML` column when the profile was solved with a PML, marking the modes that carry less than 75% of their power inside the window (see `PML_indices` and `window_confinement` in [Variable Descriptions](variables.md))
- per-shape confinement factors and scattering loss (if calculated)
- effective areas (if calculated)

The line above the table gives the wavelength and the mode solver that produced the modes, for example `Wavelength: 1550.0 nm    Solver: FEM`. A saved CSV records both below the table.

Returns the table as a dictionary keyed by profile name, each table holding one list per column. A multi-wavelength profile returns one table per wavelength, keyed by wavelength. An unsolved profile returns an empty table.

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **save** (*bool*) – whether to save the table to a file or not, default: False
  * **file_name** (*str*) – name of the file to save, default: ‘mode_report’
  * **file_type** (*str*) – file type to save, ‘txt’, ‘latex’, or ‘csv’, default: ‘txt’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### label_profile

Saves a copy of the default profile (settings, shapes, mesh and any solved modes) under `name` in the `profiles` dictionary of the simulation file, meshing it first if needed. A multi-wavelength profile is saved whole, with each member meshed and keeping its own name. Named profiles are read with `profile=NAME` in [`get`](../interface.md#get), [`get_fields`](file-management.md#get_fields), [`get_grid`](file-management.md#get_grid), [`get_shape`](file-management.md#get_shape) and [`get_profile`](file-management.md#get_profile), and one wavelength of a multi-wavelength one with `profile='NAME.WAVELENGTH'`. They are the inputs to `overlap`, `mode_order` and the EME section functions, and [`reset`](setup.md#reset) changes one only when given its name.

* **Parameters:**
  * **name** (*str*) – save the current simulation state to this name, default: ‘0’
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### overlap

Calculate overlap integral between two modes. The result is returned by this function and saved on the profile named by `profile_b`, where `get('overlap', profile=profile_b)` reads the latest result and `get('overlaps', profile=profile_b)` a record of every overlap computed against it (see [Variable Descriptions](variables.md)).

> Coldren, Larry A., Scott W. Corzine, and Milan L. Mashanovitch, ‘’Diode lasers and photonic integrated circuits,’’ John Wiley & Sons, 2012.
$$
\mathrm{overlap} = \frac{4 n_\mathrm{eff,1} n_\mathrm{eff,2}}{(n_\mathrm{eff,1} + n_\mathrm{eff,2})^2} \frac{\left| \iint \vec E_1 \times \vec H_2 \, \mathrm{d}x \, \mathrm{d}y \right|^2}{\iint \left| \vec E_1 \times \vec H_1 \right| \, \mathrm{d}x \, \mathrm{d}y \, \iint \left| \vec E_2 \times \vec H_2 \right| \, \mathrm{d}x \, \mathrm{d}y}

$$

* **Parameters:**
  * **profile_a** (*str* *or* *int*) – label of first profile, default: ‘_default’
  * **mode_a** (*int*) – mode number from the first profile, default: 0
  * **simulation_name_a** (*str*) – simulation name for the first mode set, default: ‘emode’
  * **profile_b** (*str* *or* *int*) – label of second profile, default: ‘_default’
  * **mode_b** (*int*) – mode number from the second profile, default: 0
  * **simulation_name_b** (*str*) – simulation name for the second mode set, default: ‘emode’

### farfield

The far field of a mode, normalized to 1 W in the mode. The transverse E on the plane is decomposed into plane waves in the profile’s background material, its angular spectrum. Each direction of travel is labeled by its direction cosines `ux` and `uy`, the sines of its angles from the axis along x and y. The far field in each direction follows from stationary phase, and the field on a screen at a finite distance is the plane-wave sum itself (the Rayleigh-Sommerfeld solution), so it holds at any distance, including within a wavelength of the plane. With `port`, the mode leaves the solved chain through that port, and the axis points away from the chain. Otherwise it is a mode of `profile` traveling along +z.

Only E radiates, so the result is exact for a field already in the uniform medium and close for a weakly guiding mode: the fundamental mode of SMF-28 radiates 0.997 of its 1 W, and its far field matches the Hankel transform of the exact HE11 field within 5e-6 of the peak. A mode whose index is far above the background radiates less than would cross a real facet into it.

* **Parameters:**
  * **mode** (*int*) – the mode, default: 0
  * **port** (*str* *or* *None*) – an external port of the chain solved by [`EME`](eme.md#EME), such as ‘left’ or ‘right’, default: None (a mode of `profile`)
  * **profile** (*str*) – the profile whose mode radiates when `port` is None, default: ‘_default’
  * **wavelength** (*float* *or* *None*) – [nm] which of a multi-wavelength profile’s or chain’s wavelengths to use, the nearest one present, default: None (the first)
  * **screen** (*Screen* *or* *None*) – a plane screen to evaluate the field on, default: None
  * **max_angle** (*float* *or* *None*) – [degrees] the largest angle from the axis sampled along x and y, at most 90, default: None (eight standard deviations of the angular spectrum)
  * **num_angles** (*int*) – the directions sampled along each axis, default: 201
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

Returns a `FarField`:

- `ux`, `uy`: the direction cosines sampled. Directions with `ux**2 + uy**2 > 1` carry no power. `theta_x` and `theta_y` are the same as angles in degrees.
- `fields`: ‘Ex’, ‘Ey’ and ‘Ez’, each of shape (len(ux), len(uy)), the far field times `r exp(j k r)` [V]. For a left port, z points away from the chain.
- `intensity`: the radiant intensity [W/sr], and `cut('x')` or `cut('y')` its angles and values along one axis.
- `radiated_power`: [W] its integral over the directions sampled.
- `divergence`: [degrees] the half-angles along x and y from the second moments of the intensity, `arcsin(2 sigma_u)`, which is a Gaussian beam’s 1/e<sub>2</sub> half-angle, `lambda / (pi n w0)`.
- `m_squared`: the beam quality factor M<sub>2</sub> along x and y from the second moments of the near field and its angular spectrum (ISO 11146). It is 1 for a Gaussian beam, `2m + 1` along the axis of order `m` of a Hermite-Gauss beam, and 1.036 for the fundamental mode of a step-index fiber.
- `waist` and `waist_position`: [nm] the embedded waist radius along x and y (twice the second-moment width), and its distance ahead of the plane (negative behind it).
- `centroid`: [nm] the near field’s intensity centroid (x, y).
- `screen`: with a screen, a `ScreenField`: the positions `s` and `t` [nm] along the screen’s axes, the same points `x`, `y`, `z` [nm] in the plane’s frame, `fields` with all six components (‘Ex’ … ‘Hz’, V/m and A/m), `Sn` [W/m<sub>2</sub>] the Poynting flux through the screen along its `normal`, and `power_through_screen` [W].

`FarField.plot()` draws the intensity against the angles, its two cuts and, with a screen, the flux on the screen, with matplotlib in the client’s own Python.

A `Screen` sits `distance` [nm] ahead of the plane at `center` (x, y) [nm], by default the near field’s centroid. It spans `width` and `height` [nm] along its own axes u and v, sampled at `points` (one number, or one per axis, default: 101). `tilt` (degrees) turns it by `tilt[0]` about y, tipping its normal toward +x, then by `tilt[1]`, tipping it toward +y. Untilted, u is x and v is y. No part of it may lie behind the plane.

```python
import emodeconnection as emc

ff = em.farfield(mode=0, screen=emc.Screen(distance=100e3, width=60e3, height=60e3))
print(ff.divergence, ff.m_squared)
ff.plot()
```

### mode_order

Calculate mode ordering between two mode lists. The result is returned as a list.

* **Parameters:**
  * **profile_a** (*str* *or* *int*) – label of first profile, default: ‘’
  * **profile_b** (*str* *or* *int*) – label of second profile, default: ‘’
  * **raw_fields** (*bool*) – use the raw (un-normalized) field data for the ordering comparison instead of the interpolated fields, default: False
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### scattering

Calculates the scattering loss from a specified shape and mode using the Volume Current Method [1]. Results are saved in the variables `SHAPE.metadata['scattering_vertical_edges']` (total loss from all vertical interfaces), `SHAPE.metadata['scattering_horizontal_edges']` (total loss from all horizontal interfaces), `SHAPE.metadata['scattering_sum']` (total scattering loss), `SHAPE.metadata['edges']` (list of edge points for calculating scattering loss), and `SHAPE.metadata['scattering_all_edges']` (scattering loss from corresponding edges). The fields are read at the edge itself, as the limit from outside the shape: the tangential components, which are continuous there, and the normal component of the cladding’s side. An FEM solve reads them from its elements, so the loss does not depend on `x_resolution` or `y_resolution`, and converges with `fem_resolution`. An FDM solve extrapolates them to the edge from the two cells beside it, and converges with the grid. This is the value that EMode 1.0.7 and earlier, which read the fields one grid cell outside the edge, approached as the grid was refined. A shape with `roughness_field_side='inside'` reads them as the limit from inside it instead. The normal component there is smaller by the ratio of the cladding’s permittivity to the shape’s, so the sidewall loss is lower. For a slab, the loss agrees with Payne and Lacey’s result within 1 %. The scattering results are also returned by this function as a dictionary keyed by shape name. For a multi-wavelength profile, the return value is a dict keyed by wavelength.

What is modeled:

- **Edges.** Every edge of the outline of a shape with roughness (`roughness_rms` and `correlation_length` set with [`shape`](setup.md#shape)), except an edge that lies on the window boundary, such as the bottom of a slab that fills the window’s lower edge. Each edge radiates independently, so the losses of the edges add.
- **Vertical, horizontal and angled edges.** A vertical edge (a sidewall) takes the first of a pair of `roughness_rms` and `correlation_length` values, and a horizontal edge (a top or bottom surface) the second. An angled edge, such as a sloped sidewall, takes the first value. Its loss is computed twice, once as a vertical wall over the edge’s vertical extent and once as a horizontal surface over its horizontal extent, and the two are weighted by $\sin^2\theta$ and $\cos^2\theta$, with $\theta$ the edge’s angle from the horizontal. An edge steeper than 45 degrees counts toward `scattering_vertical_edges`, a shallower one toward `scattering_horizontal_edges`. A value per edge, in the order of the outline’s vertices, sets each edge on its own.
- **Roughness statistics.** The roughness varies along the propagation direction only, with an exponential autocorrelation $R(u) = \sigma^2 e^{-|u|/L_c}$, where $\sigma$ is `roughness_rms` and $L_c$ is `correlation_length`. Its power spectrum is the Lorentzian $\tilde{R}(\Omega) = 2 \sigma^2 L_c / (1 + L_c^2 \Omega^2)$, evaluated at the mismatch between the mode’s propagation constant and the component along the guide of each radiated wave’s wave vector.

The loss is in dB/m of power. With `include_scattering=True` it is part of `loss_dB_per_m`, and with `EME_settings(apply_scattering=True)` an EME section applies it.

[1] T. Barwicz and H. A. Haus, “Three-dimensional analysis of scattering losses due to sidewall roughness in microphotonic waveguides,” J. Lightwave Technol. 23, 2719 (2005).

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **shape** (*str*) – name of the shape for calculating the interfacial scattering, can also be a list of shapes or None (which calculates scattering for all shapes), default: None
  * **shapes** (*str*) – alias for shape
  * **mode_list** – mode number, list of mode numbers, or ‘all’, default: ‘all’
  * **simulation_name** (*str*) – simulation name for the second mode set, default: ‘emode’

### plot

Interactive plot for the fields (if available), refractive index, and shapes, or saving a plot. Colorbars are in V/nm for the electric fields, A/nm for the magnetic fields, and W/nm<sub>2</sub> for the Poynting vectors.

For EME plots in the ‘z-x’ or ‘z-y’ planes, the data dropdown also offers an ‘Outline’ view that displays a geometry-only outline of the declared sections. Once sections are declared with `straight_section()`, `pwd_section()`, `taper_section()`, `bend_section()` or `gds_section()`, calling `plot()` before running `EME()` shows only the ‘Outline’ view, which is useful to check the section layout before solving. After `EME()` has run, ‘Outline’ is available alongside the field components.

A plot of a $\chi^{(2)}$ section uses the declared `excitation` rather than a unit mode, because conversion depends on power. Each slice is drawn from the forward amplitudes recorded along it, so the generated wavelength builds along the guide instead of stepping at slice boundaries. Without a declared excitation the field shown is the small-signal response, and the solver says so.

* **Parameters:**
  * **component** (*str* *or* *None*) – field component or index, ‘Ex/y/z’, ‘Hx/y/z’, ‘Sx/y/z’, ‘Index’ or ‘Shapes’, default: None (‘Ex’, or ‘Index’ for a circuit with a closed loop)
  * **plot_function** (*str*) – plotting function, one of ‘real’, ‘imag’, ‘abs’, ‘abs^2’ or ‘log’, default: ‘real’
  * **mode** (*int*) – mode number, default: 0
  * **aspect_ratio** (*str* *or* *float*) – the height:width aspect ratio, ‘norm’ uses the normal aspect ratio of 0.707, ‘real’ uses the real aspect ratio defined by the simulation window, or a float specifies the aspect ratio, default: ‘norm’
  * **index_outline** (*bool*) – setting index outline, default: True
  * **text_display** (*bool*) – setting text display, default: True
  * **mesh_display** (*bool*) – setting mesh display: the finite-difference grid for an FDM solve, or the triangle mesh for an FEM solve (in the cross-section view), default: False
  * **window_display** (*bool*) – setting window display, default: False
  * **legend** (*bool*) – setting inclusion of a legend on the index and shape plots, default: True
  * **port** (*int* *or* *str*) – (EME) the input port that the field is excited from, either a port index or a port name (see [`Port`](../interface.md#Port)), default: 0
  * **plane** (*str*) – (EME) plot cross-section plane setting. For 2D simulations, this defaults to ‘x-y’. For 3D simulations, it accepts ‘x-y’, ‘z-x’, or ‘z-y’. The ‘z-y’ panel also draws the plane of each [`monitor`](eme.md#monitor), default: ‘z-x’
  * **slice_position** (*float* *or* *None*) – (EME) location of the third dimension for a cross-section display. For example, if plane is ‘z-x’, then the slice_position refers to the y-position of the cross-section. If None, it reduces the third dimension with the reduction selected in the plot window’s slice menu: ‘sum’ (default), which totals the field across the fixed transverse axis, ‘mean’, which averages it, ‘abs sum’, which totals the field’s magnitude, so it cannot cancel where the field has transverse phase structure and shows a non-negative envelope with no longitudinal fringes, or ‘abs sum (approximate)’, which draws the same from each mode’s magnitude summed across the axis, exact for one mode, approximate where modes of different shapes interfere, and faster. The reduction is chosen in the window only and is not an argument of `plot()`. Default: None
  * **forward_only** (*bool*) – (EME) render only the forward-propagating component of the field instead of the total (forward + backward) field. This only changes the display decomposition of the already-solved field and does not re-solve, default: False
  * **wavelength** (*float*) – (EME) which wavelength’s field to render on a multi-wavelength circuit, such as the pump or the second harmonic of a $\chi^{(2)}$ section. Default: None, the circuit’s first wavelength
  * **resolution** (*float* *or* *str*) – (EME) sample spacing in nm along the propagation axis for the ‘z-x’/’z-y’ longitudinal panels, where smaller is finer and ‘auto’ picks a spacing of roughly one sample per horizontal display pixel, default: ‘auto’
  * **excitation** (*str*) – (EME) render the field launched by a free-space field declared with [`free_space_field`](eme.md#free_space_field), instead of unit amplitude in `mode` at `port`. It also selects which port the field is viewed at. This is the only API surface for viewing one. In the plot window, the same choice appears in the Mode menu as `'<name> (free space)'`. Default: None
  * **view** (*str*) – (EME) what the ‘z-x’ panel shows, either ‘layout’ (every section where its connections place it on the chip, bends turning and sections after a turn turned with them, both axes in um) or ‘simulation’ (the circuit unrolled along its length, as solved), or ‘schematic’ (a block diagram of the circuit’s sections and connections, which needs no solve, see [circuit views](circuit-views.md#circuit-views)), default: ‘layout’. The ‘Physical space’ checkbox in the plot window switches between them. Field components follow the guide on the layout, while ‘Index’ and ‘Shapes’ stay unrolled. A circuit with a closed loop (a ring closed with [`connect_ports`](eme.md#connect_ports)) has no field reconstruction yet: its ‘z-x’ panel draws the layout outline only, ‘Index’ and ‘Shapes’ show its cross-sections, and asking for a field component raises an error.
  * **blend_slices** (*bool*) – (EME) blend adjacent slices’ fields linearly for a smooth picture of the ‘z-x’ and ‘z-y’ panels, or draw each slice from its own basis alone (False). It is also a checkbox in the plot window’s Settings menu. Default: True
  * **contours** (*bool* *or* *None*) – draw the field contours (True) or not (False). It is also a checkbox in the plot window’s Settings menu. Default: None (on for the ‘x-y’ plane, off for the ‘z-x’ and ‘z-y’ planes)
  * **section** (*str*) – (EME) zoom every view to this section, by name. An unknown name raises an error listing the sections. Default: None (the whole circuit)
  * **normalization** (*str*) – the field family the color scale is normalized to, ‘vector’ (the full transverse vector at the excitation plane), ‘component’ (the plotted component alone) or ‘section’ (each section of a ‘z-x’ or ‘z-y’ panel scaled by its own peak, so a dim section such as a free-space gap stays visible), default: ‘vector’
  * **profile** (*str* *or* *None*) – render a stored profile by name instead of the EME section. Once a simulation has declared sections, the plot always follows the section, so this is the only way to view a profile saved by an earlier `label_profile()` call. An unknown name raises an error listing the available profiles, default: None
  * **file_name** (*str*) – if specified, forces the function to save a file with the given parameters and will not display the interactive plot, file is saved under a directory called EM_figures, default: None
  * **file_type** (*str*) – file type for saving a plot, ‘pdf’ or ‘png’, default: ‘’ (no extension is added to `file_name` unless a file type is given)
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### material_explorer

Interactive material explorer to plot the refractive indices of all available materials. The default wavelength range in the plot corresponds to the recommended range from the material reference listed below the plot. If wavelengths are specified outside this range, the model will be plotted with a dashed line instead of a solid line. User defined materials are also available.

* **Parameters:**
  * **material** (*str*) – the material the explorer opens on, a name from the material database. The window’s Material menu still switches it. An unknown name raises an error. Default: ‘SiO2’
  * **file_name** (*str*) – if specified, forces the function to save a file with the given parameters and will not display the interactive plot, file is saved under a directory called EM_figures, default: None
  * **file_type** (*str*) – file type for saving a plot, ‘pdf’ or ‘png’, default: ‘’ (no extension is added to `file_name` unless a file type is given)
  * **simulation_name** (*str*) – simulation name, default: ‘emode’

### refractive_index

Returns the refractive index from a material name (retrieved from the internal reference list), a MaterialSpec object, or from a custom refractive index value. Optionally, the material’s reference (or citation) may be returned.

* **Parameters:**
  * **material** (*str* *,* [*MaterialSpec*](../interface.md#MaterialSpec) *,* *float* *, or* *list*) – material name, a MaterialSpec (a rotated crystal returns its 3×3 index tensor), or a float/list for a custom value. For AlGaAs, the fraction of Al relative to Ga is included in the material name separated by a comma, for example: “AlGaAs, 0.2” for a Al_{0.2}Ga_{0.8}As.
  * **wavelength** (*float*) – [nm] wavelength, default: 1550
  * **reference** (*bool*) – additionally return the citation for the material, default: False
* **Returns:**
  [n_x, n_y, n_z] or ([n_x, n_y, n_z], reference)

### permeability

Returns the relative permeability from a material name (retrieved from the internal reference list), a MaterialSpec object, or from a custom permeability value. Optionally, the material’s reference (or citation) may be returned.

* **Parameters:**
  * **material** (*str* *,* [*MaterialSpec*](../interface.md#MaterialSpec) *,* *float* *, or* *list*) – material name, a MaterialSpec, or a float/list of 3 floats for a custom value
  * **wavelength** (*float*) – [nm] wavelength, default: 1550
  * **reference** (*bool*) – additionally return the citation for the material, default: False
* **Returns:**
  [permeability_x, permeability_y, permeability_z] or ([permeability_x, permeability_y, permeability_z], reference)

### permittivity

Returns the relative permittivity from a material name (retrieved from the internal reference list), a MaterialSpec object, or from a custom value. For isotropic materials this is a 3-element array, and for fully anisotropic materials, such as a crystal rotated by a MaterialSpec’s `theta`, `phi` and `psi`, it is a 3×3 tensor. Optionally, the material’s reference (or citation) may be returned.

* **Parameters:**
  * **material** (*str* *,* [*MaterialSpec*](../interface.md#MaterialSpec) *,* *float* *, or* *list*) – material name, a MaterialSpec, or a float/list for a custom value
  * **wavelength** (*float*) – [nm] wavelength, default: 1550
  * **reference** (*bool*) – additionally return the citation for the material, default: False
* **Returns:**
  [eps_x, eps_y, eps_z], a 3×3 array, or the corresponding tuple with reference

### d_matrix

Returns the second-order nonlinear d-matrix of a material. Optionally, the material’s reference (or citation) may be returned.

* **Parameters:**
  * **material** (*str*) – material name
  * **wavelength** (*float*) – [nm] wavelength, default: 1550
  * **reference** (*bool*) – additionally return the citation for the material, default: False
* **Returns:**
  d-matrix with shape (3, 6), or (d-matrix, reference)

### mesh

Generalized mesh tool for arbitrary shapes on a rectangular grid. This is called internally by `FDM` if it has not already been called by the user. Generates vertices for each shape, the actual refractive index for each shape, arrays to define the center points (`x`, `y`) of the mesh grid, and the relative permittivity and permeability matrices (`permittivity` and `permeability`).

* **Parameters:**
  * **profile** (*str*) – profile name, default: ‘_default’
  * **run_mesh** (*bool*) – whether to actually run the meshing step now, or just mark the profile as prepared for meshing without running it, default: True
  * **verbose** (*bool*) – control the display of the progress bar, default: True
  * **simulation_name** (*str*) – simulation name, default: ‘emode’
