# Calculations

> How calculations derive data in Konstrukt — guided and script calculations, sources and joins, destination mapping, the working-set and output previews, diagnostics, write modes including suggestions, the dependency graph, run order, status and cycle detection.

A calculation (*beräkning*) is a saved [Kex](kex.html) script that reads value types and dimensions and writes to one or more value types. Calculations are **triggered by data changes**: when any source a calculation reads changes, the calculation runs again, and so does everything downstream of it. You do not schedule calculations or wire triggers; the platform works out the order from what each calculation reads and writes.

```flow
Source data | value types, dimensions -> Working set | joined rows -> Formula | per row -> Output | destination grain -> Destination value type
```

## Two editing modes, one execution model

A calculation is always a Kex script. The admin interface offers two ways to edit one:

| Mode | Calculation type label | Editing |
|---|---|---|
| Guided | *Beräkning* | A form: sources, joins, property defaults, formula, destination |
| Script | *Skript* | Free Kex in a syntax-highlighted editor |

A guided calculation is a Kex script with a model annotation that tells the editor to render it as a form:

```kex
@@model: "Formula", version: "1.0"

@("Planned salaries")
var PlannedSalaries =
  Salary
  main Salary
  check includes
…
write to SalaryCost <- $result = …
```

`@@model` marks the script as a guided calculation, and `@("Alias")` gives a variable its display name in the form. **Edit in script mode** (*Redigera i skriptläge*) shows the underlying script.

!!! warning "Converting to script mode is one-way"
    If you remove the `@@model` annotation and save, the calculation is permanently a script calculation. It can no longer be opened in the guided editor.

Edits in either mode are held locally until you save. While there are unsaved changes, a bar offers **Reset** (*Återställ*) and **Save** (*Spara*).

## The guided editor

The guided editor is laid out from top to bottom in this order:

1. **Source data** (*Källdata*). Choose the value types to read. Each source has an alias and a list of included dimensions. For each source you also choose whether it *requires all values in the working set* or *allows missing values*.
2. **Derived join**, stated in plain text, for example *"The system will assume 'Planned salaries' as the main source — a full outer join on 'Month'"*. **Configure** opens the join settings.
3. **Formula** (*Formel*). An expression editor with live validation.
4. **Working-set table** (*Arbetssettabell*). A preview of the rows the formula iterates over.
5. **Destination value type** (*Destinationsvärdetyp*), with dimension mapping, aggregation and write mode.
6. **Output** (*Utdata*). A preview of the result at the destination's grain.

Side panels: **Sources** (*Källor*), **Advanced** (*Avancerat*, the join configuration), **Property defaults** (*Standardvärden för egenskaper*) and **Details** (*Detaljer*).

### Joins

The Advanced panel sets how each source joins the main source. The GUI terms map to Kex include options:

| GUI | Swedish | Kex |
|---|---|---|
| Main | *Main* | `main` |
| Inner | *Inre* | `include` |
| Full outer | *Fullständig yttre* | `include all` |
| Left | *Vänster* | `include optional` |
| Join on bound property | *Lägg till bunden egenskap* | `on Dimension.Property` |

The main source contributes all its dimensions automatically. For other sources, you tick dimensions per source. A dimension that does not exist on the main source is flagged *(Dimension finns ej i Main)*.

### Aggregation of sources

This is a two-stage process that is easy to confuse:

- **Implicit aggregation, always applied.** Each source is summed (`sum()`) to its own dimensions before the join. A source may hold both user-entered and calculated rows for the same combination, and these are added together first.
- **Pre-aggregation, optional.** In the Advanced panel you can explicitly remove dimensions from a source before the join. The source is then aggregated with a chosen function: sum, min, max, average or count. This lowers the source's grain.

### Property defaults

A property default (*Standardvärden för egenskaper*) sets a value to use when a property used in the formula is missing, so that the expression does not fail. It corresponds to Kex `default Dimension.Property to <constant>`.

### Destination

For each dimension of the destination value type you choose where its value comes from (*Från*, "From"):

