<!-- TE10 Studio documentation: /docs/api/setups-solving -->
# Setups and solving

## Creating setups

### `prj.setups.driven`

```python
prj.setups.driven(name, start, stop, step=None, points=None, sweep="uniform", order=2, cores=4,
                  linear_tol=None, save_fields="solution", far_field="solution", min_solved=None) -> Setup
```

A frequency-domain sweep. Frequencies are GHz as numbers, or strings with units.

| Parameter | Meaning |
|---|---|
| `start`, `stop` | The band. `start=0` adds a fitted DC point: the solver solves down to `min_solved` (default: chosen from the model) and the 0 Hz S-matrix is fitted from the lowest solves |
| `step` or `points` | A frequency step, or a number of points |
| `sweep` | `"uniform"`, `"adaptive"` or `"interpolating"` ([below](#frequency-sweeps)) |
| `order` | Element order: 1 fast, 2 accurate (default), 3 high accuracy |
| `cores` | Solver processes for local solves |
| `linear_tol` | The iterative solver's tolerance (default 1e-8). It bounds a preconditioned residual, not the S-parameter error |
| `save_fields`, `far_field` | `"solution"` (default: at the solution frequency, from the last adaptive pass), `"all"` (every sweep point: slow, and a full field set per point and excitation) or `"none"` |

### `prj.setups.eigenmode`

```python
prj.setups.eigenmode(name, modes=5, target="1GHz", order=2, cores=4) -> Setup
```

The `modes` resonances nearest `target`. Results: [`result.eigenmodes()`](/docs/api/results#eigenmodes).

### Looking up setups

`prj.setups["S1"]` returns a `Setup`; `prj.setups.names()` lists them.

## Setup

| Member | |
|---|---|
| `name` | The setup name |
| `solve(...)` | Run and wait; returns a [`Result`](/docs/api/results) |
| `submit(...)` | Start without waiting; returns a [`Job`](#jobs) |
| `estimate(backend="skypilot")` | What a cloud solve would run on and cost at most, without starting it |
| `palace_overrides` | Raw Palace JSON deep-merged into the generated configuration (still schema-checked) |
| `core` | The internal setup object, for the [settings below](#setup-attributes) |

### `Setup.solve`

```python
setup.solve(backend="local", cores=None, timeout=None, poll=2.0, max_cost=None, over_budget=False, **resources) -> Result
```

Meshes, solves and waits. `timeout` (seconds) raises if the job isn't done by then. Other parameters as
for `submit`.

### `Setup.submit`

```python
setup.submit(backend="local", cores=None, name=None, variations=None, max_cost=None, over_budget=False, **resources) -> Job
```

| Parameter | Meaning |
|---|---|
| `backend` | Where it runs ([backends](#backends)) |
| `cores` | Solver processes (MPI ranks) |
| `name` | The job's name (default: from the project and setup) |
| `variations` | A list of `{variable: value}` dicts: one case per dict (as `prj.sweep` builds) |
| `max_cost` | Cloud only: dollars. A job whose cost cap (price per hour × time limit) is above it isn't started |
| `over_budget` | Cloud only: start even when this month's AWS spend is over the account's AWS Budget |
| `**resources` | Override the cluster profile's defaults: `nodes`, `walltime` (`"01:00:00"`), `partition`, `account`, `modules`, `container`, `memory_gb`, `threads_per_rank`, `extra_directives` |

### Backends

| `backend=` | Runs |
|---|---|
| `"local"` | On this computer |
| a cluster profile name (or a `ClusterProfile`) | On that cluster, over SSH: Slurm, PBS, LSF, Grid Engine, HTCondor, Flux, or a plain host. See [Clusters and cloud](/docs/api/clusters-cloud) |
| `"here"` | On the cluster whose login node the script runs on (finds the scheduler itself) |
| `"skypilot"` | On an AWS machine sized and priced from the mesh, with the project's cloud settings |
| `("export", "slurm", "/folder")` | Writes a zip with the mesh, settings and a job script to submit by hand |

### Setup attributes

Set these on `setup.core` (they are what the app's Solver Setup window edits):

| Attribute | Default | Meaning |
|---|---|---|
| `amr_enabled` | `True` | Adaptive meshing |
| `max_delta_s` | `0.02` | Stop when the largest \|ΔS\| between passes is below this |
| `amr_converged_passes` | `1` | Passes in a row that must meet the target |
| `amr_min_passes` | `1` | Never stop before this many passes |
| `amr_max_levels` | `5` | Maximum refinements (passes − 1) |
| `amr_max_elements` | `0` | Maximum unknowns (0 = from this computer's memory) |
| `amr_solution_freq` | `0.0` | Hz; 0 = the highest sweep frequency |
| `amr_max_delta_freq_pct` | `1.0` | Eigenmode convergence: frequency change per pass, % |
| `amr_error_tol` | `0.01` | The solver's own error target (advanced) |
| `amr_uniform_levels` | `0` | Uniform refinements before adapting |
| `reuse_adapted_mesh` | `True` | Skip the passes when nothing that affects the mesh changed |
| `mesh_per_wavelength` | `0.0` | Elements per wavelength (0 = the default for the order) |
| `mesh_min_size`, `mesh_max_size` | `0.0` | Element size limits in metres (0 = none) |
| `linear_ksp_type`, `linear_tol`, `linear_max_its`, `linear_preconditioner` | `"GMRES"`, `1e-8`, `200`, `"Default"` | Linear solver |
| `frequency_sweep.fit_tol`, `frequency_sweep.fit_max_samples` | `1e-3`, `150` | Interpolating sweep |
| `eigen_num_modes`, `eigen_target_freq`, `eigen_tol`, `eigen_max_its` | | Eigenmode settings |

```python
setup = prj.setups.driven("S1", 0.1, 2, step=0.05)
setup.core.max_delta_s = 0.005        # electrically small: tighter target
setup.core.amr_min_passes = 3
```

### Raw Palace settings

```python
setup.palace_overrides = {"Solver": {"Linear": {"Tol": 1e-8, "MaxIts": 400}}}
```

The dict is deep-merged into the configuration TE10 generates for Palace, then checked against Palace's
schema. Use it for solver options TE10 has no setting for.

## Frequency sweeps

| `sweep=` | How | Use for |
|---|---|---|
| `"uniform"` | A full solve at every point | Few points, or a reference |
| `"adaptive"` | The solver's reduced-order model, evaluated at every point (wave-port modes too, with exact solves as a fallback) | Most sweeps, including sharply resonant designs |
| `"interpolating"` | About 40 solved points; every Sij fitted with one rational model (vector fitting), checked with extra solves until two rounds agree within `fit_tol` (\|ΔS\| ≤ 1e-3, or 0.01 dB / 0.1°) | Smooth broadband responses with many points |

The interpolating sweep writes `port-S.csv` at every requested point and `port-S-fit.json` (which points
were solved and which fitted, the final check error, the pole count, and whether the fit is passive). If it
doesn't converge within `fit_max_samples` solves, only the solved points are written. Below 60 points it
solves every point.

Projects with frequency-dependent (Djordjevic–Sarkar) materials are solved in sub-bands.

## Adaptive meshing

On by default. The mesh is refined at the solution frequency until max |ΔS| ≤ `max_delta_s` (eigenmode:
`amr_max_delta_freq_pct`), then the sweep runs once on that mesh. The per-pass table is in
`convergence.json` (in a job's case folder, or `logs/<setup>/` for solves from the app);
`te10_studio.solver.adaptive.load_report(path)` reads it.

Electrically short structures barely change between early passes even on a coarse mesh: give them a
smaller `max_delta_s` or a larger `amr_min_passes`.

**Reuse:** when nothing that affects the mesh changed since a setup's last solve (geometry, materials,
boundaries, ports, mesh rules, element order, solution frequency, adaptive settings), the next solve skips
the passes and sweeps on the earlier adapted mesh. Changing only the sweep, `save_fields` or `far_field`
keeps it. Scripted jobs look for a matching earlier job in the project's `jobs/` folder. Set
`setup.core.reuse_adapted_mesh = False` to adapt again.

Cluster and cloud jobs apply the same ΔS stop with a small watcher script shipped in the job package
(standard-library Python); without `python3` on the cluster, the solver's own error tolerance and the pass
limit stop the refinement.

## Jobs

`setup.submit()` and `prj.sweep()` return a `Job`; `prj.jobs()` lists the project's jobs (also those
started from the app). Save the project to remember a job.

| Member | Returns |
|---|---|
| `status()` | `em.JobState`, asking the backend |
| `state` | The last known `JobState` |
| `wait(poll=5.0, timeout=None)` | The final `JobState` |
| `logs(lines=200)` | The tail of the job's log, `str` |
| `cancel()` | |
| `fetch()` | Downloads the results; returns the local folder |
| `results(fetch=True)` | `list[Result]`, one per case (variation) |
| `result()` | The single `Result` |
| `cleanup()` | Cloud: deletes the job's machine (done automatically once `results()` has downloaded) |
| `estimate` | Cloud: the machine, price, model size and cost cap; the time and cost estimate once started |
| `record` | The internal job record (`record.name`, ...) |

`em.JobState` values: `PREPARED`, `PENDING`, `RUNNING`, `COMPLETED`, `FAILED`, `CANCELLED`, `UNKNOWN`
(`.value` is the lower-case string).

```python
job = prj.setups["S1"].submit(backend="mycluster", cores=64, walltime="01:00:00")
prj.save("model.te10")                 # remembers the job
state = job.wait(poll=30)
if state == em.JobState.COMPLETED:
    job.result().write_touchstone("model.s2p")
else:
    print(job.logs())
```

## Cloud solves

```python
setup = prj.setups["S1"]
print(setup.estimate())                       # machine, $/h, model size, time limit and cap
result = setup.solve(backend="skypilot", max_cost=2.0)
```

The machine is sized from the mesh (unless the project's cloud settings fix it) and priced before
anything starts. The machine is deleted after `results()` downloads; for a failed or cancelled job call
`job.cleanup()`. Connect an AWS account first: `te10 cloud connect`, or **Connect Cloud...** in the app.
See [Solving in the cloud](/docs/app/cloud).
