
# Calculations

> MCP: wywołaj `read_docs({ operations: [operation] })` i podaj tylko pola ze zwróconego `inputSchema`. Przykłady HTTP poniżej zawierają kopertę zapisu, `requestId` i identyfikatory nadawane przez MCP (`projectId` przy tworzeniu, `documentId` przy tworzeniu dokumentu). Nie dodawaj tych pól do wywołania MCP. Typ rewizji bierze się ze schematu operacji.

A saved calculation has one `calculationId`, a type, state, keyed results, and a revision.
The registry exposes `catchment`, `surface-runoff`, `hydraulics/pipeline`, `hydraulics/weir`,
`reservoir`, `hydraulics/culvert`, `hydraulics/bridge`, `hydraulics/open-channel` and `hydrology/annual-maxima`.

## Discovery

POST `/api/v1/actions/calculations/types/list` lists registered types.
POST `calculations/types/get` with `{ "type": "catchment" }` returns its state schema,
default state, tasks, result keys, exported values, and slots.

POST `calculations/methods/list` lists registered methods. The optional `type` filter narrows the list.
POST `calculations/methods/get` with `{ "methodId": "catchment.qn" }` returns the input schema,
output schema, and method explanation. The `knowledge` entries are canonical method-reference
sections with `topicId`, `title`, and `bodyMarkdown`, including shared content and every declared
variant. Discovery does not fabricate a run or evaluate a method. GET on an action URL returns
its request and response schemas.

Successful calculation actions return `X-Calculation-Catalogue-Version: calculations.7`.
The catalogue comes from the calculation type registry.

## Road bridges

`hydraulics/bridge` stores a surveyed section, bank stations, three Manning roughness zones,
slope, design-flow selection, water-level selection, materials, foundations, abutments and piers.
Its methods are `bridge.waterLevel`, `bridge.opening`, `bridge.backwater` and `bridge.pierScour`.
The corresponding result keys use the `bridge/` prefix.

The default state is an editable schematic lowland section with two floodplains.
Water level uses compound Manning conveyance or preserves an entered elevation.
Opening calculations follow WR-M-12 §5.3.1 for an erodible bed or §5.3.2 for a non-erodible bed.
Both ice adjustments use the net opening at the strict 30 m boundary.

Backwater follows WR-M-12 §5.5 and pier scour follows §5.4 using the verified chart tables.
Authorised zero-limit chart extensions carry explicit warnings. Other out-of-range readings are
unavailable for design and retain diagnostic values. Without wet piers, pier scour is inactive.
Clearance uses the pre-scour backwater level.

Set `sizing: "bridge"` on an evaluate request to obtain a transient `bridgeProposal` beside
`results` and `evaluationBasis`. The proposal enumerates centimetre widths at the current centre,
within the surveyed section, and checks the complete hydraulic chain. It is never saved in results.
`sizeBridgeOpening(state, adopted)` and `withAdoptedOpening(state, proposal)` are exported from
`@operat/calculation-core/hydraulics`. Adoption replaces only the two abutment stations.

Oblique wings store `wingAngleDeg`. Non-cohesive soil can store `sedimentD90M` for local scour.
A pier can specify `scourMaterial` for the soil below protection and `approachZone` for the
velocity-distribution factor. The selected report receives all stored method results, so an
opening-only or scour-only report can use the water-level run's common survey evidence.

## Validation and evaluation

`calculations/validate` and `calculations/evaluate` accept `{ type, state, dependencies, projectId? }`.
Validation checks state and dependency admission. Evaluation returns `{ results, evaluationBasis }`.
Neither action saves results or changes project data.

For `hydraulics/open-channel`, `given: { "kind": "depth", "depthM": 1 }` computes discharge.
`given: { "kind": "discharge" }` computes normal depth from the `designFlow` slot.
The slot accepts `catchment/qp` with a probability selector and
`surface-runoff/peak-discharge` with a null selector.
The result key is `open-channel/result`, the method is `openChannel.manning`, and the exported
value is `open-channel/discharge`. Ambiguous terrace depths remain unavailable with candidate
depths in the evidence, so the caller can supply a depth instead of choosing a branch implicitly.

