<!-- TE10 Studio documentation: /docs/api/examples -->
# Examples

Save any of these as a `.py` file and run it with `te10 run <file>`. Each is complete and checks its
result against theory where there is one. Some use the project saved by an earlier one (noted in their
first lines).

| Script | Shows |
|---|---|
| [`01_waveguide.py`](#wr-90-waveguide-against-theory) | WR-90 waveguide against theory |
| [`02_microstrip.py`](#50-ω-microstrip-on-fr-4) | 50 Ω microstrip on FR-4 |
| [`03_width_sweep.py`](#parametric-sweep-of-a-trace-width) | Parametric sweep of a trace width |
| [`04_cavity_eigenmodes.py`](#cavity-resonances) | Cavity resonances |
| [`05_build123d_shapes.py`](#any-build123d-shape) | Any build123d shape |
| [`06_optimize_length.py`](#optimisation-with-scipy) | Optimisation with SciPy |
| [`07_cluster_submit_and_collect.py`](#submit-to-a-cluster-collect-later) | Submit to a cluster, collect later |
| [`08_palace_overrides.py`](#raw-solver-settings) | Raw solver settings |

## WR-90 waveguide against theory

`01_waveguide.py`: A parametric box, wave ports chosen by face, a driven solve, Touchstone output, and a check of the S21 phase against the TE10 dispersion relation.

```python
"""WR-90 waveguide: S-parameters vs. the TE10 dispersion relation, written to Touchstone."""
import math

import numpy as np

from te10_studio import api as em

a, b = 22.86, 10.16                                  # mm
prj = em.Project("wr90", units="mm")
prj.variables["L"] = "50mm"
air = prj.modeler.box("Air", size=(a, b, "L"), origin=(-a / 2, -b / 2, 0))   # outer faces are PEC by default
prj.excitations.wave_port("P1", air.face("-z"))
prj.excitations.wave_port("P2", air.face("+z"))
setup = prj.setups.driven("S1", start=8, stop=12, step=0.5, order=2)

res = setup.solve(cores=4)
sp = res.s_parameters()
f = sp.frequencies_ghz * 1e9
beta = np.sqrt((2 * math.pi * f / 299792458.0) ** 2 - (math.pi / (a * 1e-3)) ** 2)
expected = np.degrees(-beta * prj.variables["L"])
err = (sp.get_phase_deg(2, 1) - expected + 180) % 360 - 180
print(f"|S11| max {sp.get_db(1, 1).max():.1f} dB, |S21| min {sp.get_db(2, 1).min():.3f} dB, phase error max {abs(err).max():.2f} deg")
print("Touchstone:", res.write_touchstone("wr90.s2p"))
prj.save("wr90.te10")
```

## 50 Ω microstrip on FR-4

`02_microstrip.py`: Variables and expressions, materials, mesh priority, and wave ports that span the substrate and the air. Prints the effective permittivity from the S21 phase.

```python
"""50-ohm microstrip on FR4 with wave ports spanning substrate and air; effective permittivity."""
import math

import numpy as np

from te10_studio import api as em

prj = em.Project("microstrip", units="mm")
for name, value in {"h": "1.6mm", "w": "3mm", "t": "0.035mm", "L": "20mm"}.items():
    prj.variables[name] = value
width, air_h = "10*w", "8*h"
sub = prj.modeler.box("Substrate", size=(width, "L", "h"), origin=("-5*w", 0, 0), material="FR4")
air = prj.modeler.box("Air", size=(width, "L", air_h), origin=("-5*w", 0, "h"))
trace = prj.modeler.box("Trace", size=("w", "L", "t"), origin=("-w/2", 0, "h"), material="copper", priority=1)

# A port covers the whole cross-section at each end: the substrate face and the air face.
prj.excitations.wave_port("P1", [sub.face("-y"), air.face("-y")])
prj.excitations.wave_port("P2", [sub.face("+y"), air.face("+y")])
setup = prj.setups.driven("S1", start=1, stop=2, step=1, order=2)

res = setup.solve(cores=4)
sp = res.s_parameters()
f = sp.frequencies_ghz * 1e9
phase = np.unwrap(np.radians(sp.get_phase_deg(2, 1)))
eps_eff = (-phase / (2 * math.pi * f / 299792458.0 * prj.variables["L"])) ** 2
for fi, e in zip(sp.frequencies_ghz, eps_eff):
    print(f"{fi:.1f} GHz: eps_eff = {e:.3f}")
prj.save("microstrip.te10")
```

## Parametric sweep of a trace width

`03_width_sweep.py`: One job with one result per width (an array job on a cluster). Uses the project saved by the microstrip example.

```python
"""Parametric sweep of the trace width: one job (an array job on a cluster), one result per width.

    te10 run 03_width_sweep.py                 # on this computer
    te10 run 03_width_sweep.py my-cluster      # on a cluster profile (Analysis > Cluster Profiles)
"""
import sys

from te10_studio import api as em

backend = sys.argv[1] if len(sys.argv) > 1 else "local"
prj = em.Project.open("microstrip.te10")          # made by 02_microstrip.py
job = prj.sweep({"w": ["2mm", "3mm", "4mm"]}, "S1", backend=backend, cores=4)
print(job, "->", job.wait(poll=5).value)
for res in job.results():
    sp = res.s_parameters()
    print(res.variables, f"|S11| at {sp.frequencies_ghz[-1]:.1f} GHz: {sp.get_db(1, 1)[-1]:.1f} dB")
prj.save("microstrip.te10")                        # the job is remembered (see `te10 jobs`)
```

## Cavity resonances

`04_cavity_eigenmodes.py`: An eigenmode solve of a PEC box, compared with the analytic resonances.

```python
"""Rectangular PEC cavity: the first resonances against the analytic formula."""
import math

from te10_studio import api as em

a, b, d = 22.86, 10.16, 30.0
prj = em.Project("cavity", units="mm")
prj.modeler.box("Air", size=(a, b, d))
setup = prj.setups.eigenmode("E1", modes=3, target="5GHz", order=2)
res = setup.solve(cores=4)

c0 = 299792458.0
analytic = sorted(c0 / 2 * math.sqrt((m / a) ** 2 + (n / b) ** 2 + (p / d) ** 2) * 1e3
                  for m in range(3) for n in range(3) for p in range(3)
                  if (p > 0 and (m or n)) or (p == 0 and m and n))[:3]
for (f, q), exact in zip(sorted(res.eigenmodes()), analytic):
    print(f"{f:.4f} GHz (analytic {exact / 1e9:.4f} GHz), Q = {q:.3g}")
```

## Any build123d shape

`05_build123d_shapes.py`: CAD made with build123d added with a material; booleans and transforms on API objects.

```python
"""Anything build123d can make goes into the model with modeler.add (drawn in project units)."""
import build123d as bd

from te10_studio import api as em

prj = em.Project("shapes", units="mm")
# A filleted, drilled block: build123d does the CAD, the API adds it with a material.
block = bd.Box(20, 12, 6)
block = bd.fillet(block.edges().filter_by(bd.Axis.Z), radius=2)
block -= bd.Cylinder(2, 6)
part = prj.modeler.add("Block", block, material="FR4")
print(part, f"volume {part.volume:.1f} mm^3")

# Booleans and transforms on API objects
pin = prj.modeler.cylinder("Pin", radius=1, height=10, origin=(6, 0, -2), material="copper")
pin.move((0, 2, 0))
prj.modeler["Block"].subtract(pin, keep_tools=True)
print([o.name for o in prj.modeler], prj.modeler["Block"].history)
prj.save("shapes.te10")
```

## Optimisation with SciPy

`06_optimize_length.py`: Tunes a waveguide length for −90° of S21 phase at 10 GHz; the geometry and ports follow the variable on every solve.

```python
"""Optimization loop: find the waveguide length that gives S21 phase -90 deg at 10 GHz (scipy)."""
from scipy.optimize import minimize_scalar

from te10_studio import api as em

a, b = 22.86, 10.16
prj = em.Project("tune", units="mm")
prj.variables["L"] = "20mm"
air = prj.modeler.box("Air", size=(a, b, "L"), origin=(-a / 2, -b / 2, 0))
prj.excitations.wave_port("P1", air.face("-z"))
prj.excitations.wave_port("P2", air.face("+z"))
setup = prj.setups.driven("S1", start=10, stop=10, step=1, order=2)


def cost(length_mm: float) -> float:
    prj.variables["L"] = f"{length_mm}mm"            # geometry and ports follow the variable
    phase = setup.solve(cores=4).s_parameters().get_phase_deg(2, 1)[0]
    err = (phase + 90 + 180) % 360 - 180
    print(f"L = {length_mm:.3f} mm -> phase {phase:.2f} deg")
    return err * err


best = minimize_scalar(cost, bounds=(5, 25), method="bounded", options={"xatol": 0.05})
print(f"Best L = {best.x:.3f} mm")
```

## Submit to a cluster, collect later

`07_cluster_submit_and_collect.py`: Submits and saves the project (which remembers the job); a second run collects the finished results.

```python
"""Submit a solve to a cluster and come back later for the results.

    te10 run 07_cluster_submit_and_collect.py submit my-cluster
    te10 run 07_cluster_submit_and_collect.py collect
"""
import sys

from te10_studio import api as em

prj = em.Project.open("wr90.te10")                 # made by 01_waveguide.py
if sys.argv[1:2] == ["submit"]:
    job = prj.setups["S1"].submit(backend=sys.argv[2], cores=64, walltime="01:00:00")
    print("submitted:", job)
    prj.save("wr90.te10")                          # remembers the job
else:
    for job in prj.jobs():
        print(job, job.status().value)
        if job.state.value == "completed":
            print("  ", job.result().write_touchstone(f"{job.record.name}.s2p"))
    prj.save("wr90.te10")
```

## Raw solver settings

`08_palace_overrides.py`: Palace options the API doesn't expose, merged into the generated configuration.

```python
"""Settings the API doesn't expose yet: raw Palace JSON merged into the generated config."""
from te10_studio import api as em

prj = em.Project.open("wr90.te10")                 # made by 01_waveguide.py
setup = prj.setups["S1"]
setup.palace_overrides = {"Solver": {"Linear": {"Tol": 1e-8, "MaxIts": 400}}}
res = setup.solve(cores=4)
print(res.s_parameters().get_db(2, 1))
```
