# The geometry file

cardiac-geometriesx saves a geometry as **one file**. The file holds the mesh, the tags, the
fibres and the fields, and it describes itself: the unit, the names of the tags and what each
field means are stored inside it. A simulator, or a colleague, needs nothing else. This page is
the standard of that file, called **format 1**, and the commands that make, check and convert it.

```{contents}
:local:
:depth: 2
```

## Format 1

The file is an [io4dolfinx](https://github.com/scientificcomputing/io4dolfinx) file. It holds:

- the mesh;
- the tags, as `Cell tags`, `Facet tags`, `Edge tags` and `Vertex tags`;
- the fibres `f0`, `s0` and `n0`;
- each field, under its own name;
- one attribute group, `cardiac_geometries`, with one attribute, `metadata`: a JSON document,
  stored as its UTF-8 bytes in a `uint8` array, because that is the form both backends store.

`.h5` means the `h5py` backend (the default, and what pulse, beat and simcardemsx write) and
`.bp` means `adios2`. Both hold format 1. io4dolfinx's `adios2` backend cannot read back a field
whose name contains `_time` (for example `activation_time`): such a field can be written to a `.bp`
file but not read from it, so use `.h5` for such files.

`Geometry.save(path)` writes the file and nothing beside it. `Geometry.from_file(comm, path)`
reads it. The metadata of a converted ventricle looks like this (the elements are shown
schematically, the file stores the arrays of `cardiac_geometries.utils.element2array`):

```json
{
  "format": 1,
  "unit": "m",
  "markers": {
    "BASE": [10, 2], "RV_ENDO": [20, 2], "LV_ENDO": [30, 2], "EPI": [40, 2],
    "LV_WALL": [1, 3], "RV_WALL": [2, 3], "MITRAL_VALVE": [7, 3], "TRICUSPID_VALVE": [8, 3],
    "AORTIC_VALVE": [9, 3], "PULMONARY_VALVE": [10, 3]
  },
  "microstructure": {"f0": ["DG", 0, 3], "s0": ["DG", 0, 3], "n0": ["DG", 0, 3]},
  "additional_data": {
    "celltype": {"type": "Function", "element": ["P", 1], "values": {"endo": 0, "epi": 1, "mid": 2},
                 "description": "ToR-ORd cell type, from Alya's 1 endo, 2 mid, 3 epi"},
    "activation_time": {"type": "Function", "element": ["P", 1], "unit": "ms",
                        "description": "Local activation time"}
  },
  "info": {"mesh_type": "converted", "source": "rodero_05_dolfinx_v2", "mapping": "rodero_05.toml",
           "cardiac_geometry_version": "..."}
}
```

| Key | Meaning |
|---|---|
| `format` | The version of this standard. A reader refuses a file of a higher format with `FormatError`, naming the version of cardiac-geometriesx that is needed |
| `unit` | The unit of the coordinates: `"m"`, `"cm"` or `"mm"`. It sits at the top level, not in `info`, because readers need it |
| `markers` | Each tag name as `[tag, dimension]`: dimension `tdim - 1` for facets, `tdim` for cells (2 and 3 for a 3D mesh) |
| `microstructure` | The element of each fibre field |
| `additional_data` | Each other field or tag set: its type (`Function` or `MeshTags`) and element, and what the field is (`unit`, `values`, `description`, `recipe`) |
| `info` | How the geometry was made. `cardiac_geometry_version` is the version that wrote the file |

### Formats 0 and 1

Files written before format 1 are **format 0**: an io4dolfinx file with no `metadata` attribute,
and JSON files beside it (`markers_<stem>.json`, `info_<stem>.json`,
`microstructure_<stem>.json` and `additional_data_<stem>.json`). An old generator's folder also
holds an `info.json`.

- `Geometry.from_file` reads both. For format 0 it reads those of the four JSON files that
  exist. Such a geometry has no unit, and `check` reports that (C1 and C2). A folder's
  `info.json` is not read by `from_file`: only `convert` reads it, and merges it into the
  converted file's `info["source_info"]`.
- `Geometry.save` always writes format 1. It deletes the four old JSON files of the same stem
  (`markers_<stem>.json`, `info_<stem>.json`, `microstructure_<stem>.json` and
  `additional_data_<stem>.json`), which would describe another file. It keeps a file of the
  same stem written with the other backend (`geometry.bp` beside `geometry.h5`) and warns
  about it: a command given a folder that holds both reads `geometry.h5`. The JSON files then
  stay too, since they may belong to that file, and the format-1 file ignores them.
- `Geometry.save_folder` and `Geometry.from_folder` are deprecated. Use `save` and `from_file`.
- `geox convert` turns a format-0 geometry into format 1 ([below](geometry-file-convert)).

The generators record their unit: millimetres for `lv_ellipsoid`, `lv_ellipsoid_2D`, `slab`,
`slab_dolfinx` and the cylinders, centimetres for `biv_ellipsoid`, and millimetres for `ukb`.
The deprecated `slab_in_bath` takes `unit=` and has no default. `from_volume` requires `unit=`.
A generator writes `geometry.h5` (or `geometry.bp` with `--io-backend adios2`) and no
visualisation files; see [`export`](geometry-file-export) for those.

## What the file must hold

### Unit

`"m"`, `"cm"` or `"mm"`.

### Facet markers (dimension 2)

| Name | Meaning |
|---|---|
| `LV_ENDO` | The boundary of the LV cavity, including the cavity side of any valve region, so that the cavity is closed |
| `RV_ENDO` | The same for the RV, in a BiV |
| `EPI` | Epicardium |
| `BASE` | The basal cap of a clipped geometry |
| `MV`, `AV`, `TV`, `PV` | The valve planes, as surfaces: where the mesh ends at a valve |

- A ventricle needs `LV_ENDO`, `EPI`, and `BASE` or the valve planes. A BiV also needs `RV_ENDO`.
- Other geometries (slabs, cylinders) keep their own facet names, such as `X0` and `Z1`. The names
  above are reserved: if you use one, it must mean this.
- `lv_ellipsoid` and `biv_ellipsoid` still write their own names (`ENDO`, or `LV` and `RV`).
  `check` warns about such old names (C5) and gives the standard one, and `convert` renames them.

### Cell markers (dimension 3)

Every cell tag has a name.

- **The valve regions** `MITRAL_VALVE`, `AORTIC_VALVE`, `TRICUSPID_VALVE` and `PULMONARY_VALVE` are
  the valve planes as solids, closing a cavity.
- **Every other cell is myocardium**, whatever its name: `Wall`, `MYOCARDIUM`, `LV_WALL`,
  `RV_WALL`, an AHA segment. The one exception is `Bath`, the fluid of the deprecated
  `slab_in_bath`, which keeps its name.

### Fibres

`f0` and `s0` are required for mechanics, and `n0` is optional (it is `f0 × s0` when absent). They
are unit length and orthogonal at their own dofs, to 1e-6. A simulator should check them again at
its own quadrature degree, since a P1 field that is unit length at the nodes is not unit length
between them.

### Fields

Every field has a `unit`, a `values` legend (a categorical field) or a `description`. A categorical
field stores integers as floats; readers round them, and `check` refuses a value that is not
within 1e-8 of one in the legend.

These names are reserved:

| Name | Kind | Meaning |
|---|---|---|
| `celltype` | categorical, P1 or DG0, `values = {endo = 0, epi = 1, mid = 2}` exactly | The O'Hara-Rudy numbering, which the `celltype` parameters of the ORd 2011 and ToR-ORd 2019 models use. `recipe` records how it was computed, if it was |
| `activation_time` | `unit = "ms"`, P1 | A measured or prescribed local activation time |

## Commands

Each command wraps a Python function: `check`, `convert`, `export`, `summarize` (for `inspect`,
so as not to shadow the standard library's module) and `compute_celltype`/`add_celltype` (for
`celltype`), in `cardiac_geometries.check`, `.convert`, `.export`, `.summary` and `.celltype`.

| Command | What it does |
|---|---|
| `geox <generator> OUTDIR ...` (`lv-ellipsoid`, `biv-ellipsoid`, `slab`, `ukb`, ...) | Writes `OUTDIR/geometry.h5` in format 1, with the unit. Then it exports into `OUTDIR/viz/`, unless `--no-export` is given. Without pyvista, or on more than one rank, it warns instead |
| `geox rotate FOLDER -o OUTDIR --target-normal X Y Z` | Rotates the geometry in `FOLDER` (its geometry file, or an old folder) so that its base normal is the target, and writes `OUTDIR/geometry.h5` |
| `geox from-volume OUTDIR VOLUME ...` | A geometry from a tetrahedral volume, with cell regions, fibres and fields read from it ([below](geometry-file-from-volume)) |
| `geox convert SOURCE OUT.h5 --mapping MAPPING.toml` | An existing geometry, a file of any format or an old folder, into one format-1 file |
| `geox celltype FILE [--endo 0.3] [--epi 0.3] [--space P_1]` | Computes `celltype` and writes it into the file |
| `geox inspect FILE [--json]` | Prints what the file holds, then the result of `check` |
| `geox check FILE` | Prints the problems, and exits with 1 if any is an error |
| `geox export FILE [-o DIR]` | Writes ParaView files, by default into `<stem>-viz/` beside the file |

The Python generator functions do not export, so a library that calls them needs no pyvista.

The generators and `rotate` also write `markers.json` and `info.json` into `OUTDIR`: copies of
the file's markers and info to read without opening the file (`ukb --reuse-mesh` reads
`info.json` to tell whether an earlier mesh fits). The geometry file does not need them, and
`from_file` does not read them.