Without `projectId`, evaluation uses only the supplied state. Linked inputs require authorized
project context. Each dependency contains `slotKey`, `sourceCalculationId`, `valueKey`, and
`selector`. A value without a selector uses JSON `null`.

## Save an evaluated calculation

The `water-design/commands` action retains its project authorization, write envelope, and
water-design revision. Calculation operations use these payloads:

| Operation | Fields |
| --- | --- |
| `create_calculation` | `type`, `title`, `state`, `dependencies`, optional `evaluationBasis` |
| `update_calculation` | `calculationId`, `expectedRevision`, optional `state`, `dependencies`, and `evaluationBasis` |
| `rename_calculation` | `calculationId`, `title` |
| `delete_calculation` | `calculationId` |
| `save_catchment_analysis` | New: `creationId`, native `state`, optional `title`. Existing: `calculationId`, `expectedRevision`, native `state` |
| `import_catchment` | `calculationId`, `expectedRevision`, `geometry`, `coverage` |
| `update_catchment_geometry` | `calculationId`, `expectedRevision`, `geometry` |

Writes answer with an acknowledgement: the saved `calculationId` and all revisions changed by the
transaction (a catchment save adds its `featureId` and `layerId`). Read the calculation afterwards;
the response contains the write acknowledgement.
`expectedRevision` on update is the calculation revision, independent of the command's outer
water-design revision.

An omitted `evaluationBasis` makes no preview assertion. An empty array asserts that the saved
state has no active linked inputs. A supplied basis must match every active linked slot, source id,
value key, selector, and source revision exactly. A mismatch returns `SOURCE_CHANGED` and saves nothing.

Deleting a source while another calculation depends on it returns `DEPENDENCY_IN_USE`.
A link that closes a cycle returns `DEPENDENCY_CYCLE`. A stale calculation revision returns
`REVISION_CONFLICT`. Invalid source, value, slot, or selector admission returns `INVALID_DEPENDENCY`.
These codes appear in `validationCode`.

Every calculation write carries the existing presentation envelope `{ sessionId, lane:
'project-presentation', sequence }`. Keep this envelope, the complete command, and the outer
water-design revision unchanged on a resend after an unreachable server or lost acknowledgement.
The server records terminal results and rejections durably. An equal sequence
returns its recorded acknowledgement and revisions without repeating the write or emitting events.
Reusing a sequence for another payload is rejected. A different write still checks revisions and
conflicts when stale. A newer settled sequence supersedes older attempts.

Generic creation derives its calculation id from project, user, session, lane, and sequence;
native creation uses `native:<creationId>`. Resending cannot create duplicate rows.
Resource writes use the same
water-design command envelope. Admission is checked again before every recorded answer.

## Queries

The `water-design/query` action accepts these calculation query kinds:

| Kind | Fields | Result |
| --- | --- | --- |
| `calculations` | Optional `type`, `search`, `limit`, `afterId` | `calculations` summaries and `nextAfterId` |
| `unreadable_calculations` | — | Saved `calculations` that no longer read as their type; they can only be deleted |
| `calculation` | `calculationId` | Saved `calculation`, or `null` |
| `calculation_dependencies` | `calculationId` | `dependencies` |
| `dependency_options` | `type`, `state`, `slotKey`, optional `targetCalculationId` | Compatible source `options` |

Lists contain at most 100 summaries per page. Results and dependencies are available through the
individual queries. Reads never recalculate or write. Project opening recalculates outdated method
runs from saved state before those results are used as current inputs.

## Catchment resources

