> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mangrovesystems.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 2.1: Calculation Architecture

> Break methodology formulas into discrete calculation steps, understand operator types, and build multi-step models in the Model Editor.

<Panel>
  <Card title="Accounting Academy" className="accounting-academy-card">
    <div className="accounting-academy-content">
      <Steps className="my-0">
        <Step title="MODULE 1: Fundamentals" icon="bookmark" iconType="solid" stepNumber={1} titleSize="p">
          * [1.1: Core Concepts & the Data Lifecycle](/accounting-academy/module-1/1-1-core-concepts-data-lifecycle)
          * [1.2: Translating Methodologies to Mangrove](/accounting-academy/module-1/1-2-translating-methodologies-to-mangrove)
          * [1.3: Events and Datapoints](/accounting-academy/module-1/1-3-events-and-datapoints)
          * [Exercise: Design and Build](/accounting-academy/module-1/1-exercise-design-and-build)
        </Step>

        <Step title="MODULE 2: Calculations" icon="bookmark" iconType="solid" stepNumber={2} titleSize="p">
          * [2.1: Calculation Architecture](/accounting-academy/module-2/2-1-calculation-architecture)
          * [2.2: Expanding Your Data Model](/accounting-academy/module-2/2-2-expanding-your-data-model)
          * [Exercise: Multi-Step Calculations](/accounting-academy/module-2/2-exercise-multi-step-calculations)
        </Step>

        <Step title="MODULE 3: Batch Partitioning & LCA" icon="bookmark" iconType="solid" stepNumber={3} titleSize="p">
          * [3.1: What Is a Batch?](/accounting-academy/module-3/3-1-what-is-a-batch)
          * [3.2: Batch Partitioning Strategies](/accounting-academy/module-3/3-2-batch-partitioning)
          * [3.3: Life Cycle Assessment & Emissions](/accounting-academy/module-3/3-3-lca-and-emissions)
          * [3.4: Allocating Emissions to Batches](/accounting-academy/module-3/3-4-allocating-emissions-to-batches)
          * [Exercise: Batch Partitioning & LCA](/accounting-academy/module-3/3-exercise-batch-partitioning-and-lca)
        </Step>

        <Step title="MODULE 4: Mass Balance with Ledgers" icon="bookmark" iconType="solid" stepNumber={4} titleSize="p">
          * [4.1: Introduction to Mass Balance](/accounting-academy/module-4/4-1-intro-to-mass-balance)
          * [4.2: Designing the Ledger Structure](/accounting-academy/module-4/4-2-designing-the-ledger-structure)
          * [4.3: Multiple Batch Types for Different Stages](/accounting-academy/module-4/4-3-multiple-batch-types)
          * [Exercise: Design & Build Mass Balance](/accounting-academy/module-4/4-exercise-design-and-build-mass-balance)
        </Step>

        <Step title="MODULE 5: Integration Testing" icon="bookmark" iconType="solid" stepNumber={5} titleSize="p">
          * [5.1: The Complete Model Assembly](/accounting-academy/module-5/5-1-the-complete-model-assembly)
          * [5.2: Testing Patterns](/accounting-academy/module-5/5-2-testing-patterns)
          * [5.3: Common Integration Pitfalls](/accounting-academy/module-5/5-3-common-integration-pitfalls)
          * [Exercise: Integration Testing](/accounting-academy/module-5/5-exercise-integration-testing)
        </Step>

        <Step title="MODULE 6: Advanced Patterns & Production" icon="bookmark" iconType="solid" stepNumber={6} titleSize="p">
          * [6.1: Model Design Best Practices](/accounting-academy/module-6/6-1-model-design-best-practices)
          * [6.2: Advanced Techniques](/accounting-academy/module-6/6-2-advanced-techniques)
          * [6.3: Production Readiness](/accounting-academy/module-6/6-3-production-readiness)
          * [Exercise: Production Deployment](/accounting-academy/module-6/6-exercise-production-deployment)
        </Step>
      </Steps>
    </div>
  </Card>
</Panel>

