Metadata-Version: 2.4
Name: wavesimpro
Version: 1.27.0
Summary: WavesimPro Python API — cloud execution client for the Rayfos simulation platform
Author: Rayfos
Project-URL: Repository, https://github.com/rayfos/wavesimpro
Keywords: wavesim,simulation,electromagnetic,rayfos,api
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.20.0
Requires-Dist: requests>=2.28.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: tqdm>=4.60.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"

# wavesimpro

Python client for the Rayfos Wavesim cloud: build a simulation setup, run it on a Rayfos
compute node, and read the results back as NumPy arrays.

Wavesim is a single-wavelength frequency-domain solver (vectorial Maxwell when a polarized
source is present, scalar Helmholtz otherwise). This package talks to the Rayfos JobServer
REST API; it does not contain the solver.

## Install

```bash
pip install wavesimpro
python -m wavesimpro setup      # one-time: API key + server URL wizard
```

The wizard stores the credentials; `wavesimpro.configure(api_key=..., api_url=...)` sets
them for one process instead.

## Quick start

```python
import wavesimpro as wp

props = wp.create_wavesim_properties(
    wavelength=1.0, pixel_size=0.1, boundary_width=5.0,
    domain=wp.create_simulation_domain(20, 20, 20),
    mediums=[wp.create_medium("Silicon", 3.48, 0.0)],
    primitives=[wp.create_box_primitive("core", 0, 0, 0, 10, 0.5, 20, medium="Silicon")],
    # TE0 solved by the engine on the z = -6 um voxel layer (index 40 of 200), launched along +z
    sources=[wp.create_mode_source("in", 0, 0, -6.0, axis="z", plane_index=40, polarization="TE")],
    monitors=[wp.create_monitor("out", 0, 0, 8.0, 10, 10, 0)],
)
run = wp.simulate(props, name="strip waveguide")
field = wp.read_binary_field(run.download("output.bin"))
```

## Typed setup: `Setup` → `submit` → `Run`

The same run with objects instead of dicts; `simulate` / `simulate_pro` / `execute_via_api` build a
`Setup` and go through `submit` too:

```python
import wavesimpro as wp

s = wp.Setup(wavelength=1.55, pixel_size=0.04, grid=(250, 60, 50), boundary_width=3.0, background=1.444)
s.add(wp.Box(n=3.48, size=(40, 0.5, 0.22)))
s.add(wp.ModeSource("in", axis="x", plane_index=60, polarization="TE"))
s.add(wp.ModePort("out", axis="x", plane_index=180, modes=["TE0", "TM0"]))
run = wp.submit(s).wait()
ports = run.port_results()   # modal powers at "out"
E = run.get_field()          # output.bin: the only monitor is an engine port, which writes no file
```

Shapes: `Box`, `Sphere`, `Ellipsoid`, `Cylinder`, `Cone`, `Prism`, `Stl`, `Gds`, `VoxelArray`
(or a `permittivity=` array on the `Setup`); media: `Medium`; sources: `FieldSource`, `PlaneWave`,
`GaussianBeam`, `PointSource`, `ModeSource`; read-outs: `Monitor`, `ModePort`. `Run` has `wait`,
`status`, `cancel`, `get_field`, `get_monitors`, `get_permittivity`, `port_results`,
`mode_sources`, `monitor_regions`, `list_files`, `download`.

## What the API covers

- Setup helpers for domains, media, primitives (box, sphere, ellipsoid, cylinder, cone,
  N-sided prism, STL, GDSII layouts, voxel arrays), sources (point, plane wave, Gaussian beam,
  custom field, custom-from-file, engine-solved waveguide mode) and monitors:
  `create_box_primitive`, `create_sphere_primitive`, `create_ellipsoid_primitive`,
  `create_cylinder_primitive`, `create_cone_primitive`, `create_prism_primitive`,
  `create_stl_primitive`, `create_gds_primitive` (with `create_gds_layer_config` /
  `create_gds_structure_override`), `create_voxels_model_primitive`.
- Per-primitive sub-pixel flag (`subpixel=True/False` on every shape, STL and GDSII helper)
  to choose which shapes get smoothed interfaces. Off by default: a setup with no averaged
  shape is voxelised exactly as before 1.10 and runs on every compute node.
- Per-axis pixel sizes (`pixel_size=[dx, dy, dz]`) and sub-pixel permittivity averaging
  (`subpixel_factor=`), when the compute node supports them.
- Engine-solved waveguide mode sources on any cut (`create_mode_source(axis=..., plane_index=...,
  order=... or target_neff=...)`) and engine-solved mode ports that read them back
  (`create_monitor(modes=["TE0", "TM0"], axis=..., plane_index=...)`, results in
  `Run.port_results()`; what was launched in `Run.mode_sources()`).
- Preflight memory check and cost estimate before a run.
- Binary upload/download helpers for permittivity volumes, source fields and monitors.

## Monitors: which voxels you get

