Skip to main content

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 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:

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:

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. See the measured PPO results and KSTAR assumptions and numerical limits. 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, and the historical KAIROS installation record is in 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.

The same workflow is available without a display:

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:

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:

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:

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:

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 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

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:

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 tests the installed package in PBS. Its current-overhaul result must be verified on KAIROS independently of the historical test recorded in KAIROS.md.

Metadata

Release files for craft-tokamak 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for craft-tokamak 0.1.0
File Size Uploaded Provenance Actions
craft_tokamak-0.1.0.tar.gz 1.8 MB Without provenance Details for craft_tokamak-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for craft-tokamak 0.1.0
File Interpreter ABI Platform Actions
craft_tokamak-0.1.0-py3-none-any.whl Python 3 none any Details for craft_tokamak-0.1.0-py3-none-any.whl

Total release size: 3.7 MB

Release files / craft_tokamak-0.1.0.tar.gz

Download URL craft_tokamak-0.1.0.tar.gz
Size 1.8 MB
Tags Source
SHA-256 checksum
How to use checksums
3fb12d3ea1b7e33242bc2d2212146233535b29443b62207e7179aa93244009dd
BLAKE2b-256 checksum
How to use checksums
6717032ee22d1760b3819b688e4b288cfca06c12779ce5d764e28041abe99347
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.7

Release files / craft_tokamak-0.1.0-py3-none-any.whl

Download URL craft_tokamak-0.1.0-py3-none-any.whl
Size 1.9 MB
Tags Python 3
SHA-256 checksum
How to use checksums
8fb9ef3ab6dd8bf454948dc6ad418c979e9c6d4da91f1fd34b9697f4deffe613
BLAKE2b-256 checksum
How to use checksums
8f15214c678485e64edb11b463b7bb6d7ec59668cb4f9a86866c88da510aba71
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.7

Security for craft-tokamak 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page