HomeFeaturesExamplesTutorialsHelpTheoryVerificationPricingContact
BoreTherm Online help

Command-line reference

Run boretherm-cli.exe --help from the extracted folder. The full maintained reference follows.

# boretherm-cli reference (CLI v2)

`boretherm-cli.exe` runs the BoreTherm core on project files for scripting, batch work and coupling
with other tools. It uses the same core as the GUI, so its numbers are the GUI's numbers. This page
is the reference; `boretherm-cli --help` and `boretherm-cli <command> --help` print the short form.

`boretherm-cli --help --json` (or `help <command> --json`, `<command> --help --json`) prints the command
table as one JSON document (`boretherm.help/1`: commands, options, exit codes, schema names) for
wrappers and AI agents. The guide for AI agents is `docs/agents.md`, shipped as `AGENTS.md` next to
`boretherm-cli.exe` together with a Claude Code skill in `sdk/agent/boretherm/`.

Plan: P12a in `docs/phase4/PLAN_PHASE4.md`. Source: `cli/` (the whole CLI runs through
`boretherm::cli::cliMain()` in `cli/cli.hpp`; `cli/main.cpp` only converts the command line).

## 1. Grammar

```
boretherm-cli <command> <project|-> [positionals] [options]
```

- One grammar for every command. Options may come before or after the positionals, and every
  valued option also accepts `--name=value`.
- `-` as the project reads the project JSON from standard input. Standard input can be used once
  per call (project, `--overrides -` or `run -`).
- A project can also be a legacy project file (`.dat`); it is imported first (classic-method compatibility
  options on). The import notes go to the text output, or to standard error with `--json`.
- Arguments are UTF-8 (paths with umlauts work). Standard output is binary: JSON and CSV written
  to it have LF line ends.
- Standard output holds one document: `--csv -` together with `--json` (to standard output) or with
  `--out -` is a usage error.

### Common options (every command)

| Option | Meaning |
|---|---|
| `--json [file\|-]` | Write the versioned JSON result (section 4). Without a file, or with `-`, the JSON goes to standard output and the text output is suppressed, so standard output holds exactly one JSON document. The token after `--json` is taken as its file only when the command's positionals are complete: for `trt` those of the subcommand (`trt import` / `trt evaluate`: the data or test file, `trt apply`: the project and the result file), so `trt evaluate --json test.trt.json` reads the test file and writes the JSON to standard output; for `schema` a schema name is never the file. `--json=file` is always unambiguous. The JSON file (and the error document) never replaces a file the command reads or writes (a positional, `--out`, `--csv`, `--project`, `--overrides`, `--data`, `--spec`, `--site`, `--dxf`, `--in`, `--import`, `--export`, `--price-list`, `--dts`, `--layout-csv`, `--vtu`, `--png`): naming one is a usage error (exit code 1) and the file is left as it was. |
| `--quiet`, `-q` | No text output, no notes, no progress. Errors still go to standard error; `--json` output is still written. |
| `--progress` | Progress lines on standard error: `PROGRESS 0.42 <stage>` (fraction 0..1 with two decimals, then a free-text stage). On by default when `--json` is given. |
| `--no-progress` | No progress lines. |
| `--help`, `-h` | Help of the command. |

### Project options (commands that take a project)

| Option | Meaning |
|---|---|
| `--set <id>=<value>` | Override one input. Repeatable. |
| `--overrides <file.json\|->` | Override several inputs from a JSON file. Repeatable. |
| `--strict` | Keys of the project file that BoreTherm does not read are errors (exit code 1) instead of notes (W6-audit-io; for scripted imports). |

`--set` and `--overrides` apply in command-line order; a later value wins. The JSON output lists
every override applied (`"overrides": [{"id", "value"}]`, SI values). An unknown id is an error
that names the id or key probably meant (`--set ground.conductivty=2` → `did you mean
"ground.conductivity"?`).

**`--set` changes only this run, except where a command writes the project it loaded.** These
commands save the changed values with the project they write, and say so in a `note:` line on
standard error (`the --set / --overrides changes (...) are saved in the project written to ...`; not
with `--quiet`):

| Command | Writes the project |
|---|---|
| `trt apply` | in place (the project argument) unless `--out <file\|->` or `--dry-run` |
| `loads generate-hourly\|per-year\|time-series\|generate-btes` | with `--out <file\|->` |
| `site-check`, `fill` | with `--out <file\|->` |
| `import-eed` | always (the converted project; applying `--set` before writing is its purpose) |

Every other command leaves the project file unchanged.

**What loading the project file noticed** (W6-audit-io, edge-case audit A6). Every command that
takes a project prints, as `note:` lines on standard error (not with `--quiet`; `validate` lists them
as problems instead):
- a key the program does not read, at its path in the file, with the key probably meant when one is
  close (case-insensitive edit distance): `"ground.conductivty" is not a key BoreTherm reads: it was
  ignored. Did you mean "ground.conductivity"?`. A key unknown in several items of an array is listed
  once (`"field[0].label" ... (in 16 items)`). Keys starting with `$`, `_` or `//` are annotations
  (`"$schema"`, `"_comment"`) and never listed;
- a consequential physical input missing from the file and filled with its default: ground
  conductivity, volumetric heat capacity, surface temperature and geothermal heat flux; borehole `H` and
  `rb` (`field[i]`); `flow.flowRate`; `fluid.kind` (and the mass fraction of a mixture); the monthly
  heating / cooling energies of monthly loads; `limits.TfMin` / `TfMax`
  (`"ground.conductivity" is not in the file ("ground.conductivty" was ignored): the default 2.5 W/(m K)
  is used instead.`);
- an older form read as its new form (the inclined layout types of plan P7).

Older and partial files load exactly as before (the same project, the same results). Without
`--strict` nothing is refused; with `--strict` an unknown key stops the command with
`strict mode: the file has 1 key(s) BoreTherm does not read: ground.conductivty (ground.conductivity?)`.

**Ids.** An id is either
1. a **parameter id** of the registry (`boretherm-cli params <project>` lists them with units and
   bounds), e.g. `ground.conductivity`, `borehole.H`, `layout.spacing`, `loads.heatingScale`,
   `ground.layer[2].conductivity`, `design.section[0].bottom` — the same ids studies and Monte Carlo
   use. The value is **SI** (`--set ground.volumetricHeatCapacity=2.2e6`), or a number followed by
   the parameter's display unit as `params` prints it
   (`--set "ground.volumetricHeatCapacity=2.2 MJ/(m3 K)"`, `--set "flow.flowRate=0.5 l/s"`), or by
   its SI unit as the schemas' `x-unit` name it (`--set "borehole.rb=0.08 m"`,
   `--set "limits.TfMin=5 degC"`, `--set "flow.flowRate=5e-4 m3/s"`). Units compare without spaces;
   `°C`, `degC`, `deg C` and `C` are the same, as are `°` and `deg`, `m³` and `m3`, `yr`, `a` and
   `years`. Values outside the registry's bounds are refused (exit code 1). Setting `layout.spacing`
   regenerates a generated layout, as in the GUI. An inclined generated layout (plan P25) adds
   `layout.inclination.tilt` (any mode), `layout.inclination.spread` (Arc) and
   `layout.inclination.azimuth` (Same direction, Radial outwards), in rad or with `°`
   (`--set "layout.inclination.tilt=20 °"`); or
