﻿---
title: Types and errors
description: The value types, array forms, handles, errors, threads and units that every part of the Python SDK shares.
url: https://help.tangerina.io/deformable/v0.1.1/user-guides/python/types-and-errors/
---

# Types and errors – Python SDK – Deformable v0.1.1

This page explains the rules that every part of the package follows: how you pass points and meshes in, what comes
back, who frees what, and what happens when a call fails. Every name on this page is in the `deformable` module.

The examples on this page build on each other. Run them in order in one Python session, starting with the first.
For every field and member of these types, see the
[Python API reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/overview/); the vectors and transforms are on the
[math reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/math/).

## Points, vectors and transforms

The package returns points as `Vector3(x, y, z)` and UVs as `Vector2(x, y)`. Both are named tuples. The one exception
is the skinned surface `SurfaceEmbedding.deform` returns: a `DeformedSurface` holds flat arrays of 32-bit floats, three
per position or normal. Anywhere the package takes a point or a vector, a plain tuple or list of numbers works too.

`AffineTransform(linear, translation)` maps row vectors: a point p goes to p · linear + translation. So `linear[i]`
is where axis i goes. A matrix M that maps column vectors (M · p, as in Blender) gives `linear[i][j] = M[j][i]`.
`IDENTITY` is the transform that leaves every point where it is.

```python
import deformable

turn = deformable.AffineTransform(((0.0, 1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)), (0.0, 0.0, 5.0))
print(turn.linear[0], turn.translation)
print(deformable.IDENTITY.translation)
```

```text
(0.0, 1.0, 0.0) (0.0, 0.0, 5.0)
(0.0, 0.0, 0.0)
```

This transform turns the x axis into the y axis, then moves points 5 units along z.

## Mesh classes

The mesh classes are plain dataclasses. They hold whatever array form you give them. Any object with the same
attribute names works in place of a mesh class, so you can pass your own mesh type.

| Class | Fields | Made by |
|---|---|---|
| `TetrahedralMesh` | `positions`, and `tetrahedrons` with four node indices each | `tetrahedralize`, `extrude`, `span_layers` |
| `TriangleMesh` | `positions`, and `triangles` with three vertex indices each | `triangulate`, `autocage` |
| `PolygonMesh` | `positions`; `polygon_sizes`, the corner count of each polygon; `polygon_vertices`, the vertex of each corner, polygon after polygon | `splinters_from_image` |
| `SurfaceMesh` | `mesh`, a `PolygonMesh`, plus the optional per-corner `normals`, `uv_sets` and `colours` | `SurfaceEmbedding.arrays` |

`FaceHole(face, first_corner, corner_count)` marks a run of a polygon's corners as a hole loop, for `triangulate`
and `verify_surface`. Every field of these classes is on the [meshes reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/meshes/).

### Orientation

Every tetrahedral mesh the library takes must be positively oriented. For a tetrahedron (X0, X1, X2, X3), with
eᵢ = Xᵢ - X0, the value -e1 · (e2 × e3) is positive: the corners are left-handed. Face k is the face opposite
corner k, and `face_corners(k)` gives its three corners. The tools make positive tetrahedrons, though a thick
`extrude` shell can invert some where the mesh curves sharply. If you build a
mesh yourself and `add_object` raises `DEGENERATE_TETRAHEDRON_INVERTED`, your tetrahedrons are right-handed: swap two
corners of each one.

Triangle cages face outward: seen from outside, the corners of a triangle run counter-clockwise.

## Array forms

Every array input takes any of these forms:

- A sequence of groups: a list of `(x, y, z)` tuples, of lists, or of `Vector3`.
- A flat sequence of numbers, group after group.
- Any buffer: `array.array`, `memoryview`, `bytes`, or another object with the buffer protocol, flat or with one row
  per group. A buffer that already holds the C type, `array("d")` for positions or `array("I")` for indices, is
  copied as one block. Any other buffer, such as `array("f")` from Blender's `foreach_get`, is read number by number.

```python
import array

positions = [(x, y, z) for z in (0.0, 1.0) for y in (0.0, 1.0) for x in (0.0, 1.0)]
triangles = [
    (0, 2, 3), (0, 3, 1), (4, 5, 7), (4, 7, 6), (0, 1, 5), (0, 5, 4),
    (2, 6, 7), (2, 7, 3), (0, 4, 6), (0, 6, 2), (1, 3, 7), (1, 7, 5),
]
parameters = deformable.TetrahedralizeParameters(0.5)
from_tuples = deformable.tetrahedralize(deformable.TriangleMesh(positions, triangles), parameters).mesh

flat_positions = array.array("d", [coordinate for position in positions for coordinate in position])
flat_triangles = array.array("I", [vertex for triangle in triangles for vertex in triangle])
from_buffers = deformable.tetrahedralize(deformable.TriangleMesh(flat_positions, flat_triangles), parameters).mesh

print(from_tuples == from_buffers, from_buffers.positions[0], from_buffers.tetrahedrons[0])
```