**MPI.** Reading, writing, `inspect`, `check` and `celltype` run under MPI, so a simulator can call
`check` when it loads a geometry. `export` and `convert` are one-off preparation and raise
`RuntimeError` on more than one rank.

### inspect

For a ventricle after conversion (an example, with numbers measured on physcardems'
`rodero_05_dolfinx_v2`; the fibres' line and the version are illustrative):

```
rodero_05.h5  format 1  unit m  written by cardiac-geometriesx 0.24.0  backend h5py
mesh     tetrahedron, degree 1: 24811 cells, 5943 vertices, volume 142.9 cm³
         bounds [0.0187, 0.0000, 0.0000] to [0.1176, 0.0926, 0.0958] m
facets   BASE 10: 1422   RV_ENDO 20: 1950   LV_ENDO 30: 1692   EPI 40: 2216
         7280 exterior facets, all tagged once
cells    LV_WALL 1: 13775   RV_WALL 2: 9252   MITRAL_VALVE 7: 534   TRICUSPID_VALVE 8: 532
         AORTIC_VALVE 9: 369   PULMONARY_VALVE 10: 349
fibres   f0, s0, n0 on DG0: |f| - 1 at most 2e-16, |f0·s0| at most 3e-16
fields   celltype (P1)          endo 2171, epi 2096, mid 1676
         activation_time (P1)   130.0 to 181.7 ms
info     mesh_type converted, source rodero_05_dolfinx_v2, mapping rodero_05.toml
check    no problems
```

`--json` prints the same as one JSON document. In Python, `summarize(geometry)` returns the
dictionary and `format_summary` the text.

### check

Errors make the file non-conforming; warnings do not. `check` prints the errors first.

| Code | Severity | Problem |
|---|---|---|
| C1 | error | No `metadata` (a format-0 file), or a format higher than this reader knows |
| C2 | error | No unit, or one other than m, cm, mm |
| C3 | error | A tag value in the cell or facet tags with no name in `markers` |
| C4 | error | A reserved name used with the wrong dimension (e.g. `LV_ENDO` as a cell marker) |
| C5 | warning | An old facet set (`LV`/`RV`, `ENDO_LV`/`ENDO_RV`, `ENDO`, ...), naming the standard name |
| C6 | error | `RV_ENDO` without `LV_ENDO`, or `LV_ENDO` without `EPI` and either `BASE` or a valve plane |
| C7 | error | Only one of `f0` and `s0`; or `|f| - 1` or the dot product of two fibre fields above 1e-6 at the dofs |
| C8 | error | A field with no `unit`, `values` or `description`; a categorical value outside its legend; a reserved field of the wrong kind |
| C9 | warning | A marker name whose tag no entity has |
| C10 | warning | Exterior facets without a tag (the count) |

A geometry with no tags, fibres or fields, only a mesh and a unit, passes `check`.

(geometry-file-export)=
### export

`geox export` writes VTU files that ParaView opens without extra readers. It needs pyvista (the
`pyvista` extra; without it the command ends with the install line).

- `volume.vtu`: the mesh, with the cell tags and the DG0 fields as cell data and the P1 fields as
  point data;
- `facets.vtu`: the tagged facets, with their tags as cell data;
- one `<name>.vtu` for each field or fibre on any other Lagrange or DG space (P2, DG1, ...), on
  that space's own grid, so nothing is interpolated;
- one `<name>_points.vtu` for each quadrature field: a point cloud at the quadrature points, for
  ParaView's glyphs;
- `markers.json`: the legend of the tags, since ParaView shows them as numbers.

(geometry-file-convert)=
### convert

`geox convert SOURCE OUT.h5 --mapping MAPPING.toml` reads a geometry, a file of any format or an
old folder, applies the mapping and writes one format-1 file. The result is checked first, and an
error stops the conversion before anything is written. The mapping is a TOML file:

| Key | Meaning |
|---|---|
| `unit` | Required when the source has none. It must agree with the source when the source has one |
| `[facets]` | Old name = new name. Names not listed are kept |
| `[cells]` | Tag = name. This replaces the source's cell markers |
| `[fields.<name>]` | `file` (an io4dolfinx file of a field on the same input mesh, relative to the source folder, or to the folder holding a source file), `name` in that file, `element` (e.g. `"P_1"`), and `unit`, `values` or `description` |
| `[info]` | Free keys added to `info` |

`convert` compares the dof and cell counts a field file records with the mesh, and refuses a file
that does not match. **It cannot detect a field file of the same size written on a renumbered
mesh.** That field would be read in the wrong order, with no error. The field file must have been
written on the same input mesh as the geometry, in the same numbering.

The worked example is the rodero_05 case of physcardems. The comments say where each name came
from.

```toml
# geox convert <physcardems>/cases/rodero_05/rodero_05_dolfinx_v2 rodero_05.h5 --mapping rodero_05.toml
unit = "m"

[facets]
LV = "LV_ENDO"         # markers.json
RV = "RV_ENDO"

[cells]                # convert_rodero.py: TISSUE_NAMES
1 = "LV_WALL"
2 = "RV_WALL"
7 = "MITRAL_VALVE"     # by elimination, since 9 is the aortic valve
8 = "TRICUSPID_VALVE"  # by elimination, since 10 is the pulmonary valve
9 = "AORTIC_VALVE"     # simcardemsx's case.py: the LV's outflow region
10 = "PULMONARY_VALVE" # case.py: PULMONARY_VALVE_TAG, the most superior of the four

[fields.celltype]
file = "ep_node_fields.bp"
name = "celltype"
element = "P_1"
values = { endo = 0, epi = 1, mid = 2 }

[fields.activation_time]
file = "ep_node_fields.bp"
name = "lat_ms"
element = "P_1"
unit = "ms"
```

physcardems' `sf_IKs` is left out, since it is never read. The demo [Converting a geometry](../demos/convert.py)
runs a small case through this mapping.

### celltype

`geox celltype FILE` computes the transmural cell type with the algorithm of beat's
`expand_layer_biv`: one Laplace solve from `LV_ENDO` to `EPI` and, in a BiV, one from `RV_ENDO`,
the minimum of the two, and then the `endo` and `epi` thresholds (default 0.3 and 0.3). It writes
`celltype` in the numbering above, on P1 by default (`--space DG_0` for cells), with
`recipe = {method = "laplace", endo, epi, space}`, into the file it read. Running it again
replaces the field. The file is replaced only once the new one is written
(`Geometry.save_replacing`), so a failure leaves the original. A format-0 file is refused, since
it has no unit and its JSON files would be left beside a format-1 file: convert it first.

Note that beat's own `expand_layer` and `expand_layer_biv` number the layers differently (mid 0,
endo 1, epi 2).

(geometry-file-from-volume)=
### from-volume

`from_volume` (and `geox from-volume`) reads a tetrahedral volume that pyvista reads (VTU, VTK,
...). The patient mesh demo shows it at work.

| Argument | Meaning |
|---|---|
| `unit` (required) | The unit after `scale` |
| `scale` | Multiplies the coordinates |
| `surfaces` or `rule` | The facets. Use the facet names above |
| `cell_tags`, `cell_names` | A cell-data array of integer tags, and a name for each tag. Without them every cell is `Wall` |
| `fibers` | Names of the point- or cell-data arrays for `f0`, `s0` and `n0`, read instead of computed. Giving it together with `create_fibers` is refused |
| `fields` | Point- or cell-data arrays copied in as fields, each with its `unit`, `values` or `description` |

On the command line the new tables go in one TOML file, `--data DATA.toml`, in the format of
`convert`'s `[cells]` and `[fields]`:

```toml
cell_tags = "tissue"

[cells]
1 = "LV_WALL"
2 = "RV_WALL"

[fibers]
f0 = "fibre_dir"
s0 = "sheet_dir"

[fields.height]
array = "height"
unit = "mm"
```