Catchment geometry belongs to the feature whose id equals `calculationId` on `system:calculations`.
Generic map edits can change visibility. Calculation commands own geometry and deletion.
Imported coverage contains `{ label, areaM2, runoffCoefficient }` rows and retains the supplied coefficient.
Use the matched [public catchment analysis](catchments.md#save-and-re-save-a-native-catchment) `calculationState` as the native state. The server resolves the bundle grid and derives the outlet point; callers supply no geometry or grid internals.

Native capture and outlet geometry are immutable. Retrying the same native `creationId` reuses the
calculation and does not bump its revision when the state is unchanged.

Saved native outlines resolve grid metadata from the exact captured bundle and generation.
An unavailable or mismatched release fails the footprint read explicitly.

## CLI

For installed command syntax, read the [CLI calculation reference](https://tarvena.pl/docs/cli/tarvena-command-reference.md#calculations).

## Insert saved calculations into S_6

Read `documents/config/describe` for the current configuration and its `calculations` picker.
Each picker item contains `calculationId`, `label`, `available`, and `results` with `resultKey`,
`label`, and `status` (`ok`, `unavailable`, or `inactive`). The catalog reads all calculation
pages and rejects a catalog assembled across different project revisions. Deleted selections
remain visible as unavailable choices.

Keep the existing configuration and selections when adding a calculation. A selection names one
calculation and the stable keys of the results the operat states. List every result explicitly;
`resultKeys` must name at least one, and a result that is not listed is not rendered:

```json
{
  "calculationSelections": [
    { "calculationId": "native:outlet-1", "resultKeys": ["catchment/snq", "catchment/qn"] },
    { "calculationId": "calculation:area-2", "resultKeys": ["catchment/ssq", "catchment/snq", "catchment/qp"] }
  ]
}
```

Save the complete configuration through `documents/config/update` with its current
`expectedConfigRevision`. This saves selection metadata. Then preview and apply
`documents/structure/reconcile` to add or remove S_6, and preview and apply
`documents/sections/refresh` for S_6. Apply uses the preview's body/config revisions and
`relevantInputToken`; reread and preview again after a conflict.

S_6 contains one generated block per selected calculation, keyed `calculation:<calculationId>`.
`documents/generated-blocks/refresh` can refresh one block with the same preview/apply protocol.
Document blocks remain snapshots until an explicit refresh. A deleted calculation blocks generation
until its unavailable selection is removed. A selected inactive result stays selected and says
that the result is not produced with the current settings. S_9 and S_10 read selected QN and SNQ
results by result key, including water-sign SNQ. Document runoff totals use only selected results.

Mention a whole calculation as `@calculation:<calculationId>`, one result as
`@calculation:<calculationId>#catchment/snq`, or an ordered subset as
`@calculation:<calculationId>#catchment/ssq,catchment/snq`. The comma-separated list contains
unique, known result keys without spaces and must be non-empty. An invalid suffix stays unresolved;
it never selects the whole calculation. All forms resolve the saved method report without
recalculating. A subset produces one combined report containing only those results. A bare mention
is a deliberate user choice to include all results, including results added later. Conversion always
writes explicit keys to preserve the old instance's scope.

Reference-graph targets store the calculation id. Scoped mentions use payload
`{ "resultKeys": ["catchment/ssq", "catchment/snq"] }`; whole-calculation mentions use `null`.
Mention replacement accepts one edge
per target; duplicate targets return `invalid_request` without changing existing edges. If a source
contains several scoped mentions of the same calculation, send their ordered key union in one edge.
If any of those mentions deliberately selects the whole calculation, send a `null` payload.

Catchment document reports contain methods, results and input values. They omit applicability
warnings, quality/provenance columns, recalculation history, record identity and internal method
ids. Station observations and full method texts remain. Qmax stores and states its adopted
`exceedanceProbabilityPercent`.

## Annual maxima

`hydrology/annual-maxima` transfers manually entered annual maxima from one gauge (`oneGauge`)
or interpolates linearly between two gauges (`twoGauges`). Its result is `annual-maxima/series`;
it exports no referenceable values. `targetArea` accepts `catchment/area` in km² with selector `null`.

Each gauge groups optional `stationId`, `name`, `areaKm2`, and `series`. An IMGW `stationId` is
exactly nine digits (`id_stacji`). Each observation contains `hydrologicalYear` and `dischargeM3s`.
The IMGW hydrological year runs from 1 November to 31 October and is numbered by the year it ends.
One-gauge state also contains `exponent`, defaulting to exactly `2 / 3`. The inclusive KZGW area
ratio range 0.5–1.5 is a warning; `areaRatio` means target area divided by gauge area.

Two-gauge state contains `upstream` and `downstream`. Only common hydrological years are calculated;
the result retains missing years and downstream flow decreases as evidence. A target outside the
gauge areas gives `TARGET_OUTSIDE_GAUGES`; disjoint series give `NO_COMMON_YEARS`.
A frequency analysis is still required to obtain a probability flow from the resulting series.