```text
True Vector3(x=0.0, y=0.0, z=0.0) (8, 4, 5, 0)
```

Results are copied out of the library at once. They are lists of `Vector3`, of `int` and of index tuples, and they
stay valid after later calls. The one exception is `SurfaceEmbedding.deform`, which returns flat `array.array`
copies for speed.

## Enumerations

Every enumeration is an `enum.IntEnum`, so its members compare equal to their numbers, and a plain `int` works as an
argument. A number the library does not define raises `INVALID_ARGUMENT`.

| Enumeration | Used by |
|---|---|
| `StepOutcome` | `Scene.step`, see [Scene](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/scene/) |
| `ClipMode` | `embed_surface`, see [Render surfaces](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/render-surfaces/) |
| `ExtrudeDirection` | `extrude`, see [Tools](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/tools/) |
| `SelfIntersectionCheck`, `MeshIssueKind` | `verify_surface`, see [Tools](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/tools/) |
| `Status` | `DeformableError`, below |

The members and their numbers are under each enumeration in the Python API reference:
[`StepOutcome`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/scene/#stepoutcome),
[`ClipMode`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/render-surfaces/#clipmode),
[`ExtrudeDirection`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/tools/#extrudedirection),
[`SelfIntersectionCheck`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/mesh-checks/#selfintersectioncheck),
[`MeshIssueKind`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/mesh-checks/#meshissuekind) and
[`Status`](https://help.tangerina.io/deformable/v0.1.1/api-references/python/errors/#status).

## Errors

The package raises these exceptions.

| Exception | When |
|---|---|
| `DeformableError` | The library refused a call. |
| `LicenseError` | The trial or license does not allow a call. A subclass of `DeformableError`, see [License errors](#license-errors). |
| `ValueError` | The package refused an argument before the call, or the handle is closed. |
| `TypeError` | An argument has the wrong type, such as a string where numbers belong. |
| `LibraryNotFoundError` | No shared library was found. It is a subclass of `OSError`. |

### DeformableError

A `DeformableError` carries four attributes:

- `status`: a member of `deformable.Status`, such as `Status.NON_CLOSED_BOUNDARY`. A code newer than the package comes
  through as a plain `int`.
- `message`: the library's message, in English.
- `first_index` and `second_index`: the elements the failure concerns, such as the tetrahedron, the polygon or the
  two vertices of an edge. They are 0 when the status names none.

`str(error)` is the status name, a colon and the message. In these guides, a status name such as `NON_CLOSED_BOUNDARY`
means a `DeformableError` with that status. Nothing is created when a call fails.

```python
cube = from_tuples
tetrahedrons = [list(tetrahedron) for tetrahedron in cube.tetrahedrons]
tetrahedrons[3][0], tetrahedrons[3][1] = tetrahedrons[3][1], tetrahedrons[3][0]

with deformable.Scene() as scene:
    material = scene.add_material(deformable.MaterialParameters.default())
    try:
        scene.add_object(deformable.TetrahedralMesh(cube.positions, tetrahedrons), material)
    except deformable.DeformableError as error:
        print(error.status == deformable.Status.DEGENERATE_TETRAHEDRON_INVERTED, error.first_index)
        print(error)
```

```text
True 3
DEGENERATE_TETRAHEDRON_INVERTED: tetrahedron 3 is inverted
```

Swapping two corners turns tetrahedron 3 inside out, so `add_object` refuses the mesh and names the tetrahedron.

The status codes are the same as the C SDK's. The full list, with what each index names, is on the
[errors reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/errors/#status).

### License errors

Engine calls check the trial or license of this computer first. When it does not allow the call, the call raises
`LicenseError`, a subclass of `DeformableError`, with one of these statuses, and nothing is created. Its message is
written to show the user as it is, such as **Trial ended — Buy license**. Two statuses have their own subclass of
`LicenseError`: `LicenseRequiredError` and `TrialLimitExceededError`, whose `tetrahedrons` and `limit` name the count
that would take part in the simulation and the limit.

| Status | When |
|---|---|
| `LICENSE_REQUIRED` | The trial ended, the computer has no trial, or the license was removed. |
| `TRIAL_LIMIT_EXCEEDED` | More than 2,500 tetrahedrons would take part in the simulation during the trial; a disabled object does not count. `first_index` is that count, `second_index` the limit. `Scene.add_object` adds nothing then, and the scene goes on with the objects it holds. |
| `LICENSE_NEEDS_ONLINE` | The trial has not started, the license needs its renewal, or the clock is behind. |
| `LICENSE_SERVICE_UNAVAILABLE` | `activate`, `deactivate` or `refresh` could not reach our licensing service, the service refused this copy of the library, its answer did not verify, or `set_online_access(False)` turned contacts off. |
| `LICENSE_KEY_REJECTED` | Our licensing service refused the key: unknown, revoked or expired, of another product, or its seat is in use on another device; or the service takes no more devices. |
| `LICENSE_STORAGE_FAILED` | The license state could not be saved in your user folder. |

The mesh tools, `verify_surface`, `meshes_intersect`, `boundary_faces`, `material_region_indices`, `embed_surface`,
`SurfaceEmbedding.deform`, `Scene.add_object`, `Scene.step` and `Scene.skip_to` check the license.
Creating a scene, setting its values, reading its outputs and closing handles never do, so your tool can always
clean up. `deformable.license` reads and changes the license state: see
[License](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/getting-started/#license).

```python
with deformable.Scene() as scene:
    material = scene.add_material(deformable.MaterialParameters.default())
    try:
        scene.add_object(cube, material)
        scene.step(1.0, substeps=10)
    except deformable.TrialLimitExceededError as error:
        print(f"{error.tetrahedrons} tetrahedrons, the trial allows {error.limit}")
    except deformable.LicenseError as error:
        print(error.message)
```

While the trial or the license allows the calls, this prints nothing.

### What the package refuses before the call

Some arguments cannot be checked by the library, so the package checks them first:

- A negative index, handle or count, or one too large for its C type, raises `ValueError`. Indices and handles
  stop below 2^32.
- Vertex or index data that is not a whole number of groups raises `ValueError`, for example 2 numbers for a
  position.
- A UV set without one pair per corner raises `ValueError`.
- A string where numbers belong raises `TypeError`, and so does a preset name that is not a `str`.
- Any call on a closed `Scene`, `SurfaceEmbedding` or `CancelFlag` raises `ValueError`.

```python
try:
    deformable.boundary_faces(deformable.TetrahedralMesh([0.0, 1.0], [(0, 1, 2, 3)]))
except ValueError as error:
    print(error)
```

```text
positions holds 2 numbers, not a whole number of groups of 3
```

## Handles

Three classes own a library handle: `Scene`, `SurfaceEmbedding` and `CancelFlag`. Each one frees its handle in
one of three ways:

- at the end of a `with` block;
- when you call `close()`;
- when the garbage collector collects it, at a time you do not control.

`close()` waits for the calls in flight on the object from other threads, then frees the handle. Closing twice does
nothing, and `closed` is `True` afterwards. Any later call raises `ValueError`.

```python
scene = deformable.Scene()
scene.close()
try:
    scene.step(0.0, 10)
except ValueError as error:
    print(scene.closed, error)
```

```text
True the scene is closed
```

Object and material handles are not classes. They are `int` values that count up from 0 in creation order, and they
belong to the scene that made them.

### Cancel a long call

A `CancelFlag` stops a long call from another thread. Call `set()` to raise it, `clear()` to use it again, and
`is_set()` to read it. `Scene.step`, `triangulate`, `tetrahedralize` and `autocage` take one. See the
[cancel flag reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/errors/#cancelflag).

A tool stops with `CANCELLED`. A step stops between two substeps and returns a `StepReport` whose outcome is
`StepOutcome.CANCELLED`; it does not raise.

```python
with deformable.CancelFlag() as cancel:
    cancel.set()
    try:
        deformable.tetrahedralize(deformable.TriangleMesh(positions, triangles), parameters, cancel)
    except deformable.DeformableError as error:
        print(error.status.name, cancel.is_set())
```

```text
CANCELLED True
```

[Tools](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/tools/#cancel-a-tool) shows how to set the flag from another thread while a tool
runs.

## Threads

Library calls release the global interpreter lock, so other Python threads run while a call works.

- A `Scene` can move between threads. Calls on one scene from several threads run one at a time.
- Tools, `SurfaceEmbedding` reads and skinning, and cancel flags work from several threads at once.
- Results are bitwise identical run to run, whatever the worker count.

## Units

Lengths cross in host units: positions, driven targets, glue plane offsets and every tool input. Time is in seconds.
Forces, gravity, node masses and material values are in simulation units. `Scene.set_scale` converts host
lengths to simulation lengths. The default scale of 1 makes them the same, and the default gravity of 9.81 makes a
unit read as a metre. The tools always work in their input's unit. See
[Units and axes](https://help.tangerina.io/deformable/v0.1.1/user-guides/engine/how-the-engine-works/#units-and-axes).

## Versions

`deformable.__version__` is the package version, such as `"0.1.0"`. `deformable.library_version()` loads the library
and returns its version, as `major.minor.patch`. The two match when the package and the library come from the same
release. See [Getting started](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/getting-started/) for how the package finds the library.

## Next steps

- [Scene](https://help.tangerina.io/deformable/v0.1.1/user-guides/python/scene/): materials, objects, driving, glue, stepping and outputs.
- [Errors reference](https://help.tangerina.io/deformable/v0.1.1/api-references/python/errors/): every status, with what its indices name.
- [Support](https://help.tangerina.io/deformable/v0.1.1/support/): report a bug in the SDK.