| From | Meaning |
|---|---|
| *Källa* (Source) | Taken from a source dimension, e.g. `Planned salaries.Month` |
| *Kex* | A dynamic Kex expression |
| *Fixed* | A constant dimension value |

Every dimension of the destination must receive a value. You also set:

- **Aggregation** (*Aggregering*): how rows are combined to the destination grain.
- **Write mode**: write all values (*Skriv alla värden*) or only non-zero values (*Skriv endast icke-nollvärden*). Writing only non-zero values keeps the destination sparse, which reduces storage and downstream recalculation.

### Working set and output

The working-set table and the output are a pair. Together they show how a formula turns input into results:

| Table | Grain | Columns |
|---|---|---|
| Working set | The join grain, before the formula | Dimensions annotated with their source, one value column per source, and the formula result per row |
| Output | The destination grain, after formula and aggregation | Destination dimensions and the value, with summary statistics (rows, sum, mean, max, min) |

The previews show the first 1,000 rows and report the total count. Both tables support search, per-column filters, sorting, export and full screen. The difference in row count between the two — for example 6,396 working-set rows aggregating to 647 output rows — makes the calculation's grain visible.

### Diagnostics

The info icon in the working-set table opens **Diagnostics**. It has two tabs:

- **Transformation line**: every step the Kex compiler applies, with the query text before and after each step.
- **Script**: the final script.

Steps include:

- *Initial global query*
- *Create semantic query*
- *Correct identifier names*
- *Check includes*
- *Determine product dimensions*
- *Rewrite point-in-time references*
- *Expand wildcards*
- *Exclude calculated data*
- *Resolve spreads*
- *Resolve includes*
- *Rewrite special functions*
- *Aggregate scalars*
- *Suggest select dimensions*

Steps that change nothing are shown as *(No change)*.

Diagnostics make Kex's implicit resolution inspectable. They are the main tool for answering "why did this join or aggregation happen?".

## Script calculations

A script calculation is a Kex script with at least one `write` statement. The script panel is a line-numbered editor that can be opened in a modal. The output panel shows the last run, or the validation error with the identifier at fault, together with **Diagnostics** and **Retry** (*Försök igen*).

Rules for calculation scripts:

