Metadata-Version: 2.4
Name: craft-tokamak
Version: 0.1.0
Summary: CRAFT: Control with Reinforcement learning And Feedback for Tokamaks (TORAX-based)
Author: JangWoo Choi, Jaemin Seo
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: torax==1.0.3
Requires-Dist: gymtorax>=1.0
Requires-Dist: gymnasium>=1.0
Requires-Dist: stable-baselines3>=2.3
Requires-Dist: numpy
Requires-Dist: pyyaml
Requires-Dist: freeqdsk
Requires-Dist: h5netcdf
Provides-Extra: tokamaker
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"

# CRAFT — Control with Reinforcement learning And Feedback for Tokamaks

CRAFT builds reinforcement-learning feedback experiments around TORAX 1.0.3.
An experiment specifies the plasma model, actions, observations, tracked signals,
reward and training budget. A local Tk GUI and the command line use the same YAML
configuration and validation. Numerical jobs run on the execution host; the GUI
stays on the workstation.

The default is a neutral draft with no selected geometry, actions, observations
or targets. [examples/Iter baseline scenario.yaml](<examples/Iter baseline scenario.yaml>) provides one W/q95
example with BGB transport, KBM pedestal scaling and TokaMaker equilibrium.

## Install and start

Use a Python environment compatible with the pinned numerical dependencies:

```bash
python -m pip install -e .
craft init my_experiment
```

Run `craft init` inside an empty directory to use that directory, or
`craft init my_experiment` to create a new one.

`init` creates a workspace: `workspace.yaml`, `experiment.yaml` (a neutral draft, or the
research experiment with `--preset research`), `plant/` presets, `model/` with the bundled
trained runs, `scenarios/` with the research scenario lists, `module/` plugin examples and
`runs/` for outputs.

For the research example:

```bash
craft init my_research --no-gui
craft check --config "my_research/plant/Iter baseline scenario.yaml"
craft gui --workspace my_research
```

An additional repository example is [a provisional KSTAR 18437 thermal-beta proxy](examples/kstar_18437_proxy.yaml).
See the [measured PPO results](docs/RESEARCH_PPO_20261024.md) and
[KSTAR assumptions and numerical limits](docs/KSTAR_OPEN_LOOP_20261023.md).
`craft init` copies the environment examples to `plant/` and the measured
102,400-step model as `model/Iter baseline PPO`. Model copies are independent
of the bundled originals; scratch files and evaluation results go under `runs/`.
`module/` contains a copyable `modules_api.py` template plus KBM pedestal and
TokaMaker examples. Edit selected source in the GUI's Python modules page;
loaded equilibrium models and their parameters are selectable in Geometry.
The KSTAR example is a calibrated H-mode proxy, not experimental validation.
An additional `KSTAR H-mode - TokaMaker KBM.yaml` example uses the actual
equilibrium and pedestal API modules for a shot-7081-inspired stationary
scenario. Its adjacent provenance JSON includes the cited measurements,
assumed inputs and numerical refinement results; it is not an experimental
reconstruction or an L-H transition model.

**Geometry presets.** With the TokaMaker equilibrium active, Geometry → *Requested plasma
shape* offers a **Geometry preset** list (`templates/geometry_presets/*.yaml`): *ITER baseline*
(the research preset's shape) and *KSTAR #43187 (EFIT04-matched)* (R 1.8 m, a 0.44 m, δ 0.45,
B₀ 1.89 T, κ command 1.85; matches EFIT04 at 6-13 s: q95 4.56, κ 1.81, V 11.8 m³; Miller
boundary without X-point). A preset sets the shape, mesh and first-solve pressure, the initial
value and range of the Ip and κ commands, and the machine values of a KBM pedestal together;
transport, sources and targets are unchanged. From Python:
`craft.geometry_presets.apply_geometry_preset(config_mapping, "KSTAR 43187")`.