A monitor is an axis-aligned box in micrometres, relative to the coordinate-system centre. The
domain of N voxels spans [-S/2, S/2], so voxel *i* occupies [-S/2 + i·v, -S/2 + (i+1)·v] with
v = S/N (centre at -S/2 + (i+0.5)·v, for even and odd N alike). The compute node extracts the
**outer cover** of the box: every voxel it touches — first index floor(lo), last index
ceil(hi) − 1 with lo/hi the box edges in voxel units. An edge exactly on a voxel face does not
pull in the neighbour; a zero-thickness box is the one voxel containing the plane. So a box of
exactly k voxels aligned to the grid gives k planes, and the same box centred on a voxel centre
straddles k + 1; the result is never smaller than what you asked for unless the domain clamps it.

The node writes `monitors.json` next to the `monitor_<name>.bin` files with, per monitor, the
inclusive index ranges, the shape, the voxel size and the realised physical box; read it with
`run.monitor_regions()`. Monitor files are full resolution — nothing is downsampled on download.

An engine-solved mode port (`create_monitor(modes=...)`) is a read-out into `ports.json`, not a
box: it writes no monitor file. A run whose only monitors are engine ports therefore keeps
`output.bin`, and `run.get_field()` returns the full field; `run.get_monitors()` skips engine ports.

## Mode sources and ports: conventions

One set of rules for `create_mode_source`, mode ports (`create_monitor(modes=...)`) and their
results (`Run.port_results()`, `Run.mode_sources()`):

- **Time and propagation.** Time dependence exp(−iωt); a forward wave travels as exp(+iβw) along
  +axis (the cut normal), β = 2π n_eff / λ.
- **The cut.** A voxel layer `plane_index` normal to `axis`, in the cyclic frame normal x → (u, v) =
  (y, z), y → (z, x), z → (x, y). `window = (u0, u1, v0, v1)` in voxels on the cut, end exclusive;
  None = the whole face. TE ('u') has its transverse E mostly along u, TM ('v') along v.
- **Which mode.** Among the guided modes of the family, by `order` (0 = highest n_eff), or the one
  nearest `target_neff`. Today the engine solves the **FD mode** (finite-difference full-vector,
  Fallahkhair, Li, Murphy 2008); the **PS-operator mode** (the eigenmode of the engine's own
  pseudo-spectral discretisation, which it propagates unchanged) becomes its default without an API
  change. An FD mode is not exactly an eigenvector of the engine's operator: delivered power and
  n_eff come out a few tenths of a percent to a few percent off.
- **Amplitude.** A source's amplitude A is relative to its own mode's unit power: |A|² is the power
  launched, arg A the phase. Several sources are set relative to one another by their A. No power
  unit appears anywhere.
- **Phase reference.** A source's phase is referred to its cut layer (the drive ends there); a
  port's to its cut layer (the centre of its fitted window).
- **Reading.** A port reports, per mode, a+ (towards +axis) and a− with |a±|² in the same unit, so a
  source with A = 1 reads a+ = 1 at a port on the same uniform guide, and transmission is |a+|²/|A|².
  The port's modes are fitted together on every plane of a window of straight guide.
- **Choosing a mode before running.** `setup.solve_modes()` (or `submit(setup, solve_modes_only=True)`
  then `run.modes()`) builds the permittivity on the compute node and lists, for every engine Mode
  source and every mode of every engine port, all the modes the engine finds on that cut (n_eff, TE/TM,
  energy shares, confinement, edge fraction, thumbnails) and `Selected`, the one the cut's `order` /
  `target_neff` picks: what a run would launch or read. No field is solved; it is priced as one
  iteration and leaves the version editable. A source is solved where its drive is centred (behind the
  cut), as the run launches it. Needs 1.19.0 compute nodes (`EngineModeSolve:Cpp`).
- **Limits.** One voxel size on all axes; lossless cuts only (a cut crossing a lossy material is
  refused on the node, because the engine's FD solve would use Re(ε) and launch the lossless guide's
  mode: use the Studio solver for lossy guides); a compute node advertising `EngineModeSource` /
  `EngineModePort`.

## Cost before upload

`client.preflight_check(..., max_iterations=n)` (called for you by `simulate*`, `submit` and
`execute_via_api`) returns a `cost` block on the cloud server: the upper-bound compute-token
cost at the run's iteration cap (voxels × iterations × field components × rate), your remaining
balance and whether the submit would be allowed. The run is charged for the iterations it
actually takes. The high-level calls stop before uploading anything when the cost is refused.
`client.get_quota()` returns the balance; `client.estimate_cost(project_id, version_id)` prices a
saved version.

## Errors and warnings

Every `RayfosAPIError` message carries the server's full detail: the message, each
`errors[]`/`warnings[]` entry and, for a quota refusal, the estimated cost and remaining balance.
A pixel above the Nyquist limit in the highest-index medium (half the wavelength there) is warned
about; the solver's own grid guidance is lambda/4 to lambda/8 in the medium.
`run.status()["commandStatus"]["engine"]` names the engine the node actually ran (`"Cpp"` or
`"Python"`), also for `engine="Any"`.

See `CHANGELOG.md` for what each version added. Issues and feature requests: support@rayfos.com.
