> For the complete documentation index, see [llms.txt](https://calctree.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://calctree.gitbook.io/docs/integrations/graphql-api/queries/calculate.md).

# Calculate

Update values and re-evaluate a specific calculation in a CalcTree workspace

## Calculate

The Calculate mutation allows you to update and re-evaluate a specific calculation in a CalcTree workspace by providing input statements. It is used to perform a calculation based on provided input values. It takes a set of input statements, processes them, and returns the updated values for each statement in the calculation.

{% hint style="info" %}
**`calculate` does not save.** It re-evaluates in memory and returns updated values, but never modifies the stored calculation. It is exposed as **both** a Query and a Mutation with identical arguments — either works. To persist changes use Creating & updating calculations; to pass inputs **by name** instead of by statement ID use SimpleCalculate.
{% endhint %}

### Input Parameters

<table><thead><tr><th>Parameter</th><th width="240">Type</th><th width="118">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>workspaceId</code></td><td><code>ID!</code></td><td>Yes</td><td>The unique ID of the CalcTree workspace</td></tr><tr><td><code>calculationId</code></td><td><code>ID!</code></td><td>Yes</td><td>The unique ID of the calculation</td></tr><tr><td><code>revisionId</code></td><td><code>ID!</code></td><td>Yes</td><td>The unique ID of the revision to calculate</td></tr><tr><td><code>statements</code></td><td><code>[StatementInput!]!</code></td><td>Yes</td><td>An array of input statements for the calculation</td></tr></tbody></table>

{% hint style="info" %}
**Statements**

‘Statements’ as used here refer to parameters, and code-sources on a page. A statement could be ; a parameter used to input a magnitude, a parameter with a formula that evaluates math, a Python code source with functions in it.\
\
Each statement has it's own unique statementID, which can be retrieved from the response from a [getCalculation call](https://calctree.gitbook.io/docs/integrations/graphql-api/queries/getcalculation).
{% endhint %}

Each `StatementInput` has only two fields: `statementId` (the ID of an existing statement, from GetCalculation) and `formula` (the replacement formula text). To **create** statements or set titles/engines, use `createOrUpdateCalculation` with `CreateStatementInput` instead.

#### Sample Mutation

```graphql
query Calculate(
  $workspaceId: ID!,
  $calculationId: ID!,
  $revisionId: ID!,
  $statements: [StatementInput!]!
) {
  calculate(
    workspaceId: $workspaceId,
    calculationId: $calculationId,
    revisionId: $revisionId,
    statements: $statements
  ) {
    revisionId
    calculationId
    statements {
      statementId
      title
      formula
      namedValues {
        name
        value
      }
    errors
    }
  }
}

```

{% hint style="info" %}
**Named Values and pushing value updates to statements**

Here, the `namedValues` array are in the response, and will return the resulting output of calculations. The fields in the `namedValue` array can not be updated. Rather, if values are to be updated, this is done by updating the value in the `formula` field.\
\
**Example**

If value of x is 3, and it is to be update to 5, to evaluate a calculation, the formula field needs to be updated from `"formula": "x=3"` to `"formula": "x=5"` .
{% endhint %}

#### Sample Header

```
{
  "x-api-key": "your_API_key" 
}
```

#### Sample Variables

```json
{
  "workspaceId": "your-workspace-id",
  "calculationId": "your-calculation-id",
  "revisionId": "your-revision-id",
  "statements": [
    {
      "statementId": "oMByVYo8RukM1cRiZtQyK",
      "formula": "b = 300 mm"
    },
    {
      "statementId": "v7vYcy8NjM5vS2GKTdBA3",
      "formula": "h = 500 mm"
    },
    {
      "statementId": "Vdbfy9Qj6DzvMUM7Fe-QI",
      "formula": "F = 5000 N"
    },
    {
      "statementId": "NH0JQx2nnM9MGuoFvAwbJ",
      "formula": "A = 150 mm^2"
    }
  ]
}
```

If changing the value of the input `b` from `300mm` to `500mm` , then the array for that statement would need to be updated to:

```
{
  "statementId": "oMByVYo8RukM1cRiZtQyK",
  "formula": "b = 500 mm"
}
```

**Note:** the <kbd>statementId</kbd> must be maintained to update it's value.

#### Sample Response

```json
{
  "data": {
    "calculate": {
      "revisionId": "rev5678",
      "calculationId": "your-calculation-id",
      "statements": [
        {
          "statementId": "oMByVYo8RukM1cRiZtQyK",
          "title": "Base Width",
          "formula": "b = 500 mm",
          "namedValues": [
            { "name": "b", "value": 500 }
          ],
          "errors": []
        },
        {
          "statementId": "v7vYcy8NjM5vS2GKTdBA3",
          "title": "Height",
          "formula": "h = 500 mm",
          "namedValues": [
            { "name": "h", "value": 500 }
          ],
          "errors": []
        },
        {
          "statementId": "Vdbfy9Qj6DzvMUM7Fe-QI",
          "title": "Force",
          "formula": "F = 5000 N",
          "namedValues": [
            { "name": "F", "value": 5000 }
          ],
          "errors": []
        },
        {
          "statementId": "NH0JQx2nnM9MGuoFvAwbJ",
          "title": "Area",
          "formula": "A = 150 mm^2",
          "namedValues": [
            { "name": "A", "value": 150 }
          ],
          "errors": []
        },
        {
          "statementId": "Di3lmw44HjOVV4Sfz3cJo",
          "title": "Moment of Inertia",
          "formula": "I = (b * h^3) / 12",
          "namedValues": [
            { "name": "I", "value": 520833333.33 }
          ],
          "errors": []
        },
        {
          "statementId": "C6RBN9BgyIjxfN04jOayT",
          "title": "Shear Stress",
          "formula": "V = F / A",
          "namedValues": [
            { "name": "V", "value": 33.33 }
          ],
          "errors": []
        }
      ]
    }
  }
}
```

#### Error field

The `errors` field appears in each statement of the `calculate` query response. It contains details if a formula fails to evaluate correctly.

Each error includes:

* A `message` describing the issue
* A `_tag` indicating the error type (e.g., `"MathJSError"`)
* A `cause` block with structured data to help you debug the issue (e.g., what types were expected vs. received)

> **It’s recommended to always include the `errors` field in your query response** to help diagnose any issues in the submitted formulas.

```
"errors": [
  {
    "cause": {
      "data": {
        "category": "wrongType",
        "fn": "addScalar",
        "index": 1,
        "actual": ["number"],
        "expected": ["Unit"]
      }
    },
    "_tag": "MathJSError",
    "message": "Error executing formula. 🐛"
  }
]
```

In this case, the formula attempted to add a **unitless number** (e.g. `100`) to a **value with units** (e.g. `20m`). The system expected a `Unit`, but received a `number`, causing a type mismatch.

> **Note:** The `errors` field is intended to help diagnose issues in formula evaluation, but interpreting errors can sometimes be nuanced. While we aim to provide clear and structured error messages, debugging may still require some trial and error or best-effort interpretation in complex cases.

### Description of Returned Fields

| Field           | Type               | Description                                                                                                                                                                       |
| --------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `revisionId`    | `String`           | The unique ID of the new calculation revision                                                                                                                                     |
| `calculationId` | `String`           | The unique ID of the calculation                                                                                                                                                  |
| `statements`    | `Array`            | An array of the calculated statements                                                                                                                                             |
| `statementId`   | `String`           | The unique ID of the statement                                                                                                                                                    |
| `title`         | `String`           | The title of the statement                                                                                                                                                        |
| `formula`       | `String`           | The formula used in the statement                                                                                                                                                 |
| `namedValues`   | `Array of Objects` | An array of response name value pairs representing variables and their calculated values.                                                                                         |
| `errors`        | `Array of Objects` | An optional array containing any errors that occurred during evaluation of the formula. Useful for debugging invalid formulas or type mismatches. Empty if no errors are present. |

***

### Usage Example in Python

Here’s how to use the `Calculate` mutation in **Python** using the `requests` library:

```python
import requests

# Define the API endpoint and your API key
url = "https://graph.calctree.com/graphql"
headers = {
    "Content-Type": "application/json",
    "x-api-key": apiKey,
}

# Define the GraphQL query and variables
query = """
query Calculate($workspaceId: ID!, $calculationId: ID!, $revisionId: ID!, $statements: [StatementInput!]!) {
  calculate(workspaceId: $workspaceId, calculationId: $calculationId, revisionId: $revisionId, statements: $statements) {
    revisionId
    calculationId
    statements {
      statementId
      title
      formula
      namedValues {
        name
        value
      }
      errors
    }
  }
}
"""

variables = {
    "workspaceId": "your-workspace-id",
    "calculationId": "your-calculation-id",
    "revisionId": "your-revision-id",
    "statements": [
        {
            "statementId": "oMByVYo8RukM1cRiZtQyK",
            "formula": "b = 300 mm"
        },
        {
            "statementId": "v7vYcy8NjM5vS2GKTdBA3",
            "formula": "h = 500 mm"
        },
        {
            "statementId": "Vdbfy9Qj6DzvMUM7Fe-QI",
            "formula": "F = 5000 N"
        },
        {
            "statementId": "NH0JQx2nnM9MGuoFvAwbJ",
            "formula": "A = 150 mm^2"
        }
    ]
}

# Make the POST request
response = requests.post(url, json={"query": query, "variables": variables}, headers=headers)

# Print the response
print(response.json())

```

### Tips for Using this query

* Ensure your `workspaceId`, `calculationId`, `revisionId`, and `statements` are accurate.
* Use the calculate query to extract the statement structure and statementIDs to use as inputs in this mutation.
* Unless working with a specific revision, set revisionID to "ffffffff" to access the latest version of the calculation.
* Use and update the `formula` field to change values.
* Keep statement IDs consistent when adjusting formulas.
* Use the `namedValues` array to understand the outputs of each statement.
* Include the `error` field in your reponse to help diagnose any issues in your query.