Choose **Experiment preset** and open `Iter baseline scenario.yaml`. **Plant response test**
loads a preset's saved actions, accepts their absolute values over time, and
plots the environment response without a policy. **Resume training**
continues a checkpoint; **Evaluate trained model** tests a saved policy. Both
list saved models from the directory configured at initialization, excluding demos and work folders. **Blank experiment**
starts an empty draft. Existing `preset: research`, `--preset research` and
`--plant cgm` configurations remain supported for compatibility. The research example
requires OpenFUSIONToolkit/TokaMaker on the execution host; it is not a
machine-neutral physics example. Installation details are in
[SERVERS.md](docs/SERVERS.md), and the historical KAIROS installation record is
in [KAIROS.md](docs/KAIROS.md).

## One experiment, prepared jobs

The Start gallery creates or opens experiments. One experiment document has
checklist navigation for **Overview**, **Environment**, **Agent** and **Training**.
Evaluation settings appear when opening a saved policy through **Evaluate trained model**.
Components belong under Environment; targets and Reward &
termination belong under Agent. The Jobs panel holds prepared jobs. Preparing a
job freezes its settings; later experiment edits require a new preparation to
affect that job. See [GUI.md](docs/GUI.md).

The same workflow is available without a display:

```bash
craft components
craft check --config "my_research/plant/Iter baseline scenario.yaml" --import
craft job --config "my_research/plant/Iter baseline scenario.yaml" --pbs \
  --workdir /scratch/your_account/my_research/plant \
  --queue debug --walltime 00:10:00 --cpus 48 \
  --python /home/your_account/craft/.venv/bin/python
```

`check` validates configuration, component ownership and job prerequisites.
`--import` also checks component factories in a separate process; it does not
run a numerical episode. `job` writes a YAML snapshot, a provenance manifest and a PBS script, or a shell
script without `--pbs`. It does not submit the job. Add `--model RUN` for a
saved-policy evaluation job. PBS export rejects Windows paths and requires a
`/scratch/…` workspace. Copy the snapshot, script and referenced assets there,
preserving their relative layout; install required component packages on the
execution host.

Inside a compute allocation:

```bash
craft train --config "my_research/plant/Iter baseline scenario.yaml"
craft train --resume "my_research/model/Iter baseline scenario" --episodes 5000
craft eval --model "my_research/model/Iter baseline scenario"
craft simulate --config "my_research/plant/Iter baseline scenario.yaml" --command P_nbi=50e6
craft plot path/to/trajectory.csv --out trajectory.png
craft plot runs/eval/a/episode_00 runs/eval/b/episode_00 --out compare.png --panel W_thermal_total --label A --label B
```

Giving `craft plot` several results (`trajectory.csv`, `torax.nc` or episode folders, mixed) overlays
them on one graph: one subplot per `--panel` signal, one line per result, `target.*` setpoints dashed.
Labels default to the folder names. The same view opens from **Compare selected…** in the
`batch_summary.json` / `plant_response_summary.json` result window.

`python -m craft` provides the same commands. Each has `--help`. The training
budget is **total episode-equivalent timesteps**: episodes × steps per episode,
including completed timesteps on resume. CPU allocation and parallel environment
count are separate settings. CRAFT parallelizes environments on one node;
requesting additional nodes does not distribute training across them.

## Timing, signals and reward

One agent step spans `plant.numerics.fixed_dt` seconds. The episode lasts
`plant.numerics.t_final`; their ratio must be an integer. TORAX can take internal
solver steps during a control interval. An action's `step` is its largest command
change per agent step, in physical units.

Targets are scalar TORAX outputs in native units:

```yaml
targets:
  channels:
    T_e_volume_avg: {min: 4.0, max: 6.0, scale: 2.0}
```

A target's `scale` is the absolute tracking error at which its reward factor is
0.1. Reward is the product of the channel factors at each control step. Failure
rewards and physical termination bounds are separate settings. Logging a metric
does not add an observation or a reward objective. Changing action order,
observation order or target channels requires a compatible new policy.

