Compare commits
28 changed files with 783 additions and 5398 deletions
14
README.md
14
README.md
|
|
@ -49,7 +49,7 @@ linear systems, ideally with double precision.
|
|||
|
||||
**Requirements:**
|
||||
|
||||
* python >=3.12
|
||||
* python >=3.11
|
||||
* numpy
|
||||
* scipy
|
||||
|
||||
|
|
@ -118,12 +118,8 @@ python3 -m pytest -q | tee test_results.txt
|
|||
- `meanas.fdfd`: frequency-domain wave equations, sparse operators, SCPML, and
|
||||
iterative solves for driven problems.
|
||||
- `meanas.fdfd.waveguide_2d` / `meanas.fdfd.waveguide_3d`: waveguide mode
|
||||
solvers, including targeted complex bases from the default half-sized
|
||||
beta-squared or explicit signed-beta formulations, transpose-left and
|
||||
Lorentz-dual projection fields on a shared field-array axis, separately
|
||||
returned PML-mode diagnostics, overlap-based tracking,
|
||||
mode-source construction, and overlap windows for port-based excitation and
|
||||
analysis.
|
||||
solvers, mode-source construction, and overlap windows for port-based
|
||||
excitation and analysis.
|
||||
- `meanas.fdtd`: Yee-step updates, CPML boundaries, flux/energy accounting, and
|
||||
on-the-fly phasor extraction for comparing time-domain runs against FDFD.
|
||||
- `meanas.fdmath`: low-level finite-difference operators, vectorization helpers,
|
||||
|
|
@ -176,10 +172,8 @@ The tracked examples under `examples/` are the intended entry points for users:
|
|||
- `examples/eme_bend.py`: straight-to-bent waveguide mode matching with
|
||||
cylindrical bend modes, interface scattering, and a cascaded bend-network
|
||||
example built with `scikit-rf`.
|
||||
- `examples/eme_taper_cmt.py`: sampled-interface EME with stable S cascading for a
|
||||
- `examples/eme_taper_cmt.py`: sampled cross-section local-mode CMT for a
|
||||
continuously varying rib-waveguide taper.
|
||||
- `examples/eme_taper_pml_modes.py`: targeted complex/PML mode solving,
|
||||
tracking, and construction of EME taper sections.
|
||||
- `examples/fdfd.py`: direct frequency-domain waveguide excitation and overlap /
|
||||
Poynting analysis without a time-domain run.
|
||||
|
||||
|
|
|
|||
|
|
@ -13,24 +13,3 @@
|
|||
::: meanas.fdfd.scpml
|
||||
|
||||
::: meanas.fdfd.farfield
|
||||
|
||||
## SCPML conventions
|
||||
|
||||
`stretch_with_scpml` now uses `-1` for the low-index face and `+1` for the
|
||||
high-index face, matching CPML and propagation conventions. It returns copied
|
||||
widths by default; pass `copy=False` to request mutation explicitly.
|
||||
|
||||
Both SCPML builders accept `kappa_function(depth)` for real stretching and
|
||||
`max_imag_ratio` to limit the final dimensionless `abs(Im(s))/Re(s)`. Start a
|
||||
mode-solver convergence study with `max_imag_ratio=1.0`: overly strong imaginary
|
||||
stretching can produce above-light-line PML artifacts. The cap is not a general
|
||||
spectral guarantee, and weaker absorption can increase boundary reflections.
|
||||
Check domain size, PML thickness, strength, mode localization, and residuals.
|
||||
The general scattering profile remains uncapped by default.
|
||||
|
||||
`uniform_grid_scpml` builds unit widths by applying `stretch_with_scpml` to
|
||||
both faces of each enabled axis. Both builders divide imaginary grading by
|
||||
physical layer thickness and sample electric widths at cell centers and
|
||||
magnetic widths at cell edges. This corrects the uniform builder's previous
|
||||
thickness-independent strength and reversed E/H sample offsets; retune existing
|
||||
uniform-builder profiles using domain/PML convergence checks.
|
||||
|
|
|
|||
|
|
@ -13,12 +13,3 @@
|
|||
::: meanas.fdtd.energy
|
||||
|
||||
::: meanas.fdtd.phasor
|
||||
|
||||
CPML derivatives use electric widths for forward differences and magnetic
|
||||
widths for backward differences. `cpml_params(..., dx=1.0)` specifies the uniform
|
||||
physical cell width normal to a face; arbitrary nonuniform PML grading is not
|
||||
implemented by this constructor. Scale the timestep consistently with the grid.
|
||||
|
||||
`ln_R_per_layer` must be finite and strictly negative. Zero attenuation raises
|
||||
`ValueError`; disable individual CPML faces with `None` in the parameter table
|
||||
passed to `updates_with_cpml`.
|
||||
|
|
|
|||
|
|
@ -5,149 +5,3 @@
|
|||
::: meanas.fdfd.waveguide_3d
|
||||
|
||||
::: meanas.fdfd.waveguide_cyl
|
||||
|
||||
## Overlap measures and normalization
|
||||
|
||||
`waveguide_2d.inner_product(..., measure="physical", conj_h=True)` uses real
|
||||
Yee widths for physical Poynting power. `measure="stretched"` keeps complex
|
||||
widths for coordinate reaction. `lorentz_metric` and `lorentz_overlap` default
|
||||
to the stretched measure. Use the same grid and measure when constructing and
|
||||
using dual fields. A real overlap grid still defines a consistent constructed
|
||||
dual basis, even when the eigenproblem uses a separate PML grid.
|
||||
|
||||
`normalized_fields_e/h(..., normalization="lorentz")` normalizes unconjugated
|
||||
self-reaction to one. This fixes phase up to a sign and is distinct from unit
|
||||
forward power, which remains the default. Zero-power or self-orthogonal modes
|
||||
raise `ValueError`; open self-orthogonal modes require paired primal/dual
|
||||
normalization through `ModeBasis`.
|
||||
|
||||
## Targeted and reproducible mode solving
|
||||
|
||||
For modes near an effective index guess, use `solve_modes_near` with
|
||||
`target_wavenumbers=[omega * n_guess]`. It targets the electric beta-squared
|
||||
operator at `(omega * n_guess)**2`; `solve_modes_near_beta` instead targets the
|
||||
first-order signed-beta operator. Both use the LU shift-invert backend and
|
||||
support `eigensolver_opts={"v0": starting_vector}`. Factorization cost and
|
||||
memory depend on the grid, so this is not universally faster than indexed
|
||||
solving. `solve_modes` keeps its global mode-number semantics and now accepts
|
||||
`rng` or `v0` for reproducible initialization.
|
||||
|
||||
`waveguide_3d.mode_from_2d` accepts a supplied transverse electric eigenvector
|
||||
and reuses field reconstruction, normalization, numerical-dispersion
|
||||
correction, Yee staggering, rotation, and full-grid embedding without solving
|
||||
an eigenproblem.
|
||||
|
||||
## Interface and sampled-taper scattering
|
||||
|
||||
All scattering matrices use outgoing rows and incoming columns, ordered
|
||||
`[left, right]`:
|
||||
|
||||
```text
|
||||
[b_left ] [R_left T_right_to_left] [a_left ]
|
||||
[b_right] = [T_left_to_right R_right] [a_right]
|
||||
```
|
||||
|
||||
`get_s` and `get_abcd` require explicit `dxes`. Mixed Petrov-Galerkin testing is
|
||||
the default: left electric duals test H continuity, and right magnetic duals
|
||||
test E continuity. Both incidence directions are solved together with full
|
||||
projection matrices. Mixed scattering supports unequal mode counts.
|
||||
`formulation="galerkin"` selects equal-count left testing of both equations.
|
||||
Neither formulation silently clips transmission. The optional `force_nogain`
|
||||
and `force_reciprocal` flags are numerical projections, not general physical
|
||||
tests for arbitrary open or evanescent modal coordinates.
|
||||
|
||||
`get_taper_s` replaces finite-difference CMT with half propagation in the left
|
||||
basis, a midpoint interface, and half propagation in the right basis for each
|
||||
sampled interval. Redheffer composition avoids growing passive backward
|
||||
transfer branches. Refine section sampling and modal/PML bases to establish
|
||||
convergence. The ineffective `rtol`, `atol`, and `max_step` arguments have been
|
||||
removed. The existing `eme_taper_cmt.py` example filename is retained.
|
||||
|
||||
```python
|
||||
prepared = eme.prepare_taper(sections, dxes)
|
||||
s_original = eme.evaluate_taper_s(prepared)
|
||||
s_longer = eme.evaluate_taper_s(prepared, z_coords=prepared.z_coords * 1.2)
|
||||
s_changed_beta = eme.evaluate_taper_s(
|
||||
prepared, wavenumber_matrices=beta_matrices,
|
||||
)
|
||||
```
|
||||
|
||||
`PreparedTaper` owns read-only copies of phase-aligned interface data. Beta
|
||||
matrix overrides have shape `(section, mode, mode)` in the original supplied
|
||||
section bases; recorded basis transforms are applied automatically. Explicit
|
||||
backward branches require backward beta overrides when forward beta is changed.
|
||||
Evaluation performs no field overlaps or eigensolves. Length sweeps reuse the
|
||||
sampled model; wavelength sweeps with reused fields are explicitly frozen-basis
|
||||
approximations. Reprepare when fields, duals, grids, or formulations change.
|
||||
|
||||
`cascade_s(left, right, internal_modes=...)` connects spatially ordered S
|
||||
matrices, including unequal external ports. Public `abcd_to_s` and `s_to_abcd`
|
||||
use `[f_right, b_right] = ABCD @ [f_left, b_left]` and require equal port counts.
|
||||
`get_taper_abcd` converts the stable S result; zero transmission or an
|
||||
unrepresentable transfer matrix raises `LinAlgError`. Prefer S for long lossy
|
||||
devices. Singular interface and cascade systems also raise contextual errors
|
||||
rather than silently substituting pseudoinverses.
|
||||
|
||||
::: meanas.fdfd.eme
|
||||
|
||||
## Orientation bias under modal truncation
|
||||
|
||||
Mixed testing is a projected approximation: H continuity is tested on the left
|
||||
and E continuity on the right. Swapping the ports changes the testing spaces
|
||||
when the retained modal subspaces are incomplete. This effect survives checks
|
||||
of reciprocity and unitarity.
|
||||
|
||||
A reproducible Maxwell counterexample is a uniform isotropic medium with two
|
||||
degenerate linear polarizations. Keep one polarization on each port, rotated
|
||||
so their overlap is `a=0.8`. There is no material interface: true reflection is
|
||||
zero and transmission into the retained receiver is `a`. The other polarization
|
||||
carries the remaining transmitted power, `1-a**2=0.36`.
|
||||
|
||||
| Calculation | R_left | R_right | T_left_to_right | T_right_to_left |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| Exact full basis, then restrict ports | 0 | 0 | 0.8 | 0.8 |
|
||||
| Truncated mixed | 0.219512 | -0.219512 | 0.975610 | 0.975610 |
|
||||
| Swap ports, mixed, then reorder | -0.219512 | 0.219512 | 0.975610 | 0.975610 |
|
||||
| Truncated left Galerkin | 0 | 0 | 1.25 | 0.8 |
|
||||
| Euclidean E/H least squares | 0 | 0 | 0.8 | 0.8 |
|
||||
|
||||
An independent driven 3D FDFD solve with PML agrees with the exact reference
|
||||
from either incidence direction: transmission is 0.8 within `1e-12`, with
|
||||
reflection below `2e-8` in the test fixture. Keeping both polarizations makes
|
||||
mixed testing match the exact complete scattering matrix and restores
|
||||
port-relabeling covariance.
|
||||
|
||||
For the single retained polarization, mixed testing yields
|
||||
`r=(1-a**2)/(1+a**2)` and `t=2*a/(1+a**2)`. The spurious reflection is quadratic
|
||||
in a small angle between adjacent retained polarizations. However, longitudinal
|
||||
refinement alone is insufficient: rotating a single retained vector through a
|
||||
uniform degenerate medium makes the sampled chain approach artificial following
|
||||
of that vector (`|T|` approaches 1), while the physical endpoint overlap remains
|
||||
0.8. Keeping the complete degenerate block recovers the physical result at every
|
||||
sampling density tested.
|
||||
|
||||
Two tempting corrections are insufficient. Averaging the two port orientations
|
||||
cancels reflection in this example but leaves transmission at 0.975610. Plain
|
||||
Euclidean E/H least squares gives the correct uniform-medium result, but is not
|
||||
a general replacement. A second fixture uses exact degenerate modes of diagonal
|
||||
positive epsilon/mu tensors, with electric scaling `(1,2)` on the left and
|
||||
`(1,3)` on the right and a 30-degree polarization rotation on both ports. After
|
||||
single-mode truncation, least squares has unequal directional transmissions
|
||||
(approximately 0.850839 and 1.092163) and a maximum singular value of 1.104947.
|
||||
The complete Fresnel solution is reciprocal and lossless.
|
||||
|
||||
The mixed default remains unchanged. Retain complete coupled/degenerate blocks
|
||||
when the geometry can mix them, check modal-basis convergence as well as section
|
||||
sampling, and compare against independent full-field results. Neither orientation
|
||||
averaging nor gain/reciprocity postprocessing recovers omitted-channel physics.
|
||||
Orientation discrepancy is a useful diagnostic, not a bound on transmission
|
||||
error. These examples use real power-orthonormal propagating modes; for general
|
||||
complex modes, the reciprocity constraint involves the modal orthogonality
|
||||
matrix, as derived by [Svendsen, Haakestad, and Skaar](https://arxiv.org/abs/1301.2458).
|
||||
|
||||
Reproduce the analytic, full-basis, candidate-formulation, taper-refinement, and
|
||||
driven-FDFD checks with:
|
||||
|
||||
```sh
|
||||
OPENBLAS_NUM_THREADS=1 python -m pytest meanas/test/test_eme_orientation.py -q
|
||||
```
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ Relevant starting examples:
|
|||
scattering between two nearby waveguide cross-sections
|
||||
- `examples/eme_bend.py` for straight-to-bent mode matching with cylindrical
|
||||
bend modes and a cascaded bend-network example
|
||||
- `examples/eme_taper_cmt.py` for sampled-interface EME through continuously
|
||||
- `examples/eme_taper_cmt.py` for local-mode CMT through sampled continuously
|
||||
varying taper cross-sections
|
||||
- `examples/fdfd.py` for direct frequency-domain waveguide excitation
|
||||
|
||||
|
|
|
|||
|
|
@ -264,7 +264,7 @@ def main() -> None:
|
|||
skrf = require_optional('skrf', package_name='scikit-rf')
|
||||
|
||||
grid, epsilon, dxes_2d, omega = build_geometry()
|
||||
epsilon_slice = epsilon[:, :, :, 1]
|
||||
epsilon_slice = epsilon[:, :, :, 2]
|
||||
rmin = RADIUS + grid.xyz[0].min()
|
||||
|
||||
straight_modes, straight_wavenumbers = solve_straight_modes(epsilon_slice, omega=omega, dxes_2d=dxes_2d)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
"""
|
||||
Sampled-interface EME example for a continuously varying rib-waveguide taper.
|
||||
Local-mode CMT example for a continuously varying rib-waveguide taper.
|
||||
|
||||
This example keeps geometry construction outside `meanas.fdfd.eme`: it samples a
|
||||
width taper at several cross-sections, solves and normalizes each local mode with
|
||||
|
|
@ -112,15 +112,14 @@ def print_summary(
|
|||
print('sampled taper effective indices:', ', '.join(f'{value:.5f}' for value in neffs))
|
||||
print(f'abrupt endpoint reflection |S_00|^2 = {abs(abrupt_s[0, 0]) ** 2:.6f}')
|
||||
print(f'abrupt endpoint transmission |S_{n_modes},0|^2 = {abs(abrupt_s[n_modes, 0]) ** 2:.6f}')
|
||||
print(f'taper reflection |S_00|^2 = {abs(taper_s[0, 0]) ** 2:.6f}')
|
||||
print(f'taper transmission |S_{n_modes},0|^2 = {abs(taper_s[n_modes, 0]) ** 2:.6f}')
|
||||
print(f'taper total output power = {numpy.sum(abs(taper_s[:, 0]) ** 2):.6f}')
|
||||
print(f'taper CMT reflection |S_00|^2 = {abs(taper_s[0, 0]) ** 2:.6f}')
|
||||
print(f'taper CMT transmission |S_{n_modes},0|^2 = {abs(taper_s[n_modes, 0]) ** 2:.6f}')
|
||||
print(f'taper CMT total output power = {numpy.sum(abs(taper_s[:, 0]) ** 2):.6f}')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sections, neffs, _omega, dxes_2d = solve_taper_sections()
|
||||
prepared = eme.prepare_taper(sections, dxes=dxes_2d)
|
||||
taper_s = eme.evaluate_taper_s(prepared)
|
||||
taper_s = eme.get_taper_s(sections, dxes=dxes_2d)
|
||||
abrupt_s = eme.get_s(
|
||||
sections[0].modes,
|
||||
sections[0].wavenumbers,
|
||||
|
|
|
|||
|
|
@ -1,110 +0,0 @@
|
|||
"""Build tracked complex/PML modal bases for a slowly varying taper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy
|
||||
|
||||
from meanas.fdmath import vec
|
||||
from meanas.fdfd import eme, scpml, waveguide_2d
|
||||
|
||||
|
||||
WAVELENGTH = 1.55
|
||||
OMEGA = 2 * numpy.pi / WAVELENGTH
|
||||
SHAPE = (17, 17)
|
||||
SPACING = 0.25
|
||||
PML_CELLS = 3
|
||||
EPS_CLADDING = 1.45 ** 2
|
||||
EPS_CORE = 2.0 ** 2
|
||||
|
||||
|
||||
def build_grids() -> tuple[list[list[numpy.ndarray]], list[list[numpy.ndarray]]]:
|
||||
"""Build matching physical and complex-stretched transverse Yee grids.
|
||||
|
||||
Returns:
|
||||
The real overlap grid followed by the PML-stretched solve grid.
|
||||
"""
|
||||
physical = [[numpy.full(size, SPACING) for size in SHAPE] for _ in range(2)]
|
||||
stretched = [[values.copy() for values in family] for family in physical]
|
||||
for axis in (0, 1):
|
||||
for polarity in (-1, +1):
|
||||
stretched = scpml.stretch_with_scpml(
|
||||
stretched,
|
||||
axis=axis,
|
||||
polarity=polarity,
|
||||
omega=OMEGA,
|
||||
epsilon_effective=EPS_CLADDING,
|
||||
thickness=PML_CELLS,
|
||||
max_imag_ratio=1.0,
|
||||
)
|
||||
return physical, stretched
|
||||
|
||||
|
||||
def build_epsilon(edge_fill: float) -> numpy.ndarray:
|
||||
"""Construct and vectorize one taper cross-section permittivity profile.
|
||||
|
||||
Args:
|
||||
edge_fill: Fractional core fill used for the two cells beside the
|
||||
central three-cell-wide core.
|
||||
|
||||
Returns:
|
||||
Vectorized three-component relative permittivity field.
|
||||
"""
|
||||
epsilon = numpy.full((3, *SHAPE), EPS_CLADDING)
|
||||
center_x, center_y = (size // 2 for size in SHAPE)
|
||||
epsilon[:, center_x - 1:center_x + 2, center_y] = EPS_CORE
|
||||
mixed_epsilon = EPS_CLADDING + edge_fill * (EPS_CORE - EPS_CLADDING)
|
||||
epsilon[:, center_x - 1:center_x + 2, center_y - 1] = mixed_epsilon
|
||||
epsilon[:, center_x - 1:center_x + 2, center_y + 1] = mixed_epsilon
|
||||
return vec(epsilon)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Solve, track, and summarize the sampled complex modal bases."""
|
||||
physical_dxes, solve_dxes = build_grids()
|
||||
z_coords = numpy.array([0.0, 5.0, 10.0])
|
||||
epsilon_samples = [build_epsilon(edge_fill) for edge_fill in (0.30, 0.35, 0.40)]
|
||||
solved = [
|
||||
waveguide_2d.solve_modes_near(
|
||||
OMEGA,
|
||||
solve_dxes,
|
||||
epsilon,
|
||||
target_wavenumbers=[1.45 * OMEGA],
|
||||
modes_per_target=3,
|
||||
candidate_margin=3,
|
||||
overlap_dxes=physical_dxes,
|
||||
)
|
||||
for epsilon in epsilon_samples
|
||||
]
|
||||
bases = [basis for basis, _diagnostics in solved]
|
||||
tracked = waveguide_2d.track_mode_path(bases, overlap_dxes=physical_dxes)
|
||||
tracked_diagnostics = [
|
||||
waveguide_2d.compute_mode_diagnostics(
|
||||
basis,
|
||||
OMEGA,
|
||||
solve_dxes,
|
||||
epsilon,
|
||||
target_wavenumbers=[1.45 * OMEGA],
|
||||
overlap_dxes=physical_dxes,
|
||||
)
|
||||
for basis, epsilon in zip(tracked, epsilon_samples, strict=True)
|
||||
]
|
||||
sections = eme.mode_sections_from_bases(z_coords, tracked)
|
||||
prepared = eme.prepare_taper(sections, physical_dxes)
|
||||
# Fields and interface overlaps are reused: these are frozen-basis length
|
||||
# sweeps. Wavelength-dependent beta overrides would also freeze the fields.
|
||||
length_sweep = [eme.evaluate_taper_s(prepared, z_coords=z_coords * scale)
|
||||
for scale in (0.8, 1.0, 1.2)]
|
||||
|
||||
for z_coord, basis, diagnostics in zip(z_coords, tracked, tracked_diagnostics, strict=True):
|
||||
print(
|
||||
f'z={z_coord:5.1f}: '
|
||||
f'beta={basis.wavenumbers[0]:.6g}, '
|
||||
f'PML participation={diagnostics.pml_participation[0]:.3f}, '
|
||||
f'right residual={diagnostics.right_residuals[0]:.2e}',
|
||||
)
|
||||
print(f'constructed {len(sections)} tracked EME sections with {len(sections[0].modes)} modes each')
|
||||
print('frozen-basis length sweep |T_00|:', [float(abs(ss[len(tracked[0]), 0])) for ss in length_sweep])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -145,7 +145,7 @@ def main() -> None:
|
|||
|
||||
# PMLs in every direction
|
||||
pml_params = [
|
||||
[cpml_params(axis=dd, polarity=pp, dt=dt, dx=dx, thickness=pml_thickness, epsilon_eff=n_air ** 2)
|
||||
[cpml_params(axis=dd, polarity=pp, dt=dt, thickness=pml_thickness, epsilon_eff=n_air ** 2)
|
||||
for pp in (-1, +1)]
|
||||
for dd in range(3)]
|
||||
update_E, update_H = updates_with_cpml(cpml_params=pml_params, dt=dt, dxes=dxes, epsilon=epsilon, dtype=complex)
|
||||
|
|
@ -203,7 +203,7 @@ def main() -> None:
|
|||
dxes_fdfd = copy.deepcopy(dxes)
|
||||
for pp in (-1, +1):
|
||||
for dd in range(3):
|
||||
dxes_fdfd = stretch_with_scpml(dxes_fdfd, axis=dd, polarity=pp, omega=omega, epsilon_effective=n_air ** 2, thickness=pml_thickness)
|
||||
stretch_with_scpml(dxes_fdfd, axis=dd, polarity=pp, omega=omega, epsilon_effective=n_air ** 2, thickness=pml_thickness)
|
||||
# Compare the extracted phasor to the FDFD operator on the stretched grid,
|
||||
# not the unstretched Yee spacings used by the raw time-domain update.
|
||||
A = e_full(omega=omega, dxes=dxes_fdfd, epsilon=epsilon)
|
||||
|
|
|
|||
|
|
@ -273,7 +273,7 @@ def main2():
|
|||
|
||||
# PMLs in every direction
|
||||
pml_params = [
|
||||
[cpml_params(axis=dd, polarity=pp, dt=dt, dx=dx, thickness=pml_thickness, epsilon_eff=n_cladding ** 2)
|
||||
[cpml_params(axis=dd, polarity=pp, dt=dt, thickness=pml_thickness, epsilon_eff=n_cladding ** 2)
|
||||
for pp in (-1, +1)]
|
||||
for dd in range(3)]
|
||||
update_E, update_H = updates_with_cpml(cpml_params=pml_params, dt=dt, dxes=dxes, epsilon=epsilon, dtype=complex)
|
||||
|
|
@ -330,7 +330,7 @@ def main2():
|
|||
dxes_fdfd = copy.deepcopy(dxes)
|
||||
for pp in (-1, +1):
|
||||
for dd in range(3):
|
||||
dxes_fdfd = stretch_with_scpml(dxes_fdfd, axis=dd, polarity=pp, omega=omega, epsilon_effective=n_cladding ** 2, thickness=pml_thickness)
|
||||
stretch_with_scpml(dxes_fdfd, axis=dd, polarity=pp, omega=omega, epsilon_effective=n_cladding ** 2, thickness=pml_thickness)
|
||||
# Residuals must be checked on the stretched FDFD grid, because the FDTD run
|
||||
# already includes those same absorbing layers through CPML.
|
||||
A = e_full(omega=omega, dxes=dxes_fdfd, epsilon=epsilon)
|
||||
|
|
|
|||
|
|
@ -2,153 +2,17 @@
|
|||
Solvers for eigenvalue / eigenvector problems
|
||||
"""
|
||||
from collections.abc import Callable
|
||||
import dataclasses
|
||||
import numpy
|
||||
from numpy.typing import NDArray, ArrayLike
|
||||
from numpy.linalg import norm
|
||||
from scipy import sparse
|
||||
import scipy.sparse.linalg as spalg
|
||||
from scipy.optimize import linear_sum_assignment
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True, eq=False)
|
||||
class TargetedEigensolution:
|
||||
"""Paired right and transpose-left eigenvectors near a spectral target.
|
||||
|
||||
Attributes:
|
||||
eigenvalues: Eigenvalues associated with the columns of both vector
|
||||
matrices.
|
||||
right_eigenvectors: Right eigenvectors stored column-wise.
|
||||
left_eigenvectors: Bilinear-left eigenvectors stored column-wise. These
|
||||
satisfy a transpose, rather than Hermitian-transpose, eigenproblem.
|
||||
"""
|
||||
|
||||
eigenvalues: NDArray[numpy.complex128]
|
||||
right_eigenvectors: NDArray[numpy.complex128] = dataclasses.field(repr=False)
|
||||
left_eigenvectors: NDArray[numpy.complex128] = dataclasses.field(repr=False)
|
||||
|
||||
|
||||
type TargetedEigensolver = Callable[..., TargetedEigensolution]
|
||||
|
||||
|
||||
def scipy_eigs_near(
|
||||
operator: sparse.sparray,
|
||||
target: complex,
|
||||
how_many: int,
|
||||
*,
|
||||
tolerance: float = 1e-10,
|
||||
max_iterations: int | None = None,
|
||||
ncv: int | None = None,
|
||||
pairing_rtol: float = 1e-7,
|
||||
v0: ArrayLike | None = None,
|
||||
) -> TargetedEigensolution:
|
||||
"""
|
||||
Solve for paired right and bilinear-left eigenvectors near ``target``.
|
||||
|
||||
One sparse LU factorization of ``operator - target * I`` is reused for the
|
||||
right solve and for the transpose-left solve. The left vectors therefore
|
||||
satisfy ``left.T @ operator = eigenvalue * left.T``; this deliberately uses
|
||||
a transpose rather than a Hermitian transpose so the result is suitable for
|
||||
unconjugated Lorentz-reciprocity projections.
|
||||
|
||||
Args:
|
||||
operator: Square sparse operator to diagonalize.
|
||||
target: Shift-invert spectral target.
|
||||
how_many: Number of eigenpairs to return.
|
||||
tolerance: ARPACK convergence tolerance for both solves.
|
||||
max_iterations: Optional ARPACK iteration limit.
|
||||
ncv: Optional number of Arnoldi vectors. A size-aware default is used
|
||||
when omitted.
|
||||
pairing_rtol: Relative tolerance for matching right and transpose-left
|
||||
eigenvalues.
|
||||
v0: Optional finite starting vector shared by both solves.
|
||||
|
||||
Returns:
|
||||
Paired eigenvalues and column-wise right and transpose-left vectors.
|
||||
|
||||
Raises:
|
||||
ValueError: If the dimensions, counts, tolerances, or starting vector
|
||||
are invalid.
|
||||
RuntimeError: If the independently solved spectra cannot be paired.
|
||||
"""
|
||||
if how_many < 1:
|
||||
raise ValueError('how_many must be positive')
|
||||
if not numpy.isfinite(tolerance) or tolerance <= 0:
|
||||
raise ValueError('tolerance must be finite and positive')
|
||||
if not numpy.isfinite(pairing_rtol) or pairing_rtol <= 0:
|
||||
raise ValueError('pairing_rtol must be finite and positive')
|
||||
|
||||
operator = sparse.csc_array(operator, dtype=complex)
|
||||
size = operator.shape[0]
|
||||
if operator.shape != (size, size):
|
||||
raise ValueError('operator must be square')
|
||||
if how_many >= size - 1:
|
||||
raise ValueError('how_many must be smaller than operator dimension minus one')
|
||||
|
||||
shifted = operator - target * sparse.eye_array(size, format='csc', dtype=complex)
|
||||
factor = spalg.splu(shifted)
|
||||
dtype = numpy.dtype(numpy.complex128)
|
||||
inverse = spalg.LinearOperator(
|
||||
operator.shape,
|
||||
matvec=lambda vector: factor.solve(vector, trans='N'),
|
||||
dtype=dtype,
|
||||
)
|
||||
inverse_transpose = spalg.LinearOperator(
|
||||
operator.shape,
|
||||
matvec=lambda vector: factor.solve(vector, trans='T'),
|
||||
dtype=dtype,
|
||||
)
|
||||
if ncv is None:
|
||||
ncv = min(size, max(2 * how_many + 1, 4 * how_many))
|
||||
start = None if v0 is None else numpy.asarray(v0, dtype=complex)
|
||||
if start is not None and (start.shape != (size,) or not numpy.isfinite(start).all()):
|
||||
raise ValueError('v0 must be a finite vector matching the operator dimension')
|
||||
|
||||
eigenvalues, right = spalg.eigs(
|
||||
operator,
|
||||
k=how_many,
|
||||
sigma=target,
|
||||
which='LM',
|
||||
OPinv=inverse,
|
||||
tol=tolerance,
|
||||
maxiter=max_iterations,
|
||||
ncv=ncv,
|
||||
v0=start,
|
||||
)
|
||||
left_values, left = spalg.eigs(
|
||||
operator.T,
|
||||
k=how_many,
|
||||
sigma=target,
|
||||
which='LM',
|
||||
OPinv=inverse_transpose,
|
||||
tol=tolerance,
|
||||
maxiter=max_iterations,
|
||||
ncv=ncv,
|
||||
v0=start,
|
||||
)
|
||||
|
||||
rows, columns = linear_sum_assignment(numpy.abs(eigenvalues[:, None] - left_values[None, :]))
|
||||
paired_columns = columns[numpy.argsort(rows)]
|
||||
left_values = left_values[paired_columns]
|
||||
left = left[:, paired_columns]
|
||||
pairing_error = numpy.abs(eigenvalues - left_values)
|
||||
pairing_scale = numpy.maximum(1.0, numpy.maximum(numpy.abs(eigenvalues), numpy.abs(left_values)))
|
||||
if numpy.any(pairing_error > pairing_rtol * pairing_scale):
|
||||
raise RuntimeError('could not pair right and transpose-left eigenvalues')
|
||||
|
||||
return TargetedEigensolution(
|
||||
eigenvalues=numpy.asarray(eigenvalues, dtype=complex),
|
||||
right_eigenvectors=numpy.asarray(right, dtype=complex),
|
||||
left_eigenvectors=numpy.asarray(left, dtype=complex),
|
||||
)
|
||||
|
||||
|
||||
def power_iteration(
|
||||
operator: sparse.spmatrix,
|
||||
guess_vector: NDArray[numpy.complex128] | None = None,
|
||||
iterations: int = 20,
|
||||
*,
|
||||
rng: numpy.random.Generator | int | None = None,
|
||||
) -> tuple[complex, NDArray[numpy.complex128]]:
|
||||
"""
|
||||
Use power iteration to estimate the dominant eigenvector of a matrix.
|
||||
|
|
@ -157,18 +21,15 @@ def power_iteration(
|
|||
operator: Matrix to analyze.
|
||||
guess_vector: Starting point for the eigenvector. Default is a randomly chosen vector.
|
||||
iterations: Number of iterations to perform. Default 20.
|
||||
rng: Generator or seed used only when ``guess_vector`` is omitted.
|
||||
|
||||
Returns:
|
||||
(Largest-magnitude eigenvalue, Corresponding eigenvector estimate)
|
||||
"""
|
||||
rng = numpy.random.default_rng()
|
||||
if guess_vector is None:
|
||||
rng = numpy.random.default_rng(rng)
|
||||
v = rng.random(operator.shape[0]) + 1j * rng.random(operator.shape[0])
|
||||
else:
|
||||
v = numpy.array(guess_vector, dtype=complex, copy=True)
|
||||
if v.shape != (operator.shape[0],) or not numpy.isfinite(v).all() or not numpy.any(v):
|
||||
raise ValueError('guess_vector must be finite, nonzero, and match the operator dimension')
|
||||
v = guess_vector
|
||||
|
||||
for _ in range(iterations):
|
||||
v = operator @ v
|
||||
|
|
@ -206,14 +67,12 @@ def rayleigh_quotient_iteration(
|
|||
(operator - sparse.eye_array(operator.shape[0]))
|
||||
|
||||
def shift(eigval: float) -> sparse.sparray:
|
||||
"""Construct a sparse scalar identity shift."""
|
||||
return eigval * sparse.eye_array(operator.shape[0])
|
||||
|
||||
if solver is None:
|
||||
solver = spalg.spsolve
|
||||
except TypeError:
|
||||
def shift(eigval: float) -> spalg.LinearOperator:
|
||||
"""Construct a matrix-free scalar identity shift."""
|
||||
return spalg.LinearOperator(
|
||||
shape=operator.shape,
|
||||
dtype=operator.dtype,
|
||||
|
|
@ -221,7 +80,6 @@ def rayleigh_quotient_iteration(
|
|||
)
|
||||
if solver is None:
|
||||
def solver(A: spalg.LinearOperator, b: ArrayLike) -> NDArray[numpy.complex128]:
|
||||
"""Solve a matrix-free shifted system with BiCGSTAB."""
|
||||
return spalg.bicgstab(A, b)[0]
|
||||
assert solver is not None
|
||||
|
||||
|
|
@ -242,9 +100,6 @@ def signed_eigensolve(
|
|||
operator: sparse.spmatrix | spalg.LinearOperator,
|
||||
how_many: int,
|
||||
negative: bool = False,
|
||||
*,
|
||||
rng: numpy.random.Generator | int | None = None,
|
||||
v0: ArrayLike | None = None,
|
||||
) -> tuple[NDArray[numpy.complex128], NDArray[numpy.complex128]]:
|
||||
"""
|
||||
Find the largest-magnitude positive-only (or negative-only) eigenvalues and
|
||||
|
|
@ -255,24 +110,13 @@ def signed_eigensolve(
|
|||
how_many: How many eigenvalues to find.
|
||||
negative: Whether to find negative-only eigenvalues.
|
||||
Default False (positive only).
|
||||
rng: Optional generator or seed for reproducible initialization.
|
||||
v0: Finite nonzero starting vector, taking precedence over ``rng``.
|
||||
|
||||
Returns:
|
||||
(sorted list of eigenvalues, 2D ndarray of corresponding eigenvectors)
|
||||
`eigenvectors[:, k]` corresponds to the k-th eigenvalue
|
||||
"""
|
||||
# Use power iteration to estimate the dominant eigenvector
|
||||
if v0 is None:
|
||||
generator = numpy.random.default_rng(rng)
|
||||
start = generator.random(operator.shape[0]) + 1j * generator.random(operator.shape[0])
|
||||
else:
|
||||
start = numpy.array(v0, dtype=complex, copy=True)
|
||||
lm_eigval, _ = power_iteration(operator, guess_vector=start)
|
||||
if not numpy.issubdtype(operator.dtype, numpy.complexfloating):
|
||||
start = start.real
|
||||
if not numpy.any(start):
|
||||
raise ValueError('v0 must have a nonzero real part for a real operator')
|
||||
lm_eigval, _ = power_iteration(operator)
|
||||
|
||||
'''
|
||||
Shift by the absolute value of the largest eigenvalue, then find a few of the
|
||||
|
|
@ -291,11 +135,9 @@ def signed_eigensolve(
|
|||
shifted_operator = operator + spalg.LinearOperator(shape=operator.shape,
|
||||
matvec=lambda v: shift * v)
|
||||
|
||||
shifted_eigenvalues, eigenvectors = spalg.eigs(
|
||||
shifted_operator, which='LM', k=how_many,
|
||||
ncv=min(operator.shape[0], 2 * how_many + 50), v0=start,
|
||||
)
|
||||
shifted_eigenvalues, eigenvectors = spalg.eigs(shifted_operator, which='LM', k=how_many, ncv=2 * how_many + 50)
|
||||
eigenvalues = shifted_eigenvalues - shift
|
||||
|
||||
k = eigenvalues.argsort()
|
||||
return eigenvalues[k], eigenvectors[:, k]
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -38,148 +38,132 @@ def prepare_s_function(
|
|||
return s_factor
|
||||
|
||||
|
||||
def _stretch_factors(
|
||||
distance: NDArray,
|
||||
correction: float,
|
||||
s_function: s_function_t,
|
||||
kappa_function: s_function_t | None,
|
||||
max_imag_ratio: float | None,
|
||||
) -> NDArray[numpy.complex128]:
|
||||
"""Evaluate the final dimensionless coordinate stretch."""
|
||||
kappa = numpy.asarray(1.0 if kappa_function is None else kappa_function(distance))
|
||||
sigma = numpy.asarray(s_function(distance)) / correction
|
||||
if numpy.iscomplexobj(kappa) or not numpy.isfinite(kappa).all() or (kappa < 1).any():
|
||||
raise ValueError('kappa_function must return finite real stretches at least one')
|
||||
if numpy.iscomplexobj(sigma) or not numpy.isfinite(sigma).all():
|
||||
raise ValueError('s_function must return finite real values')
|
||||
if max_imag_ratio is not None:
|
||||
sigma = numpy.clip(sigma, -max_imag_ratio * kappa, max_imag_ratio * kappa)
|
||||
return kappa + 1j * sigma
|
||||
|
||||
|
||||
def _validate_profile(omega: float, epsilon_effective: float, max_imag_ratio: float | None) -> None:
|
||||
if not numpy.isfinite(omega) or not numpy.isreal(omega) or omega <= 0:
|
||||
raise ValueError('omega must be finite, real, and positive')
|
||||
if not numpy.isfinite(epsilon_effective) or epsilon_effective <= 0:
|
||||
raise ValueError('epsilon_effective must be finite and positive')
|
||||
if max_imag_ratio is not None and (not numpy.isfinite(max_imag_ratio) or max_imag_ratio <= 0):
|
||||
raise ValueError('max_imag_ratio must be finite and positive')
|
||||
|
||||
|
||||
def uniform_grid_scpml(
|
||||
shape: Sequence[int],
|
||||
thicknesses: Sequence[int],
|
||||
omega: float,
|
||||
epsilon_effective: float = 1.0,
|
||||
s_function: s_function_t | None = None,
|
||||
*,
|
||||
kappa_function: s_function_t | None = None,
|
||||
max_imag_ratio: float | None = None,
|
||||
) -> list[list[NDArray]]:
|
||||
"""Create unit-cell Yee widths with SCPML on both faces of each axis.
|
||||
) -> list[list[NDArray[numpy.float64]]]:
|
||||
"""
|
||||
Create dx arrays for a uniform grid with a cell width of 1 and a pml.
|
||||
|
||||
``shape`` and ``thicknesses`` contain three axis sizes and per-face PML
|
||||
thicknesses; zero disables an axis. ``s_function`` specifies the imaginary
|
||||
grading, defaulting to prepare_s_function(). ``kappa_function`` optionally
|
||||
returns dimensionless real stretch values >= 1 at normalized depths.
|
||||
Each face is built by stretch_with_scpml, including its physical-thickness
|
||||
scaling and electric-center / magnetic-edge sampling convention.
|
||||
If you want something more fine-grained, check out `stretch_with_scpml(...)`.
|
||||
|
||||
``max_imag_ratio`` optionally bounds abs(Im(s))/Re(s) after frequency
|
||||
scaling. A value of 1 is a useful mode-solver starting point, not a proof
|
||||
against spectral artifacts. Converge domain size, thickness, and strength;
|
||||
reducing absorption can increase boundary reflections. The general
|
||||
scattering profile remains uncapped by default.
|
||||
Args:
|
||||
shape: Shape of the grid, including the PMLs (which are 2*thicknesses thick)
|
||||
thicknesses: `[th_x, th_y, th_z]`
|
||||
Thickness of the PML in each direction.
|
||||
Both polarities are added.
|
||||
Each th_ of pml is applied twice, once on each edge of the grid along the given axis.
|
||||
`th_*` may be zero, in which case no pml is added.
|
||||
omega: Angular frequency for the simulation
|
||||
epsilon_effective: Effective epsilon of the PML. Match this to the material
|
||||
at the edge of your grid.
|
||||
Default 1.
|
||||
s_function: created by `prepare_s_function(...)`, allowing customization of pml parameters.
|
||||
Default uses `prepare_s_function()` with no parameters.
|
||||
|
||||
Returns:
|
||||
Complex cell widths (dx_lists_mut) as discussed in `meanas.fdmath.types`.
|
||||
"""
|
||||
_validate_profile(omega, epsilon_effective, max_imag_ratio)
|
||||
shape, thicknesses = tuple(shape), tuple(thicknesses)
|
||||
if len(shape) != 3 or len(thicknesses) != 3:
|
||||
raise ValueError('shape and thicknesses must contain three entries')
|
||||
if any(not isinstance(n, int | numpy.integer) or isinstance(n, bool) or n <= 0 for n in shape):
|
||||
raise ValueError('shape entries must be positive integers')
|
||||
if any(not isinstance(t, int | numpy.integer) or isinstance(t, bool) or t < 0 or 2 * t > n
|
||||
for n, t in zip(shape, thicknesses, strict=True)):
|
||||
raise ValueError('PML thicknesses must be nonnegative integers fitting both faces')
|
||||
if s_function is None:
|
||||
s_function = prepare_s_function()
|
||||
result = [[numpy.ones(n) for n in shape] for _ in range(2)]
|
||||
for axis, thickness in enumerate(thicknesses):
|
||||
if not thickness:
|
||||
continue
|
||||
for polarity in (-1, 1):
|
||||
stretch_with_scpml(
|
||||
result, axis, polarity, omega, epsilon_effective, thickness,
|
||||
s_function, kappa_function=kappa_function,
|
||||
max_imag_ratio=max_imag_ratio, copy=False,
|
||||
)
|
||||
return result
|
||||
|
||||
shape = tuple(shape)
|
||||
thicknesses = tuple(thicknesses)
|
||||
|
||||
# Normalized distance to nearest boundary
|
||||
def ll(u: NDArray[numpy.float64], n: int, t: int) -> NDArray[numpy.float64]:
|
||||
return ((t - u).clip(0) + (u - (n - t)).clip(0)) / t
|
||||
|
||||
dx_a = [numpy.array(numpy.inf)] * 3
|
||||
dx_b = [numpy.array(numpy.inf)] * 3
|
||||
|
||||
# divide by this to adjust for epsilon_effective and omega
|
||||
s_correction = numpy.sqrt(epsilon_effective) * numpy.real(omega)
|
||||
|
||||
for k, th in enumerate(thicknesses):
|
||||
s = shape[k]
|
||||
if th > 0:
|
||||
sr = numpy.arange(s, dtype=numpy.float64)
|
||||
dx_a[k] = 1 + 1j * s_function(ll(sr, s, th)) / s_correction
|
||||
dx_b[k] = 1 + 1j * s_function(ll(sr + 0.5, s, th)) / s_correction
|
||||
else:
|
||||
dx_a[k] = numpy.ones((s,))
|
||||
dx_b[k] = numpy.ones((s,))
|
||||
return [dx_a, dx_b]
|
||||
|
||||
|
||||
def stretch_with_scpml(
|
||||
dxes: list[list[NDArray]],
|
||||
dxes: list[list[NDArray[numpy.float64]]],
|
||||
axis: int,
|
||||
polarity: int,
|
||||
omega: float,
|
||||
epsilon_effective: float = 1.0,
|
||||
thickness: int = 10,
|
||||
s_function: s_function_t | None = None,
|
||||
*,
|
||||
kappa_function: s_function_t | None = None,
|
||||
max_imag_ratio: float | None = None,
|
||||
copy: bool = True,
|
||||
) -> list[list[NDArray]]:
|
||||
"""Add SCPML to one face, returning independent widths by default.
|
||||
) -> list[list[NDArray[numpy.float64]]]:
|
||||
"""
|
||||
Stretch dxes to contain a stretched-coordinate PML (SCPML) in one direction along one axis.
|
||||
|
||||
Args:
|
||||
dxes: Yee widths [dx_e, dx_h]; two or three spatial axes are supported.
|
||||
axis: Axis normal to the absorbing face.
|
||||
polarity: -1 selects the low-index face; +1 selects the high-index face.
|
||||
omega: Positive real angular frequency.
|
||||
epsilon_effective: Positive effective permittivity at the boundary.
|
||||
thickness: Number of cells on this face; zero is a no-op.
|
||||
s_function: Imaginary grading at normalized depths, from prepare_s_function.
|
||||
kappa_function: Optional dimensionless real stretch profile, >= 1.
|
||||
max_imag_ratio: Optional final abs(Im(s))/Re(s) bound. A value of 1 is
|
||||
a mode-solver starting configuration; check PML/domain convergence.
|
||||
copy: Return copied widths by default. False explicitly mutates dxes.
|
||||
Args:
|
||||
dxes: Grid parameters `[dx_e, dx_h]` as described in `meanas.fdmath.types`
|
||||
axis: axis to stretch (0=x, 1=y, 2=z)
|
||||
polarity: direction to stretch (-1 for -ve, +1 for +ve)
|
||||
omega: Angular frequency for the simulation
|
||||
epsilon_effective: Effective epsilon of the PML. Match this to the material at the
|
||||
edge of your grid. Default 1.
|
||||
thickness: number of cells to use for pml (default 10)
|
||||
s_function: Created by `prepare_s_function(...)`, allowing customization
|
||||
of pml parameters. Default uses `prepare_s_function()` with no parameters.
|
||||
|
||||
Coordinates and physical PML thickness are obtained from the real input
|
||||
electric widths. Multiple nonoverlapping faces can be added successively.
|
||||
The imaginary sign follows the exp(+i omega t) convention used by meanas.
|
||||
Returns:
|
||||
Complex cell widths (dx_lists_mut) as discussed in `meanas.fdmath.types`.
|
||||
Multiple calls to this function may be necessary if multiple absorpbing boundaries are needed.
|
||||
"""
|
||||
_validate_profile(omega, epsilon_effective, max_imag_ratio)
|
||||
if len(dxes) != 2 or len(dxes[0]) != len(dxes[1]) or axis not in range(len(dxes[0])):
|
||||
raise ValueError('axis must select a spatial axis in both Yee width families')
|
||||
if polarity not in (-1, 1):
|
||||
raise ValueError('polarity must be -1 or +1')
|
||||
if not isinstance(thickness, int | numpy.integer) or isinstance(thickness, bool):
|
||||
raise TypeError('thickness must be an integer')
|
||||
n = len(dxes[0][axis])
|
||||
if thickness < 0 or thickness > n or len(dxes[1][axis]) != n:
|
||||
raise ValueError('thickness must fit the matching Yee width arrays')
|
||||
widths = [[values.copy() for values in family] for family in dxes] if copy else dxes
|
||||
if thickness == 0:
|
||||
return widths
|
||||
if s_function is None:
|
||||
s_function = prepare_s_function()
|
||||
da, db = (numpy.array(family[axis], dtype=complex, copy=True) for family in widths)
|
||||
if not numpy.isfinite(da).all() or not numpy.isfinite(db).all() or (da.real <= 0).any() or (db.real <= 0).any():
|
||||
raise ValueError('cell widths must be finite with positive real parts')
|
||||
position = numpy.concatenate(([0.0], da.real.cumsum()))
|
||||
electric = (position[:-1] + position[1:]) / 2
|
||||
magnetic = position[:-1]
|
||||
if polarity == -1:
|
||||
selected = slice(0, thickness)
|
||||
bound = position[thickness]
|
||||
length = bound - position[0]
|
||||
depths = [(bound - coordinates[selected]) / length for coordinates in (electric, magnetic)]
|
||||
|
||||
dx_ai = dxes[0][axis].astype(complex)
|
||||
dx_bi = dxes[1][axis].astype(complex)
|
||||
|
||||
if thickness == 0:
|
||||
dxes[0][axis] = dx_ai
|
||||
dxes[1][axis] = dx_bi
|
||||
return dxes
|
||||
|
||||
pos = numpy.hstack((0, dx_ai.cumsum()))
|
||||
pos_a = (pos[:-1] + pos[1:]) / 2
|
||||
pos_b = pos[:-1]
|
||||
|
||||
# divide by this to adjust for epsilon_effective and omega
|
||||
s_correction = numpy.sqrt(epsilon_effective) * numpy.real(omega)
|
||||
|
||||
if polarity > 0:
|
||||
# front pml
|
||||
bound = pos[thickness]
|
||||
d = bound - pos[0]
|
||||
|
||||
def l_d(x: NDArray[numpy.float64]) -> NDArray[numpy.float64]:
|
||||
return (bound - x) / (bound - pos[0])
|
||||
|
||||
slc = slice(thickness)
|
||||
|
||||
else:
|
||||
selected = slice(-thickness, None)
|
||||
bound = position[-thickness - 1]
|
||||
length = position[-1] - bound
|
||||
depths = [(coordinates[selected] - bound) / length for coordinates in (electric, magnetic)]
|
||||
correction = length * numpy.sqrt(epsilon_effective) * numpy.real(omega)
|
||||
da[selected] *= _stretch_factors(depths[0], correction, s_function, kappa_function, max_imag_ratio)
|
||||
db[selected] *= _stretch_factors(depths[1], correction, s_function, kappa_function, max_imag_ratio)
|
||||
widths[0][axis], widths[1][axis] = da, db
|
||||
return widths
|
||||
# back pml
|
||||
bound = pos[-thickness - 1]
|
||||
d = pos[-1] - bound
|
||||
|
||||
def l_d(x: NDArray[numpy.float64]) -> NDArray[numpy.float64]:
|
||||
return (x - bound) / (pos[-1] - bound)
|
||||
|
||||
slc = slice(-thickness, None)
|
||||
|
||||
dx_ai[slc] *= 1 + 1j * s_function(l_d(pos_a[slc])) / d / s_correction
|
||||
dx_bi[slc] *= 1 + 1j * s_function(l_d(pos_b[slc])) / d / s_correction
|
||||
|
||||
dxes[0][axis] = dx_ai
|
||||
dxes[1][axis] = dx_bi
|
||||
|
||||
return dxes
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -10,8 +10,6 @@ The intended workflow is:
|
|||
2. Solve the corresponding 2D mode problem with `solve_mode(...)`.
|
||||
3. Turn that mode into a one-sided source with `compute_source(...)`.
|
||||
4. Build an overlap window with `compute_overlap_e(...)` for port readout.
|
||||
5. For two-port discontinuities, `get_s_fdfd(...)` automates the source,
|
||||
solve, and monitor-plane modal decomposition loop.
|
||||
|
||||
`polarity` is part of the public convention throughout this module:
|
||||
|
||||
|
|
@ -21,16 +19,15 @@ The intended workflow is:
|
|||
That same convention controls which side of the selected slice is used for the
|
||||
overlap window and how the expanded field is phased.
|
||||
"""
|
||||
from typing import Any, TypedDict, cast, Literal
|
||||
from typing import Any, TypedDict, cast
|
||||
import warnings
|
||||
import operator
|
||||
from collections.abc import Callable, Sequence
|
||||
from collections.abc import Sequence
|
||||
import numpy
|
||||
from numpy.typing import NDArray
|
||||
from numpy import complexfloating, floating
|
||||
from numpy import complexfloating
|
||||
|
||||
from ..fdmath import vec, unvec, dx_lists2_t, dx_lists_t, cfdfield_t, fdfield, cfdfield
|
||||
from . import functional, operators, scpml, solvers, waveguide_2d
|
||||
from ..fdmath import vec, unvec, dx_lists_t, cfdfield_t, fdfield, cfdfield
|
||||
from . import operators, waveguide_2d
|
||||
|
||||
|
||||
class Waveguide3DMode(TypedDict):
|
||||
|
|
@ -78,86 +75,40 @@ def solve_mode(
|
|||
The returned fields are normalized through the `waveguide_2d`
|
||||
normalization convention before being expanded back to 3D.
|
||||
"""
|
||||
args_2d, _order, _reverse, _dx_prop = _mode_cross_section(omega, dxes, axis, slices, epsilon, mu)
|
||||
e_xy, wavenumber_2d = waveguide_2d.solve_mode(mode_number, **args_2d)
|
||||
return mode_from_2d(e_xy, wavenumber_2d, omega=omega, dxes=dxes, axis=axis,
|
||||
polarity=polarity, slices=slices, epsilon=epsilon, mu=mu)
|
||||
|
||||
|
||||
def _mode_cross_section(
|
||||
omega: complex,
|
||||
dxes: dx_lists_t,
|
||||
axis: int,
|
||||
slices: Sequence[slice],
|
||||
epsilon: fdfield,
|
||||
mu: fdfield | None,
|
||||
) -> tuple[dict[str, Any], NDArray, NDArray, complex]:
|
||||
if axis not in range(3):
|
||||
raise ValueError('axis must be 0, 1, or 2')
|
||||
if numpy.ndim(epsilon) != 4 or epsilon.shape[0] != 3:
|
||||
raise ValueError('epsilon must have shape (3, nx, ny, nz)')
|
||||
slices = tuple(slices)
|
||||
if len(slices) != 3 or any(not isinstance(part, slice) for part in slices):
|
||||
raise ValueError('slices must contain three slices')
|
||||
sizes = [len(range(size)[part]) for size, part in zip(epsilon.shape[1:], slices, strict=True)]
|
||||
if sizes[axis] != 1 or any(size == 0 for size in sizes):
|
||||
raise ValueError('slices must select one propagation cell and a nonempty cross-section')
|
||||
if mu is None:
|
||||
mu = numpy.ones_like(epsilon)
|
||||
elif mu.shape != epsilon.shape:
|
||||
raise ValueError('mu must match epsilon')
|
||||
|
||||
slices = tuple(slices)
|
||||
|
||||
#
|
||||
# Solve the 2D problem in the specified plane
|
||||
#
|
||||
# Define rotation to set z as propagation direction
|
||||
order = numpy.roll(range(3), 2 - axis)
|
||||
reverse = numpy.roll(range(3), axis - 2)
|
||||
dx_prop = 0.5 * sum(dx[axis][slices[axis]].sum() for dx in dxes)
|
||||
if not numpy.isfinite(dx_prop) or dx_prop == 0:
|
||||
raise ValueError('propagation cell width must be finite and nonzero')
|
||||
args: dict[str, Any] = {
|
||||
reverse_order = numpy.roll(range(3), axis - 2)
|
||||
|
||||
# Find dx in propagation direction
|
||||
dxab_forward = numpy.array([dx[order[2]][slices[order[2]]] for dx in dxes])
|
||||
dx_prop = 0.5 * dxab_forward.sum()
|
||||
|
||||
# Reduce to 2D and solve the 2D problem
|
||||
args_2d: dict[str, Any] = {
|
||||
'omega': omega,
|
||||
'dxes': [[dx[i][slices[i]] for i in order[:2]] for dx in dxes],
|
||||
'epsilon': vec([epsilon[i][slices].transpose(order) for i in order]),
|
||||
'mu': vec([mu[i][slices].transpose(order) for i in order]),
|
||||
}
|
||||
return args, order, reverse, dx_prop
|
||||
e_xy, wavenumber_2d = waveguide_2d.solve_mode(mode_number, **args_2d)
|
||||
|
||||
#
|
||||
# Apply corrections and expand to 3D
|
||||
#
|
||||
|
||||
def mode_from_2d(
|
||||
e_xy: NDArray,
|
||||
wavenumber_2d: complex,
|
||||
*,
|
||||
omega: complex,
|
||||
dxes: dx_lists_t,
|
||||
axis: int,
|
||||
polarity: int,
|
||||
slices: Sequence[slice],
|
||||
epsilon: fdfield,
|
||||
mu: fdfield | None = None,
|
||||
normalization: Literal['power', 'lorentz'] = 'power',
|
||||
) -> Waveguide3DMode:
|
||||
"""Convert a supplied 2D electric eigenmode to a staggered full-grid mode.
|
||||
|
||||
``e_xy`` contains vectorized Ex/Ey in the rotated plane (the order used by
|
||||
solve_mode). It must solve the 2D problem extracted from ``epsilon`` and
|
||||
``dxes`` at ``slices``. No eigensolver is called. The helper reconstructs E/H,
|
||||
normalizes them, applies propagation-grid dispersion and half-cell shifts,
|
||||
rotates components, and embeds them in the full epsilon-shaped grid.
|
||||
|
||||
``polarity`` is +1 toward increasing indices and -1 toward decreasing
|
||||
indices. ``normalization`` follows waveguide_2d.normalized_fields_e.
|
||||
"""
|
||||
if polarity not in (-1, 1):
|
||||
raise ValueError('polarity must be -1 or +1')
|
||||
args_2d, _order, reverse_order, dx_prop = _mode_cross_section(omega, dxes, axis, slices, epsilon, mu)
|
||||
slices = tuple(slices)
|
||||
expected = 2 * numpy.prod([len(values) for values in args_2d['dxes'][0]])
|
||||
e_xy = numpy.asarray(e_xy)
|
||||
if e_xy.shape != (expected,) or not numpy.isfinite(e_xy).all() or not numpy.isfinite(wavenumber_2d):
|
||||
raise ValueError('the 2D eigenvector and wavenumber must be finite and match the cross-section')
|
||||
wavenumber_2d = complex(wavenumber_2d)
|
||||
# Correct wavenumber to account for numerical dispersion.
|
||||
wavenumber = 2 / dx_prop * numpy.arcsin(wavenumber_2d * dx_prop / 2)
|
||||
|
||||
shape = [d.size for d in args_2d['dxes'][0]]
|
||||
ve, vh = waveguide_2d.normalized_fields_e(e_xy, wavenumber=wavenumber_2d, prop_phase=dx_prop * wavenumber, normalization=normalization, **args_2d)
|
||||
ve, vh = waveguide_2d.normalized_fields_e(e_xy, wavenumber=wavenumber_2d, prop_phase=dx_prop * wavenumber, **args_2d)
|
||||
e = unvec(ve, shape)
|
||||
h = unvec(vh, shape)
|
||||
|
||||
|
|
@ -209,8 +160,6 @@ def compute_source(
|
|||
polarity: Propagation direction (+1 for +ve, -1 for -ve)
|
||||
slices: `epsilon[tuple(slices)]` is used to select the portion of the grid to use
|
||||
as the waveguide cross-section. `slices[axis]` should select only one item.
|
||||
epsilon: Dielectric distribution on the same full grid as E and dxes.
|
||||
Used by the boundary-source operator.
|
||||
mu: Magnetic permeability (default 1 everywhere)
|
||||
|
||||
Returns:
|
||||
|
|
@ -392,552 +341,3 @@ def expand_e(
|
|||
|
||||
E_expanded[slices_exp] = phase_E * numpy.array(E)[slices_in]
|
||||
return cfdfield_t(E_expanded)
|
||||
|
||||
|
||||
def _slice_start(name: str, slices: Sequence[slice], axis: int, shape: Sequence[int]) -> int:
|
||||
if len(slices) != 3:
|
||||
raise ValueError(f'{name} must contain exactly three slices')
|
||||
axis_slice = slices[axis]
|
||||
if axis_slice.start is None or axis_slice.stop is None:
|
||||
raise ValueError(f'{name}[axis] must have explicit start and stop')
|
||||
if axis_slice.step not in (None, 1):
|
||||
raise ValueError(f'{name}[axis] must not use a step')
|
||||
if axis_slice.stop - axis_slice.start != 1:
|
||||
raise ValueError(f'{name}[axis] must select exactly one cell')
|
||||
if axis_slice.start < 0 or axis_slice.stop > shape[axis]:
|
||||
raise ValueError(f'{name}[axis] lies outside the simulation domain')
|
||||
return axis_slice.start
|
||||
|
||||
|
||||
def _as_slice_tuple(name: str, slices: Sequence[slice], axis: int, shape: Sequence[int]) -> tuple[slice, slice, slice]:
|
||||
_slice_start(name, slices, axis, shape)
|
||||
return (slices[0], slices[1], slices[2])
|
||||
|
||||
|
||||
def _nonbool_index(value: object) -> int:
|
||||
if isinstance(value, bool | numpy.bool_):
|
||||
raise TypeError
|
||||
return operator.index(value)
|
||||
|
||||
|
||||
def _as_mode_numbers(name: str, mode_numbers: Sequence[int]) -> tuple[int, ...]:
|
||||
modes: list[int] = []
|
||||
for mode in mode_numbers:
|
||||
try:
|
||||
mode_i = _nonbool_index(mode)
|
||||
except TypeError as err:
|
||||
raise ValueError(f'{name} entries must be integers') from err
|
||||
if mode_i < 0:
|
||||
raise ValueError('mode numbers must be non-negative')
|
||||
modes.append(mode_i)
|
||||
if not modes:
|
||||
raise ValueError('each FDFD port must contain at least one mode number')
|
||||
return tuple(modes)
|
||||
|
||||
|
||||
def _validate_fdfd_port_specs(
|
||||
left_mode_numbers: Sequence[int],
|
||||
right_mode_numbers: Sequence[int],
|
||||
left_source_slice: Sequence[slice],
|
||||
left_monitor_slice: Sequence[slice],
|
||||
right_source_slice: Sequence[slice],
|
||||
right_monitor_slice: Sequence[slice],
|
||||
axis: int,
|
||||
shape: Sequence[int],
|
||||
) -> tuple[
|
||||
tuple[int, ...],
|
||||
tuple[int, ...],
|
||||
tuple[slice, slice, slice],
|
||||
tuple[slice, slice, slice],
|
||||
tuple[slice, slice, slice],
|
||||
tuple[slice, slice, slice],
|
||||
]:
|
||||
if axis not in (0, 1, 2):
|
||||
raise ValueError('axis must be 0, 1, or 2')
|
||||
|
||||
left_modes_i = _as_mode_numbers('left_mode_numbers', left_mode_numbers)
|
||||
right_modes_i = _as_mode_numbers('right_mode_numbers', right_mode_numbers)
|
||||
|
||||
left_source = _as_slice_tuple('left_source_slice', left_source_slice, axis, shape)
|
||||
left_monitor = _as_slice_tuple('left_monitor_slice', left_monitor_slice, axis, shape)
|
||||
right_source = _as_slice_tuple('right_source_slice', right_source_slice, axis, shape)
|
||||
right_monitor = _as_slice_tuple('right_monitor_slice', right_monitor_slice, axis, shape)
|
||||
|
||||
left_source_i = _slice_start('left_source_slice', left_source, axis, shape)
|
||||
left_monitor_i = _slice_start('left_monitor_slice', left_monitor, axis, shape)
|
||||
right_monitor_i = _slice_start('right_monitor_slice', right_monitor, axis, shape)
|
||||
right_source_i = _slice_start('right_source_slice', right_source, axis, shape)
|
||||
if not (left_source_i < left_monitor_i < right_monitor_i < right_source_i):
|
||||
raise ValueError('port slices must be ordered as left source, left monitor, right monitor, right source')
|
||||
|
||||
return left_modes_i, right_modes_i, left_source, left_monitor, right_source, right_monitor
|
||||
|
||||
|
||||
def _port_decomposition(
|
||||
incoming_modes: Sequence[Waveguide3DMode],
|
||||
outgoing_modes: Sequence[Waveguide3DMode],
|
||||
*,
|
||||
dxes: dx_lists_t,
|
||||
axis: int,
|
||||
incoming_polarity: int,
|
||||
outgoing_polarity: int,
|
||||
slices: Sequence[slice],
|
||||
) -> tuple[NDArray[numpy.complex128], tuple[cfdfield_t, ...], int]:
|
||||
mode_count = len(incoming_modes)
|
||||
if len(outgoing_modes) != mode_count:
|
||||
raise ValueError('incoming and outgoing monitor bases must contain the same number of modes')
|
||||
overlaps = (
|
||||
*(
|
||||
compute_overlap_e(
|
||||
E=mode['E'],
|
||||
wavenumber=mode['wavenumber'],
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
polarity=incoming_polarity,
|
||||
slices=slices,
|
||||
)
|
||||
for mode in incoming_modes
|
||||
),
|
||||
*(
|
||||
compute_overlap_e(
|
||||
E=mode['E'],
|
||||
wavenumber=mode['wavenumber'],
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
polarity=outgoing_polarity,
|
||||
slices=slices,
|
||||
)
|
||||
for mode in outgoing_modes
|
||||
),
|
||||
)
|
||||
basis_fields = (
|
||||
*(
|
||||
expand_e(
|
||||
E=mode['E'],
|
||||
wavenumber=mode['wavenumber'],
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
polarity=incoming_polarity,
|
||||
slices=slices,
|
||||
)
|
||||
for mode in incoming_modes
|
||||
),
|
||||
*(
|
||||
expand_e(
|
||||
E=mode['E'],
|
||||
wavenumber=mode['wavenumber'],
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
polarity=outgoing_polarity,
|
||||
slices=slices,
|
||||
)
|
||||
for mode in outgoing_modes
|
||||
),
|
||||
)
|
||||
matrix = numpy.empty((2 * mode_count, 2 * mode_count), dtype=complex)
|
||||
for row, overlap in enumerate(overlaps):
|
||||
overlap_vec_conj = vec(overlap).conj()
|
||||
for col, basis_field in enumerate(basis_fields):
|
||||
matrix[row, col] = vec(basis_field) @ overlap_vec_conj
|
||||
return matrix, overlaps, mode_count
|
||||
|
||||
|
||||
def _decompose_port_field(
|
||||
decomposition: tuple[NDArray[numpy.complex128], tuple[cfdfield_t, ...], int],
|
||||
field: cfdfield_t,
|
||||
) -> tuple[NDArray[numpy.complex128], NDArray[numpy.complex128]]:
|
||||
matrix, overlaps, mode_count = decomposition
|
||||
field_vec = vec(field)
|
||||
measured = numpy.asarray([field_vec @ vec(overlap).conj() for overlap in overlaps])
|
||||
coeffs, _resid, _rank, _sing = numpy.linalg.lstsq(matrix, measured, rcond=None)
|
||||
return coeffs[:mode_count], coeffs[mode_count:]
|
||||
|
||||
|
||||
def _copy_cross_section(
|
||||
target: NDArray,
|
||||
cross_section: NDArray,
|
||||
axis: int,
|
||||
index: int,
|
||||
) -> None:
|
||||
slices: list[slice | int] = [slice(None), slice(None), slice(None), slice(None)]
|
||||
slices[axis + 1] = index
|
||||
target[tuple(slices)] = cross_section
|
||||
|
||||
|
||||
def _validate_cross_section(name: str, field: NDArray) -> NDArray:
|
||||
array = numpy.asarray(field)
|
||||
if array.ndim != 3 or array.shape[0] != 3:
|
||||
raise ValueError(f'{name} must have shape (3, n0, n1)')
|
||||
if not numpy.isfinite(array).all():
|
||||
raise ValueError(f'{name} must contain only finite values')
|
||||
return array
|
||||
|
||||
|
||||
def _as_axis_pair(name: str, value: int | Sequence[int]) -> tuple[int, int]:
|
||||
if isinstance(value, int):
|
||||
pair = (value, value)
|
||||
else:
|
||||
pair = tuple(operator.index(v) for v in value)
|
||||
if len(pair) != 2:
|
||||
raise ValueError(f'{name} must be an integer or a two-entry sequence')
|
||||
if min(pair) < 0:
|
||||
raise ValueError(f'{name} entries must be non-negative')
|
||||
return pair
|
||||
|
||||
|
||||
def _pad_cross_section(field: NDArray, padding_cells: tuple[int, int]) -> NDArray:
|
||||
if padding_cells == (0, 0):
|
||||
return field
|
||||
return numpy.pad(
|
||||
field,
|
||||
(
|
||||
(0, 0),
|
||||
(padding_cells[0], padding_cells[0]),
|
||||
(padding_cells[1], padding_cells[1]),
|
||||
),
|
||||
mode='edge',
|
||||
)
|
||||
|
||||
|
||||
def _pad_dxes_2d(dxes_2d: dx_lists2_t, padding_cells: tuple[int, int]) -> list[list[NDArray[floating | complexfloating]]]:
|
||||
padded: list[list[NDArray[floating | complexfloating]]] = [[numpy.empty(0), numpy.empty(0)] for _ in range(2)]
|
||||
for eh in range(2):
|
||||
for axis_2d in range(2):
|
||||
values = numpy.asarray(dxes_2d[eh][axis_2d])
|
||||
pad = padding_cells[axis_2d]
|
||||
if pad == 0:
|
||||
padded[eh][axis_2d] = values.copy()
|
||||
else:
|
||||
padded[eh][axis_2d] = numpy.pad(values, (pad, pad), mode='edge')
|
||||
return padded
|
||||
|
||||
|
||||
def get_s_fdfd(
|
||||
omega: complex,
|
||||
dxes: dx_lists_t,
|
||||
epsilon: fdfield,
|
||||
*,
|
||||
left_mode_numbers: Sequence[int],
|
||||
left_source_slice: Sequence[slice],
|
||||
left_monitor_slice: Sequence[slice],
|
||||
right_source_slice: Sequence[slice],
|
||||
right_monitor_slice: Sequence[slice],
|
||||
right_mode_numbers: Sequence[int] | None = None,
|
||||
axis: int = 0,
|
||||
solve_dxes: dx_lists_t | None = None,
|
||||
mu: fdfield | None = None,
|
||||
matrix_solver: Callable[..., Any] | None = None,
|
||||
matrix_solver_opts: dict[str, Any] | None = None,
|
||||
source_scales: Sequence[complex] | None = None,
|
||||
incident_amplitude_atol: float = 1e-12,
|
||||
return_diagnostics: bool = False,
|
||||
) -> NDArray[numpy.complex128] | tuple[NDArray[numpy.complex128], dict[str, Any]]:
|
||||
"""
|
||||
Extract a two-port guided-mode scattering matrix from local 3D FDFD solves.
|
||||
|
||||
The returned S-matrix is ordered as `[[R_L, T_R_to_L], [T_L_to_R, R_R]]`, with
|
||||
reference planes at the supplied monitor slices. Each column is normalized
|
||||
by the incident modal amplitude measured on the corresponding input monitor.
|
||||
"""
|
||||
if incident_amplitude_atol <= 0:
|
||||
raise ValueError('incident_amplitude_atol must be positive')
|
||||
|
||||
epsilon = numpy.asarray(epsilon)
|
||||
if epsilon.ndim != 4 or epsilon.shape[0] != 3:
|
||||
raise ValueError('epsilon must have shape (3, nx, ny, nz)')
|
||||
if mu is not None:
|
||||
mu = numpy.asarray(mu)
|
||||
if mu.shape != epsilon.shape:
|
||||
raise ValueError('mu must have the same shape as epsilon')
|
||||
|
||||
if right_mode_numbers is None:
|
||||
right_mode_numbers = left_mode_numbers
|
||||
|
||||
shape = epsilon.shape[1:]
|
||||
left_modes_i, right_modes_i, left_source, left_monitor, right_source, right_monitor = _validate_fdfd_port_specs(
|
||||
left_mode_numbers,
|
||||
right_mode_numbers,
|
||||
left_source_slice,
|
||||
left_monitor_slice,
|
||||
right_source_slice,
|
||||
right_monitor_slice,
|
||||
axis,
|
||||
shape,
|
||||
)
|
||||
n_left = len(left_modes_i)
|
||||
n_right = len(right_modes_i)
|
||||
n_total = n_left + n_right
|
||||
|
||||
if solve_dxes is None:
|
||||
solve_dxes = dxes
|
||||
if source_scales is None:
|
||||
source_scale_array = numpy.ones((n_total,), dtype=complex)
|
||||
else:
|
||||
source_scale_array = numpy.asarray(source_scales, dtype=complex)
|
||||
if source_scale_array.shape != (n_total,):
|
||||
raise ValueError('source_scales must have one entry per incident mode')
|
||||
|
||||
def solve_modes(mode_numbers: Sequence[int], polarity: int, slices: Sequence[slice]) -> tuple[Waveguide3DMode, ...]:
|
||||
return tuple(
|
||||
solve_mode(mode_number, omega=omega, dxes=dxes, axis=axis, polarity=polarity, slices=slices, epsilon=epsilon, mu=mu)
|
||||
for mode_number in mode_numbers
|
||||
)
|
||||
|
||||
left_source_modes = solve_modes(left_modes_i, +1, left_source)
|
||||
right_source_modes = solve_modes(right_modes_i, -1, right_source)
|
||||
|
||||
left_in_modes = solve_modes(left_modes_i, +1, left_monitor)
|
||||
left_out_modes = solve_modes(left_modes_i, -1, left_monitor)
|
||||
right_in_modes = solve_modes(right_modes_i, -1, right_monitor)
|
||||
right_out_modes = solve_modes(right_modes_i, +1, right_monitor)
|
||||
left_decomposition = _port_decomposition(
|
||||
left_in_modes,
|
||||
left_out_modes,
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
incoming_polarity=+1,
|
||||
outgoing_polarity=-1,
|
||||
slices=left_monitor,
|
||||
)
|
||||
right_decomposition = _port_decomposition(
|
||||
right_in_modes,
|
||||
right_out_modes,
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
incoming_polarity=-1,
|
||||
outgoing_polarity=+1,
|
||||
slices=right_monitor,
|
||||
)
|
||||
|
||||
s = numpy.zeros((n_total, n_total), dtype=complex)
|
||||
raw_outgoing = numpy.zeros_like(s)
|
||||
incident_amplitudes = numpy.zeros((n_total,), dtype=complex)
|
||||
electric_fields: list[cfdfield_t] = []
|
||||
magnetic_fields: list[cfdfield_t] = []
|
||||
|
||||
excitation_modes: list[tuple[int, int, Sequence[slice], Waveguide3DMode]] = [
|
||||
*((col, +1, left_source, left_source_modes[col]) for col in range(n_left)),
|
||||
*((n_left + col, -1, right_source, right_source_modes[col]) for col in range(n_right)),
|
||||
]
|
||||
|
||||
for column, polarity, source_slice, source_mode in excitation_modes:
|
||||
current = compute_source(
|
||||
E=source_mode['E'],
|
||||
wavenumber=source_mode['wavenumber'],
|
||||
omega=omega,
|
||||
dxes=dxes,
|
||||
axis=axis,
|
||||
polarity=polarity,
|
||||
slices=source_slice,
|
||||
epsilon=epsilon,
|
||||
mu=mu,
|
||||
)
|
||||
current = cfdfield_t(source_scale_array[column] * current)
|
||||
solve_kwargs: dict[str, Any] = {
|
||||
'omega': omega,
|
||||
'dxes': solve_dxes,
|
||||
'J': vec(current),
|
||||
'epsilon': vec(epsilon),
|
||||
'mu': vec(mu),
|
||||
'matrix_solver_opts': {} if matrix_solver_opts is None else dict(matrix_solver_opts),
|
||||
}
|
||||
if matrix_solver is not None:
|
||||
solve_kwargs['matrix_solver'] = matrix_solver
|
||||
e_field = unvec(solvers.generic(**solve_kwargs), shape)
|
||||
left_in, left_out = _decompose_port_field(left_decomposition, e_field)
|
||||
right_in, right_out = _decompose_port_field(right_decomposition, e_field)
|
||||
if column < n_left:
|
||||
incident = left_in[column]
|
||||
else:
|
||||
incident = right_in[column - n_left]
|
||||
if abs(incident) <= incident_amplitude_atol:
|
||||
raise ValueError(f'incident modal amplitude for column {column} is zero')
|
||||
|
||||
raw_column = numpy.concatenate((left_out, right_out))
|
||||
|
||||
incident_amplitudes[column] = incident
|
||||
raw_outgoing[:, column] = raw_column
|
||||
s[:, column] = raw_column / incident
|
||||
if return_diagnostics:
|
||||
electric_fields.append(cfdfield_t(e_field))
|
||||
magnetic_fields.append(cfdfield_t(functional.e2h(omega, solve_dxes, mu=mu)(e_field)))
|
||||
|
||||
if not return_diagnostics:
|
||||
return s
|
||||
|
||||
guided_powers = numpy.sum(numpy.abs(s) ** 2, axis=0).real
|
||||
diagnostics: dict[str, Any] = {
|
||||
'axis': axis,
|
||||
'left_mode_numbers': left_modes_i,
|
||||
'right_mode_numbers': right_modes_i,
|
||||
'left_source_slice': left_source,
|
||||
'left_monitor_slice': left_monitor,
|
||||
'right_source_slice': right_source,
|
||||
'right_monitor_slice': right_monitor,
|
||||
'left_wavenumbers': numpy.asarray([mode['wavenumber'] for mode in left_out_modes]),
|
||||
'right_wavenumbers': numpy.asarray([mode['wavenumber'] for mode in right_out_modes]),
|
||||
'source_scales': source_scale_array,
|
||||
'electric_fields': tuple(electric_fields),
|
||||
'magnetic_fields': tuple(magnetic_fields),
|
||||
'incident_amplitudes': incident_amplitudes,
|
||||
'raw_outgoing_amplitudes': raw_outgoing,
|
||||
'guided_powers': guided_powers,
|
||||
'unresolved_powers': 1.0 - guided_powers,
|
||||
'left_modes': left_out_modes,
|
||||
'right_modes': right_out_modes,
|
||||
}
|
||||
return s, diagnostics
|
||||
|
||||
|
||||
def get_s_fdfd_from_2d_ports(
|
||||
left_epsilon: NDArray,
|
||||
right_epsilon: NDArray,
|
||||
*,
|
||||
omega: complex,
|
||||
dxes_2d: dx_lists2_t,
|
||||
mode_numbers: Sequence[int],
|
||||
right_mode_numbers: Sequence[int] | None = None,
|
||||
axis: int = 0,
|
||||
left_mu: NDArray | None = None,
|
||||
right_mu: NDArray | None = None,
|
||||
prop_dx: float | None = None,
|
||||
pml_cells: int = 8,
|
||||
pml_buffer_cells: int = 2,
|
||||
source_monitor_cells: int = 5,
|
||||
monitor_interface_cells: int = 6,
|
||||
transverse_padding_cells: int | Sequence[int] = 0,
|
||||
transverse_pml_cells: int | Sequence[int] = 0,
|
||||
pml_epsilon_effective: float = 1.0,
|
||||
matrix_solver: Callable[..., Any] | None = None,
|
||||
matrix_solver_opts: dict[str, Any] | None = None,
|
||||
source_scales: Sequence[complex] | None = None,
|
||||
return_diagnostics: bool = False,
|
||||
) -> NDArray[numpy.complex128] | tuple[NDArray[numpy.complex128], dict[str, Any]]:
|
||||
"""
|
||||
Extrude two 2D port cross-sections into a short 3D FDFD interface problem.
|
||||
"""
|
||||
if axis not in (0, 1, 2):
|
||||
raise ValueError('axis must be 0, 1, or 2')
|
||||
if min(pml_cells, pml_buffer_cells, source_monitor_cells, monitor_interface_cells) < 1:
|
||||
raise ValueError('PML, buffer, source/monitor, and monitor/interface cell counts must be positive')
|
||||
|
||||
padding_cells = _as_axis_pair('transverse_padding_cells', transverse_padding_cells)
|
||||
transverse_pml = _as_axis_pair('transverse_pml_cells', transverse_pml_cells)
|
||||
|
||||
left_epsilon = _pad_cross_section(_validate_cross_section('left_epsilon', left_epsilon), padding_cells)
|
||||
right_epsilon = _pad_cross_section(_validate_cross_section('right_epsilon', right_epsilon), padding_cells)
|
||||
if left_epsilon.shape != right_epsilon.shape:
|
||||
raise ValueError('left_epsilon and right_epsilon must have the same shape')
|
||||
if left_mu is not None:
|
||||
left_mu = _pad_cross_section(_validate_cross_section('left_mu', left_mu), padding_cells)
|
||||
if left_mu.shape != left_epsilon.shape:
|
||||
raise ValueError('left_mu must match left_epsilon')
|
||||
if right_mu is not None:
|
||||
right_mu = _pad_cross_section(_validate_cross_section('right_mu', right_mu), padding_cells)
|
||||
if right_mu.shape != right_epsilon.shape:
|
||||
raise ValueError('right_mu must match right_epsilon')
|
||||
if (left_mu is None) != (right_mu is None):
|
||||
raise ValueError('left_mu and right_mu must be supplied together')
|
||||
|
||||
if right_mode_numbers is None:
|
||||
right_mode_numbers = mode_numbers
|
||||
dxes_2d_padded = _pad_dxes_2d(dxes_2d, padding_cells)
|
||||
transverse_shape = left_epsilon.shape[1:]
|
||||
transverse_axes = tuple(ax for ax in (0, 1, 2) if ax != axis)
|
||||
if prop_dx is None:
|
||||
prop_dx = float(numpy.median(numpy.real(numpy.concatenate([numpy.asarray(d) for d in dxes_2d_padded[0]]))))
|
||||
if prop_dx <= 0:
|
||||
raise ValueError('prop_dx must be positive')
|
||||
|
||||
left_source_i = pml_cells + pml_buffer_cells
|
||||
left_monitor_i = left_source_i + source_monitor_cells
|
||||
interface_i = left_monitor_i + monitor_interface_cells
|
||||
right_monitor_i = interface_i + monitor_interface_cells
|
||||
right_source_i = right_monitor_i + source_monitor_cells
|
||||
axis_size = right_source_i + pml_buffer_cells + pml_cells + 1
|
||||
|
||||
shape3 = [0, 0, 0]
|
||||
shape3[axis] = axis_size
|
||||
shape3[transverse_axes[0]] = transverse_shape[0]
|
||||
shape3[transverse_axes[1]] = transverse_shape[1]
|
||||
|
||||
epsilon = numpy.empty((3, *shape3), dtype=numpy.result_type(left_epsilon, right_epsilon))
|
||||
mu = None if left_mu is None else numpy.empty((3, *shape3), dtype=numpy.result_type(left_mu, right_mu))
|
||||
for index in range(axis_size):
|
||||
cross_epsilon = left_epsilon if index < interface_i else right_epsilon
|
||||
_copy_cross_section(epsilon, cross_epsilon, axis, index)
|
||||
if mu is not None:
|
||||
assert left_mu is not None
|
||||
assert right_mu is not None
|
||||
cross_mu = left_mu if index < interface_i else right_mu
|
||||
_copy_cross_section(mu, cross_mu, axis, index)
|
||||
|
||||
dxes: list[list[NDArray[floating | complexfloating]]] = [[numpy.empty(0), numpy.empty(0), numpy.empty(0)] for _ in range(2)]
|
||||
for eh in range(2):
|
||||
dxes[eh][axis] = numpy.full(axis_size, prop_dx, dtype=float)
|
||||
dxes[eh][transverse_axes[0]] = dxes_2d_padded[eh][0].copy()
|
||||
dxes[eh][transverse_axes[1]] = dxes_2d_padded[eh][1].copy()
|
||||
|
||||
solve_dxes: dx_lists_t = [[d.copy() for d in dx] for dx in dxes]
|
||||
for stretch_axis, thickness in ((axis, pml_cells), (transverse_axes[0], transverse_pml[0]), (transverse_axes[1], transverse_pml[1])):
|
||||
if thickness == 0:
|
||||
continue
|
||||
solve_dxes = scpml.stretch_with_scpml(
|
||||
solve_dxes,
|
||||
axis=stretch_axis,
|
||||
polarity=+1,
|
||||
omega=float(numpy.real(omega)),
|
||||
epsilon_effective=pml_epsilon_effective,
|
||||
thickness=thickness,
|
||||
)
|
||||
solve_dxes = scpml.stretch_with_scpml(
|
||||
solve_dxes,
|
||||
axis=stretch_axis,
|
||||
polarity=-1,
|
||||
omega=float(numpy.real(omega)),
|
||||
epsilon_effective=pml_epsilon_effective,
|
||||
thickness=thickness,
|
||||
)
|
||||
|
||||
def port_slice(index: int) -> tuple[slice, slice, slice]:
|
||||
slices_l = [slice(None), slice(None), slice(None)]
|
||||
slices_l[axis] = slice(index, index + 1)
|
||||
return (slices_l[0], slices_l[1], slices_l[2])
|
||||
|
||||
result = get_s_fdfd(
|
||||
omega=omega,
|
||||
dxes=dxes,
|
||||
solve_dxes=solve_dxes,
|
||||
epsilon=epsilon,
|
||||
mu=mu,
|
||||
axis=axis,
|
||||
left_mode_numbers=mode_numbers,
|
||||
left_source_slice=port_slice(left_source_i),
|
||||
left_monitor_slice=port_slice(left_monitor_i),
|
||||
right_mode_numbers=right_mode_numbers,
|
||||
right_source_slice=port_slice(right_source_i),
|
||||
right_monitor_slice=port_slice(right_monitor_i),
|
||||
matrix_solver=matrix_solver,
|
||||
matrix_solver_opts=matrix_solver_opts,
|
||||
source_scales=source_scales,
|
||||
return_diagnostics=return_diagnostics,
|
||||
)
|
||||
if not return_diagnostics:
|
||||
return result
|
||||
|
||||
s, diagnostics = result
|
||||
diagnostics.update({
|
||||
'interface_index': interface_i,
|
||||
'pml_cells': pml_cells,
|
||||
'pml_buffer_cells': pml_buffer_cells,
|
||||
'source_monitor_cells': source_monitor_cells,
|
||||
'monitor_interface_cells': monitor_interface_cells,
|
||||
'transverse_padding_cells': padding_cells,
|
||||
'transverse_pml_cells': transverse_pml,
|
||||
'prop_dx': prop_dx,
|
||||
'epsilon': epsilon,
|
||||
'mu': mu,
|
||||
'dxes': dxes,
|
||||
'solve_dxes': solve_dxes,
|
||||
})
|
||||
return s, diagnostics
|
||||
|
|
|
|||
|
|
@ -13,61 +13,52 @@ from numpy import floating, complexfloating
|
|||
from .types import fdfield, fdfield_updater_t
|
||||
|
||||
|
||||
def _derivative(axis: int, forward: bool, widths: NDArray | None) -> fdfield_updater_t:
|
||||
"""Periodic difference using views, with one output allocation at most."""
|
||||
def derivative(f: NDArray, *, out: NDArray | None = None) -> NDArray:
|
||||
f = numpy.asarray(f)
|
||||
if f.ndim != 3 or f.shape[axis] == 0:
|
||||
raise ValueError('derivatives require a nonempty three-dimensional axis')
|
||||
if widths is not None and (numpy.ndim(widths) != 1 or len(widths) != f.shape[axis]):
|
||||
raise ValueError('cell widths must match the differentiated axis')
|
||||
dtype = f.dtype if widths is None else numpy.true_divide.resolve_dtypes((f.dtype, numpy.asarray(widths).dtype, None))[2]
|
||||
if out is None:
|
||||
output = numpy.empty(f.shape, dtype=dtype)
|
||||
else:
|
||||
output = numpy.asarray(out)
|
||||
if output.shape != f.shape:
|
||||
raise ValueError('out must match the field shape')
|
||||
if numpy.shares_memory(f, output) or (widths is not None and numpy.shares_memory(widths, output)):
|
||||
raise ValueError('out must not alias the field or widths')
|
||||
if not output.flags.writeable or not numpy.can_cast(dtype, output.dtype, casting='same_kind'):
|
||||
raise ValueError('out must be writable with a compatible dtype')
|
||||
low, high = [slice(None)] * 3, [slice(None)] * 3
|
||||
low[axis], high[axis] = slice(None, -1), slice(1, None)
|
||||
first, last = [slice(None)] * 3, [slice(None)] * 3
|
||||
first[axis], last[axis] = slice(0, 1), slice(-1, None)
|
||||
destination = low if forward else high
|
||||
numpy.subtract(f[tuple(high)], f[tuple(low)], out=output[tuple(destination)])
|
||||
destination = last if forward else first
|
||||
numpy.subtract(f[tuple(first)], f[tuple(last)], out=output[tuple(destination)])
|
||||
if widths is not None:
|
||||
expand = [1, 1, 1]
|
||||
expand[axis] = len(widths)
|
||||
numpy.divide(output, numpy.asarray(widths).reshape(expand), out=output)
|
||||
return output
|
||||
return derivative
|
||||
|
||||
|
||||
def deriv_forward(
|
||||
dx_e: Sequence[NDArray[floating | complexfloating]] | None = None,
|
||||
) -> tuple[fdfield_updater_t, fdfield_updater_t, fdfield_updater_t]:
|
||||
"""Forward periodic derivatives divided by electric Yee widths.
|
||||
|
||||
Each callable accepts ``derivative(field, *, out=None)``. An output buffer
|
||||
must match the field shape and must not alias the field or width arrays.
|
||||
Slice-based subtraction avoids a full-size roll temporary.
|
||||
"""
|
||||
return tuple(_derivative(axis, True, None if dx_e is None else dx_e[axis]) for axis in range(3))
|
||||
Utility operators for taking discretized derivatives (backward variant).
|
||||
|
||||
Args:
|
||||
dx_e: Lists of cell sizes for all axes
|
||||
`[[dx_0, dx_1, ...], [dy_0, dy_1, ...], ...]`.
|
||||
|
||||
Returns:
|
||||
List of functions for taking forward derivatives along each axis.
|
||||
"""
|
||||
if dx_e is not None:
|
||||
derivs = (lambda f: (numpy.roll(f, -1, axis=0) - f) / dx_e[0][:, None, None],
|
||||
lambda f: (numpy.roll(f, -1, axis=1) - f) / dx_e[1][None, :, None],
|
||||
lambda f: (numpy.roll(f, -1, axis=2) - f) / dx_e[2][None, None, :])
|
||||
else:
|
||||
derivs = (lambda f: numpy.roll(f, -1, axis=0) - f,
|
||||
lambda f: numpy.roll(f, -1, axis=1) - f,
|
||||
lambda f: numpy.roll(f, -1, axis=2) - f)
|
||||
return derivs
|
||||
|
||||
|
||||
def deriv_back(
|
||||
dx_h: Sequence[NDArray[floating | complexfloating]] | None = None,
|
||||
) -> tuple[fdfield_updater_t, fdfield_updater_t, fdfield_updater_t]:
|
||||
"""Backward periodic derivatives divided by magnetic Yee widths.
|
||||
|
||||
Callables accept the same non-aliasing ``out`` buffer as deriv_forward.
|
||||
"""
|
||||
return tuple(_derivative(axis, False, None if dx_h is None else dx_h[axis]) for axis in range(3))
|
||||
Utility operators for taking discretized derivatives (forward variant).
|
||||
|
||||
Args:
|
||||
dx_h: Lists of cell sizes for all axes
|
||||
`[[dx_0, dx_1, ...], [dy_0, dy_1, ...], ...]`.
|
||||
|
||||
Returns:
|
||||
List of functions for taking forward derivatives along each axis.
|
||||
"""
|
||||
if dx_h is not None:
|
||||
derivs = (lambda f: (f - numpy.roll(f, 1, axis=0)) / dx_h[0][:, None, None],
|
||||
lambda f: (f - numpy.roll(f, 1, axis=1)) / dx_h[1][None, :, None],
|
||||
lambda f: (f - numpy.roll(f, 1, axis=2)) / dx_h[2][None, None, :])
|
||||
else:
|
||||
derivs = (lambda f: f - numpy.roll(f, 1, axis=0),
|
||||
lambda f: f - numpy.roll(f, 1, axis=1),
|
||||
lambda f: f - numpy.roll(f, 1, axis=2))
|
||||
return derivs
|
||||
|
||||
|
||||
TT = TypeVar('TT', bound='NDArray[floating | complexfloating]')
|
||||
|
|
|
|||
|
|
@ -41,7 +41,6 @@ def cpml_params(
|
|||
m: float = 3.5,
|
||||
ma: float = 1,
|
||||
cfs_alpha: float = 0,
|
||||
dx: float = 1.0,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Construct the parameter block for one CPML face.
|
||||
|
|
@ -52,17 +51,12 @@ def cpml_params(
|
|||
`+1` for the high-index face).
|
||||
dt: Timestep used by the Yee update.
|
||||
thickness: Number of Yee cells occupied by the CPML region.
|
||||
ln_R_per_layer: Finite, strictly negative logarithmic attenuation target
|
||||
per layer. Zero attenuation is not supported; disable a face with
|
||||
``None`` in the updates_with_cpml parameter table instead.
|
||||
ln_R_per_layer: Logarithmic attenuation target per layer.
|
||||
epsilon_eff: Effective permittivity used when choosing the CPML scaling.
|
||||
mu_eff: Effective permeability used when choosing the CPML scaling.
|
||||
m: Polynomial grading exponent for `sigma` and `kappa`.
|
||||
ma: Polynomial grading exponent for the complex-frequency shift `alpha`.
|
||||
cfs_alpha: Maximum complex-frequency shift parameter.
|
||||
dx: Physical cell width normal to this face, uniform within the CPML.
|
||||
The default assumes unit cells. Arbitrary nonuniform grading is
|
||||
not supported by this parameter constructor.
|
||||
|
||||
Returns:
|
||||
Dictionary with:
|
||||
|
|
@ -84,13 +78,7 @@ def cpml_params(
|
|||
if epsilon_eff <= 0:
|
||||
raise ValueError('epsilon_eff must be positive')
|
||||
|
||||
if not numpy.isfinite(ln_R_per_layer) or ln_R_per_layer >= 0:
|
||||
raise ValueError('ln_R_per_layer must be finite and negative; use None to disable a CPML face')
|
||||
|
||||
if not numpy.isfinite(dx) or dx <= 0:
|
||||
raise ValueError('dx must be finite and positive')
|
||||
|
||||
sigma_max = -ln_R_per_layer / (2 * dx) * (m + 1)
|
||||
sigma_max = -ln_R_per_layer / 2 * (m + 1)
|
||||
kappa_max = numpy.sqrt(epsilon_eff * mu_eff)
|
||||
alpha_max = cfs_alpha
|
||||
|
||||
|
|
@ -164,7 +152,7 @@ def updates_with_cpml(
|
|||
The closures retain the CPML auxiliary state internally.
|
||||
"""
|
||||
|
||||
Dfx, Dfy, Dfz = deriv_forward(dxes[0])
|
||||
Dfx, Dfy, Dfz = deriv_forward(dxes[1])
|
||||
Dbx, Dby, Dbz = deriv_back(dxes[1])
|
||||
|
||||
psi_E: list[list[tuple[Any, Any]]] = [[(None, None) for _ in range(2)] for _ in range(3)]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import numpy
|
||||
from numpy.linalg import norm
|
||||
import pytest
|
||||
from scipy import sparse
|
||||
|
||||
from ._solver_cases import diagonal_eigen_case
|
||||
from .utils import assert_close
|
||||
from ..eigensolvers import power_iteration, rayleigh_quotient_iteration, scipy_eigs_near, signed_eigensolve
|
||||
from ..eigensolvers import power_iteration, rayleigh_quotient_iteration, signed_eigensolve
|
||||
|
||||
|
||||
def test_rayleigh_quotient_iteration_with_linear_operator() -> None:
|
||||
|
|
@ -100,27 +99,3 @@ def test_signed_eigensolve_returns_largest_positive_modes() -> None:
|
|||
|
||||
assert_close(eigvals, [3.0, 5.0], atol=1e-6)
|
||||
assert eigvecs.shape == (4, 2)
|
||||
|
||||
|
||||
def test_scipy_eigs_near_returns_paired_bilinear_left_vectors() -> None:
|
||||
operator = sparse.csc_array(numpy.diag([1.0 + 0.1j, 2.0 - 0.2j, 4.0 + 0.3j, 7.0]))
|
||||
|
||||
solution = scipy_eigs_near(operator, target=3.1, how_many=2)
|
||||
|
||||
assert_close(numpy.sort_complex(solution.eigenvalues), numpy.sort_complex([2.0 - 0.2j, 4.0 + 0.3j]))
|
||||
gram = solution.left_eigenvectors.T @ solution.right_eigenvectors
|
||||
assert numpy.linalg.cond(gram) < 2
|
||||
for index, eigenvalue in enumerate(solution.eigenvalues):
|
||||
right = solution.right_eigenvectors[:, index]
|
||||
left = solution.left_eigenvectors[:, index]
|
||||
assert norm(operator @ right - eigenvalue * right) < 1e-10
|
||||
assert norm(operator.T @ left - eigenvalue * left) < 1e-10
|
||||
|
||||
|
||||
@pytest.mark.parametrize('parameter', ['tolerance', 'pairing_rtol'])
|
||||
@pytest.mark.parametrize('invalid', [numpy.nan, numpy.inf, -numpy.inf])
|
||||
def test_scipy_eigs_near_rejects_nonfinite_tolerances(parameter: str, invalid: float) -> None:
|
||||
operator = sparse.csc_array(numpy.diag([1.0, 2.0, 3.0, 4.0]))
|
||||
|
||||
with pytest.raises(ValueError, match=rf'{parameter} must be finite and positive'):
|
||||
scipy_eigs_near(operator, target=2.1, how_many=1, **{parameter: invalid})
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ from typing import cast
|
|||
|
||||
import numpy
|
||||
import pytest
|
||||
from scipy import sparse
|
||||
|
||||
from ..fdmath import vec
|
||||
from ..fdfd import eme, waveguide_2d, waveguide_3d, waveguide_cyl
|
||||
from ..fdfd import eme, waveguide_2d, waveguide_cyl
|
||||
from ._test_builders import complex_ramp, unit_dxes
|
||||
from .utils import assert_close
|
||||
|
||||
|
|
@ -14,10 +15,7 @@ DXES = unit_dxes((2, 2))
|
|||
WAVENUMBERS_L = numpy.array([1.0, 0.8])
|
||||
WAVENUMBERS_R = numpy.array([0.9, 0.7])
|
||||
OMEGA = 1 / 1500
|
||||
FDFD_OMEGA = 2 * numpy.pi / 16
|
||||
REAL_DXES = unit_dxes((5, 5))
|
||||
FDFD_SHAPE_2D = (7, 7)
|
||||
FDFD_DXES_2D = unit_dxes(FDFD_SHAPE_2D)
|
||||
|
||||
|
||||
def _mode(scale: float) -> tuple[numpy.ndarray, numpy.ndarray]:
|
||||
|
|
@ -32,11 +30,34 @@ def _mode_sets() -> tuple[list[tuple[numpy.ndarray, numpy.ndarray]], list[tuple[
|
|||
return left_modes, right_modes
|
||||
|
||||
|
||||
def _gain_only_tr(*args, **kwargs) -> tuple[numpy.ndarray, numpy.ndarray]:
|
||||
return numpy.array([[2.0, 0.0], [0.0, 0.5]]), numpy.zeros((2, 2))
|
||||
|
||||
|
||||
def _gain_and_reflection_tr(*args, **kwargs) -> tuple[numpy.ndarray, numpy.ndarray]:
|
||||
return numpy.array([[2.0, 0.0], [0.0, 0.5]]), numpy.array([[0.0, 1.0], [2.0, 0.0]])
|
||||
|
||||
|
||||
def _nonsymmetric_tr(left_marker: object):
|
||||
def fake_get_tr(_eh_left, wavenumbers_left, _eh_right, _wavenumbers_right, **kwargs):
|
||||
if wavenumbers_left is left_marker:
|
||||
return (
|
||||
numpy.array([[1.0, 2.0], [0.5, 1.0]]),
|
||||
numpy.array([[0.0, 1.0], [2.0, 0.0]]),
|
||||
)
|
||||
return (
|
||||
numpy.array([[1.0, -1.0], [0.0, 1.0]]),
|
||||
numpy.array([[0.0, 0.5], [1.5, 0.0]]),
|
||||
)
|
||||
|
||||
return fake_get_tr
|
||||
|
||||
|
||||
def _dummy_modes() -> tuple[list[tuple[numpy.ndarray, numpy.ndarray]], numpy.ndarray]:
|
||||
return [_mode(0.0), _mode(0.7)], numpy.array([1.0, 0.5])
|
||||
|
||||
|
||||
def test_get_tr_returns_finite_coordinate_transfer_matrices() -> None:
|
||||
def test_get_tr_returns_finite_bounded_transfer_matrices() -> None:
|
||||
left_modes, right_modes = _mode_sets()
|
||||
|
||||
transmission, reflection = eme.get_tr(
|
||||
|
|
@ -53,8 +74,7 @@ def test_get_tr_returns_finite_coordinate_transfer_matrices() -> None:
|
|||
assert reflection.shape == (2, 2)
|
||||
assert numpy.isfinite(transmission).all()
|
||||
assert numpy.isfinite(reflection).all()
|
||||
# These arbitrary fields are not power-normalized: coefficients may exceed one.
|
||||
assert singular_values.max() > 1.0
|
||||
assert (singular_values <= 1.0 + 1e-12).all()
|
||||
|
||||
|
||||
def test_get_tr_accepts_scaled_dual_projection_modes() -> None:
|
||||
|
|
@ -75,53 +95,73 @@ def test_get_tr_accepts_scaled_dual_projection_modes() -> None:
|
|||
)
|
||||
|
||||
assert_close(dual_t, plain_t)
|
||||
assert_close(dual_r, plain_r, atol=1e-11)
|
||||
assert_close(dual_r, plain_r)
|
||||
|
||||
|
||||
def test_get_abcd_maps_left_state_to_right_state() -> None:
|
||||
def test_get_abcd_matches_explicit_block_formula() -> None:
|
||||
left_modes, right_modes = _mode_sets()
|
||||
ss = eme.get_s(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, DXES)
|
||||
transfer = eme.get_abcd(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, DXES).toarray()
|
||||
incoming = numpy.array([1.0, .3j, -.4j, .2])
|
||||
outgoing = ss @ incoming
|
||||
state_left = numpy.concatenate((incoming[:2], outgoing[:2]))
|
||||
state_right = numpy.concatenate((outgoing[2:], incoming[2:]))
|
||||
assert_close(transfer @ state_left, state_right, atol=1e-11)
|
||||
t12, r12 = eme.get_tr(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, dxes=DXES)
|
||||
t21, r21 = eme.get_tr(right_modes, WAVENUMBERS_R, left_modes, WAVENUMBERS_L, dxes=DXES)
|
||||
t21_inv = numpy.linalg.pinv(t21)
|
||||
|
||||
expected = numpy.block([
|
||||
[t12 - r21 @ t21_inv @ r12, r21 @ t21_inv],
|
||||
[-t21_inv @ r12, t21_inv],
|
||||
])
|
||||
abcd = eme.get_abcd(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, dxes=DXES)
|
||||
|
||||
assert sparse.issparse(abcd)
|
||||
assert abcd.shape == (4, 4)
|
||||
assert_close(abcd.toarray(), expected)
|
||||
|
||||
|
||||
def test_get_s_left_incidence_matches_get_tr() -> None:
|
||||
def test_get_s_plain_matches_block_assembly_from_get_tr() -> None:
|
||||
left_modes, right_modes = _mode_sets()
|
||||
transmission, reflection = eme.get_tr(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, DXES)
|
||||
ss = eme.get_s(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, DXES)
|
||||
t12, r12 = eme.get_tr(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, dxes=DXES)
|
||||
t21, r21 = eme.get_tr(right_modes, WAVENUMBERS_R, left_modes, WAVENUMBERS_L, dxes=DXES)
|
||||
expected = numpy.block([[r12, t12], [t21, r21]])
|
||||
|
||||
ss = eme.get_s(left_modes, WAVENUMBERS_L, right_modes, WAVENUMBERS_R, dxes=DXES)
|
||||
|
||||
assert ss.shape == (4, 4)
|
||||
assert_close(ss[:2, :2], reflection, atol=1e-11)
|
||||
assert_close(ss[2:, :2], transmission, atol=1e-11)
|
||||
assert numpy.isfinite(ss).all()
|
||||
assert_close(ss, expected)
|
||||
|
||||
|
||||
def test_get_s_force_nogain_caps_singular_values(monkeypatch) -> None:
|
||||
raw = numpy.diag([2., .5, 1.2, .3])
|
||||
monkeypatch.setattr(eme, '_interface_s', lambda *args, **kwargs: raw.copy())
|
||||
monkeypatch.setattr(eme, 'get_tr', _gain_only_tr)
|
||||
modes, wavenumbers = _dummy_modes()
|
||||
plain_s = eme.get_s(modes, wavenumbers, modes, wavenumbers, DXES)
|
||||
clipped_s = eme.get_s(modes, wavenumbers, modes, wavenumbers, DXES, force_nogain=True)
|
||||
assert numpy.linalg.svd(plain_s, compute_uv=False).max() > 1
|
||||
assert_close(numpy.linalg.svd(clipped_s, compute_uv=False), [1., 1., .5, .3])
|
||||
|
||||
plain_s = eme.get_s(modes, wavenumbers, modes, wavenumbers)
|
||||
clipped_s = eme.get_s(modes, wavenumbers, modes, wavenumbers, force_nogain=True)
|
||||
|
||||
plain_singular_values = numpy.linalg.svd(plain_s, compute_uv=False)
|
||||
clipped_singular_values = numpy.linalg.svd(clipped_s, compute_uv=False)
|
||||
|
||||
assert plain_singular_values.max() > 1.0
|
||||
assert (clipped_singular_values <= 1.0 + 1e-12).all()
|
||||
assert numpy.isfinite(clipped_s).all()
|
||||
|
||||
|
||||
def test_get_s_force_reciprocal_symmetrizes_output(monkeypatch) -> None:
|
||||
raw = numpy.arange(16, dtype=float).reshape(4, 4)
|
||||
monkeypatch.setattr(eme, '_interface_s', lambda *args, **kwargs: raw.copy())
|
||||
modes, wavenumbers = _dummy_modes()
|
||||
ss = eme.get_s(modes, wavenumbers, modes, wavenumbers, DXES, force_reciprocal=True)
|
||||
assert_close(ss, .5 * (raw + raw.T))
|
||||
left = numpy.array([1.0, 0.5])
|
||||
right = numpy.array([0.9, 0.4])
|
||||
modes, _wavenumbers = _dummy_modes()
|
||||
|
||||
monkeypatch.setattr(eme, 'get_tr', _nonsymmetric_tr(left))
|
||||
ss = eme.get_s(modes, left, modes, right, force_reciprocal=True)
|
||||
|
||||
assert_close(ss, ss.T)
|
||||
|
||||
|
||||
def test_get_s_force_nogain_and_reciprocal_returns_finite_output(monkeypatch) -> None:
|
||||
raw = numpy.arange(16, dtype=float).reshape(4, 4)
|
||||
monkeypatch.setattr(eme, '_interface_s', lambda *args, **kwargs: raw.copy())
|
||||
monkeypatch.setattr(eme, 'get_tr', _gain_and_reflection_tr)
|
||||
modes, wavenumbers = _dummy_modes()
|
||||
ss = eme.get_s(modes, wavenumbers, modes, wavenumbers, DXES, force_nogain=True, force_reciprocal=True)
|
||||
assert_close(ss, ss.T, atol=1e-14)
|
||||
ss = eme.get_s(modes, wavenumbers, modes, wavenumbers, force_nogain=True, force_reciprocal=True)
|
||||
|
||||
assert ss.shape == (4, 4)
|
||||
assert numpy.isfinite(ss).all()
|
||||
assert_close(ss, ss.T)
|
||||
assert (numpy.linalg.svd(ss, compute_uv=False) <= 1.0 + 1e-12).all()
|
||||
|
||||
|
||||
|
|
@ -421,8 +461,8 @@ def _abcd_to_s(abcd: numpy.ndarray) -> numpy.ndarray:
|
|||
t12 = aa - bb * cc / dd
|
||||
return numpy.array(
|
||||
[
|
||||
[r12, t21],
|
||||
[t12, r21],
|
||||
[r12, t12],
|
||||
[t21, r21],
|
||||
],
|
||||
dtype=complex,
|
||||
)
|
||||
|
|
@ -441,25 +481,6 @@ def _expected_bragg_reflector_s(n_low: float, n_high: float, periods: int) -> nu
|
|||
)
|
||||
|
||||
|
||||
def _fdfd_cross_section(core_epsilon: float) -> numpy.ndarray:
|
||||
epsilon = numpy.ones((3, *FDFD_SHAPE_2D), dtype=float)
|
||||
epsilon[:, 2:5, 2:5] = core_epsilon
|
||||
return epsilon
|
||||
|
||||
|
||||
def _small_fdfd_kwargs() -> dict:
|
||||
return {
|
||||
'omega': FDFD_OMEGA,
|
||||
'dxes_2d': FDFD_DXES_2D,
|
||||
'mode_numbers': [0],
|
||||
'pml_cells': 4,
|
||||
'pml_buffer_cells': 2,
|
||||
'source_monitor_cells': 5,
|
||||
'monitor_interface_cells': 5,
|
||||
'matrix_solver_opts': {'atol': 1e-10, 'rtol': 1e-8},
|
||||
}
|
||||
|
||||
|
||||
def test_get_s_is_near_identity_for_identical_solved_straight_modes() -> None:
|
||||
mode, wavenumber, _epsilon = _build_straight_mode()
|
||||
|
||||
|
|
@ -534,189 +555,6 @@ def test_get_s_accepts_complex_leaky_wavenumbers_for_abrupt_interface() -> None:
|
|||
assert_close(ss, numpy.array([[0.0, 1.0], [1.0, 0.0]], dtype=complex), atol=1e-12, rtol=1e-12)
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_identical_guides_are_nearly_transmissive() -> None:
|
||||
epsilon = _fdfd_cross_section(2.25)
|
||||
|
||||
ss = waveguide_3d.get_s_fdfd_from_2d_ports(epsilon, epsilon, **_small_fdfd_kwargs())
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
assert numpy.isfinite(ss).all()
|
||||
assert abs(ss[0, 0]) < 0.03
|
||||
assert abs(ss[1, 1]) < 0.04
|
||||
assert abs(abs(ss[1, 0]) - 1.0) < 0.02
|
||||
assert abs(abs(ss[0, 1]) - 1.0) < 0.03
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_mismatch_returns_finite_diagnostics() -> None:
|
||||
left = _fdfd_cross_section(2.25)
|
||||
right = _fdfd_cross_section(1.5)
|
||||
|
||||
ss, diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(left, right, return_diagnostics=True, **_small_fdfd_kwargs())
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
assert numpy.isfinite(ss).all()
|
||||
assert len(diagnostics['electric_fields']) == 2
|
||||
assert len(diagnostics['magnetic_fields']) == 2
|
||||
assert diagnostics['electric_fields'][0].shape == (3, 33, *FDFD_SHAPE_2D)
|
||||
assert numpy.isfinite(diagnostics['electric_fields'][0]).all()
|
||||
assert numpy.isfinite(diagnostics['magnetic_fields'][0]).all()
|
||||
assert numpy.isfinite(diagnostics['guided_powers']).all()
|
||||
assert numpy.isfinite(diagnostics['unresolved_powers']).all()
|
||||
assert numpy.isfinite(diagnostics['raw_outgoing_amplitudes']).all()
|
||||
assert numpy.isfinite(diagnostics['incident_amplitudes']).all()
|
||||
assert (numpy.abs(diagnostics['incident_amplitudes']) > 1e-3).all()
|
||||
assert_close(diagnostics['unresolved_powers'], 1.0 - diagnostics['guided_powers'])
|
||||
assert diagnostics['guided_powers'][0] < 1.05
|
||||
|
||||
|
||||
def test_get_s_fdfd_normalization_is_source_scale_invariant() -> None:
|
||||
left = _fdfd_cross_section(2.25)
|
||||
right = _fdfd_cross_section(1.5)
|
||||
kwargs = _small_fdfd_kwargs()
|
||||
|
||||
base, base_diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(left, right, return_diagnostics=True, **kwargs)
|
||||
scaled, scaled_diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(left, right, source_scales=[2.0, 0.3], return_diagnostics=True, **kwargs)
|
||||
|
||||
assert_close(numpy.abs(scaled), numpy.abs(base), atol=1e-6, rtol=1e-6)
|
||||
assert abs(abs(scaled_diagnostics['incident_amplitudes'][0] / base_diagnostics['incident_amplitudes'][0]) - 2.0) < 1e-6
|
||||
assert abs(abs(scaled_diagnostics['incident_amplitudes'][1] / base_diagnostics['incident_amplitudes'][1]) - 0.3) < 1e-6
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_diagnostics_order_generated_slices() -> None:
|
||||
epsilon = _fdfd_cross_section(2.25)
|
||||
|
||||
_ss, diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(epsilon, epsilon, return_diagnostics=True, **_small_fdfd_kwargs())
|
||||
|
||||
left_source = diagnostics['left_source_slice'][0].start
|
||||
left_monitor = diagnostics['left_monitor_slice'][0].start
|
||||
interface_index = diagnostics['interface_index']
|
||||
right_monitor = diagnostics['right_monitor_slice'][0].start
|
||||
right_source = diagnostics['right_source_slice'][0].start
|
||||
|
||||
assert left_source == 6
|
||||
assert left_monitor == 11
|
||||
assert interface_index == 16
|
||||
assert right_monitor == 21
|
||||
assert right_source == 26
|
||||
assert left_source < left_monitor < interface_index < right_monitor < right_source
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_transverse_padding_and_pml_updates_diagnostics() -> None:
|
||||
epsilon = _fdfd_cross_section(2.25)
|
||||
|
||||
ss, diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(
|
||||
epsilon,
|
||||
epsilon,
|
||||
transverse_padding_cells=(2, 3),
|
||||
transverse_pml_cells=(1, 2),
|
||||
return_diagnostics=True,
|
||||
**_small_fdfd_kwargs(),
|
||||
)
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
assert diagnostics['epsilon'].shape == (3, 33, 11, 13)
|
||||
assert diagnostics['transverse_padding_cells'] == (2, 3)
|
||||
assert diagnostics['transverse_pml_cells'] == (1, 2)
|
||||
assert numpy.iscomplexobj(diagnostics['solve_dxes'][0][1])
|
||||
assert numpy.iscomplexobj(diagnostics['solve_dxes'][0][2])
|
||||
assert numpy.abs(numpy.imag(diagnostics['solve_dxes'][0][1][0])) > 0
|
||||
assert numpy.abs(numpy.imag(diagnostics['solve_dxes'][0][2][0])) > 0
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_supports_nondefault_axis() -> None:
|
||||
epsilon = _fdfd_cross_section(2.25)
|
||||
|
||||
ss, diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(epsilon, epsilon, axis=1, return_diagnostics=True, **_small_fdfd_kwargs())
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
assert diagnostics['epsilon'].shape == (3, FDFD_SHAPE_2D[0], 33, FDFD_SHAPE_2D[1])
|
||||
assert diagnostics['left_source_slice'][1].start == 6
|
||||
assert numpy.isfinite(ss).all()
|
||||
|
||||
|
||||
def test_get_s_fdfd_rejects_bad_port_slice_order() -> None:
|
||||
epsilon = numpy.ones((3, 12, 5, 5), dtype=float)
|
||||
dxes = [[numpy.ones(12), numpy.ones(5), numpy.ones(5)] for _ in range(2)]
|
||||
|
||||
with pytest.raises(ValueError, match='ordered'):
|
||||
waveguide_3d.get_s_fdfd(
|
||||
FDFD_OMEGA,
|
||||
dxes,
|
||||
epsilon,
|
||||
left_mode_numbers=[0],
|
||||
left_source_slice=(slice(5, 6), slice(None), slice(None)),
|
||||
left_monitor_slice=(slice(4, 5), slice(None), slice(None)),
|
||||
right_source_slice=(slice(10, 11), slice(None), slice(None)),
|
||||
right_monitor_slice=(slice(8, 9), slice(None), slice(None)),
|
||||
)
|
||||
|
||||
|
||||
def test_get_s_fdfd_rejects_bad_source_scale_count_before_solving() -> None:
|
||||
epsilon = numpy.ones((3, 12, 5, 5), dtype=float)
|
||||
dxes = [[numpy.ones(12), numpy.ones(5), numpy.ones(5)] for _ in range(2)]
|
||||
|
||||
with pytest.raises(ValueError, match='source_scales'):
|
||||
waveguide_3d.get_s_fdfd(
|
||||
FDFD_OMEGA,
|
||||
dxes,
|
||||
epsilon,
|
||||
left_mode_numbers=[0],
|
||||
left_source_slice=(slice(2, 3), slice(None), slice(None)),
|
||||
left_monitor_slice=(slice(4, 5), slice(None), slice(None)),
|
||||
right_mode_numbers=[0, 1],
|
||||
right_source_slice=(slice(10, 11), slice(None), slice(None)),
|
||||
right_monitor_slice=(slice(8, 9), slice(None), slice(None)),
|
||||
source_scales=[1.0, 1.0],
|
||||
)
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_rejects_invalid_generated_geometry() -> None:
|
||||
epsilon = _fdfd_cross_section(2.25)
|
||||
|
||||
with pytest.raises(ValueError, match='must be positive'):
|
||||
waveguide_3d.get_s_fdfd_from_2d_ports(epsilon, epsilon, **{**_small_fdfd_kwargs(), 'pml_cells': 0})
|
||||
|
||||
|
||||
def test_get_s_fdfd_rejects_noninteger_mode_numbers_before_solving() -> None:
|
||||
epsilon = numpy.ones((3, 12, 5, 5), dtype=float)
|
||||
dxes = [[numpy.ones(12), numpy.ones(5), numpy.ones(5)] for _ in range(2)]
|
||||
|
||||
with pytest.raises(ValueError, match='mode_numbers'):
|
||||
waveguide_3d.get_s_fdfd(
|
||||
FDFD_OMEGA,
|
||||
dxes,
|
||||
epsilon,
|
||||
left_mode_numbers=[0.5], # type: ignore[list-item]
|
||||
left_source_slice=(slice(2, 3), slice(None), slice(None)),
|
||||
left_monitor_slice=(slice(4, 5), slice(None), slice(None)),
|
||||
right_source_slice=(slice(10, 11), slice(None), slice(None)),
|
||||
right_monitor_slice=(slice(8, 9), slice(None), slice(None)),
|
||||
)
|
||||
|
||||
|
||||
def test_get_s_fdfd_from_2d_ports_preserves_complex_generated_inputs(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
left = _fdfd_cross_section(2.25)
|
||||
right = _fdfd_cross_section(1.5).astype(complex)
|
||||
right += 0.1j
|
||||
dxes_2d = [
|
||||
[FDFD_DXES_2D[0][0].astype(complex) + 0.2j, FDFD_DXES_2D[0][1].astype(complex) + 0.3j],
|
||||
[FDFD_DXES_2D[1][0].astype(complex) + 0.4j, FDFD_DXES_2D[1][1].astype(complex) + 0.5j],
|
||||
]
|
||||
|
||||
def fake_get_s_fdfd(*args, **kwargs) -> tuple[numpy.ndarray, dict]:
|
||||
return numpy.eye(2, dtype=complex), {}
|
||||
|
||||
monkeypatch.setattr(waveguide_3d, 'get_s_fdfd', fake_get_s_fdfd)
|
||||
|
||||
kwargs = {**_small_fdfd_kwargs(), 'dxes_2d': dxes_2d}
|
||||
_ss, diagnostics = waveguide_3d.get_s_fdfd_from_2d_ports(left, right, return_diagnostics=True, **kwargs)
|
||||
|
||||
assert numpy.iscomplexobj(diagnostics['epsilon'])
|
||||
assert diagnostics['epsilon'][0, diagnostics['interface_index'], 0, 0].imag == pytest.approx(0.1)
|
||||
assert numpy.iscomplexobj(diagnostics['dxes'][0][1])
|
||||
assert diagnostics['dxes'][0][1][0].imag == pytest.approx(0.2)
|
||||
|
||||
|
||||
def test_quarter_wave_matching_layer_is_nearly_reflectionless_at_design_frequency() -> None:
|
||||
"""
|
||||
A single quarter-wave matching layer with
|
||||
|
|
@ -734,7 +572,7 @@ def test_quarter_wave_matching_layer_is_nearly_reflectionless_at_design_frequenc
|
|||
_mode_1, beta_1 = _build_uniform_mode(float(n1))
|
||||
quarter_wave_length = numpy.pi / (2 * numpy.real(beta_1))
|
||||
|
||||
stack_abcd = interface_12 @ _propagation_abcd(beta_1, quarter_wave_length) @ interface_01
|
||||
stack_abcd = interface_01 @ _propagation_abcd(beta_1, quarter_wave_length) @ interface_12
|
||||
ss = _abcd_to_s(stack_abcd)
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
|
|
@ -767,7 +605,7 @@ def test_quarter_wave_ar_layer_reduces_reflection_relative_to_abrupt_interface()
|
|||
interface_12 = _interface_abcd(n1, n2)
|
||||
_mode_1, beta_1 = _build_uniform_mode(float(n1))
|
||||
quarter_wave_length = numpy.pi / (2 * numpy.real(beta_1))
|
||||
ar_stack = _abcd_to_s(interface_12 @ _propagation_abcd(beta_1, quarter_wave_length) @ interface_01)
|
||||
ar_stack = _abcd_to_s(interface_01 @ _propagation_abcd(beta_1, quarter_wave_length) @ interface_12)
|
||||
|
||||
abrupt_reflection = abs(abrupt[0, 0])
|
||||
abrupt_transmission = abs(abrupt[1, 0])
|
||||
|
|
@ -798,7 +636,7 @@ def test_half_wave_uniform_slab_restores_unit_transmission_between_matched_media
|
|||
_mode_1, beta_1 = _build_uniform_mode(n1)
|
||||
half_wave_length = numpy.pi / numpy.real(beta_1)
|
||||
|
||||
stack_abcd = interface_10 @ _propagation_abcd(beta_1, half_wave_length) @ interface_01
|
||||
stack_abcd = interface_01 @ _propagation_abcd(beta_1, half_wave_length) @ interface_10
|
||||
ss = _abcd_to_s(stack_abcd)
|
||||
|
||||
assert ss.shape == (2, 2)
|
||||
|
|
@ -856,7 +694,8 @@ def test_quarter_wave_bragg_reflector_matches_closed_form_stopband_response() ->
|
|||
|
||||
stack_abcd = numpy.eye(2, dtype=complex)
|
||||
for _ in range(periods):
|
||||
stack_abcd = _propagation_abcd(beta_l, quarter_wave_low) @ interface_hl @ _propagation_abcd(beta_h, quarter_wave_high) @ interface_lh @ stack_abcd
|
||||
stack_abcd = stack_abcd @ interface_lh @ _propagation_abcd(beta_h, quarter_wave_high)
|
||||
stack_abcd = stack_abcd @ interface_hl @ _propagation_abcd(beta_l, quarter_wave_low)
|
||||
ss = _abcd_to_s(stack_abcd)
|
||||
expected = _expected_bragg_reflector_s(n_low, n_high, periods)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,210 +0,0 @@
|
|||
"""Characterize truncation bias against exact reciprocal Maxwell interfaces.
|
||||
|
||||
These tests intentionally document mixed/Galerkin projection limitations; they
|
||||
are not passivity-enforcement tests. Both complete modal bases and an independent
|
||||
driven FDFD solve establish the reference for the truncated polarization case.
|
||||
"""
|
||||
import numpy as np
|
||||
import pytest
|
||||
from numpy.testing import assert_allclose
|
||||
from scipy.sparse.linalg import spsolve
|
||||
|
||||
from ..fdmath import vec, unvec
|
||||
from ..fdfd import eme, scpml, solvers, waveguide_2d, waveguide_3d
|
||||
|
||||
|
||||
DXES = [[np.ones(1), np.ones(1)] for _ in range(2)]
|
||||
|
||||
|
||||
def _rotation(angle):
|
||||
return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
|
||||
|
||||
|
||||
def _polarizations(angle, scales=(1., 1.)):
|
||||
"""Two power-orthonormal signed-beta=1 modes on a one-cell transverse grid.
|
||||
|
||||
E_xy = sqrt(2) diag(scales) Q, and J^-1 H_xy = sqrt(2) diag(1/scales) Q.
|
||||
They solve Maxwell with diagonal epsilon=(1/sx^2,1/sy^2,1) and
|
||||
mu=(sy^2,sx^2,1) at omega=1, including nonparallel E/H traces.
|
||||
"""
|
||||
rotation = _rotation(angle)
|
||||
electric = np.diag(scales) @ rotation
|
||||
magnetic = np.diag(1 / np.asarray(scales)) @ rotation
|
||||
return [
|
||||
(np.sqrt(2) * np.array([electric[0, i], electric[1, i], 0], complex),
|
||||
np.sqrt(2) * np.array([-magnetic[1, i], magnetic[0, i], 0], complex))
|
||||
for i in range(2)
|
||||
]
|
||||
|
||||
|
||||
def _scattering(left, right, formulation='mixed'):
|
||||
return eme.get_s(left, np.ones(len(left)), right, np.ones(len(right)), DXES, formulation=formulation)
|
||||
|
||||
|
||||
def _reorder_ports(matrix):
|
||||
n = matrix.shape[0] // 2
|
||||
order = [*range(n, 2*n), *range(n)]
|
||||
return matrix[np.ix_(order, order)]
|
||||
|
||||
|
||||
def _fresnel_reference(left_angle, right_angle, left_scales=(1., 1.), right_scales=(1., 1.)):
|
||||
"""Independent exact two-polarization interface in the supplied port bases."""
|
||||
yl, yr = 1 / np.asarray(left_scales)**2, 1 / np.asarray(right_scales)**2
|
||||
reflection = np.diag((yl - yr) / (yl + yr))
|
||||
transmission = np.diag(2 * np.sqrt(yl * yr) / (yl + yr))
|
||||
ql, qr = _rotation(left_angle), _rotation(right_angle)
|
||||
return np.block([[ql.T @ reflection @ ql, ql.T @ transmission @ qr],
|
||||
[qr.T @ transmission @ ql, -qr.T @ reflection @ qr]])
|
||||
|
||||
|
||||
def _trace_least_squares(left, right):
|
||||
"""Research comparator: unweighted Euclidean tangential E/H least squares.
|
||||
|
||||
This is deliberately not a public formulation: correcting the isotropic
|
||||
polarization example does not establish reciprocity or passivity generally.
|
||||
"""
|
||||
el = np.column_stack([e[:2] for e, _h in left])
|
||||
hl = np.column_stack([h[:2] for _e, h in left])
|
||||
er = np.column_stack([e[:2] for e, _h in right])
|
||||
hr = np.column_stack([h[:2] for _e, h in right])
|
||||
outgoing = np.block([[el, -er], [-hl, -hr]])
|
||||
incoming = np.block([[-el, er], [-hl, -hr]])
|
||||
return np.linalg.lstsq(outgoing, incoming, rcond=None)[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('overlap', [.5, .8, .95])
|
||||
def test_truncated_mixed_polarizations_show_orientation_bias_despite_unitarity(overlap):
|
||||
angle = np.arccos(overlap)
|
||||
left, right = _polarizations(0)[:1], _polarizations(angle)[:1]
|
||||
result = _scattering(left, right)
|
||||
reversed_result = _reorder_ports(_scattering(right, left))
|
||||
reflection = (1-overlap**2) / (1+overlap**2)
|
||||
transmission = 2*overlap / (1+overlap**2)
|
||||
assert_allclose(result, [[reflection, transmission], [transmission, -reflection]], atol=1e-14)
|
||||
assert_allclose(reversed_result, [[-reflection, transmission], [transmission, reflection]], atol=1e-14)
|
||||
assert_allclose(result.T @ result, np.eye(2), atol=1e-14)
|
||||
assert_allclose(result, result.T, atol=1e-14)
|
||||
assert_allclose(np.linalg.norm(result-reversed_result), 2*np.sqrt(2)*reflection, atol=1e-14)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('left_scales', 'right_scales'), [((1., 1.), (1., 1.)), ((1., 2.), (1., 3.))])
|
||||
def test_complete_maxwell_bases_recover_fresnel_and_port_relabeling(left_scales, right_scales):
|
||||
left_angle, right_angle = np.pi/6, np.arccos(.8)
|
||||
left, right = _polarizations(left_angle, left_scales), _polarizations(right_angle, right_scales)
|
||||
# Establish that the synthetic fields are actual degenerate Maxwell modes,
|
||||
# not arbitrary profiles or mixed vectors with different eigenvalues.
|
||||
for modes, scales in ((left, left_scales), (right, right_scales)):
|
||||
sx, sy = scales
|
||||
epsilon, mu = np.array([1/sx**2, 1/sy**2, 1]), np.array([sy**2, sx**2, 1])
|
||||
operator = waveguide_2d.operator_e(1, DXES, epsilon, mu)
|
||||
for e, h in modes:
|
||||
assert_allclose(operator @ e[:2], e[:2], atol=1e-14)
|
||||
assert_allclose(waveguide_2d.exy2h(1, 1, DXES, epsilon, mu) @ e[:2], h, atol=1e-14)
|
||||
gram = [[waveguide_2d.lorentz_overlap(a, b, DXES) for b in modes] for a in modes]
|
||||
assert_allclose(gram, np.eye(2), atol=1e-14)
|
||||
result = _scattering(left, right)
|
||||
expected = _fresnel_reference(left_angle, right_angle, left_scales, right_scales)
|
||||
assert_allclose(result, expected, atol=1e-14)
|
||||
assert_allclose(_reorder_ports(_scattering(right, left)), expected, atol=1e-14)
|
||||
assert_allclose(result.T @ result, np.eye(4), atol=1e-14)
|
||||
assert_allclose(result, result.T, atol=1e-14)
|
||||
|
||||
|
||||
def test_missing_polarization_accounts_for_retained_submatrix_power_deficit():
|
||||
overlap = .8
|
||||
full = _scattering(_polarizations(0), _polarizations(np.arccos(overlap)))
|
||||
retained = full[np.ix_([0, 2], [0, 2])]
|
||||
assert_allclose(retained, [[0, overlap], [overlap, 0]], atol=1e-14)
|
||||
assert_allclose(abs(full[3, 0])**2, 1-overlap**2, atol=1e-14)
|
||||
assert_allclose(np.sum(abs(full[:, 0])**2), 1, atol=1e-14)
|
||||
assert_allclose(np.sum(abs(retained[:, 0])**2), overlap**2, atol=1e-14)
|
||||
|
||||
|
||||
def test_posthoc_orientation_averaging_does_not_recover_physical_transmission():
|
||||
overlap = .8
|
||||
left, right = _polarizations(0)[:1], _polarizations(np.arccos(overlap))[:1]
|
||||
averaged = .5 * (_scattering(left, right) + _reorder_ports(_scattering(right, left)))
|
||||
assert_allclose(averaged[0, 0], 0, atol=1e-14)
|
||||
assert_allclose(averaged[1, 1], 0, atol=1e-14)
|
||||
assert abs(averaged[1, 0] - overlap) > .17
|
||||
|
||||
|
||||
def test_galerkin_testing_does_not_resolve_truncated_polarization_error():
|
||||
overlap = .8
|
||||
left, right = _polarizations(0)[:1], _polarizations(np.arccos(overlap))[:1]
|
||||
result = _scattering(left, right, 'galerkin')
|
||||
assert_allclose(result, [[0, overlap], [1/overlap, 0]], atol=1e-14)
|
||||
assert not np.allclose(result, result.T)
|
||||
|
||||
|
||||
def test_trace_least_squares_recovers_uniform_reference_but_is_not_a_general_fix():
|
||||
overlap = .8
|
||||
left, right = _polarizations(0)[:1], _polarizations(np.arccos(overlap))[:1]
|
||||
assert_allclose(_trace_least_squares(left, right), [[0, overlap], [overlap, 0]], atol=1e-14)
|
||||
angle = np.pi/6
|
||||
left, right = _polarizations(angle, (1., 2.)), _polarizations(angle, (1., 3.))
|
||||
reference = _fresnel_reference(angle, angle, (1., 2.), (1., 3.))
|
||||
assert_allclose(_trace_least_squares(left, right), reference, atol=1e-14)
|
||||
truncated = _trace_least_squares(left[:1], right[:1])
|
||||
# All traces come from the exact reciprocal, lossless Maxwell bases above.
|
||||
# Euclidean residual minimization nevertheless violates both constraints
|
||||
# after truncation. Port-relabeling covariance alone is not sufficient.
|
||||
assert np.linalg.norm(truncated-truncated.T) > .3
|
||||
assert np.linalg.svd(truncated, compute_uv=False).max() > 1.10
|
||||
assert_allclose(_reorder_ports(_trace_least_squares(right[:1], left[:1])), truncated, atol=1e-14)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('side', [0, 1])
|
||||
def test_driven_fdfd_confirms_uniform_polarization_reference(side):
|
||||
omega, thickness = np.pi/8, 24
|
||||
size = 2*thickness + 64
|
||||
physical = [[np.ones(1), np.ones(1), np.ones(size)] for _ in range(2)]
|
||||
epsilon = np.ones((3, 1, 1, size))
|
||||
solve_widths = physical
|
||||
for polarity in (-1, 1):
|
||||
solve_widths = scpml.stretch_with_scpml(solve_widths, 2, polarity, omega, thickness=thickness)
|
||||
overlap = .8
|
||||
profiles = [np.array([1., 0.]), np.array([overlap, np.sqrt(1-overlap**2)])]
|
||||
polarity = 1 if side == 0 else -1
|
||||
source_index = thickness+4 if side == 0 else thickness+52
|
||||
slices = (slice(None), slice(None), slice(source_index, source_index+1))
|
||||
mode = waveguide_3d.mode_from_2d(profiles[side], omega, omega=omega, dxes=physical,
|
||||
axis=2, polarity=polarity, slices=slices, epsilon=epsilon)
|
||||
current = waveguide_3d.compute_source(mode['E'], mode['wavenumber'], omega, physical, 2, polarity, slices, epsilon)
|
||||
field = unvec(solvers.generic(omega, solve_widths, vec(current), vec(epsilon), matrix_solver=spsolve), epsilon.shape[1:])
|
||||
left_index, right_index = thickness+12, thickness+40
|
||||
beta = 2*np.arcsin(omega/2)
|
||||
phase = np.exp(-1j*beta)
|
||||
|
||||
def waves(index):
|
||||
e0, e1 = field[:2, 0, 0, index], field[:2, 0, 0, index+1]
|
||||
forward = (e1 - e0/phase) / (phase - 1/phase)
|
||||
return forward, e0-forward
|
||||
|
||||
fl, bl = waves(left_index)
|
||||
fr, br = waves(right_index)
|
||||
incoming = np.dot(profiles[side], fl if side == 0 else br)
|
||||
reflected = np.dot(profiles[side], bl if side == 0 else fr) / incoming
|
||||
transmitted = np.dot(profiles[1-side], fr if side == 0 else bl) / incoming
|
||||
transmitted *= np.exp(1j*beta*(right_index-left_index))
|
||||
assert abs(reflected) < 5e-8
|
||||
assert_allclose(transmitted, overlap, atol=1e-12)
|
||||
|
||||
|
||||
def test_longitudinal_refinement_cannot_repair_an_omitted_degenerate_polarization():
|
||||
angle = np.arccos(.8)
|
||||
reflection_magnitudes = []
|
||||
for count in (3, 9, 33):
|
||||
complete = [eme.ModeSection(z, _polarizations(angle*z), [1., 1.]) for z in np.linspace(0, 1, count)]
|
||||
truncated = [eme.ModeSection(section.z, section.modes[:1], [1.]) for section in complete]
|
||||
full = eme.get_taper_s(complete, DXES)
|
||||
expected = _fresnel_reference(0, angle).astype(complex) * np.exp(-1j)
|
||||
assert_allclose(full, expected, atol=1e-13)
|
||||
small = eme.get_taper_s(truncated, DXES)
|
||||
reflection_magnitudes.append(abs(small[0, 0]))
|
||||
# There is no material taper: the basis is merely rotated within a
|
||||
# degenerate subspace. Restricting the exact result gives |T|=.8, while
|
||||
# the truncated chain approaches artificial adiabatic following, |T|=1.
|
||||
assert abs(small[1, 0]) > .99
|
||||
assert reflection_magnitudes[-1] < reflection_magnitudes[0] / 10
|
||||
assert_allclose(abs(expected[2, 0]), .8, atol=1e-14)
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue