# Quickstart

This guide walks you from zero to a running campaign with monitoring UI.
It covers both **local** (workstation/server) and **Slurm** (HPC cluster) setups.

If you haven't read [Core concepts](/concepts) yet, do it first: it takes 5
minutes and will make this page much clearer.

This guide uses code_saturne. For code_aster, the steps are the same with
`solver = "code_aster"` in `csauto.toml`; [examples/codeaster-cube](https://github.com/simvia-tech/csauto/blob/main/examples/codeaster-cube/README.md)
is a complete code_aster campaign.

---

## Prerequisites

- Python 3.11+
- csauto installed and the `csauto` alias configured (see [Installation](/installation))
- A working code_saturne runtime (one of):
  - `native`: `code_saturne` binary installed and in `PATH`, or path set via `solver_bin`
  - `singularity`: Apptainer or Singularity + a `.sif` image file
  - `docker`: Docker engine running (the image defaults to `simvia/code_saturne`)

For Slurm: `sbatch`, `squeue`, `scancel` in `PATH`.

---

## 1. Project structure

Organize your campaign files like this:

```
my-campaign/
├── csauto.toml        ← runtime configuration
├── doe.csv            ← parameter table (one row = one case)
├── TEMPLATE/          ← your base case
│   └── DATA/
│       └── setup.xml
│       └── run.cfg
│   └── SRC/
│       └── *.cpp
└── RUNS/              ← generated by csauto (do not version-control this)
```

Keep `RESU/` out of `TEMPLATE/`. It is generated under each case in `RUNS/`
during execution.

---

## 2. Configuration (`csauto.toml`)

Create `csauto.toml` in your campaign directory.

**Local / workstation:**

```toml
runtime = "native"
solver_bin = "/opt/code_saturne/bin/code_saturne"
use_slurm = false
max_parallel = 2

host = "127.0.0.1"
port = 8000
```

**HPC with Slurm:**

```toml
runtime = "native"
solver_bin = "/opt/code_saturne/bin/code_saturne"

use_slurm = true
mpi_exec_options = "--mca btl vader,self,tcp --bind-to core"
max_parallel = 20

host = "127.0.0.1"
port = 8000
```

**Docker:**

```toml
runtime = "docker"
docker_image = "simvia/code_saturne"   # optional: the default image for code_saturne
use_slurm = false
max_parallel = 2

host = "127.0.0.1"
port = 8000
```

`max_parallel` is the default of `csauto run --max-parallel`; in the web UI, the
Run dialog has its own **Max Parallel** field. See [config.md](/config) for
all available keys and their defaults.

---

## 3. Prepare the parameter table (`doe.csv`)

Create `doe.csv`. The header row defines your parameters. Each subsequent row
is one simulation case.

```csv
case_id,density_value,turbulence_model,ref_v
case0001,1.2,Spalart-Allmaras,0.5
case0002,1.0,Spalart-Allmaras,0.5
case0003,1.2,kwSST,0.8
case0004,1.0,kwSST,0.8
```

- `case_id` is optional: omit it and csauto will generate `case0001`, `case0002`, ...
- Column names must exactly match the placeholders you use in the template.

See [doe-format.md](/doe-format) for the full format specification.

---

## 4. Prepare the template

Take your existing code_saturne case and replace the values you want to vary
with **placeholders** using `{column_name}` syntax. csauto will substitute them
with the DOE values when generating each case.

Minimum required structure:

```
TEMPLATE/
└── DATA/
    └── setup.xml
```

Below are two real examples drawn from a `setup.xml`.

**Simple value substitution**: density is read from the DOE column `density_value`:

```xml
<property name="density" choice="constant" label="Density">
  <initial_value>{density_value}</initial_value>
</property>
```

**Conditional blocks**: the turbulence model section is included only when the
DOE column `turbulence_model` matches the condition. Only one block is active
per case:

```xml
<!-- IF turbulence_model == "Spalart-Allmaras" -->
<turbulence model="Spalart-Allmaras">
  <reference_velocity>0.5</reference_velocity>
  <variable name="nu_tilda" label="nu_tilda"/>
</turbulence>
<!-- ENDIF -->

<!-- IF turbulence_model == "kwSST" -->
<turbulence model="k-omega-SST">
  <reference_velocity>{ref_v}</reference_velocity>
  <variable name="k" label="k"/>
  <variable name="omega" label="omega"/>
</turbulence>
<!-- ENDIF -->
```

Note that `{ref_v}` is inside the `kwSST` block: it is only active (and
therefore required in the DOE) when `turbulence_model == "kwSST"`. For rows
where `turbulence_model` is `Spalart-Allmaras`, the entire block is dropped
and the value of `ref_v` is ignored.

You can also place placeholders in:
- `TEMPLATE/run.cfg`
- `TEMPLATE/SRC/*.cpp` (user subroutines)
- any other text file of the template

See [doe-format.md](/doe-format) for the full placeholder and IF block syntax.

---

## 5. Generate cases

> `prepare` is a terminal-only step: there is no UI equivalent. Run it from
> the directory that contains `doe.csv` and `TEMPLATE/`.

```bash
csauto prepare doe.csv TEMPLATE RUNS
```

Re-running the same command after appending rows to `doe.csv` adds the missing
cases, as long as the already generated cases still match the current DOE rows
and template content.

Expected output:

```
RUNS/
├── registry.json
├── campaign.json          ← the solver of this campaign (code_saturne)
├── case0001/
│   ├── DATA/setup.xml     ← {density_value} replaced with 1.2, etc.
│   └── doe_row.csv        ← the DOE values used for this case
├── case0002/
├── case0003/
└── case0004/
```

If anything is wrong (missing placeholder column, empty value, missing `setup.xml`),
csauto stops with an error naming the problem.

---

## 6. Validate before launching

> `doctor` is terminal-only (`csauto status` is the terminal view of the Status
> panel). Once it passes, everything else happens in the web UI.

```bash
csauto doctor RUNS
```

This checks that:
- the runtime is available (for Docker, the `docker` command; the image itself
  is not checked)
- case directories have the expected structure
- write access to `RUNS/` is available

Fix every `[FAIL]` before proceeding.

```bash
csauto status RUNS
```

All cases should appear with status `PREPARED`.

---

> **Setup complete.** Steps 5 and 6 are the only terminal-only steps in the
> workflow. From here, the web UI is your primary interface for launching,
> monitoring, restarting, and cleaning cases.

---

## 7. Open the web UI

Start the UI server:

```bash
csauto serve RUNS --host 127.0.0.1 --port 8000
```

This uses the primary FastAPI server.

Open [http://127.0.0.1:8000](http://127.0.0.1:8000).

**On a remote server or HPC cluster**, create an SSH tunnel from your laptop first:

```bash
ssh -L 8000:127.0.0.1:8000 your-server
```

Then open [http://127.0.0.1:8000](http://127.0.0.1:8000) on your laptop.

The web UI is the recommended way to operate your campaign from this point on.
See [web-ui.md](/web-ui) for the full guide.

---

## 8. Launch runs from the UI

In the **Status** panel, all your `PREPARED` cases appear in the table.

1. Select all cases: `Ctrl/Cmd + A`
2. Click **Run**
3. Fill in the popup:
   - **n**: MPI ranks per case (e.g. `4`)
   - **nt**: OpenMP threads per rank (e.g. `2`)
   - **Max Parallel**: how many cases run at the same time (e.g. `2`; left empty,
     local runs are capped to `cpu_count // (n * nt)` at once, a scheduler receives every selected case)
4. Click **Run** in the popup

Cases move to `RUNNING`. The case next in line shows `PENDING` while it waits for
a free slot, and the others keep their status until their turn. The table
refreshes automatically.

**On a Slurm cluster**, the same UI flow applies: each case is submitted via
`sbatch` under the hood. You can verify with `squeue -u "$USER"` in the terminal.

### Alternative: launch from the command line

If you prefer the terminal, the `run` command is equivalent:

```bash
# Local
csauto run RUNS --n 4 --nt 2 --max-parallel 2

# Slurm (with use_slurm = true in csauto.toml)
csauto run RUNS --n 64 --nt 1 --max-parallel 20

# Specific cases only
csauto run RUNS --n 4 --nt 2 --case case0002 --case case0003

# Re-launch only failed cases
csauto run RUNS --n 4 --nt 2 --resume
```

---

## 9. Daily workflow from the UI

Once cases are running, everything can be done from the browser:

- **Status panel**: monitor iteration count, duration, disk usage per case
- **Residuals Plot**: inspect solver convergence curves
- **Log Tail**: stream the solver's log live (`run_solver.log`; select case → Log Tail tab)
- **Recent Errors**: scan for errors and warnings after a case fails
- **Restart**: restart from checkpoint without touching any files
- **Kill**: stop a running case immediately

For terminal-based monitoring:

```bash
# Check status table
csauto status RUNS

# Watch the solver's log in real time
csauto tail RUNS --case case0001

# Export residuals as CSV + SVG
csauto residuals RUNS --case case0001 --out residuals.csv --plot residuals.svg
```

---

## 10. Cleanup

In the **Status** panel, select the cases you want to clean and click
**Clean**. A popup lets you choose which RESU runs to keep or delete. Clean also
cuts the solver's logs over 50 MB down to their last 50 MB and removes
`.csauto.cid`. Running and pending cases are left alone.

### Alternative: command line

Always preview first with `--dry-run`:

```bash
csauto cleanup RUNS --prune-resu --keep-last 1 --max-log-mb 100 --dry-run
```

Apply when satisfied:

```bash
csauto cleanup RUNS --prune-resu --keep-last 1 --max-log-mb 100 --clear-cid
```

This keeps the most recent RESU directory per case and truncates logs above the
size limit.

---

## If something goes wrong

```bash
csauto doctor RUNS
```

Then check [troubleshooting.md](/troubleshooting) for error message → fix mappings.