<Check>
  **What you'll learn in this lesson:**

  * Break methodology formulas into discrete calculation steps
  * Understand the Model Editor's node tree architecture
  * Use operators (summation, product, quotient, Keisan) to build calculations
  * Distinguish intermediate calculations from final outputs
</Check>

In Module 1 you built a simple model with one formula: `mass × carbon_content × 3.67`. Real-world methodologies require **multi-step calculations** — chains of intermediate values that feed into a final output. This lesson teaches you how to structure those calculations in Mangrove's Model Editor.

```mermaid theme={null}
flowchart LR
    subgraph Inputs["Data Inputs"]
        E1["Event Datapoints"]
        S1["Static Inputs"]
        C1["Constants"]
    end

    subgraph Model["Model Calculation"]
        I1["Intermediate<br/>Step 1"]
        I2["Intermediate<br/>Step 2"]
        OUT["Final Output"]
        I1 --> I2
        I2 --> OUT
    end

    E1 --> I1
    S1 --> I1
    C1 --> I2

    style E1 fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style S1 fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style C1 fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style I1 fill:#66bb6a,stroke:#388e3c,stroke-width:2px,color:#000
    style I2 fill:#66bb6a,stroke:#388e3c,stroke-width:2px,color:#000
    style OUT fill:#ef5350,stroke:#c62828,stroke-width:2px,color:#000
```

## How calculations work in Mangrove

Mangrove's <a href="/production-accounting/models" target="_blank" rel="noopener noreferrer">Model Editor</a>

represents calculations as a **node tree**. Each node is either an input (data from events, static values, or constants) or a calculated node that combines its children using an operator.

<Note>
  A node tree is hierarchical — each node can have child nodes, and the calculation flows from the leaves (inputs) up to the root (final output). The Model Editor uses a YAML-based scripting interface to define this tree.
</Note>

### Node types

There are three categories of nodes in the Model Editor:

<CardGroup cols={3}>
  <Card icon="arrow-right-to-bracket" title="Input Nodes">
    * **Datapoint references** — values from events
    * **Static inputs** — fixed values from the resource library
    * **Constants** — hardcoded values (e.g., 3.67 for CO2-to-carbon ratio)
  </Card>

  <Card icon="calculator" title="Calculated Nodes">
    * Combine child nodes using an **operator**
    * Can be **intermediate** (feed into other calculations)
    * Or **final output** (produce the batch result)
  </Card>

  <Card icon="arrow-right-from-bracket" title="Output Nodes">
    * A calculated node with a `data_point_type` assigned
    * Its value becomes a **batch output datapoint**
    * Must match the slug expected by the batch type
  </Card>
</CardGroup>

### Operators

Operators define how a node combines its children. The most common operators are:

| Operator     | What it does                   | Example                                            |
| ------------ | ------------------------------ | -------------------------------------------------- |
| `summation`  | Adds all children              | `total_emissions = transport + process + embodied` |
| `difference` | Subtracts child 2 from child 1 | `net = gross - deductions`                         |
| `product`    | Multiplies all children        | `carbon = mass × percentage × factor`              |
| `quotient`   | Divides child 1 by child 2     | `rate = total / count`                             |
| `keisan`     | Custom expression (Ruby-like)  | Complex formulas, conditionals                     |

<Tabs>
  <Tab title="Simple operators">
    For straightforward math, use `summation`, `difference`, `product`, or `quotient`. Each operates on the node's children in order.

    **Example — product operator:** A node with operator `product` and three children (mass, carbon\_pct, factor) computes: `mass × carbon_pct × factor`.
  </Tab>

  <Tab title="Keisan expressions">
    For complex logic — conditionals, min/max, rounding — use the `keisan` operator. Keisan accepts Ruby-like expressions that reference child nodes by name.

    **Example — conditional calculation:**

    ```
    if hc_ratio < 0.4 then permanence_factor = 0.9
    elsif hc_ratio < 0.7 then permanence_factor = 0.8
    else permanence_factor = 0.7
    ```

    See <a href="/production-accounting/models" target="_blank" rel="noopener noreferrer">building accounting models</a>

    for the full Keisan reference.
  </Tab>
</Tabs>

## Breaking formulas into steps