- A saved calculation must contain a valid `write`.
- A calculation can write to several value types. Each `write` is a separate output in the dependency graph.
- Inside a calculation, writes affect only the rows that calculation owns: rows whose `$calcid` is the calculation's ID. The first write to a target replaces the calculation's previous rows there, and later writes to the same target in the same run upsert. See [Kex write variants](kex.html#write-variants).
- A calculation's own rows are separate from user-entered, imported and other calculations' rows for the same combination. Readers sum them together.

### Suggestions

`write suggestion to` writes **suggested values** (line state 0). The user can overwrite a suggestion, and once edited the value belongs to the user: the calculation does not overwrite it again. Suggestions are styled separately in apps (presentation rule key `Suggested`, **Suggested value**, *Föreslaget värde*). Use them for defaults that users are expected to confirm or adjust, such as a start date derived from other data or a proposed budget line.

| Variant | Effect |
|---|---|
| `write suggestion to` | Replace earlier suggestions in the target with the result |
| `write insert suggestion to` | Suggest only where no data exists |
| `write upsert suggestion to` | Update existing suggestions and add new ones |

`suggestion` is valid only in calculations.

## Dependency graph

The platform derives a directed graph from what each calculation **reads** (value types and dimensions) and **writes** (value types). A calculation depends on every calculation that writes something it reads. Cross-plan reads are part of the graph.

**Show diagram** (*Visa diagram*) draws the graph for the whole plan or for selected calculations. Select rows in the calculation list, or use the row menu on a single calculation.

| Element | Meaning |
|---|---|
| Coloured circles | Calculations, shaded by depth (level) |
| Small grey nodes | Value types |
| Layout *None* | Force-directed: shows clusters and isolated islands |
| Layout *Radial* | Radial arrangement |
| Layout *Top-down* | Dependency layers, i.e. the order in which calculations actually run |

Hovering over a calculation shows its full contract without opening it: ID and level, name, every source with its condition, and the write target with its dimension mapping.

!!! agent "Dependency graph via MCP"
    `get_calculation_graph` returns per calculation `planId`, `id`, `name`, `isEnabled`, `level`, `references[]` (value types and dimensions read, with plan IDs), `outputs[]` and `dependsOn[]`. Filter with `planIds`, `referencedEntityIds` or `outputEntityIds`. Use it to find everything affected by a change before editing a calculation.

## Run order and status

| Status | Swedish | Meaning |
|---|---|---|
| Ok | *Ok* | Valid and enabled; runs on change and can be run manually |
| Invalid | *Ogiltig* | Script validation fails; the calculation cannot run and has no place in the run order |
| Inactive | *Inaktiv* | Disabled without being deleted |

Validation errors are shown at two levels: a structured list, for example *"The formula expression is not valid"*, and the raw engine message naming the identifier at fault.

Graph validation is separate from script validation. A calculation can be valid on its own but, when activated, form a **cycle** with other calculations. The list then shows a cycle marker with a tooltip naming both edges, for example *"Creates a cycle with other calculations: reads from 32 / writes to 82"*. Cycles are not allowed.

The Details panel shows:

- name, ID and type;
- **run time** (*Körtid*) and **run order** (*Körordning*), meaning the level in the graph;
- status, last run, last changed by;
- tags and description.

The row menu offers: go to calculation, activate or deactivate, copy, export, delete.

## Precalculations

A precalculation (*förberäkning*) is an intermediate calculation that writes to no value type and is used only as a source in another calculation. It is referenced in scripts as `Calc<id>`. Precalculations remain supported. For new work, prefer Kex variables inside the calculation, or an explicit value type where the intermediate result is useful in its own right.

## Flows

Flows (*Flöden*) are saved, parameterised Kex scripts run **on demand**, not on data change — for example "start a new forecast round" with parameters for the previous forecast and the start period.

- **Running a flow.** The *Flows* side tab on a plan lists the plan's flows. Choosing one opens a run form with its parameters, **Run** (*Kör*) and the flow's status.
- **Editing flows.** **Flow editor** opens the plan's flow list (name, status, last run) with **New flow** (*Nytt Flow*). A flow has a name, ID, description, parameters and a script, plus panels for parameters and details.
- **Parameters.** Each parameter has a name, an ID used in the script (for example `@startperiod`), a type and a description.

| Parameter type | Swedish label |
|---|---|
| Decimal | *Decimal* |
| Integer | *Heltal* |
| Text | *Text* |
| Date | *Datum* |
| Date and time | *Datum och tid* |
| Boolean | *Booleansk* |
| Dimension value (of a chosen dimension) | *Dimensionsvärde* |
| Plan | *Plan* |
| Reference | *Referens* |

**Who uses flows.** Flows are for planners and other administrators, to automate larger operations that should run at a chosen moment rather than on every change. Examples:

- re-flagging many properties at once;
- moving or copying data between references and value types;
- starting a forecast round: data is fetched from the master data plan once, when the round starts, and then stays locked, instead of following master data continuously.

## Designing calculations

- **Aggregate early.** Read sources at the grain you need, and use pre-aggregation or a `var` to drop unneeded dimensions before windowing or joining.
- **Write sparsely.** Use *write only non-zero values*, or `having $result != 0`, where zeros carry no meaning.
- **Keep the graph shallow and narrow.** Every level adds recalculation latency to changes that pass through it. See [Architecture](architecture.html#the-calculation-engine).
- **Name for the graph.** Names that state the source and target make the graph and lineage panels readable.
- **Validate before saving.** Use the output preview, the working-set table and Diagnostics. Agents should call `validate_script` first.

!!! agent "Pitfalls for agents"
    Known pitfalls when changing calculations — the one-way script conversion, cycles detected on activation, invalid calculations and recalculation load — are in the [Agent guide](agent-pitfalls.html#calculations).

## Related

- [Kex](kex.html)
- [Traceability](traceability.html)
- [Architecture](architecture.html)
- [Data model](data-model.html#line-states)