Targets are sampled once per episode and held unless `targets.sampling` selects
fixed, step or random-walk requests. `targets.frontier` can cap one channel as a
function of another. Explicit evaluation trajectories must cover every selected
channel:

```bash
craft eval --model "my_research/model/Iter baseline scenario" \
  --channel W_thermal_total=0:200e6,50:200e6,50:300e6 \
  --channel q95=0:3.3
```

Times are seconds; repeated times encode a jump, and distinct times interpolate
linearly. Thermal energy is in J and heating power in W. `--command NAME=VALUE`
and `--initial NAME=VALUE` refer to the experiment's actuator names.

## Configuration and components

Precedence is neutral defaults, selected preset, saved run when applicable,
explicit plant selection, repeated `--config` overlays, then `--set` and shortcut
flags. A plant file replaces the plant; a partial plant mapping overrides fields.
A complete named plant mapping replaces the plant. Paths are anchored to the YAML
file supplying them. Runtime saved configurations use resolved paths; job export
converts paths inside the experiment back to relative paths for transfer.

`plant` contains TORAX settings. External coupling belongs under `components`,
with typed parameters and declared input/output ownership:

```yaml
preset: research
components:
  pedestal:
    use: KBM_scaling
    parameters:
      C_ped: 1.3
train:
  episodes: 100
  device: cpu
  n_envs: 1
  cpu_count: 4
  save_dir: runs/first
```

This overlays the research preset, which supplies the remaining pedestal
parameters. `--set components.pedestal.parameters.C_ped=1.3` is equivalent.
[COMPONENTS.md](docs/COMPONENTS.md) covers local components, installed entry
points, ownership, cadence and transport integration. Older adapters and input
providers are supported through conversion wrappers; new extensions should use
the Component API.

Older non-TORAX selectors, W/q95 target/reward keys and evaluation aliases are
converted on load by `config.canonicalize`, with a deprecation warning when
conversion is needed. Subsequent saves use the canonical configuration, which
is the only form used by the runtime.

## Results and reproducibility

Training writes `config.yaml`, `final_model.zip`, `vecnormalize.pkl`,
`rewards.csv` and `plugin_manifest.json`; SAC/TD3 also save their replay buffer.
Resume preserves `config.yaml` and records permitted runtime changes in
`resume_config.yaml`. Changing physics or learning settings requires a new run.

Simulation/evaluation write `trajectory.csv`, `summary.json` and `config.yaml`.
CSV columns include `target.<signal>`, `measured.<signal>`, `command.<action>` and
`realised.<action>`. The viewer also reads older MJ/MW-based trajectories.
`craft plot` saves a chart without opening Tk.

Named `eval.scenarios` support repetitions, trajectories and measurement bias.
Bias affects the policy observation before normalization; physical state,
reward and termination use the true output. Scenarios preserve the trained
interface and run sequentially in separate directories. `batch_summary.json`
records status; it does not automatically resume interrupted batches. Existing
result directories are rejected rather than overwritten.

## Python API and verification

```python
from craft import load_config, train, evaluate, simulate, make_env

cfg = load_config("my_research/plant/Iter baseline scenario.yaml")
run_dir = train(cfg)
```

Functions share the CLI implementation without parsing process arguments. Put
multiprocessing calls inside `if __name__ == "__main__":` in a custom script.
Importing `craft` does not initialize Torch, JAX or TORAX.

Run the standard suite from a checkout:

```bash
PYTHONPATH=src python -m pytest -q
```

In PowerShell, set `$env:PYTHONPATH = 'src'` before `python -m pytest -q`.
`pytest.ini` excludes numerical TORAX tests from the standard suite. Run those
explicitly in a suitable compute environment with `python -m pytest -m torax`.
[scripts/kairos_smoke.sh](scripts/kairos_smoke.sh) tests the installed package in
PBS. Its current-overhaul result must be verified on KAIROS independently of the
historical test recorded in [KAIROS.md](docs/KAIROS.md).