2. a **key path of the project file** for anything else, e.g. `--set sizing.Hmax=400`,
   `--set settings.hourlyMethod=LoadAggregation`, `--set optimization.landLength=40`,
   `--set field[3].H=120`, `--set "loads.monthly.heating_MWh=[10,9,8,6,4,2,1,1,3,5,7,9]"`. The
   value is parsed as JSON unless the key holds text. The key must exist in the project file, or be
   a key the writer leaves out at its default value (e.g. `ground.temperatureModel`). The FEM
   g-function engine (theory.md §19) is switched on and tuned this way:
   `--set settings.gfunction.engine=FEM --set settings.fem.preset=Coarse`
   (`Auto` | `Coarse` | `Medium` | `Fine` | `VeryFine`; also `settings.fem.hMin`, `hAxial`, `hMax`, `growth`,
   `axisCells`, `refineRadius`, `minCellsPerLayer`, `layerCells`, `stepsPerLevel`, `solver`, ...).
   `settings.fem.element` chooses the mesh: `Auto` (default: hexahedra for vertical fields,
   tetrahedra as soon as a borehole is inclined), `Hex8` or `Tet4` (theory.md §19.13).
   The size of the ground block (theory.md §19.1): `settings.fem.domain` = `Auto` (default: the
   larger of 3 × the field's plan extent, 2 × the deepest borehole's depth and the heat-travel
   margin `marginFactor`·√(α t_end)) or `Custom`, which uses `settings.fem.domainWidthFactor`
   (1–20, default 3) and `settings.fem.domainDepthFactor` (1–10, default 2); the factors apply only
   with `Custom`, e.g. `--set settings.fem.domain=Custom --set settings.fem.domainWidthFactor=5`.
   The project file writes the three keys only when they differ from the defaults.
   **Layout keys** (`layout.*`; `layoutSpec.*` is accepted as the same key) regenerate a generated
   layout after the change, as in the GUI (a `layout.prototype.*` key gives every borehole the new
   value; other keys keep each borehole's own H, D and r_b). Plan P25 (theory.md §14.8): the head
   pattern `layout.type` (`Single`, `Line`, `LShape`, `L2Shape`, `UShape`, `OpenRectangle`,
   `Rectangle`, `Circle`, `Hexagonal`, `ConcentricRings`), its rotation `layout.orientation` [rad]
   and its inclination `layout.inclination.mode` = `Vertical` | `SameDirection` | `RadialOutwards`
   | `RadialFan` | `Arc` with `layout.inclination.tilt`, `spread`, `azimuth`, `arcAxis` [rad],
   `centre` = `FieldCentre` | `FirstHead` | `Point`, `cx`, `cy` [m], `centreBoreholeVertical`, e.g.
   `--set layout.type=Hexagonal --set layout.inclination.mode=RadialFan --set layout.inclination.tilt=0.35`.
   `layout.axisWarningDistance` [m] (default 1) is the axis distance below which `validate` and
   `simulate` warn. A custom layout (`layout.type` `Custom`, e.g. after `fill` or a DXF import) is
   never regenerated: a layout key other than `layout.type` and `layout.axisWarningDistance` is
   stored, and a `note:` says that the boreholes did not change (set `layout.type` to a generated
   layout first).
   **Energy piles** (theory.md §15.7): `--set design.energyPile=true`,
   `--set design.loopConnection=Series` (energy piles with two or more U-loops; otherwise `validate`
   warns and the setting is not saved), `--set design.pileMechanics.thermalExpansion=1.1e-5`,
   `--set design.pileMechanics.youngsModulus=3.3e10` [Pa]. The old types `InclinedRing`, `InclinedFan` and `InclinedArc` are read and
   converted (written as pattern + inclination).

Registry ids win over key paths when both exist (`settings.years` is both; the registry checks
its bounds).

**Overrides file** (`boretherm-cli schema overrides`):

```json
{ "ground.conductivity": 2.3, "ground.volumetricHeatCapacity": "2.4 MJ/(m3 K)", "sizing.Hmax": 250 }
```

Also accepted: `{"overrides": {...}}` and `[{"id": "...", "value": ...}, ...]`.

## 2. Commands

| Command | Purpose | Exit codes besides 0/1/4 |
|---|---|---|
| `example <out.boretherm\|->` | Write the built-in example project (`-`: to standard output) | |
| `simulate <project> [--csv f] [--hourly]` | Mean fluid temperatures over the period. `--csv` writes the monthly results (and `<f>_hourly.csv` in hourly mode); `--hourly` adds the hourly series to the JSON. Unequal lengths: the range and the mean (`field.Hmin` / `Hmax` in the JSON) | 2 limits violated |
| `size <project> [--exact] [--trace] [--eed] [--3d]` | Required borehole length. `--3d` (W7-fem-combined): with the selected direct 3D model of Full FEM (`settings.fem.level=Full`), every trial length a full 3D run, starting at the 2D size (theory §19.26.6); `--exact`: exact g-function at every iteration; `--trace`: list the lengths tried; `--eed`: classic-method compatibility preset (on a layered project a note says that the layers are still used). Unequal lengths: `H` is the mean, the lengths are scaled in proportion (`Hmin` / `Hmax`) | 3 not converged |
| `optimize <project> [--csv f] [--site [file]] [site options] [--price-list f.btcost]` | Best layouts on the plot (the project's optimization setup), or inside the drilling areas of the site plan with `--site` (section 11). The cost of a candidate is the project's cost estimate; `--price-list`: the detailed cost model with this list (section 19) | 3 no feasible layout: the `optimize` document with `status` `noCandidate`, no candidates and the reason in `message` |
| `cost <project> [--price-list f.btcost] [--simple\|--detailed] [--csv f\|-]` | Cost estimate of the project's field: simple or detailed (itemised) model, group totals, net, contingency, VAT, gross, indicators (section 19) | |
| `compare <project> [--data f.json] [--scenario low\|central\|high] [--variants id,...]` | Same-service heating/cooling comparison: full-cost annuity, heat/cold LCOH, SPF, annual ecological metrics and source-dated assumptions (section 21) | |
| `heatpump <project> [--size] [--no-candidates]` | Heat pump requirement sheet (capacity at the design point, B0/W35, evaporator, source and sink temperatures, brine flow and pump head, part load, buffer, cooling, SPF and VDI 4650 JAZ) and the check of the candidates in `heatPumpSelection.candidates` with a coupled rerun each (section 22) | 2 candidates checked and none meets the requirements |
| `gfunction <project> [--csv f] [grid]` | g-function of the field (text table; `--csv` in the v1 layout `lnTts,t_s,g`) | |
| `export-gfunction <project> [<out>\|--out f] [--format csv\|json\|modelica] [grid]` | g-function table for other tools (section 5) | |
| `import-eed <file.dat> <out.boretherm\|-> [--layout-csv f]` | Convert a legacy project file; `--set`/`--overrides` apply before writing | |
| `params <project>` | Parameter registry: ids, labels, units, values, bounds | |
| `study <project> --param ... [--mode size\|simulate] [--oat] [--csv f]` | Parametric study (full grid of up to 3 axes, or one at a time). `--param id=min:max:step` or `id=v1,v2,...` in **display units**; a value outside the parameter's bounds (`params`) is a usage error (exit code 1) before anything runs; without `--param` the study stored in the project runs | 3 a run failed |
| `montecarlo <project> [--spec f] [--samples N] [--seed S] [--sampling lhs\|random] [--mode ...] [--csv f] [--runs]` | Monte Carlo over uncertain inputs. The spec file is the project's `"monteCarlo"` object (SI) or a whole project file; `--runs` adds every run to the JSON | 3 every run failed |
| `validate <project> [--no-simulate] [--strict]` | List the problems of a project (section 6) | 1 errors found |
| `schema [<name>]` | JSON Schema of a document; without a name, list the names | |
| `run <jobs.json\|-> [--jobs N]` | Batch of jobs, N in parallel (section 7) | largest code of the jobs |
| `site-check <project> [site options] [--out f]` | Check the site plan and every borehole against it; `--out` writes the project with the (converted) site plan (section 11) | 1 invalid site plan; 2 a borehole violates it |
| `fill <project> --spacing B1[,B2] [--pattern ...] [site options] [--out f] [--csv f]` | Fill the drilling areas with boreholes: grid, staggered, rowwise, perimeter (section 11) | 3 no position fits |
| `trt import\|evaluate\|apply ...` | Thermal response test: import a rig file, evaluate it (quality checks, M1/M2/M3/M5, uncertainty), apply the result to a project (section 10) | 2 a quality check failed (evaluate); 3 no method gave a result |
| `timeseries <project> --in <inputs.csv\|-> [--out f] [--kelvin] [--heat-rate] [stepper options]` | Replay a fluid-side input series (t, T_in, m_flow) through the co-simulation stepper; outputs T_out, Q_flow, T_f, T_b, dp per row (section 12) | |
| `cosim <project> --stdio [--kelvin] [stepper options]` | The co-simulation stepper behind a line protocol on standard input/output: `STEP t dt T_in m_flow` -> `OK T_out Q_flow T_f T_b dp` (section 12) | |
| `fmu info <file.fmu>` | An FMU's identity, SHA-256, capabilities, units and variables; no FMU code runs (section 13) | 3 the FMU cannot be used |
| `simulate-fmu <project> [--csv f] [--series] [run options]` | The project's co-simulation system: borehole field, Co-Simulation FMUs and sources connected port to port (section 13) | 2 limits violated |
| `size-fmu <project> [--jobs N] [run options]` | Borehole length with the co-simulation in the loop (section 13) | 3 not converged |
| `export-fmu <project> [<out.fmu>\|--out f] [--model m] [options]` | The borehole field as an FMI 2.0 Co-Simulation FMU for 64-bit Windows (section 15) | |
| `export-modelica <project> [--target buildings\|aixlib\|ibpsa] [--out f\|-]` | A borefield record for the borefield models of Buildings, AixLib or IBPSA (section 15) | 1 a feature the library cannot represent (listed) |
| `pack <project> [<out.zip>\|--out f] [--trt-data]` | One zip with the project and every file it links (section 14) | |
| `unpack <pack.zip> [<folder>\|--out d] [--overwrite]` | Unpack a pack into a folder and check the linked files (section 14) | |
| `fem-field <project> [--times 1,10,25] [--out d] [--csv f] [--ascii] [--memory MB] [--no-cache]` | The FEM ground temperature field at chosen times as VTK files for ParaView, and the evaluation of property lines, neighbours, isotherms and the plume as CSV; reuses saved or cached FEM results of the same inputs (section 17) | |
| `plume <project> [--source 2d\|3d\|both] [--thresholds -3,3] [--time end\|worst\|<years>] [--depth avg\|<m>] [--png f] [--csv f]` | The thermal plume on the site plan: isotherm areas, reach, downstream length and width, clearances to the property lines and evaluation objects (crossings), first crossing; 2D analytic, 3D FEM or both (section 18) | |
| `loads generate-hourly\|per-year\|time-series\|generate-btes <project> ...` | Hourly loads from the monthly loads; monthly loads per year (growth, step change, CSV import / export); time-series import with mass flow, flow basis and direction column; seasonal BTES operation (section 16) | |

**Time grid** (`gfunction`, `export-gfunction`): by default 50 points from t = 1 h to
ln(t/t_s) = 3, log-spaced. `--points N` (2..10000), `--tmin <s>` or `--lnmin <x>`, `--tmax <s>` or
`--lnmax <x>`.

**Boundary condition** (`gfunction`, `export-gfunction`): these commands compute the g-function without the
borehole resistances. `UFT` is then solved with R = 0, which is the `UBWT` g-function; the commands say so
(text: a `WARNING:` line, `export-gfunction`: a note on standard error; JSON: `solvedAs` = `UBWT` and
`warnings`). `simulate` and `size` use UFT with the resistances. With UBWT (or UFT here) and a borehole head
within two radii of the isothermal ground surface (D < 2 r_b) of an energy pile or of a short, wide borehole
(H / (2 r_b) < 200) they warn that
the g-function depends on the segmentation and overestimates the fluid temperature in heating, and recommend
UHTR (docs/theory.md §3.3, T-9b; the same warning comes from `simulate`, `size` and `validate`).

### CLI v1 compatibility

Every CLI v1 invocation still works and prints the same text: `simulate --csv`, `size --exact
--trace --eed`, `optimize --csv`, `gfunction --csv`, `import-eed ... --layout-csv`, `params`,
`study --param ... --simulate|--size --oat --csv`, `montecarlo --spec --samples --seed --random
--simulate|--size --csv --summary`. Aliases: `--simulate`/`--size` = `--mode simulate|size`,
`--random` = `--sampling random`, `--summary <file>` = `--json <file>` (the summary is now the
versioned `boretherm.montecarlo/1` document: the v1 keys plus `schema`, `version`, `command`,
`overrides`, `inputs`; `secondsPerRun` moved to the text output). Monte Carlo spec files may use
the v1 key `"dist"` or the project file's `"distribution"`.

Changes from v1: unknown options are refused (v1 ignored them); `simulate` returns 2 when the
fluid temperatures leave the limits (the checked extremes are the last year's with
`sizing.lastYearOnly`, as in sizing); a function that is not implemented returns 1 (v1: 2); error
messages go to standard error (unchanged) and, with `--json`, also as an error document.

## 3. Exit codes

Stable; scripts and the batch runner depend on them (`boretherm::cli::ExitCode`).

| Code | Name (`status` in JSON) | Meaning |
|---|---|---|
| 0 | `ok` | Success |
| 1 | `inputError` | Usage error, invalid project, override or option, validation found errors, or a feature not available yet |
| 2 | `limitsViolated` | `simulate`: the fluid temperatures leave the design limits; `trt evaluate`: a quality check failed; `heatpump`: candidates were checked and none meets the requirements |
| 3 | `notConverged` | `size`: not converged; `optimize`: no feasible layout (none fits the plot or the drilling areas, none can be sized, none meets the limits); `study`: a run failed; `montecarlo`: every run failed; `trt evaluate`: no method gave a result or no fit is identifiable (nothing recommended) |
| 4 | `ioError` | A file could not be read or written (missing project, unwritable output) |
| 8 | `licenceError` | The time-limited licence has expired, or the system date is more than a day before the last run (`--version` still answers). The C API returns the same code (`BORETHERM_E_LICENCE`) |
| 130 | `cancelled` | Cancelled (Ctrl+C; a second Ctrl+C ends the process at once) |

## 4. JSON output

- Every document starts with `"schema": "boretherm.<name>/<version>"` (version **1**), then
  `"version"` (BoreTherm version), `"command"`, `"project"` and `"overrides"`.
- **Versioning:** within version 1 keys may be added, never removed or changed in meaning. An
  incompatible change raises the version (`boretherm.simulate/2`). Consumers should ignore unknown
  keys.
- **Units:** SI (m, s, W, J, Pa, kg, m³/s); **temperatures in °C** as in project files (the C API
  of wave 4 uses kelvin). `boretherm-cli schema <name>` gives the unit of every number as
  `"x-unit"`.
- Numbers that are not finite are written as `null`. Numbers are written with round-trip
  precision.
- The JSON contains no absolute paths and, apart from the run times of `simulate-fmu` / `size-fmu`
  (`stats.seconds`, `stats.stepsPerSecond`) and `fem-flow` (`seconds`), no timing; whether a result
  came from a cache is reported (`timeseries`: `stepper.gfunctionFromCache`, `cacheFile`;
  `fem-field` / `plume`: `femResults`). Otherwise the same input gives the same bytes (except
  `"version"` across releases).
- When a command fails and `--json` was given, the result is an error document instead:
  `{"schema": "boretherm.error/1", "exitCode": 1, "status": "inputError", "error": "..."}`. This
  holds also for an unknown command, `help <unknown command> --json` and a bare `--json` without a
  command (`"command": ""`), and when the licence has expired (exit code 8, to the `--json` file as well).
- A machine without AVX2 (the program is compiled for it) gets the message on standard error and,
  with `--json`, the error document on standard output (exit code 1).

| Schema (`schema <name>`) | Written by |
|---|---|
| `simulate` | `simulate` (status, limits, TfMin/TfMax, field, ground, fluid, flow, resistance, pumpPower, g-function, annual and monthly series, hourly with `--hourly`, warnings; `network` with the strings, their flows, pressure drops and R_b\*, the per-borehole flows, the field pressure drop, pump power and the temperatures along the strings at T_f,min / T_f,max — only for an explicit network or a series factor > 1, so the documents of plain parallel fields are unchanged) |
| `size` | `size` (H, totalLength, limiting, converged, iterations, options, trace, warnings) |
| `optimize` | `optimize` (candidates, best first; `costModel`, and per candidate `drilledLength` and, with the detailed cost model, `costByGroup`) |
| `cost`, `price-list` | `cost` (section 19); the price list file `.btcost` (derived from its writer; the project key `costs.priceList` has the same layout) |
| `gfunction` | `gfunction`, `export-gfunction` (`t`, `lnTts`, `g` and the reference values; `solvedAs`, `warnings`) |
| `params` | `params` (id, label, group, value/min/max in SI, unit, displayScale) |
| `study` | `study` (axes with values in SI, runs with metrics) |
| `montecarlo` | `montecarlo` (inputs, metrics statistics and histograms, Spearman, optional runs; `notConverged`: Size-mode runs not sized within `sizing.Hmax`, excluded from the statistics) |
| `validate` | `validate` |
| `site-check` | `site-check` (valid, site, area, issues, violations, trench length) |
| `fill` | `fill` (pattern, B1, B2, angle, offset, capacity, heads, trench length) |
| `dxf-layers` | `site-check`, `fill` with `--dxf` but no layer options (drawing, units, layers with their closed / open lines) |
| `trt-import`, `trt-evaluation`, `trt-apply` | the `trt` subcommands (section 10) |
| `trt` | the TRT test file `.trt.json` (derived from its writer; the project keys `trt` / `trtData` have the same layout) |
| `run` | `run` |
| `pack`, `unpack` | `pack` (archive, files with entry, kind, original path, size, SHA-256, warnings), `unpack` (folder, project file, files, linked-file problems) (section 14) |
| `example`, `import-eed` | `example`, `import-eed` (files written, import warnings) |
| `loads` | `loads generate-hourly\|per-year\|time-series\|generate-btes` (`action`, the per-year sums or the series summary, `csv`, `output`) |
| `comparison` | `compare` (variants with economics, service, emissions, scenarios and VDI 4650; data set, convention, assumptions) |
| `error` | any command that fails with `--json` |
| `help` | `--help --json` (commands with synopsis, options, positionals, `takesProject`, `batch`, `resultSchemas`; common and project options; exit codes; schema names) |
| `project`, `overrides`, `jobs` | input files (the project schema is derived from the project file writer) |

**The dynamic borehole model in `simulate`** (key `dynamic`, only with `settings.boreholeModel` = `Dynamic`):
the settings used, the energy balance, the depth profiles and, with `--hourly`, the `series` (`time`, `Tin`,
`Tout`, `Tf`, `Tw`, `qw`, `Q`, `flow`, `dynamic`). Plan P23 (thermal energy storage) adds:

| Key | When | Content |
|---|---|---|
| `btes` | every dynamic run | one object per operating year: `year`, `energyIn` / `energyOut` [J] (charged: Q > 0, discharged: Q < 0, with flow), `recovery` and `recoveryCumulative` (null when nothing was charged), `hoursCharging`, `hoursDischarging`, `hoursOff`, `directionSwitches`, `TinMin`, `TinMax`, `ToutMin`, `ToutMax` [°C, with flow; null without], `ringTwEndOfCharging` / `ringTwEndOfDischarging` (mean wall temperature of each ring at the end of the year's last charging / discharging step [°C]), `ringEnergyIn` / `ringEnergyOut` (heat through the walls of each ring [J]) — the ring arrays are empty with the uniform coupling (theory.md §20.13) |
| `series.direction`, `directionSwitches` | a flow direction other than `Fixed` | +1 normal, −1 reversed, 0 pump off; the reversals over the period |
| `groupOf`, `rings` | a coupling per ring / per borehole | the ground-coupling group of each borehole; the rings (field indices, innermost first) |
| `groups`, `ringTw` | the same, with `--hourly` | per group `Tw` [°C], `qw` [W/m], `Q` [W] at the output interval; the mean wall temperature of each ring [°C] |

**Freezing check, inlet limit and load coverage** (W6-audit-core, audit 2026-10-05; `simulate` and
`size`, at the sized length):

| Key | Content |
|---|---|
| `freezing` | `basis` (`monthlyPeaks`: T_f of the base and peak cases ± Q / (2 ṁc_p) with the load of the case; `hourly`: the hourly T_in / T_out at the nominal flow; `dynamic`: the control steps with flow; `none`: no flow at all), `freezingPoint`, `TinMin` / `ToutMin` [°C] and `TinMinTime` / `ToutMinTime` [s, end of the month / hour / step], `minimum`, `minimumAt` (`inlet` / `outlet`), `margin` [K], `risk` (margin < 1 K: warning `SimWarnFreezingRisk`), `annualTinMin` [°C per year], `hoursWithoutFlow` (dynamic model and direct FEM runs: pump-off hours, not counted) |
| `coverage` | `policy` (`complete`, `repeatedYearly`, `repeatLastYear`, `zeroAfterEnd`), `supplied` and `requested` [s] |
| `energyPile` | only for `design.energyPile` (docs/theory.md §15.7 T-EP-11): `basis` (`monthlyBase` / `hourly`), `dTMin_K` / `dTMax_K` (pile temperature change from T_m), `timeMin_s` / `timeMax_s`, `strainMin` / `strainMax` (free thermal strain), `lengthChangeMin_m` / `lengthChangeMax_m`, `restrainedStressAtMin_Pa` / `restrainedStressAtMax_Pa` (fully restrained, + = compression) |
| `limits.TinMin`, `inletLimitMet` | only when `limits.TinMin` is in the project (the optional inlet limit, off by default): it takes part in `limitsMet` and in sizing like `TfMin` (`limiting` stays `TfMin`, the message names the inlet limit) |

The freezing check warns; it fails the design check only through the optional inlet limit (user
decision D1). The sizing criterion stays the mean fluid temperature.

The text output of `simulate` lists the storage years (E_in / E_out, recovery, hours, reversals) when some
year both charged and discharged the ground. Warnings: the fluid's upper temperature limit reached
(`SimWarnBtesFluidLimit`) and, with the inlet temperature given, flow reversal or a coupling per ring / per
borehole, an inlet or outlet temperature above `limits.TfMax` (`SimWarnBtesAboveTfMax`).
The schemas are JSON Schema draft 2020-12. `tests/unit/test_cli.cpp` checks every golden output
against its schema, so they stay in step.

## 5. export-gfunction

```
boretherm-cli export-gfunction office.boretherm g.txt                  # Modelica table (.txt)
boretherm-cli export-gfunction office.boretherm g.csv --points 80      # CSV: t_s,lnTts,g
boretherm-cli export-gfunction office.boretherm --format json          # to standard output
```

Without `--format` the extension decides: `.json` json, `.txt` modelica, otherwise csv. Values
are written with 17 significant digits.

The **modelica** format is a text table for `Modelica.Blocks.Tables.CombiTable1Ds`,
`CombiTable1Dv` or `CombiTimeTable` with `tableOnFile = true`:

```
#1
# BoreTherm g-function of "Example - office building, 4x4 field"
# 16 boreholes, H = 150 m, D = 4 m, rb = 0.07 m
# ground: alpha = ... m2/s, lambda = ... W/(m K), ts = H^2/(9 alpha) = ... s
# ...
double g(50,3)
3600.0000000000014 -13.283813359713198 0.46798526570087118
...
```

Columns: 1 t [s], 2 ln(t/t_s) [-], 3 g [-]. Use it as

```modelica
Modelica.Blocks.Tables.CombiTable1Ds gTable(tableOnFile = true, tableName = "g",
  fileName = Modelica.Utilities.Files.loadResource("modelica://MyPackage/Resources/g.txt"),
  columns = {2, 3});   // y[1] = ln(t/ts), y[2] = g at u = t
```

`Tb(t) − Tm = q/(2π λ)·g(t)` with q the step heat rate per metre of borehole and λ the `lambda` of
the header. The test `CliModelica.TableLoadsAndInterpolatesInOpenModelica` loads the table in
OpenModelica and checks the interpolated values (it is skipped when `omc` is not installed; set
`BORETHERM_OMC` to its path, or `BORETHERM_SKIP_OMC=1` to skip it).

## 6. validate

Checks the project without stopping at the first problem and lists every problem with a
severity, a path and a message:

```json
{ "schema": "boretherm.validate/1", "valid": false, "errors": 2, "warnings": 1, "simulated": false,
  "problems": [ { "severity": "error", "path": "design.shankSpacing",
                  "message": "the pipes do not fit in the borehole: ..." } ] }
```

- Paths are project key paths (`flow.flowRate`, `field[3].H`, `design.sections[0]`), parameter
  ids (values outside the registry's plausible range: warnings), `simulation`, or `""` when the file
  is not a readable project.
- Checks: field (empty, lengths, radii; intersecting boreholes — vertical or inclined, the axes over
  their active lengths closer than the sum of the radii — are an error, axes closer than
  `layout.axisWarningDistance` a warning, both at `field[j]` with the two borehole numbers, the
  distance and the depth: the check of the calculation, theory.md §14.9), the inclination of a
  generated layout (`layout.inclination`), ground (values, layers,
  groundwater), flow and series factor, the borehole network (strings and parallel groups: out of
  range, loops, branches, broken or overlapping groups, negative K, at path `network.strings[i]`,
  `network.groups[g]`, `network.headerMinorLossK`; a series factor next to explicit strings: warning),
  period and start month, pump efficiency, limits order,
  fluid (valid at the property temperature; limit below the freezing point: warning), pipes
  (wall thickness, fit in the borehole, neighbouring legs), sections (order, overlap, insulation),
  stored study and Monte Carlo setups, and a bad `--set` (reported at its id).
- The site plan and the costs (audit 2026-11-09) with the core's own checks, as `site-check` and
  `cost` apply them: a site plan with polygons (degenerate or self-intersecting polygons, negative
  setbacks, no allowed position, ...; at `site.polygons[i]` or `site`) and the cost settings in use
  (negative prices or quantities, rates outside [0, 1], factors ≤ 0, unknown groups, ...; at their
  `costs....` key path). `design.loopConnection` `Series` on a design that is not an energy pile with
  two or more U-loops is a warning (the loops are calculated in parallel and the setting is not
  saved); series loops with borehole sections are an error.
- **Shared input checks** (W6-audit-core, audit 2026-10-05; core header
  `boretherm/validation/input_checks.hpp`): the loads, the tilts, the inlet limit and the sizing
  settings are checked with the same rules (and the same messages) as `simulate` and `size` use, so
  both validation modes agree with the operation:
  - errors: monthly values negative or not finite and peak durations above the 730 h month (the
    first month of each column, also per year of a per-year table), hourly values negative or not
    finite (`loads.hourly.heating_kW[k]`, the message names hour k + 1), hourly columns of different
    lengths, hourly series that are not 8760 or 8760 × years values (8784 values: the leap-year hint),
    time series that are not usable, converted ground loads that are not finite (`1e307` MWh),
    `SPF ≤ 1` for heating or DHW (`loads.spf.heating`; SPF = 1 is refused: such loads are direct
    ground loads), a tilt above 85° (`field[i].tilt`), `sizing.maxIterations` < 2, a sizing range or
    tolerance `size` refuses, a non-finite `limits.TinMin`;
  - warnings: a monthly peak power with a duration of 0 h (not applied), a monthly peak that does not
    exceed the month's mean ground load (the base load supersedes it), time-series columns the borehole
    model does not apply (`flow_m3s`, `massFlow_kgs`, `direction`, `Tin_C`; the steady and short-time
    models use the nominal flow), a time series shorter than the period (no load after its end), an
    inlet limit below the freezing point.
- When there is no error, a simulation runs as the last check (unless `--no-simulate`); its
  warnings (laminar flow, limits, freezing, library range) are listed with path `simulation`
  (a warning already listed at its key by the input checks is not repeated).
- **The file itself** (W6-audit-io, audit A6, user decision D4): keys the program does not read are
  `warning`s at their path with the key probably meant (`--strict`: `error`s, and the document has
  `"strict": true`); a consequential input filled with its default is an `info` (a `warning` when an
  unknown key probably meant it, e.g. `ground.conductivity` after `ground.conductivty`); an older form
  read as its new form is an `info`. `info` entries count neither as errors nor as warnings; the text
  output adds "n note(s)" to the summary line.
- Exit code 1 when there is an error, 0 otherwise (warnings allowed).

## 7. run (batch)

```
boretherm-cli run jobs.json --jobs 8 --json results.json
```

Jobs file (`boretherm-cli schema jobs`; example in `tests/data/cli/jobs_example.json`):

```json
{ "schema": "boretherm.jobs/1",
  "defaults": { "project": "office.boretherm" },
  "jobs": [
    { "id": "base" },
    { "id": "lambda-2.2", "overrides": { "ground.conductivity": 2.2 } },
    { "id": "sized-eed", "command": "size", "args": ["--eed"], "outputs": { "json": "out/eed.json" } },
    { "id": "gtable", "command": "export-gfunction", "outputs": { "out": "out/g.txt" } }
  ] }
```

- A bare array of jobs is accepted too. Keys per job: `id` (default `job<k>`), `command`
  (`simulate` default, or `size`, `optimize`, `gfunction`, `export-gfunction`, `params`, `study`,
  `montecarlo`, `validate`, `site-check`, `fill`, `timeseries`, `"trt import"`, `"trt evaluate"`,
  `"trt apply"`, `simulate-fmu`, `size-fmu`), `project` (for the `trt` jobs: the data file, the `.trt.json` file or the project;
  `trt apply` takes the result file in `args`; `trt import` needs `outputs.out`), `overrides`, `args` (further arguments of the command) and
  `outputs` (option → file, e.g. `json`, `csv`, `out`). `defaults` supplies `command`, `project`,
  `overrides` and `args` for jobs that do not set them (default overrides come before the job's).
- Relative paths — projects, outputs and file arguments in `args` — are relative to the jobs
  file's folder.
- `--set`/`--overrides` given to `run` apply to every job before its own overrides; `--strict`
  given to `run` applies to every job.
- A job runs exactly like the command line `boretherm-cli <command> <project> --set ... <args>
  --json ... --quiet`. Without `outputs.json`, its JSON document is embedded as `result`.
- The output (`boretherm.run/1`) lists the jobs in file order with `exitCode`, `status`,
  `outputs`, `result` and `error`, then a summary. Its results do not depend on `--jobs` (tested:
  1 and N parallel jobs give the same bytes), except for the run times that `simulate-fmu` /
  `size-fmu` report and for whether a job found a g-function in the disk cache that another job
  wrote first (`timeseries`: `stepper.gfunctionFromCache`; the numbers are the same).
- Refused before anything runs: duplicate ids, two jobs writing the same file (`outputs`, `--csv` /
  `--out` in `args`, and `trt apply` writing its project in place without `--out` / `--dry-run`),
  with `--jobs` > 1 a job reading a project file that another job writes, unknown commands,
  `--json` in `args`, `export-gfunction` without `outputs.out`.
- Exit code: the largest exit code of the jobs (130 when cancelled). Parallel jobs share the
  machine's cores with the core's own parallel loops; `--jobs` between 2 and the number of cores
  suits many small jobs.

## 8. Recipes

PowerShell:

```powershell
# thermal conductivity sweep, one JSON per value
foreach ($l in 1.8, 2.2, 2.6, 3.0) {
  boretherm-cli size office.boretherm --set ground.conductivity=$l --json "size_$l.json" --quiet
  if ($LASTEXITCODE -eq 3) { "lambda $l: limits cannot be met" }
}
# pipe a legacy project file through import and simulation
boretherm-cli import-eed old.dat - | boretherm-cli simulate - --json | ConvertFrom-Json
```

Python:

```python
import json, subprocess
r = subprocess.run(["boretherm-cli", "size", "office.boretherm", "--set", "borehole.D=10", "--json"],
                   capture_output=True, text=True)
doc = json.loads(r.stdout)          # also on failure: {"schema": "boretherm.error/1", ...}
if r.returncode == 0:
    print(doc["H"], doc["limiting"])
```

## 9. For developers

- `cli/cli.hpp`: `cliMain(args, out, err, in, cancel)` and the `ExitCode` enum. `cli/cli.cpp`:
  grammar, command table, overrides, error mapping. Commands: `cli/cmd_design.cpp`
  (example, simulate, size, optimize, gfunction, export-gfunction, import-eed),
  `cli/cmd_study.cpp` (params, study, montecarlo), `cli/cmd_tools.cpp` (validate, schema, run),
  `cli/cmd_site.cpp` (site-check, fill, the site options of optimize), `cli/cmd_trt.cpp` (trt),
  `cli/schemas.cpp` (JSON Schemas).
- A new command: add a `CommandSpec` row (name, positionals, options, synopsis, summary, help),
  write the handler with `Context` (print text with `ctx.print`, progress with `ctx.progressFn()`,
  JSON with `ctx.header(...)` + `ctx.emitJson(...)`), add its schema to `schemas.cpp`, and a golden
  test. No global state: `run` executes commands concurrently in one process.
- Golden files: `tests/data/cli/*.golden.json`. After an intended change of results, run the
  tests once with `BORETHERM_UPDATE_GOLDEN=1` and review the diff.

## 10. trt (thermal response tests, plan P13)

`trt` has four subcommands. Theory: docs/theory.md §13; validation: docs/validation.md §18.

```
boretherm-cli trt import <data.csv|-> --out <test.trt.json|-> [--map <spec>]
              [--project <p.boretherm>] [--name <text>] [--resample <dt>] [--delimiter ;|tab|space|,]
              [--decimal-comma] [--duplicates average|spread|keep] [--set <setup key>=<value> ...]
boretherm-cli trt evaluate <test.trt.json|project|-> [--project <p.boretherm>]
              [--method ils|superposition|mils|recovery|all[,...]] [--model ils|chs|fls|all[,...]]
              [--window <start>:<end>] [--mc N] [--seed S] [--fit-c] [--fit-t0] [--prefer <fit id>]
              [--series] [--set <setup key>=<value> ...] [--json [file]]
boretherm-cli trt apply <p.boretherm> <result.json> [--rb grout|fixed|none] [--layer i] [--layer-value]
              [--no-lambda] [--capacity] [--temperature] [--groundwater] [--fit <fit id>]
              [--out <file|->] [--dry-run] [--set/--overrides (project)] [--json [file]]
```

`import` and `evaluate` edit the test's setup with `--set <setup key>=<value>`; `--overrides` (a
project option) applies only to `apply` and is refused by the other two. `--strict` makes unknown keys
an error in every file a subcommand reads: the test file (`evaluate`), the `--project` file (`import`,
`evaluate`) and the project (`apply`). `--json` may stand before the files (`trt evaluate --json
test.trt.json` writes the JSON to standard output); `--out - --json <file>` writes the test file or
the project to standard output and the JSON document to the file.

**import** reads a rig file and writes a `.trt.json` test file (`"schema": "boretherm.trt/1"`:
`name`, `setup`, `data`; the same layout as the project keys `"trt"` and `"trtData"`).

- **Data files (plan P19 #24):** the rig file is linked in `data.sources` (path relative to the test
  file, size, SHA-256, the import options). `--dts <file>` links a wide DTS file (fibre position x
  time) with `--dts-offset <m>` (fibre position of the ground surface), `--dts-depth <top>:<bottom>`,
  `--dts-shift <dt>` (added to the DTS times after the calendar times are matched),
  `--dts-format`, `--dts-delimiter`; `--dts-mean` puts its depth mean (one-minute bins) into `Tmean`.
  Data files up to `--store-limit` MB in total (default 50) are stored: the records in full and DTS
  files as copies. Above it the files stay linked and the records become a **compact copy** (means
  over at most 60 s, `data.compact`); evaluate, report and apply work with it alone (section 14).

- `--map` names the columns: `time=A:h,Tin=C,Tout=D,flow=E:l/min,power=F:kW`. Keys `time`, `Tin`,
  `Tout`, `flow`, `power`, `Tmean` (a mean fluid temperature from elsewhere, e.g. a DTS depth
  mean), `flowConst=<value>:<unit>` (no flow column). A column is a letter (`A`, `AB`), a 1-based
  number or a header name. Units: time `s`, `min`, `h`, `d`, `datetime` (ISO, `dd.mm.yyyy`,
  `mm/dd/yyyy` detected) or an explicit format like `dd.mm.yyyy HH:MM`; temperatures `C`, `K`, `F`;
  flow `m3/s`, `m3/h`, `l/s`, `l/min`, `l/h`, `kg/s`, `kg/h`, `gpm`; power `W`, `kW`, `MW` or a factor
  (`power=D:1056` multiplies by 1056 to W). There are no built-in presets: map the columns of your
  rig (the GUI guesses them from the header names).
- The delimiter and the decimal comma are detected; `#` lines are comments; rows without a valid time
  are skipped and reported; repeated time stamps are averaged (`--duplicates spread` spreads them).
- `--project` copies the borehole (first borehole of the field), design, fluid, resistance options,
  the ground heat capacity over the test length, the surface temperature and the geothermal heat flux
  into the setup. `--set` edits setup keys (relative to `"setup"`, JSON values): `--set T0=11.2
  --set t0Method=Manual --set borehole.H=120 --set powerSource=Measured --set criteria.maxPowerSdRel=0.02`.
- A power column switches the setup to the measured power; otherwise the power is ρ c_p V̇ (T_in − T_out).
- The heating start is detected as in the GUI's import step (rigs record the circulation before the
  heating, for T0): the time of the last record before the first one whose heat rate exceeds 30 % of
  the median heat rate. It is written to `setup.heatingStart_s`, printed, and given as
  `heatingStart_s` in the `--json` document (`null` when the series starts with heating);
  `--set heatingStart_s=<s>` overrides it.

**evaluate** runs the quality checks and the methods and prints a comparison table (the recommended
fit marked `*`). The input may also be a project file with the keys `"trt"`/`"trtData"`, or `-`.

- `--method` (default: the setup's methods, M1 + M2 + M5): `ils` M1 line-source slope (+ sequential
  evaluation), `superposition` M2, `mils` M3 moving line source, `recovery` M5, `dynamic` M4 (wave 5,
  reported as not available), `all`. `--model` the M2 forward models (default ILS, CHS, FLS).
- `--window 10h:end` (units s, min, h, d; `auto` start, `end` = heating end). `--mc N` Monte Carlo
  over the setup's input uncertainties (P5/P50/P95); N is 0 (off) or an integer from 2 to 10⁷,
  `--seed S` a non-negative integer. `--fit-c`, `--fit-t0` estimate C, T0 too.
  `--prefer <fit id>` overrides the recommendation. `--project` supplies T_s and q_geo for the T0
  plausibility check when the setup has none.
- Automatic screening preserves raw readings. Adaptive symmetric Hampel windows detect temperature outliers;
  temperature outliers, flow/power transients and flagged step-transition readings are automatically
  excluded from temperature fitting by default (`criteria.removeSpikes=true`). Findings, raw records,
  and measured heating history remain available; exclusion does not make variable power suitable for M1.
  Use `--set criteria.removeSpikes=false` to review all observations without automatic exclusion. Setup overrides include
  `--set criteria.maxSamplingInterval_s=600`, `--set criteria.minFitObservations=15`,
  `--set criteria.operatingChangeRel=0.10`, and `--set criteria.maxWindowSensitivityRel=0.10`.
- `suitability` (`suitable|review-required|unsuitable`) is distinct from the legacy `quality.passed` and
  exit status. `dataIssues[{kind,channel,start_s,end_s,excluded,reason}]` explains every finding, with
  times since heating start. Each fit also reports `suitability`, `suitabilityReasons`, and
  `windowSensitivityRel` (M1, otherwise null), `lambdaWithoutSuspect` (diagnostic M1 fit excluding
  retained suspect readings, otherwise null), and `suspectObservations`. This exclusion comparison
  is a sensitivity calculation and never silently replaces the primary fit.
  `--series` adds `screenedSeries{t_s,flags}`:
  bits 1 spike, 2 user exclusion, 4 before heating, 8 recovery, 16 missing temperature,
  32 operating change, 64 suspect temperature, 128 automatic fitting exclusion. Unsuitable fits are not recommended
  or selectable; an unavailable `--prefer` falls back to the automatic recommendation. `trt apply --fit` also refuses unsuitable or non-identifiable results. Review-required numerical results
  can still return exit code 0: inspect suitability before using them as design inputs.
- JSON `boretherm.trt-evaluation/1`: `setup` (as used), `T0`, `T0Source`, `heatingEnd_s`,
  `hasRecovery`, `window {start_s, end_s, recoveryStart_s}`, `meanPower_W`, `meanFlow`,
  `meanFluidTemperature`, `quality {passed, checks[{id, title, status pass|warning|fail|n/a, value,
  limit, unit, message}]}`, `gaps`, `interruptions`, `spikes`, `sequential {windowEnd_s, lambdaByEnd,
  rbByEnd, windowStart_s, lambdaByStart, rbByStart, lambdaRising, lambdaRiseRel}`, `fits[{id, label,
  model (M2, M5: `InfiniteLine|Cylinder|FiniteLine`), ok, error, identifiable (when ok), lambda,
  RbEff, heatCapacity, T0, darcyVelocity (each {value, stdError, ciLow, ciHigh, estimated,
  atBound}), parameters, correlation, windowStart_s, windowEnd_s, recoveryStart_s, meanPower_W,
  slope, intercept, nObservations, iterations, rmse_K, r2, residualLag1, effectiveObservations,
  seconds, warnings, series (with --series)}]`, `recommended` (fit id or null), `recommendationReason`,
  `advectionSuspected`, `monteCarlo[{fitId, samples, failed, lambda, RbEff (n, mean, sd, min, max,
  p5, p25, p50, p75, p95), seconds}]`, `notes`, `apply` (the values `trt apply` writes), `exitCode`,
  `status`. Fit ids: `ils-slope`, `superposition-ils`, `superposition-chs`, `superposition-fls`,
  `mils`, `recovery`.
- The recommended fit follows docs/theory.md §13.9: a fit whose own diagnostics flag a parameter as
  not identifiable (marked "sensitivity only") is never recommended automatically; `--prefer` still
  takes it.
- Exit code **2** when a quality check fails (the evaluation is still complete), **3** when no
  method gave a result or no fit passes its identifiability checks (nothing recommended; `trt
  apply` then needs `--fit`).

**apply** writes the recommended fit (or `--fit`) of an evaluation document into a project: λ
(homogeneous ground; with `--layer i` layer i is set so that the effective value over the test
borehole's length equals λ_TRT, `--layer-value` writes λ_TRT itself), R_b\* as the calibrated grout
conductivity (`--rb grout`, default: the multipole R_b\* of the test borehole at the test flow equals
the TRT value) or as a fixed R_b\* (`--rb fixed`), and on request C (`--capacity`, only if
estimated), the surface temperature back-computed from T0 (`--temperature`) and the Darcy velocity
(`--groundwater`, stored only). The project is rewritten in place unless `--out` is given; `--dry-run`
only lists the changes. JSON `boretherm.trt-apply/1`: `fitId`, `changes[{key, label, old, new, unit,
note}]`, `notes`, `groutConductivity`, `output`, `qualityPassed`.

Example:

```
boretherm-cli trt import rig.csv --map "time=A:dd.mm.yyyy HH:MM,Tin=B,Tout=C,flow=D:l/min" --out test.trt.json --project site.boretherm --set T0=18.85 --set t0Method=Manual
boretherm-cli trt evaluate test.trt.json --method ils,superposition --model ils,chs --mc 500 --json result.json
boretherm-cli trt apply site.boretherm result.json --rb grout --temperature --out site_trt.boretherm
```

## 11. Site plan: site-check, fill, optimize --site (plan P14)

Theory: docs/theory.md §17; validation: docs/validation.md §23. The site plan is the project key
`"site"` (drilling areas, no-go zones, corridors with their setbacks, the connection point, the
background drawing); the GUI draws it on the Layout page (wave 4).

```
boretherm-cli site-check <project> [site options] [--out <project|->]
boretherm-cli fill <project> --spacing <B1>[,<B2>] [--pattern grid|staggered|rowwise|perimeter]
              [--angle <deg>|auto] [--edge [<polygon>:]<edge>] [--offset x,y] [--count N]
              [site options] [--out <project|->] [--csv <file|->]
boretherm-cli optimize <project> --site [<site file>] [site options]
```

**Site options** (all three commands). Without them the project's own site plan is used.

| Option | Meaning |
|---|---|
| `--site <file>` | Site plan from a project file (its `"site"`), a `{"site": {...}}` document or a bare site `{"polygons": [...]}`. A `.dxf` file is read as `--dxf`. For `optimize`, `--site` without a file uses the project's site plan. |
| `--dxf <plan.dxf>` | Site plan from an ASCII DXF drawing: the closed polylines (and circles, closed splines, hatch loops) of the layers named below become polygons; a polyline whose last point repeats its first counts as closed. Without layer options `site-check` and `fill` list the drawing's layers with their closed and open lines and end with exit code 0 (`--json`: the `dxf-layers` document); `optimize` stops with a usage error that lists them. |
| `--boundary <layer>[:<m>]` | Drilling area(s) from this layer, with the setback in metres (e.g. `--boundary PLOT:1`). Repeatable; `--exclusion` (no-go zones: buildings, trees, neighbours), `--corridor` (open lines: pipes, cables, sewers; the setback is the clearance to the axis) and `--info` alike. Layer names are case-insensitive. |
| `--dxf-units <unit>` | Drawing unit when `$INSUNITS` is missing or wrong: `mm`, `cm`, `dm`, `m`, `km`, `in`, `ft`, `yd`, `mi`. A drawing without units is read in metres (with a note). |
| `--origin x,y\|auto` | Shift large (UTM / Gauss-Krüger) coordinates by this point [m] (stored as `site.origin`); `auto` takes the lower-left corner of the polygons, rounded down to whole metres. |
| `--connection x,y` | Connection point (manifold, building entry) for the trench [m]. Use `--connection=-3,12` when x is negative. |
| `--min-distance <m>` | Minimum distance between boreholes (`site.minBoreholeDistance`). |

`--set site....` edits the site plan like any other key (`--set site.polygons[1].buffer=3`,
`--set "site.connectionPoint=[4, 20]"`).

**site-check** prints the polygons (kind, points, area, setback), the drilling area, the problems of
the site plan itself (degenerate or self-crossing polygons, negative setbacks, a drilling area where no
position respects the setbacks) and every borehole that violates it: outside the drilling area, closer
to its edge than the setback, inside or too close to a no-go zone, too close to a corridor, closer to
another borehole than the minimum distance (or overlapping). Heads (collars) are checked, also for
inclined boreholes. JSON `boretherm.site-check/1`: `valid`, `site` (as in the project file), `area`,
`issues[{severity, polygon, message}]`, `boreholes`, `boreholesWithProblems`,
`violations[{borehole, kind, polygon, other, distance, required, message}]` (kinds `outsideArea`,
`nearAreaEdge`, `inExclusion`, `nearExclusion`, `nearCorridor`, `tooCloseToBorehole`; indices from
0, messages number boreholes from 1), `trenchLength`, `output`. Exit code 1 when the site plan is
invalid, 2 when a borehole violates it.

Convert a drawing once and keep the site plan in the project:

```
boretherm-cli site-check office.boretherm --dxf lageplan.dxf --boundary GRUNDSTUECK:3
    --exclusion GEBAEUDE:2 --exclusion BAEUME:1.5 --corridor KANAL:1 --connection=12,40 --out office_site.boretherm
```

**fill** places boreholes in the drilling areas; every position respects every setback, no-go zone,
corridor and the minimum distance. Length, depth and radius come from the current field (or the layout
prototype); the result becomes a custom layout.

| Pattern | Positions |
|---|---|
| `grid` (default) | lattice B1 × B2 (B2 = B1 by default) in the row direction; the lattice offset is searched (4 × 4 trials) for the most boreholes |
| `staggered` | every other row shifted by B1/2; B2 = B1·√3/2 by default (hexagonal: every neighbour at B1) |
| `rowwise` | rows B2 apart, parallel to an edge; each row packed from its start at B1 (GHEDesigner's RowWise) |
| `perimeter` | along the inward-offset outline of each drilling area (offset by its setback), B1 apart (chord) |

`--angle` gives the row direction in degrees (default: along the longest edge of the largest drilling
area; `--edge 3` or `--edge 1:3` picks edge 3 of polygon 1, numbered from 1). `--offset x,y` fixes a
lattice point instead of the search. `--count N` keeps the N most spread-out positions (farthest-point
order). `--out` writes the project with the new field, `--csv` the boreholes as
`x,y,H,D,rb,tilt_deg,azimuth_deg` (the layout CSV format). JSON `boretherm.fill/1`: `status`,
`pattern`, `B1`, `B2`, `angle` [rad], `offset`, `capacity` (positions of the full fill), `boreholes`,
`heads` ([x, y] each), `trenchLength`, `violations` (always empty), `output`. Exit code 3 when no
position fits.

**optimize --site** searches inside the site plan instead of the `landLength × landWidth` plot:
- the layout types of the setup (line, L, U, open rectangle, rectangle, ...) are placed in the drilling
  areas in the edge-aligned orientations and every `optimization.siteAngleStep` (default 15°; 0 = edge
  directions only), each at the first position where every head is allowed (with a connection point:
  the position nearest to it);
- the fill patterns `optimization.sitePatterns` (default all four) give two candidates per borehole
  count: the most spread-out subset of the fill and the compact subset (the positions nearest the
  connection point, or the centre of the fill without one); at most 20 counts per fill, then the counts
  next to the ten best are added;
- candidates with the same heads (within 1 cm, e.g. the spread subsets of two grids that both take the
  corners) are evaluated once; the other grid spacings are listed in `sameHeadsSpacings`;
- the trench is the minimum spanning tree of the heads plus the connection point.

The search, screening and exact re-sizing are those of the plot optimization; `optimization.region =
"Site"` in the project does the same without `--site`. Text: the fills appear as `Grid fill (spread)`,
`Row-wise fill (compact)`, ... (n1 = number of boreholes, n2 = 0). JSON (only with a site plan): `"region":
"Site"` and per candidate `pattern` (null for a placed layout type), `selection` (`"spread"` or
`"compact"`; null for a placed layout type), `angle` [rad], `heads` and `sameHeadsSpacings` [m] (grid
spacings of merged duplicates, usually empty); `layout` stays `Grid fill` etc. A site plan without a
region is ignored by `optimize`; the plot optimization is unchanged.

**Spacing and the actual distance.** For a fill, `spacing` (text column `B [m]`) is the spacing of the
fill grid the boreholes were taken from, not the distance between them: 11 boreholes spread over a 6 m
grid can be 14 m apart. Every candidate (plot and site) therefore reports the actual nearest-neighbour
distances of its heads: text columns `dmin [m]` (the closest pair) and `dmean [m]` (mean distance to
the nearest neighbour), CSV columns `min_distance_m`, `mean_distance_m` (appended at the end), JSON keys
`minDistance`, `meanDistance`. For the regular layouts they equal the spacing.

```
boretherm-cli optimize examples/site_office_lshape.boretherm --json best.json
boretherm-cli fill examples/site_office_lshape.boretherm --pattern staggered --spacing 7 --count 12 --out office_hex.boretherm
```

## 12. Co-simulation: timeseries and cosim --stdio (plan P12b)

Both commands run the **co-simulation stepper** (`core/include/boretherm/cosim/stepper.hpp`, theory in
`docs/theory.md` section 18): the borefield as a time-stepped component with the fluid inlet
temperature and mass flow as inputs and the outlet temperature, the heat rate, the mean fluid and
borehole wall temperatures and the pressure drop as outputs. The same engine is behind the C API
(`docs/capi.md`) and later the FMU and the Modelica package.

- Temperatures are in **degC** like every other CLI input and output; `--kelvin` switches the input
  and output temperatures to K (the C API always uses K).
- `Q_flow` is the heat rate **into the fluid** [W] = m cp (T_out − T_in) (the FMI/Modelica sign; the
  ground load of `simulate` is −Q_flow). `dp` is the field's pressure drop at |m_flow| [Pa].
- `m_flow` [kg/s] is the mass flow of the whole field; `boretherm-cli` prints the nominal one in the
  `stepper` object of the JSON (`massFlowNominal`). 0 = no flow (T_out = the stagnant fluid, Q = 0);
  negative = reverse flow (by default the borehole is symmetric).
- The fluid properties are those of the project's property temperature, as in `simulate`; R_b* and
  the pressure drop follow the flow (laminar at low flow).

**Stepper options** (both commands):

| Option | Meaning |
|---|---|
| `--borehole-model steady\|short-time\|dynamic` | Borehole model; default the project's `settings.boreholeModel`. `dynamic`: the node network of the dynamic model (P11b; W5-fmu-modelica), with the internal step of the project's dynamic time step (300 s) unless `--step` is given |
| `--step <s>` | Internal step h of the ground history (default 3600 s). Communication steps may be any length; see below |
| `--start <s>` | Start time (default 0) |
| `--preload-years N` with `--preload-power <W>` or `--preload-loads` | Pre-conditioning: N years of a constant ground load (W, > 0 injection) or of the project's own loads (hourly series, or the monthly base loads) before the start, so the ground starts disturbed |
| `--horizon-years N` | Years after the start the ground history must resolve (default the project's period) |
| `--reverse-flow symmetric\|stagnant\|refuse\|reverse-network` | m_flow < 0: the same as forward flow (default), treated as no flow, an error, or (P23, dynamic model) the network run backwards: T_in enters at the normal outlet stage and every borehole is entered through its other leg (coaxial: annulus-in ↔ centre-in; theory.md §20.12). With the dynamic model and the ground coupling per ring / per borehole, `symmetric` runs as `reverse-network` (`INFO` and the `stepper` object show the policy in use as `reverseFlow`) |
| `--no-cache`, `--cache-dir <dir>` | The g-function is cached on disk (default `%LOCALAPPDATA%\BoreTherm\gcache`, keyed by SHA-256 of everything it depends on), so the second start is instant. `--no-cache` always computes it |

**Steps.** The ground history lives on the fixed internal grid h. A communication step may be shorter
or longer than h and need not align with it: the incomplete internal step acts with the running mean
of its load, and it is committed when it completes. Outputs are those at the end of each step.
Replaying the hourly inlet temperatures of an hourly `simulate` run (with
`settings.hourlyMethod = LoadAggregation`) gives its outlet temperatures to 10⁻¹⁰ K (validation.md
section 25).

### timeseries

```
boretherm-cli timeseries office.boretherm --in modelica_run.csv --out replay.csv [--json summary.json]
```

**Input CSV** (header line optional; `,` `;` tab or spaces; `#` comment lines): one row per
communication step with
1. `t` [s]: the **end** of the interval in which the row's inputs hold (the first interval starts at
   `--start`, default 0; t must not decrease, an equal t gives the outputs without advancing);
2. `T_in` [degC, K with `--kelvin`] — or with `--heat-rate` the ground heat rate [W], > 0 injection
   (T_in then follows from the closure);
3. `m_flow` [kg/s].

**Output CSV** (to standard output without `--out`): `t_s`, the input column, `m_flow_kg_s`,
`T_out_C`, `Q_flow_W`, `T_f_C`, `T_b_C`, `dp_Pa`, `Q_mean_W` (the mean heat rate into the fluid
over the row's interval), plus `T_in_C` with `--heat-rate` (`_K` with `--kelvin`), 12 significant
digits.

**JSON** `boretherm.timeseries/1`: the header, `stepper` (borehole model, internal step, length,
T_m, R_b*, nominal flow and pressure drop, fluid density and c_p, aggregation cells, cache use),
`temperatureUnit`, `input`, `rows`, `startTime`, `endTime`, `groundEnergy` [J] (heat into the
ground), `ToutMin`, `ToutMax`, `TfMin`, `TfMax`, `output`. `timeseries` may be used in `run` jobs.

### cosim --stdio

```
boretherm-cli cosim office.boretherm --stdio [--kelvin] [stepper options]
```

After the stepper is built (g-function from the cache or computed) the command writes
`READY boretherm.cosim/1 unit=C` (`unit=K` with `--kelvin`) and then reads one command per line from
standard input and writes exactly one reply line per command (flushed). Blank lines and lines
starting with `#` get no reply. Commands are case-insensitive; numbers in replies have 17
significant digits (exact).

| Command | Reply |
|---|---|
| `STEP t dt T_in m_flow` | `OK T_out Q_flow T_f T_b dp` at t + dt (t must be the stepper time) |
| `STEPQ t dt Q_ground m_flow` | `OK T_out Q_flow T_f T_b dp T_in` with a prescribed ground heat rate [W] |
| `EVAL t T_in m_flow` | `OK T_out Q_flow T_f T_b dp` at t for the inputs held until t, without committing (event iteration) |
| `TIME` | `OK t` |
| `SAVE` | `OK <slot>`: the state kept in memory |
| `RESTORE <slot>` | `OK t`: back to a saved state (rollback) |
| `WRITE <file>` / `READ <file>` | `OK <bytes>` / `OK t`: the state serialized to / read from a file |
| `INFO` | `OK {json}` (the `stepper` object of `timeseries`) |
| `HELP` | `OK <command list>` |
| `QUIT` (or end of input) | `OK bye`, exit code 0 |

An invalid command or argument gives `ERR <message>` and the session continues; the stepper is
unchanged by a failed step. Errors before `READY` (project, options) end the command with exit
code 1 or 4 as usual.

Python, without the C API:

```python
import subprocess
p = subprocess.Popen(["boretherm-cli", "cosim", "office.boretherm", "--stdio"],
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
assert p.stdout.readline().startswith("READY")
t = 0.0
for T_in in [4.0, 3.5, 3.0]:
    p.stdin.write(f"STEP {t} 900 {T_in} 8.2\n"); p.stdin.flush()
    ok, T_out, Q_flow, T_f, T_b, dp = p.stdout.readline().split()
    t += 900
p.stdin.write("QUIT\n"); p.stdin.flush()
```

## 13. FMU import: fmu info, simulate-fmu, size-fmu (plan P18a)

BoreTherm as co-simulation master for FMI 2.0 **Co-Simulation** FMUs (heat pumps, buildings, HVAC
systems), coupled to the borehole field. The system is the project's `"cosim"` key: blocks (the
field, FMUs, constant and table sources), connections from an output port to an input port, and
the settings. Reference: [fmu_import.md](fmu_import.md); algorithm: theory.md section 21;
validation: validation.md section 29. The CLI **trusts every FMU** it is given (an FMU contains
native code; the GUI asks first). FMUs run in a separate `boretherm-fmuhost.exe` process per
instance by default, so a crashing or hanging FMU ends the run with a message (exit code 1) and
nothing else.

### fmu info

```
boretherm-cli fmu info heat_pump.fmu [--json]
```

Model name and description, FMI version, generating tool and date, GUID, SHA-256, platforms in the
archive, interfaces (Co-Simulation / Model Exchange) and the Co-Simulation flags (variable step,
state get/set, one instance per process), the default experiment, whether BoreTherm can use it
(otherwise the reason: Model Exchange only, no 64-bit Windows binary, sources only, another FMI
version), then the inputs, outputs and parameters with type, unit, start value and description.
JSON `boretherm.fmu-info/1`: `{"fmu": {...}}` with every variable, the unit definitions and the
flags. Exit code 3 when the FMU cannot be used.

### simulate-fmu

```
boretherm-cli simulate-fmu office.boretherm [--csv series.csv] [--series] [--json run.json] [run options]
```

**Run options** (they override the project's `cosim.settings`; `--set cosim.settings.<key>=<value>`
works too, e.g. `--set cosim.settings.maxIterations=50`):

| Option | Meaning |
|---|---|
| `--step <s>` | Communication step (default 600 s; any value) |
| `--years N` / `--stop <s>` | Period in years (default the project's simulation period), or a test run from the start time to `<s>` |
| `--coupling explicit\|iterate` | Algebraic loops: the value of the end of the step (default), or a fixed point at every communication point (and the step repeated with rollback where every FMU in the loop can save its state) |
| `--long-term auto\|full\|hybrid` | Hybrid (auto for more than 2 years): year 1 and the last year coupled, the years between from the ground load of year 1 |
| `--host isolated\|in-process` | FMUs in `boretherm-fmuhost.exe` (default) or in this process (faster; for trusted FMUs) |
| `--timeout <s>` | Watchdog per FMU call of the isolated host (default 60 s) |
| `--record <block.port>` | Record another output or input (repeatable); connected outputs and the field's temperatures are always recorded |
| `--output-interval <s>` | Record every n-th step (n = interval / step) |
| `--log` | The FMUs' log messages on standard error |
| `--fmu-cache <dir>`, `--gcache-dir <dir>` | Folder of the unpacked FMUs (default `%LOCALAPPDATA%\BoreTherm\fmu`) and of the g-function cache |
| `--host-exe <file>` | The FMU host executable (default: next to boretherm-cli.exe) |

Text output: the period, coupling, mode and host, every FMU with its tool and SHA-256, every
connection with its unit conversion (`[loop]` marks the connections cut in an algebraic loop), the
yearly minimum and maximum mean fluid temperature and ground energy (years of the hybrid mode
marked "from year 1"), the extremes against the limits, the steps, FMI calls and wall time, and
the warnings. `--csv` writes `t [s]` and one column per recorded signal (`block.port [unit]`), the
values at the **end of each step**. JSON `boretherm.simulate-fmu/1`: `status`
(`ok`/`limitsViolated`), `mode`, `periodYears`, `startTime`, `stopTime`, `step`, `coupling`, `host`,
`borefieldLength`, `limits`, `TfMin`, `TfMax`, `TfMinTime`, `TfMaxTime`, `limitsMet`, `yearly`
(year, coupled, TfMin, TfMax, TfMean, ToutMin, ToutMax, groundEnergy [J]), `fmus`, `connections`
(from, to, conversion, loopCut), `loops`, `warnings`, `log`, `stats` (steps, fmuCalls, iterations,
notConverged, maxChange, seconds, stepsPerSecond), and with `--series` `series` (`time`, `signals`).
Exit code 2 when the mean fluid temperature leaves the limits; 1 for an invalid system (the first
problem of the analysis, e.g. "connect the inlet temperature T_in or the heat rate Q_ground of the
borehole field"), an FMU error, a crash or a time-out.

### size-fmu

```
boretherm-cli size-fmu office.boretherm [--jobs N] [--csv series.csv] [--series] [--json size.json] [run options]
```

The mean borehole length within `sizing.Hmin` … `sizing.Hmax` (to `sizing.tolerance`) at which the
mean fluid temperature stays within the limits (`sizing.lastYearOnly` respected), with a coupled
run at every length: both ends first, then k lengths at once (`--jobs`, default the hardware
threads up to 4; 1 with `--host in-process`, since an FMU is not necessarily safe to run in several threads at
once: OpenModelica's FMUs corrupt the heap; give `--jobs` to run in-process FMUs in parallel anyway). JSON
`boretherm.size-fmu/1`: `status`, `converged`, `H`, `totalLength`, `message`, `parallelRuns`, `runs`
(every length tried with TfMin, TfMax, ok) and `run` (the run at H, as in simulate-fmu). Exit code 3
when the limits cannot be met at `Hmax`.

## 14. Project files: stored and linked files, pack, unpack (plan P19 #24)

A project refers to other files: the site plan, the FMUs and CSV tables of the co-simulation system
and the data files of a TRT. Relative paths are relative to the folder of the project file;
"Save as" into another folder re-expresses them (GUI, `relocateProjectPaths`).

**Stored site plan.** A loaded plan (PNG, JPEG, GIF, BMP, SVG, PDF, DXF) is copied into the project
(GUI default, "Store the plan in the project" on the Plan tab; "Export the stored plan…" writes it
back to a file):

```json
"site": { "background": { "type": "Image", "path": "plans/site.png", ...,
          "embedded": { "name": "site.png", "mediaType": "image/png", "size": 123456,
                        "sha256": "<64 hex digits>", "data": "<base64>" } } }
```

`path` stays as a note of the original location. Loading prefers the stored copy (images and SVG
from memory, DXF parsed from the bytes, PDF rendered from memory); old files with a path only keep
working. A copy whose size or SHA-256 does not match is a coded error (`ProjectFileEmbeddedDamaged`).
Plans over about 20 MB get a warning on the Plan tab (the project file grows by 4/3 of the plan).

**TRT data.** `trtData.sources` lists the data files of a test (`kind` Logger or Dts, `path`, `size`,
`sha256`, the logger's `import` options or the DTS settings `dts`: `depthOffset_m`, `minDepth_m`,
`maxDepth_m`, `timeShift_s`, `timeFormat`, `delimiter`, `meanTemperature`; `embedded` for a stored
DTS copy). The total size of the data files decides (default limit 50 MB, `trtDefaultEmbedLimitBytes`):

- up to the limit the records are stored in full and DTS files as copies: the project needs no
  other file;
- above it the files are linked and the records are a compact copy, means over at most 60 s
  (`"compact": { "step_s": 60, "fullRecords": N }`), with the DTS depth mean in `Tmean` when the DTS
  is the mean fluid temperature. The evaluation, the report and the apply step use the compact
  copy; the full data are read from the files on demand (GUI "Read the full data",
  `loadFullTrtData`).

Example (the Darmstadt distributed GRT, 42 days): the 5.5 MB logger alone is stored in full; with
the 1.5 GB annulus DTS file as the mean fluid temperature the data are linked and the project file
is 4.5 MB (61,420 one-minute records with the DTS mean).

**Missing or changed files** never stop a project from loading. `checkLinkedFiles` /
`linkedFileProblems` give one coded message per file: `LinkedFileMissing`,
`LinkedFileMissingStoredCopy` (the stored copy is used), `LinkedFileMissingCompactCopy` (the compact
copy is used, the full data are not available), `LinkedFileSizeChanged`, `LinkedFileChanged`
(SHA-256). The GUI shows them in the status bar after opening a project; the CLI prints them as
`note:` lines when a command loads the project.

**Pack / unpack** (Project page → Pack project… / Unpack project…, CLI `pack` / `unpack`):

```
boretherm-cli pack office.boretherm [office.zip] [--trt-data] [--json [file]]
boretherm-cli unpack office.zip [folder] [--overwrite] [--json [file]]
```

One zip file:

| Entry | Content |
|---|---|
| `<name>.boretherm` | the project, its linked paths rewritten to the entries below (relative) |
| `boretherm-pack.json` | manifest: `fileType` "BoreTherm project pack", `formatVersion` 1, `project`, `files` (entry, kind, originalPath, size, sha256) |
| `files/plan/<file>` | the site plan, when it is linked (a stored plan travels inside the project) |
| `files/fmu/<file>.fmu` | the FMUs of the co-simulation system |
| `files/tables/<file>.csv` | the CSV tables of the co-simulation system |
| `files/trt/<file>` | the linked TRT data files, only with `--trt-data` (GUI: asked, with their size); without them the packed project keeps their absolute paths and works with its stored data |
| `<name>.boretherm.fem` | the saved 3D analysis results next to the project (W6-fem-run, section 17), when there are any (stored, already compressed); the manifest names it as `femResults`; Unpack puts it next to the project, where Open finds it. The GUI packs its current 3D results even when they are not saved yet |

Each file is packed once (several blocks may share a table); a missing file is a warning
(`PackFileMissing`). Text files are deflated, compressed formats (PNG, JPEG, PDF, FMU, zip) and
files over 256 MB are stored; archives and files over 4 GiB use ZIP64. The archive is written to
`<file>.part` and renamed at the end, so a failed or cancelled pack leaves no half-written file.
Unpacking checks every entry name first (`..`, absolute paths and drive letters are refused,
`ZipUnsafeName`) and refuses to overwrite existing files unless `--overwrite`
(`UnpackTargetExists`); the GUI unpacks into a new folder named after the archive and opens the
project. Code: `core/include/boretherm/io/project_files.hpp`, `io/embedded_file.hpp`,
`trt/trt_storage.hpp`, the zip writer `core/src/fmi/zip_writer.*` (also for the FMU export).

**Compatibility.** The keys are additive: they are written only when set, so projects without a
stored plan or TRT data files are written exactly as before, and older BoreTherm versions ignore the
keys (they draw the plan from `path` and evaluate the stored records). The keys hold data, not
options, so the `compat` detection of the validation tests (`tests/validation/validation_helpers.hpp`)
has nothing to flag: results do not depend on them.

## 15. Export: export-fmu and export-modelica (plan P12c / P12d)

### export-fmu

```
boretherm-cli export-fmu office.boretherm                       # -> office.fmu (model identifier BoreTherm_office)
boretherm-cli export-fmu office.boretherm field.fmu --model dynamic --params ground.conductivity,design.groutConductivity
```

Writes the borehole field as an **FMI 2.0 Co-Simulation FMU** for 64-bit Windows (details:
`docs/fmu_export.md`). The FMU runs the co-simulation stepper of section 12 and carries the project,
the pre-computed g-function and the BoreTherm C API with its runtime DLLs (about 45 MB with the default
compression). Inputs `T_in` [K], `m_flow` [kg/s], `Q_ground` [W]; outputs `T_out`, `Q_flow`, `T_f`,
`T_b`, `dp`, `Q_mean`, `T_in_used`; calculated parameters `m_flow_nominal`, `dp_nominal`, `T_start`,
`L_total`.

| Option | Meaning |
|---|---|
| `<out.fmu>` or `--out f` | The FMU (default: the project's file name with `.fmu`) |
| `--model steady\|short-time\|dynamic` (`--borehole-model`) | Borehole model (default the project's) |
| `--step <s>`, `--horizon-years N`, `--reverse-flow ...`, `--preload-years N --preload-power <W>\|--preload-loads` | Stepper options as in section 12; the FMU's g-function covers the pre-conditioning and the horizon |
| `--params id1,id2,...` | Registry ids (`boretherm-cli params`) as FMU parameters (fixed, set before the initialisation; `.`, `[`, `]` become `_`). A changed value recomputes the g-function at `fmi2ExitInitializationMode` through the disk cache |
| `--heat-rate` | Start value of the Boolean parameter `heatRateInput`: `Q_ground` drives the field instead of `T_in` |
| `--no-embed-gfunction` | Do not embed the g-function (computed at initialisation) |
| `--name <text>`, `--identifier <id>` | `modelName` / `modelIdentifier` |
| `--level 0..9` | Deflate level (0 = stored, larger and faster; default 6) |
| `--binaries <dir>`, `--cache-dir <dir>` | Where `boretherm_fmu.dll` / `boretherm_capi.dll` are (default: next to the program); the g-function cache |

JSON (`--json`): `boretherm.export-fmu/1` with file, size, identifier, GUID, the stepper setup, the
parameters, the runtime DLLs and the archive entries.

### export-modelica

```
boretherm-cli export-modelica office.boretherm --target buildings --name OfficeField   # -> OfficeField.mo
boretherm-cli export-modelica office.boretherm --target aixlib --out -                  # to standard output
```

Writes a `<Library>.Fluid.Geothermal.Borefields.Data.Borefield.Template` record (filling, soil,
configuration with the borehole coordinates, pipe data, nominal flow per borehole and pressure drop)
for the borefield models of **Buildings**, **AixLib** or **IBPSA** (`docs/modelica.md` §5). Projects
with features these models cannot represent are refused (exit 1) with the list: inclined boreholes,
coaxial or triple-U pipes, groundwater flow, connections other than all in parallel, borehole sections,
boreholes of different length, depth or radius. Approximated with a note: ground layers (effective
conductivity and heat capacity), the pipe contact resistance (left out), the geothermal gradient (the
mean undisturbed temperature; the record's documentation gives `TExt0_start` and `dT_dz`). Options:
`--name`, `--within <package>`, `--library-version` (documentation only), `--use-rb` (use BoreTherm's
R_b* at the nominal flow: `use_Rb = true`), `--soil-density`, `--filling-density` (to split the
volumetric heat capacities; 1800 / 1600 kg/m³).

## 16. Load tools: loads generate-hourly, per-year, time-series, generate-btes (plan P19, P23)

Subcommands of `loads` for the load tools of the Loads page (theory.md §23, §20.10). All take a project
(`--set` / `--overrides` apply first), print a table of annual sums, and write the changed project
with `--out <file|->`; without `--out` nothing is written (a dry run). JSON document
`boretherm.loads/1` with `action`.

### loads generate-hourly

```
boretherm-cli loads generate-hourly office.boretherm [--method synthetic|equal]
              [--pattern residential|office|continuous] [--mean-temperature C] [--annual-amplitude K]
              [--daily-amplitude K] [--weather K] [--heating-limit C] [--cooling-limit C] [--seed N]
              [--flat-dhw] [--peak-at demand|month-end] [--no-peaks] [--add-peaks] [--years N]
              [--out hourly.boretherm] [--csv hourly.csv]
```

Hourly building loads from the monthly loads; the project's load mode becomes `Hourly`. Every 730 h
month keeps its energy; its peak power is held for its duration (whole hours, at the hours of highest
demand, or at the month end with `--peak-at month-end`, the default of `--method equal`) and is the
month's largest hour. `--pattern` sets the usage pattern and its heating / cooling limits (the other
options override them); `--add-peaks` adds the peak block on top of the month's energy (the monthly
model's rule, as the classic monthly method builds hourly loads); `--no-peaks` ignores the peaks. One year (8760 h, repeated by
the simulation) is generated, or the whole period when the monthly loads per year are on; `--years N`
forces N years. Hour 0 is the first hour of the project's start month. `--csv` writes
`hour,heating_kW,cooling_kW,dhw_kW[,outdoor_C]`. Notes (a peak that cannot be held or is below the
month's mean power) go to standard error.

JSON: `method`, `pattern`, `years`, `hours`, `perYear` (per year: `heating`, `cooling`, `dhw` with
`energy_MWh`, `max_kW`, `fullLoadHours`), `notes`, `csv`, `output`.

### loads per-year

```
boretherm-cli loads per-year office.boretherm [--import years.csv]
              [--growth P [--kind compound|linear] | --step P] [--from Y] [--only heating,cooling,dhw]
              [--no-peaks] [--off] [--export years.csv] [--out grown.boretherm]
```

Monthly loads for every year of the calculation period (`loads.perYear`, an option of the monthly
load mode). `--import` reads the table (CSV: one row per year and month, `year, month, heating_MWh,
cooling_MWh, dhw_MWh, peakHeating_kW, peakHeatingDuration_h, peakCooling_kW, peakCoolingDuration_h`;
header optional, trailing columns may be left out) and switches it on. `--growth P` fills it from the
monthly table with P % per year (compound by default, `--kind linear`), `--step P` with one change of
P % from year `--from` (default 2) on; `--only` limits the change to some energies, `--no-peaks` keeps
the peak powers; the table gets `settings.years` years. `--off` switches the table off (it stays in the
project). `--export` writes the table in the import format. JSON: `enabled`, `years` (per year the
annual `heating_MWh`, `cooling_MWh`, `dhw_MWh` and the largest `peakHeating_kW`, `peakCooling_kW`),
`output`.

The project keys work with `--set` too, e.g. `simulate grown.boretherm --set loads.perYear.enabled=false`.
`simulate` names the load mode "monthly base + peak loads per year" and adds `loadsPerYear` (years in
the table) to its JSON when the table is used; `validate` checks the table (values ≥ 0, at most 100
years; a warning when it is shorter than the period: the later years use its last year).

### loads time-series (plan P23 A)

```
boretherm-cli loads time-series store.boretherm [--import series.csv [--time-unit s|min|h|d] [--row-step S]
              [--load-unit W|kW] [--extraction-positive] [--flow-unit U] [--direction-column NAME|N|none]]
              [--flow-basis total|per-borehole] [--out series.boretherm]
```

Imports time-series loads from CSV (load mode `TimeSeries`, theory.md §20.10), or shows the stored
series and changes its flow basis. The columns are found by header name — `time`, `Q`/`load`/`power`,
`flow` (volume flow), `mdot`/`m_dot`/`m_flow`/`mass flow` or `flow [kg/s]` (mass flow), `Tin`/`inlet`,
`dir`/`direction` — or, without a header, taken in the order time, Q [, flow] [, Tin]. The numbers are
converted with the options:

| Option | Meaning |
|---|---|
| `--time-unit s\|min\|h\|d` | unit of the time column (default s); `--row-step S` ignores it: rows every S seconds |
| `--load-unit W\|kW`, `--extraction-positive` | unit and sign of the load column (BoreTherm stores > 0 = injection) |
| `--flow-unit m3/s\|l/s\|m3/h\|l/min\|kg/s\|kg/h\|t/h` | unit of the flow column; the mass units store a **mass flow** (`massFlow_kgs`), converted at run time with the density at the inlet temperature (T-P23-1). Default m3/s, or kg/s for a column named as a mass flow |
| `--flow-basis total\|per-borehole` | the flow is the pump's (default) or the **mean flow per borehole**; the whole field's flow then follows from the connections, Σ borehole flows = N × q (T-P23-2) |
| `--direction-column NAME\|N\|none` | the flow-direction column (+1 normal = the connections as drawn / charging, −1 reversed, 0 keep): a header name or a 1-based column number; `none` ignores a column named `direction` |

Without `--import`, `--flow-basis` changes the stored series. The text output and the JSON give the
rows, the step, the columns, the flow basis, the factor whole field / per borehole of the project's
network, the whole-field flow (min, max, mean) and the direction counts. JSON: `import`, `rows`,
`step_s`, `duration_s`, `repeatsYearly`, `columns`, `flowBasis`, `perBoreholeFactor`, `fieldFlow`
(`min_m3s`, `max_m3s`, `mean_m3s`), `direction` (`normal`, `reversed`, `keep`), `output`.

### loads generate-btes (plan P23 F)

```
boretherm-cli loads generate-btes store.boretherm [--charge-months 5-9] [--discharge-months 11-3]
              [--control tin|load] [--charge-tin C] [--discharge-tin C] [--charge-load kW] [--discharge-load kW]
              --flow V | --charge-flow V --discharge-flow V [--flow-unit U] [--flow-basis total|per-borehole]
              [--charge-hours 8-18] [--discharge-hours 0-24] [--row-step S] [--no-dynamic]
              [--csv series.csv] [--out store_operation.boretherm]
```

One year of seasonal operation of a borehole thermal energy store (theory.md T-P23-3), repeated every
year, for the design stage when no measured series exists. Months (1–12) charge, rest or discharge
(`11-3` runs over the new year, `1,2,12` lists months, `none`; months in neither list rest; a month in
both is an error); the defaults are May–September charging and November–March discharging. The year
starts in the project's start month. `--control tin` (default) prescribes the inlet temperature
(defaults 70 / 30 °C), `--control load` the ground load in kW (charging injects, discharging extracts).
The flows are in `--flow-unit` (default l/s; kg/s, kg/h, t/h give a mass flow) on `--flow-basis`.
`--charge-hours` / `--discharge-hours` limit the daily operation (`22-6` over midnight); outside them, at
rest the pump is off (flow 0, direction 0). `--row-step` is 300–3600 s and divides one hour (default
3600). The series gets the direction column: +1 charging, −1 discharging, 0 off.

Unless `--no-dynamic`, the dynamic borehole model is switched on and follows the series:
`settings.dynamic.inlet` = `PrescribedInletTemperature` (or `PrescribedLoad`), `flow` = `FromTimeSeries`,
`direction` = `FromTimeSeries`. `--csv` writes `time_s, Tin_C|Q_W, flow_m3s|massFlow_kgs, direction`.
JSON: `months` (12 × `charge|rest|discharge`), `control`, `dynamic`, the series summary of
`loads time-series`, `csv`, `output`.

**Project keys (P23).** Written only when set, so older projects are written unchanged:
`loads.timeSeries.massFlow_kgs`, `loads.timeSeries.flowBasis` (`Total|PerBorehole`),
`loads.timeSeries.direction` (`[1, -1, 0, ...]`), `settings.dynamic.groundCoupling`
(`Uniform|PerRing|PerBorehole`), `settings.dynamic.direction`
(`Fixed|FromTimeSeries|Automatic|TimeSeriesThenAutomatic`), `settings.dynamic.reversalHysteresis_K`
(default 1), `settings.dynamic.reversalMinTime_s` (default 3600) and `settings.dynamic.window` =
`SteadyOnly`. All work with `--set`, e.g.
`simulate store.boretherm --set settings.dynamic.groundCoupling=PerRing --set loads.timeSeries.flowBasis=PerBorehole`.

## 17. FEM temperature field: fem-field (W6-fem-field, plan P9x)

```
boretherm-cli fem-field project.boretherm [--times 1,10,25] [--out <folder>] [--stem field]
              [--csv <evaluation.csv> | --no-evaluation] [--ascii] [--memory MB] [--no-cache]
```

Runs the project with the FEM engine (a project set to the analytic engine is switched for this run,
with a note), keeps the ground temperature field of the run (theory §19.15) and writes it at the given
times.

**Reuse (W6-fem-run, theory §19.17).** The FEM run does not depend on the loads. When the saved 3D
results next to the project (`<project>.boretherm.fem`, written by the GUI on Save) or the cache
(`%LOCALAPPDATA%\BoreTherm\femcache`, or the folder in the environment variable
`BORETHERM_FEM_CACHE`) hold a run with the same fingerprint (field, ground, borehole construction,
fluid and flow, mesh and domain, period and time grid), it is reused and only the superposition with
the project's current loads is done; a new run is written to the cache (2 GB, the least recently used
runs removed first). The text output says `FEM results : reused the saved 3D results …`, `reused from
the cache` or `computed`; the JSON has `femResults` (`saved`, `cache`, `computed`), `fingerprint` and
`created` (the date of the FEM run). `--no-cache` runs the FEM without reading or writing saved or
cached results.

`simulate` and `size` keep running the FEM engine with `--set settings.gfunction.engine=FEM`
(scripts and tests use it); the GUI designs with the analytic model and has the FEM as its separate
3D analysis (`--set settings.analysis3D=true` switches that option in a project file).

**Physics of the 3D analysis (W7-fem-contracts, theory §19.18).** `--set settings.fem.groundPhysics=Simple|CoupledTH`
and `--set settings.fem.boreholePhysics=SteadyState|Transient` choose the physics; the time stepping,
coupling, boundary and initial settings are `settings.fem.transient.*`, `settings.fem.coupling.*`,
`settings.fem.boundary.*` (with `wells`) and `settings.fem.initial.*`, the hydraulic data
`ground.hydraulics.properties.*` / `ground.hydraulics.water.*` and `ground.layers[i].hydraulic.*`
(`boretherm-cli schema project` lists every key). `--set settings.fem.level=Full` (W7-fem-direct, plan §8c:
the Project page's "Full FEM") runs Simple + SteadyState as the direct 3D simulation (theory §19.20: the
ground stepped with the actual loads, no g-function; the fingerprint includes the loads); the default
`Simple` is the FEM g-function. With `--set settings.fem.boreholePhysics=Transient` (W7-fem-bhe-transient, theory
§19.23) the direct simulation keeps full transient boreholes (fluid transit, fluid / pipe / grout storage, pump off,
flow reversal, series / parallel strings); the fully coupled TH ground runs with steady-state boreholes (W7-fem-th,
theory §19.25) and with full transient boreholes (W7-fem-combined, theory §19.26): **every combination of the two
selectors runs**. A conflicting legacy borehole model (short-time or dynamic) with a direct combination is refused with
a coded error (exit code 1).
The JSON of `fem-field` has `execution` (`groundPhysics`, `boreholePhysics`, `path`, `gfunction`): the
calculation path that produced the results.

**Transient boreholes and the near-borehole model (W7-fem-bhe-transient, theory §19.21, §19.23).**
`settings.fem.transient.control` = `Auto` (default, W7-fem-combined: `LoopPower` with transient boreholes,
`WallPower` with steady-state ones) | `WallPower` | `LoopPower` | `InletTemperature` (the inlet temperature needs
time-series loads with `Tin_C`); the key is written only when it is not `Auto` (project files with an older transient
block keep their explicit control); `settings.fem.transient.boreholeDz` (axial cell length [m], 0 = automatic 1 m),
`settings.fem.transient.subStepsPerTransit` (0 = automatic 40), `settings.fem.transient.pipeVolumetricHeatCapacity`
(pipe walls [J/(m3 K)], default 1.8e6; 0 = TRCM without pipe capacity) and `settings.fem.transient.nearField` =
`Auto` | `RadialSubgrid` | `WellIndex` (every direct run). W7-fem-combined (plan §8e): every pipe can have its own
wall heat capacity, `design.pipe.volumetricHeatCapacity` and `design.innerPipe.volumetricHeatCapacity` [J/(m3 K)]
(0 = `pipeVolumetricHeatCapacity` above), and a borehole section its own for the U-tube legs / the coaxial outer pipe,
`design.sections[i].pipeVolumetricHeatCapacity` (e.g. a steel casing near the surface, about 3.6e6); written only when
set, used only by the transient boreholes. The 3D results file of a direct run stores the series `loopPower_W`,
`boreholeStorage_J`, `Tin`, `Tout`, the sub-step extremes and `conservation.loopResidual_J` (loop energy − wall
energy − borehole storage change). Example:

    boretherm-cli fem-field project.boretherm --set settings.fem.level=Full ^
        --set settings.fem.boreholePhysics=Transient --set settings.fem.transient.control=LoopPower

**Materials of the direct modes (W7-fem-materials, theory §19.22).** `ground.material.*` (homogeneous ground) and
`ground.layers[i].material.*`: `entry` = `Bulk` | `SolidPorosity`, `conductivityH`, `conductivityV` (anisotropy),
`heatCapacity` (bulk C, or (ρc)_s of the solid); the water's `ground.hydraulics.water.thermalConductivity`
(λ_w, default 0.58 W/(m K)); the porosity is `ground.hydraulics.properties.porosity` /
`ground.layers[i].hydraulic.porosity`. Only the direct paths (`settings.fem.level=Full`, transient boreholes,
fully coupled TH) use them; the analytic design and the FEM g-function keep the Ground page values. Example:
`--set ground.layers[1].material.entry=SolidPorosity --set ground.layers[1].material.conductivityH=3.2
--set ground.layers[1].material.conductivityV=2.4 --set ground.layers[1].material.heatCapacity=2.0e6`.

**Thermal boundaries of the direct modes (W7-fem-transport, theory §19.24).** `settings.fem.boundary.thermalTop`,
`thermalBottom`, `thermalSides` = `Initial` (default: the initial temperature) | `ZeroFlux` | `GeothermalFlux` (bottom
only, needs `settings.fem.initial.temperature=Undisturbed`), `inflowAtInitialTemperature` and `inflowTemperature`
(groundwater entering through a zero-flux or geothermal face) apply to every direct path, e.g.
`--set settings.fem.level=Full --set settings.fem.boundary.thermalSides=ZeroFlux --set settings.fem.boundary.thermalBottom=GeothermalFlux`.
The saved direct results (`DRCT` block of the results file) list the heat per face group (`top`, `bottom`, `sides`,
`wells`, `background`).

**Fully coupled TH ground (W7-fem-th, theory §19.25).** `--set settings.fem.groundPhysics=CoupledTH` with steady-state
boreholes runs the two-way coupled groundwater flow and heat transport (`fem-field`; `simulate` / `size` with the FEM
engine): per time step the flow with the density and viscosity of the current temperature and the heat transport are
iterated to `settings.fem.coupling.*` (`temperatureAbsTol_K`, `temperatureRelTol`, `pressureAbsTol_Pa`,
`pressureRelTol`, `residualTol`, `maxIterations`, `relaxation`, `maxRetries` 0..12, default 6; a saved value above 12
is refused with `FemSettingInvalid`); a step whose coupling does not converge
is repeated smaller, persistent failure stops with the coded error "Fully coupled TH: … did not converge …" (exit 1).
A prescribed Darcy velocity is refused with this physics: set it to 0 and give the regional flow as
`settings.fem.boundary.headGradient` / `gradientDirection` (the gradient that `fem-flow <project> --from-darcy` reports;
the GUI converts it in one step on Full FEM › Physics & run). The saved direct results add
`couplingIterations`, `maxCouplingIterations`, `couplingFailures`, the water balance (`massResidual_kg`,
`massThroughput_kg`, `massRelative`), the water per face group (`water_kg`), the entry `pore water` (heat and water
entering storage) and the frames `Hydraulic head` [m] and `Darcy velocity` [m/s].

**Fully coupled TH + full transient boreholes (W7-fem-combined, theory §19.26).** `--set
settings.fem.groundPhysics=CoupledTH --set settings.fem.boreholePhysics=Transient` runs the transient borehole columns
(multirate sub-steps, the near-borehole sub-grid) inside the coupling iteration of the coupled ground; borehole and
ground states are committed together after convergence; the energy closes per step for the ground and as loop = wall
+ borehole storage for the boreholes (validation §42). The saved direct results also carry the time split of the run
(`stepping.secondsFlow`, `secondsTransport`, `secondsFactor`, `secondsSolve`, `secondsColumns`) and the flow solves
of the coupling (`flowSolves`, `flowLagged`). `settings.fem.initial.spinUp_s` (> 0) lets the ground and the
groundwater flow evolve without loads and with the pump off for that time before the operation starts; the results
and the balances begin after it (note "Spin-up …"). Example:

    boretherm-cli fem-field project.boretherm --set settings.fem.level=Full ^
        --set settings.fem.groundPhysics=CoupledTH --set settings.fem.boreholePhysics=Transient ^
        --set ground.hydraulics.water.densityLaw=Linear --set ground.hydraulics.water.viscosityLaw=Vogel

**Sizing with the direct 3D model and what the direct paths do not offer.** `size --3d` (the GUI action "Size with
3D…" on Full FEM › Physics & run; core `sizeBoreholeLength3D`, theory §19.26.6) sizes the length with the selected
direct model: every trial length a full 3D run from the undisturbed ground, starting at the 2D size. `size` without
`--3d` and `optimize` stay 2D; with the FEM engine and a direct path `size` stops with the coded error "Sizing: the
full 3D simulation (Full FEM) has no g-function …" (exit 1). The co-simulation stepper, the C API
stepper and FMU export need a g-function: with `settings.fem.level=Full` and the FEM engine they stop with the coded
error "Co-simulation, FMU and stepper: the full 3D simulation … has no g-function and no stepper …" (exit code 1); with
the analytic engine they run the 2D model as before (the 3D level does not apply there).

The files written:

- `<stem>_y<years>.vtu` per time (`_m<months>` for times between whole years): a VTK XML unstructured
  grid of the FEM mesh (hexahedra or tetrahedra) with the point data `Temperature` [°C] and
  `TemperatureChange` [K] (against the undisturbed ground). Coordinates: x east, y north as the
  borehole heads, **z = elevation** (negative below the surface). Raw binary data by default,
  `--ascii` for readable (larger) files.
- `<stem>.pvd`: the ParaView collection of these files with the time in years. Open it in ParaView
  (File → Open) to step through the times; *Contour* on `TemperatureChange` gives the isotherms,
  *Slice* the plan and section views.
- `<stem>_evaluation.csv` (or `--csv <file>`; `--no-evaluation` skips it): the site plan's Boundary
  polygons and the project's evaluation lines and points (`femEvaluation`, set on the 3D analysis
  page or in the project file) with the largest warming and cooling over the period, their times
  and the first year each threshold is reached; the isotherm extents (area, reach from the nearest
  borehole, downstream length with groundwater) at the end of the period and at most; and the
  largest warming / cooling of every object per month end. English headers, comma separated, `.`
  decimals, years as decimal numbers.

`--times`: years (decimals allowed, rounded to month ends), within the simulation period; default
the first year and the end of the period. Default folder: `<project>_fem_field` next to the
project. `--memory MB` limits the kept field (default 1000 MB; above it fewer time steps are kept,
a note says so). The field superposes the **monthly base loads**; peak loads are not in it.
Thresholds are the project's (`femEvaluation.thresholds`, default −2, −1, +1, +2 K); BoreTherm
does not check legal limits.

JSON (`--json`): `directory`, `files`, `evaluationCsv`, `element` (`Hex8` / `Tet4`), `nodes`,
`elements`, `framesKept`, `stepsInRun`, `fieldBytes`, `femResults`, `fingerprint`, `created`,
`timesYears`, `thresholds_K`, `objects`
(name, source `siteBoundary` / `user`, kind, `distance_m`, `maxWarming_K`, `maxCooling_K`,
`firstExceededYears` per threshold, null = never) and `isotherms` (`threshold_K`, `areaEnd_m2`,
`reachEnd_m`, `reachMax_m`, `downstreamEnd_m`, `downstreamMax_m`, null without groundwater).

The evaluation objects in the project file (written only when used):

```json
"femEvaluation": {
  "siteBoundaries": true,
  "objects": [ { "name": "Property line north", "kind": "Line", "points": [[-20, 15], [40, 15]],
                 "closed": false, "top": 0, "bottom": 0 },
               { "name": "Neighbour well", "kind": "Point", "points": [[35, -5]], "top": 10, "bottom": 60 } ],
  "thresholds": [-2, -1, 1, 2],
  "mapDepth": -1,
  "reportYears": [10]
}
```

`top` = `bottom` = 0: the boreholes' depth range; `mapDepth` < 0: the plan map is averaged over the
boreholes' active length.

## 18. Thermal plume: plume (W6-plume)

```
boretherm-cli plume project.boretherm [--source 2d|3d|both] [--thresholds -3,3] [--time end|worst|<years>]
              [--depth avg|<m>] [--png out.png] [--csv out.csv] [--no-cache] [--json [file|-]]
```

Computes the design (the analytic 2D model, as Calculate in the GUI) and the **thermal plume**: the
change of the ground temperature against the undisturbed ground around the field in the plan, at the
end of every month of the period, from the **monthly base loads** (peak loads are not included;
theory §24). For every threshold it gives the region beyond it (cooling: colder than a negative
threshold, warming: warmer than a positive one):

- its **area**, its **reach** (the largest distance from the field edge, the convex hull of the
  boreholes' plan traces), and with groundwater its **length downstream** of the field's downstream
  edge and its **width** across the flow;
- the **clearance** to every property line (the site plan's Boundary polygons) and to every
  evaluation line or point of the project (`femEvaluation.objects`, the same objects as for the 3D
  analysis); a **negative clearance is a crossing** (the region reaches beyond the property line, or
  the object lies in the region, by that much);
- the **first month** at which the threshold is reached on each object (never: `-`/null);
- the largest area over the period and its month.

Options:

- `--source 2d` (default): the analytic plume (finite line sources; with groundwater moving finite
  line sources; inclined boreholes as vertical pieces; the effective homogeneous ground of the design;
  the heat split of the boundary condition). `3d`: the FEM temperature field of the 3D analysis (needs
  the 3D module; the saved 3D results next to the project or the cache are reused as by `fem-field`,
  `--no-cache` runs the FEM again). `both`: both on the same map and evaluated in the same way.
- `--thresholds t1,t2,…`: signed thresholds in K (default: the project's `plume.thresholds`, ±3 K).
  BoreTherm has no built-in legal limits.
- `--time end` (default) the end of the period; `worst` the month with the largest extent (the sum of
  the areas beyond the thresholds); `<years>` the month ending at that time (e.g. `10`, `2.5`).
- `--depth avg` (default) averaged over the active borehole length (shallowest top to deepest
  bottom); `<m>` at that depth.
- `--csv <file>`: the extents and the clearances as CSV (English headers, `.` decimals; the same file
  as *Export CSV…* on the Thermal plume page).
- `--png <file>`: the plan figure (1400 × 1000): the change raster of the first source, the isotherms
  (2D solid, 3D dashed), the site plan's polygons and a DXF drawing (as lines), the boreholes, the
  evaluation objects and the dimension lines (crossings in red). Pictures and PDF plans are drawn
  only by the GUI and the report.

The map window covers the field, the site plan's boundaries and the objects with a margin of
max(10 m, 2.5 √(α t_end)) and, with groundwater, the distance the heat travels downstream; it is
enlarged while an isotherm touches its edge (a note says so). An isotherm of the 3D plume that
reaches the edge of the FEM block is noted (its extents are lower bounds).

The project file keeps the plume settings of the GUI (written only when not the default):

```json
"plume": { "thresholds": [-3, 3], "source": "Both", "time": "End", "month": -1, "depth": -1 }
```

`source` `Analytic2D` | `Fem3D` | `Both`, `time` `End` | `Worst` | `Month` (with `month`, 0-based),
`depth` < 0: averaged. The CLI uses its own options (default `2d`, `end`, averaged) and takes only
the thresholds from the project.

JSON (`--json`, schema `plume`): `thresholds_K`, `time`, `depth_m` (null: averaged), `map` (x0, x1,
y0, y1, nx, ny), `groundwater`, `flowAngle_rad`, `femResults` (with 3D), `objects` (name, kind
`PropertyLine` / `Line` / `Point`), `results` per source (`source` `2d` / `3d`, `month` 1-based,
`timeYears`, `depth_m`, `zTop_m`, `zBottom_m`, `isotherms`: `threshold_K`, `area_m2`, `reach_m`,
`downstream_m`, `width_m` (null without groundwater), `clipped`, `areaMax_m2`, `monthAreaMax`,
`reachMax_m`, `monthReachMax`, `clearances`: `object`, `distance_m`, `crossing`, `firstMonth`), `csv`,
`png`, `notes`.

```
boretherm-cli plume office.boretherm --thresholds -2,-1,1 --time worst --png plume.png --csv plume.csv
boretherm-cli plume office.boretherm --source both --depth 50 --json plume.json
```

## 19. Cost estimate: cost, optimize --price-list (W4-cost)

```
boretherm-cli cost project.boretherm [--price-list list.btcost] [--simple|--detailed] [--csv out.csv|-] [--json [file|-]]
boretherm-cli optimize project.boretherm --price-list list.btcost [...]
```

The cost estimate of the project's field (design: `docs/cost_model.md`, formulas: theory §25). Two
models give the same result:

- **Simple** (`costs.mode` `Simple`, the default): fixed + per borehole to drill + per metre (active or
  drilled length) + per circuit + per metre of trench, then contingency and VAT. A project without cost
  settings uses its old optimization prices (`optimization.cost`) as the simple model with basis
  Active and 0 % contingency and VAT: the cost the optimizer computed before W4-cost, bit for bit.
- **Detailed** (`costs.mode` `Detailed`): an itemised price list. The quantities come from the design
  (drilled metres by drilling class and ground layer, deep boreholes, probe metres, grout and cuttings
  volume, circuits, manifolds, welds, trench, connection pipes along the trench tree, header, fluid and
  concentrate mass, TRT count, building entries); the prices from the project's price list, or the
  built-in **"Germany 2026 (indicative)"** (public sources, not a quote; the output says so).
  Regional and index factor, contingency and VAT are settings of the list.

Options: `--price-list <file>` loads a price list (a `.btcost` file or a project with one) and switches
to the detailed model; `--simple` / `--detailed` choose the model for this run (detailed without a list:
the built-in one); `--csv <file>` writes the item table (`pos,id,group,name,quantity,unit,unit_price,
total,din276,enabled`, then the group totals, net, contingency, net total, VAT and gross; `-`: standard
output). Exit code 0.

JSON (`schema cost`): `model`, `currency`, `priceList` {`name`, `date`, `builtin`, `regionalFactor`,
`indexFactor`} (detailed), `quantities` {...}, `items` [{`id`, `item`, `group`, `name`, `quantity`,
`derivedQuantity`, `overridden`, `unit`, `listPrice`, `unitPrice`, `total`, `din276`, `source`,
`enabled`, `outOfRange`, `range`}], `groups` [{`id`, `name`, `din276`, `total`}], `net`,
`contingencyRate`, `contingency`, `netTotal`, `vatRate`, `vat`, `gross`, `indicators`
{`perDrilledMetre`, `perActiveMetre`, `perKwPeak`, `peakExtraction_kW`}, `warnings`, `csv`.

**Key paths.** Every setting is a project key (layout: `core/src/cost/cost_json.hpp`), so `--set` and
batch jobs reach it. Item ids contain a dot; the key path takes them as they are:

```
boretherm-cli cost p.boretherm --set costs.mode=Detailed --set costs.priceList.items.C.grout.unitPrice=650
boretherm-cli cost p.boretherm --set costs.simple.perMetre=85 --set costs.simple.basis=Drilled
boretherm-cli cost p.boretherm --detailed --set costs.quantities.footLength=2 --set costs.quantities.headerLength=20
```

**Price list files** (`.btcost`, `schema price-list`): `{"fileType": "BoreTherm price list",
"formatVersion": 1, "name", "notes", "currency", "priceDate", "country", "regionalFactor",
"indexFactor", "contingency", "vat", "deepThreshold", "probePeXaFactor", "manifold": {"maxPorts"},
"groups": [...], "drillingClasses": [...], "probePrices": {...}, "concentratePrices": {...}, "items":
{"<id>": {...}}}`. A file is read over the built-in list: missing keys and items keep the built-in
values, so `{"fileType": "BoreTherm price list", "items": {"C.grout": {"unitPrice": 650}}}` is a
complete list. Built-in items can be disabled (`"enabled": false`), not removed; own items take any id
(`X.1`) with their own `name`.

**optimize.** Every candidate is estimated at its sized length with the project's cost settings (or
the list of `--price-list`); the objective *TotalCost* ranks by the net total (incl. contingency,
excl. VAT). The `optimize` document gains `costModel`, and every candidate `drilledLength` and, with
the detailed model, `costByGroup` (`{"A": ..., "B": ...}`).

**Compatibility.** Projects that use only the old four prices are written as before (no `costs`
key); `optimization.cost` stays and, in the simple mode, holds a copy of the simple model's four
prices for older versions. `"existing": true` on a borehole (connected, not drilled) is written only
when set. Costs have no thermal meaning, so the `compat` detection of the validation tests has nothing
to flag.

## 20. Groundwater flow: fem-flow (W7-fem-hydraulic)

```
boretherm-cli fem-flow <project> [--steady] [--from-darcy] [--vtu <file.vtu>] [--json [file]]
```

Builds the 3D analysis mesh of the project (as `fem-field` and the 3D view: `settings.fem` mesh and
domain) and computes the **background groundwater flow** of the fully coupled thermo-hydraulic ground
(docs/theory.md 19.19): the initial hydraulic state of a fully coupled TH run
(`settings.fem.initial.pressure`: `Hydrostatic` — at rest — or `SteadyFlow` — the steady flow of the
hydraulic boundary conditions and wells) at the initial temperature, from the hydraulic data of the
ground (`ground.hydraulics`) and its layers (`ground.layers[i].hydraulic`) and the conditions
`settings.fem.boundary`. It works whatever the 3D ground physics is set to (a note says when the
project's physics is Simple: the data are then unused by the 3D analysis). Needs the FEM module.

- `--steady` computes the steady flow also when the initial pressure is hydrostatic.
- `--from-darcy` first converts the prescribed Darcy velocity (Ground page, `ground.groundwater` or
  the layers' `darcyVelocity`) into the head gradient that carries it, i = Σ v_l b_l / Σ K_l b_l over
  the active depth (v = K i for a homogeneous ground), sets Head sides, the steady-flow initial state
  and the prescribed velocity to 0 (as the GUI's "From the Darcy velocity…").
- `--vtu <file>` writes the point data `HydraulicHead` [m], `Pressure` [Pa, gauge],
  `DarcyVelocityX/Y/Up` [m/s] (Up = elevation component) and `DarcySpeed` (ParaView; depth as the
  mesh's z, positive down).

Printed: the mesh, the state, the head range, the mean / largest Darcy velocity (m/s and m/a), the water
balance per face of the ground block and of the wells, the largest node residual of the water balance
(relative to the node throughput; ~1e-15 for a direct solve) and, as notes, the groundwater inputs still
at their pre-filled ("assumed") values. JSON (`schema fem-flow`): `element`, `nodes`, `elements`,
`headNodes`, `initial`, `headMin_m`, `headMax_m`, `meanSpeed_m_s`, `maxSpeed_m_s`, `faces`
(`face` top / bottom / xMin / xMax / yMin / yMax, `inflow_m3_s`, `outflow_m3_s`),
`wellInjection_m3_s`, `wellExtraction_m3_s`, `relativeResidual`, `assumed` (project keys), `vtu`,
`seconds`.

```
boretherm-cli fem-flow p.boretherm --set settings.fem.boundary.headGradient=0.005 --steady
boretherm-cli fem-flow p.boretherm --set ground.hydraulics.properties.kxx=5e-12 --set ground.hydraulics.properties.kyy=5e-12 --steady --vtu flow.vtu
boretherm-cli fem-flow p.boretherm --from-darcy --json flow.json
```

A face report books the supply of a node that lies on two prescribed-head faces on one of them (the
sides first): where an inflow and an outflow face meet, both totals are smaller than the through-flow
by the same amount; the sum over all faces balances exactly.

## 21. System comparison: compare (P28)

```
boretherm-cli compare building.boretherm --json comparison.json
boretherm-cli compare building.boretherm --variants air,gas,pellet --scenario high --json
boretherm-cli compare building.boretherm --data local-comparison-data.json --json
boretherm-cli schema comparison
boretherm-cli schema comparison-data
```

The comparison uses the saved `comparison` object, or the default comparison
when the project does not yet contain one. The BHE subject always remains in
the variant filter. Default alternative IDs are `air`, `gas`, `oil`, `pellet`,
`district` and `hybrid`; unknown filter IDs or scenario names are errors.
Every enabled variant supplies the same building heat, DHW and cooling service.
Direct ground-load and time-series projects cannot supply that service basis
and are rejected. A cooling load requires cooling provision for every variant.

JSON follows the normal CLI envelope with kind `comparison`. It includes
`dataName`, `dataDate`, `convention`, `warnings`, the exact `assumptions` object
and a `variants` array. Each variant contains the `economics` cash flows and
cost-group annuities, `service` energy/performance balance, annual statutory and
direct-CO2 ecological estimates, criteria score, exclusion/lowest-cost markers
and BHE break-even year. `lowScenario` and `highScenario` use their configured
carbon-price anchors; they are sensitivities, not confidence intervals. An
undefined cost per kWh (for an absent service) is JSON `null`.

Component prices in the saved comparison are net. The engine applies the chosen
gross/net convention, annualises discounted replacements, energy and operation,
and credits grants and optional linear residual value. `lcohHeat` excludes cold
energy/cooling allocations; `lcohHeatCold` uses all useful heat plus cold.
`costOfCold` gives the separate cooling allocation. Explicit tariff overrides
and paths use the selected tax convention and must exclude separately modelled
fuel CO2 charges. Source data carry their own tax/time basis.

Coupling is selected by the project key `loads.spf.mode="FromFluidTemperature"`
(`Fixed` remains the default). The settings object `loads.spf.heatPump` contains
datasheet/generic/Carnot COP, capacity/source limits and heating-curve inputs.
Use a project/overrides JSON for structured COP points. Run `params <project>`
to discover supported scalar override IDs. Heat pump variants carry `vdi4650`:
the JAZ after VDI 4650 Blatt 1:2024 (`scopHeating`, `scopDhw`, `scopTotal`,
`coverage`, the factors used, `brineMin_C`, `notes`; `applicable` false and the
figures `null` outside the standard's tables). Its inputs are the heat pump
settings `variableSpeed`, `dhwInternalCoil`, `defrostDeduction` and
`measuredSpread_K` besides the COP model and the heating curve.

For saved comparisons the study registry also exposes `comparison.interest`,
`comparison.period`, `comparison.residualValue`, `comparison.grantRate`,
`comparison.drillingScale` and available price/carbon entries under
`comparison.data.<datum-id>`. Registry display units govern `study --param`,
as for other study inputs. Monte Carlo JSON adds `pBheCheapest`, BHE `bheLcoh`
and `bheSpf` statistics and per-variant `comparisonLcoh` statistics. These describe
the supplied uncertainty distributions, not an unconditional forecast.

The built-in `DE 2026-10` set is dated 18 October 2026. Plant investment follows
the KWW Technikkatalog 12/2025 cost curves (status `study`), service data VDI 2067
Tables A2/A3 (status `standard`); tariffs and the chiller and district-heating
connection costs remain labelled assumptions. The confirmed statutory factors end on 31 December 2026;
unverified 2027 replacements are not bundled as law. Automatic KfW grants are
indicative pending equipment, applicant and building eligibility. Review all
warnings before using the cost ranking. See [System comparison](system_comparison.md),
[theory section 27](theory.md#27-system-comparison-and-coupled-heat-pump-economics-boretherm-p28-2026-10-17)
and the [data provenance notes](../core/data/comparison/README.md).

## 22. Heat pump selection: heatpump

```
boretherm-cli heatpump building.boretherm --json
boretherm-cli heatpump building.boretherm --set heatPumpSelection.lockoutHoursPerDay=2 --json
boretherm-cli heatpump building.boretherm --set heatPumpSelection.operation=MonoEnergetic --set heatPumpSelection.bivalence_C=-5 --json
boretherm-cli heatpump building.boretherm --overrides candidates.json --size --json
boretherm-cli schema heatpump
```

The command simulates the project and writes the requirement sheet a brine/water heat pump must meet
(spec: [heat_pump_selection.md](heat_pump_selection.md), formulas: theory section 27.7): the heating
capacity at the design point (DHW surcharge, lock-out factor 24 / (24 - t), mono-energetic split with a
heating rod), the capacity at B0/W35 for catalogue comparison (B0/W35 is the rating point, not the design
point), the evaporator capacity and its consistency with the SPF the field was sized with, the source limits
(TfMin - margin, TfMax + margin, antifreeze), the sink temperatures and the lift, the brine flow and pump
head (field pressure drop + `headerPressureDrop_Pa` + `passiveHxPressureDrop_Pa` when the project cools passively;
each candidate adds its evaporator), the evaporator pressure drop guidance (35 kPa at 3.2 l/min per kW), the part-load profile with starts and the buffer rule
(hourly loads; with monthly loads estimated from a synthetic hourly profile, `partLoad.estimated` and the lines'
`estimated`), passive / active cooling (`coolingByHeatPump` false: by a separate unit, not checked against the
candidates) and the seasonal performance (SPF, VDI 4650 JAZ; `performance.sizedToRequirement` when the project's
heat pump has no nominal power and is sized to the requirement). `--no-candidates` does not validate the
candidates.

The design point: sink = heating-curve flow temperature at the design outdoor temperature (mono-energetic:
the bivalence temperature); source = the lowest field outlet temperature with flow (the evaporator inlet,
as EN 14511 rates the brine). `designPoint.sourceBasis` names the simulated temperature used.

Every enabled candidate of `heatPumpSelection.candidates` (EN 14511 test points, operating limits,
modulation, optional internal pump, evaporator pressure drop, cooling; the values of one unit, `units` identical
units in parallel, listed as "name × n") is checked line by line, `status` `met`, `tight` (margin below
`tightCapacityFraction`, default 10 %, or `tightTemperature_K`, default 1 K), `notMet` or `notApplicable`
with a `reason`, and simulated again in the fluid-temperature coupled mode with its COP model
(`simulation`: TfMin, TfMax, `limitsMet`, `sourceLimitMet`, SPF, JAZ, ground extraction and its change;
with `--size` also the required length). `--no-candidates` writes the sheet only.

Inputs: the project key `heatPumpSelection` (written only when used; defaults in the spec). Scalars with
`--set heatPumpSelection.<key>=<value>`; the candidates as a JSON array, e.g.
`--set 'heatPumpSelection.candidates=[{"name":"HP 12","points":[{"source_C":0,"sink_C":35,"cop":4.6,"capacity_kW":12.4}],"minSource_C":-5,"maxFlow_C":60}]'`,
or with `--overrides`. `validate` checks them. Projects with prescribed ground loads or time-series loads
have no building load and are refused (exit code 1).

JSON (`boretherm.heatpump/1`): `status`, `operation`, `designPoint`, `requirements` (an object keyed by
line id: `label`, `value`, `unit`, `explanation`, `applicable`, `flagged`, `estimated`, `note`), `sourceRange`,
`partLoad`, `performance`, `candidates` (`name`, `units`, `label`, `overall`, `meetsRequirements`,
`evaporatorPressureDrop_Pa`, `requiredHead_Pa`, `checks` keyed by line id, `simulation`, `warnings`), `anyCandidateMeets`, `warnings`. Every number has an `x-unit` in the schema; a
value that does not apply is `null`. Exit code 0, or 2 when at least one candidate was checked and none
meets the requirements. The result is a preliminary selection: check the manufacturer's data.