Real-world methodology formulas are often written as a single equation, but in Mangrove you break them into **discrete steps**. This makes models easier to test, debug, and audit.

<Steps>
  <Step title="Identify the final output">
    What is the batch's primary output? For Mangrove Biochar, it's **net carbon delivered (tCO2e)**. This becomes the root of your node tree.
  </Step>

  <Step title="Work backwards to find intermediate values">
    What calculations feed into the final output? Each intermediate value becomes its own node. For example, `net_carbon = gross_carbon - total_emissions` has two intermediate inputs.
  </Step>

  <Step title="Map inputs to the leaves">
    Each leaf node is either an event datapoint, a static input, or a constant. These are the raw data that enters the calculation.
  </Step>

  <Step title="Choose operators for each step">
    Select the appropriate operator for each calculated node. Prefer simple operators over Keisan when possible — they're easier to read and debug.
  </Step>
</Steps>

**Example — Mangrove Biochar multi-step calculation:**

```mermaid theme={null}
flowchart TB
    M["Biochar Mass<br/>(from event)"] --> DRY["Dry Mass<br/>= mass × (1 - moisture/100)"]
    MOIST["Moisture %<br/>(from event)"] --> DRY
    DRY --> CARBON["Carbon Content<br/>= dry_mass × carbon_pct"]
    CPCT["Carbon %<br/>(from lab analysis)"] --> CARBON
    CARBON --> CO2["Gross tCO2e<br/>= carbon × 3.67"]
    FACTOR["3.67<br/>(constant)"] --> CO2

    style M fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style MOIST fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style CPCT fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style FACTOR fill:#42a5f5,stroke:#1976d2,stroke-width:2px,color:#000
    style DRY fill:#66bb6a,stroke:#388e3c,stroke-width:2px,color:#000
    style CARBON fill:#66bb6a,stroke:#388e3c,stroke-width:2px,color:#000
    style CO2 fill:#ef5350,stroke:#c62828,stroke-width:2px,color:#000
```

<Tip>
  Give intermediate nodes descriptive names (e.g., `dry_feedstock_mass` instead of `step_1`). Clear naming makes models self-documenting and easier to debug.
</Tip>

## Execution order and dependencies

The Model Editor evaluates nodes **bottom-up** — leaf nodes (inputs) are resolved first, then their parents, up to the root (output). You don't need to specify execution order; the tree structure defines it.

<Note>
  **Circular dependencies** are not allowed. If node A depends on node B, and node B depends on node A, the model will fail validation. The Model Editor catches this when you save.
</Note>

### Testing your model

After building a model, use the <a href="/production-accounting/models" target="_blank" rel="noopener noreferrer">Console</a>

in the Model Editor to test it:

1. Select a time range that includes test events
2. Review the calculated values at each node
3. Verify intermediate outputs match your expectations
4. Confirm the final output produces the correct result

***

### Check your understanding

<Accordion icon="circle-question" title="What is the difference between an intermediate calculation and a final output?">
  An **intermediate calculation** is a node whose value feeds into another calculation — it exists to break complex formulas into manageable steps. A **final output** is a calculated node with a `data_point_type` assigned — its value becomes a batch output datapoint visible in the batch record.
</Accordion>

<Accordion icon="circle-question" title="When should you use a Keisan expression instead of a simple operator?">
  Use **Keisan** when the calculation requires logic that simple operators can't express — such as **conditionals** (if/else), **min/max** comparisons, **rounding**, or **complex multi-variable formulas**. For straightforward arithmetic (add, subtract, multiply, divide), prefer the built-in operators for clarity.
</Accordion>

<Accordion icon="circle-question" title="Why should you break a single methodology formula into multiple calculation steps?">
  Breaking formulas into steps makes models **easier to test** (you can verify each intermediate value), **easier to debug** (you can identify exactly where a calculation goes wrong), and **easier to audit** (verifiers can trace each step back to source data). It also enables reuse — intermediate values can feed into multiple downstream calculations.
</Accordion>

***

Next, you'll learn how to expand your data model with additional event types in [Lesson 2.2: Expanding Your Data Model](/accounting-academy/module-2/2-2-expanding-your-data-model).
