Skip to content

Files

Read and write dw3d meshes: the .rec format with its metadata appendix, and .vtk/.vtu through meshio.

A mesh is (points, triangles, labels): (n, 3) points, (m, 3) vertex indices and (m, 2) labels, the two regions each triangle separates (label 0 is the medium). The files store the points as given: these functions neither scale nor reorder their columns. A file therefore keeps the mask's order, (z, y, x) for a microscope stack; a program that reads its columns as (x, y, z), as ParaView, MeshLab and other VTK readers do, shows the mirror image of the tissue, unless it exchanges columns 0 and 2 (and two corners of every triangle, so that each still faces the same side), as dw3d.viewing.plot_cells_polyscope does for what it draws.

The .rec reader and writer are iorec's (iorec.load_rec, iorec.save_rec, iorec.load_rec_appendix); this module keeps dw3d's names and signatures, types dw3d's own appendix keys when it reads a version-1 appendix, and writes the appendix in version 1 (see APPENDIX_VERSION_WRITTEN). Matthieu Perez 2024

load_meshio_mesh

load_meshio_mesh(filename: str | Path) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64]]

Read a mesh file using meshio; the labels come from the triangle cell arrays label1 and label2.

Parameters:

Name Type Description Default
filename str | Path

The path to the file on disk.

required

Raises:

Type Description
ValueError

If the file has no label1 or label2 triangle cell array, or if those arrays are empty. (Before 0.7.0 a missing array raised meshio's KeyError.)

ReadError

If meshio can't read the file for any reason.

Returns:

Type Description
tuple[NDArray[float64], NDArray[int64], NDArray[int64]]

tuple[np.array, np.array, np.array]: (points, triangles, labels): points (num_points, 3), triangles (num_triangles, 3) and labels (num_triangles, 2), with the dtypes stored in the file (float64 and int64 for a file written by save_vtk from dw3d's own arrays). A crop_face array is not read; use load_meshio_mesh_with_crop_faces.

load_meshio_mesh_with_crop_faces

load_meshio_mesh_with_crop_faces(filename: str | Path) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64], NDArray[np.bool_] | None]

load_meshio_mesh, plus the crop faces a crop_face cell array records.

Parameters:

Name Type Description Default
filename str | Path

The path to the file on disk.

required

Raises:

Type Description
ValueError

If the file has no label1 or label2 triangle cell array, or if those arrays are empty.

Returns:

Name Type Description
tuple tuple[NDArray[float64], NDArray[int64], NDArray[int64], NDArray[bool_] | None]

(points, triangles, labels, crop_faces); crop_faces is (n_triangles,) bool, or None when the file has no crop_face array (a file written before crop faces were recorded, or by another program). None says nothing about whether the mesh was cropped.

save_vtk

save_vtk(filename: str | Path, points: NDArray[float64], triangles: NDArray[int64], labels: NDArray[int64], binary_mode: bool = False, crop_faces: NDArray[bool_] | None = None) -> None

Save a vtk mesh file at filename. Binary or text mode are available.

Binary mode is more compact but might not be universally understood. meshio picks the format from the file extension (.vtk, .vtu, ...). The labels are written as the triangle cell arrays label1 and label2.

Parameters:

Name Type Description Default
filename str | Path

where to save the mesh file.

required
points NDArray[float64]

(n, 3) mesh points, written as given.

required
triangles NDArray[int64]

(m, 3) mesh triangles (topology).

required
labels NDArray[int64]

(m, 2) the two regions each triangle separates.

required
binary_mode bool

Choose binary mode. Defaults to False.

False
crop_faces NDArray[bool_] | None

(n_triangles,), True on the crop faces (see dw3d.crop_faces). When given, written as the cell array crop_face (1 on a crop face, 0 elsewhere) beside label1 and label2. Defaults to None, which writes the file exactly as before this option existed.

None

Raises:

Type Description
ValueError

if crop_faces is not a boolean array with one entry per triangle, or if the mesh has no triangle (since 0.8.0; before, meshio raised IndexError while writing a .vtk file, and wrote .vtu files that meshio cannot read back). Nothing is written then; save_rec writes an empty .rec file, which load_rec reads back.

rec_dimension

rec_dimension(filename: str | Path) -> int

Whether a .rec/.arec file holds a 2-D mesh (segments) or a 3-D mesh (triangles).

The .rec format carries no dimension marker. Since 0.8.0 both packages' algorithms record dimension in the metadata appendix (dw2d always, dw3d whenever it writes an appendix); when the key is present it decides. Otherwise the layout does: in a text file, the number of coordinates on the point rows; in a binary file, which of the two layouts accounts exactly for the geometry's bytes before the appendix (_layouts_of_a_binary_rec). A file both layouts would fit (possible in principle for a binary file, never observed) is refused rather than guessed.

Parameters:

Name Type Description Default
filename str | Path

the path to the file.

required

Returns:

Name Type Description
int int

2 or 3.

Raises:

Type Description
FileNotFoundError

if the file does not exist.

ValueError

if the appendix's dimension is not 2 or 3, or if the layout fits neither or both dimensions.

load_rec

load_rec(filename: str | Path) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64]]

Read a rec mesh file, text or binary (detected from the content).

A metadata appendix, if any, is ignored; read it with load_rec_appendix. Crop faces are returned as ordinary triangles, in the file's row order; read them with load_rec_with_crop_faces. A 2-D file (rec_dimension) is refused: read it with dw2d.io.load_rec.

Parameters:

Name Type Description Default
filename str | Path

The path to the file on disk.

required

Raises:

Type Description
ValueError

If the path given is not a .rec or .arec file, or if it holds a 2-D mesh.

FileNotFoundError

If the file doesn't exist.

Returns:

Type Description
tuple[NDArray[float64], NDArray[int64], NDArray[int64]]

tuple[np.array, np.array, np.array]: (points, triangles, labels): points (num_points, 3) float64, triangles (num_triangles, 3) int64 and labels (num_triangles, 2) int64.

load_rec_with_crop_faces

load_rec_with_crop_faces(filename: str | Path) -> tuple[NDArray[np.float64], NDArray[np.int64], NDArray[np.int64], NDArray[np.bool_] | None]

Read a rec mesh file and the crop faces its metadata appendix records.

A file written by MeshReconstructionAlgorithm.save_to_rec_mesh, or by save_rec with crop_faces, holds its crop faces as the last block of triangle rows and records the block in the appendix as crop_faces = <first row> <count>. This reads that range back as a mask over the triangle rows, in the file's own row order.

Parameters:

Name Type Description Default
filename str | Path

The path to the file on disk.

required

Raises:

Type Description
ValueError

if the appendix's range is not the last block of the file's triangles, if a crop face does not carry the medium label 0, or as load_rec (not a .rec or .arec file).

FileNotFoundError

if the file doesn't exist.

Returns:

Name Type Description
tuple tuple[NDArray[float64], NDArray[int64], NDArray[int64], NDArray[bool_] | None]

(points, triangles, labels, crop_faces), the first three as load_rec returns them; crop_faces is (n_triangles,) bool, or None when the file records no crop_faces key (a file written before crop faces were recorded, or by another program). None says nothing about whether the mesh was cropped.

crop_faces_from_appendix_range

crop_faces_from_appendix_range(crop_range: tuple[int, ...], labels: NDArray[int64]) -> NDArray[np.bool_]

Turn the appendix's crop_faces = <first row> <count> into a mask over the triangle rows.

Parameters:

Name Type Description Default
crop_range tuple[int, ...]

(first, count) as parsed from the appendix.

required
labels NDArray[int64]

(n_triangles, 2) the file's labels, to check the range against.

required

Raises:

Type Description
ValueError

if the range is not two integers ending at the last row, or if a row in it does not carry the medium label 0.

Returns:

Type Description
NDArray[bool_]

NDArray[np.bool_]: (n_triangles,), True on rows first to first + count - 1.

write_rec_appendix

write_rec_appendix(metadata: dict[str, Any], *, written_by: str) -> bytes

Build the trailing .rec/.arec metadata appendix block.

The block is a sequence of ASCII #-prefixed key = value lines (appendix version 1, APPENDIX_VERSION_WRITTEN), headed by the rec-appendix 1 line, built by iorec.write_rec_appendix. It must be appended at the very end of the file: a trailing # block is invisible to every reader that predates it (both text and binary mode), since those readers read a count and then np.fromfile(..., count=n), which stops exactly there. A leading block breaks both readers. See tests/test_rec_appendix.py::test_legacy_reader_ignores_trailing_appendix.

Parameters:

Name Type Description Default
metadata dict[str, Any]

appendix fields, e.g. coordinate_frame, axis_order, spacing, spacing_unit, source_shape, crop_offset, crop_faces. Sequence-valued fields (spacing, source_shape, crop_offset, crop_faces) are written space-separated.

required
written_by str

the dw3d version string that produced this file. Stamped by the writer -- the appendix is never hand-edited.

required

Returns:

Name Type Description
bytes bytes

the ASCII appendix block (including a trailing newline), ready to be

bytes

concatenated onto the geometry bytes/text already written.

parse_rec_appendix

parse_rec_appendix(block_text: str) -> dict[str, Any]

Parse a .rec/.arec metadata appendix block into a dict.

Parameters:

Name Type Description Default
block_text str

the appendix block, headed by the # rec-appendix <version> line: version 1 (# key = value lines) or version 2 (# key: <JSON> lines).

required

Raises:

Type Description
ValueError

if block_text does not start with a rec-appendix <version> header, if the version is not 1 or 2, or if a value cannot be read as its key's type.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: parsed fields, plus "_version" (the schema version, an int). Sequence-valued fields known to the schema are parsed into tuples (spacing and enclosed_media_inscribed_radius of float; source_shape, crop_offset, crop_faces, media, enclosed_media_voxels, unresolved_regions and unresolved_regions_voxels of int), and resampled_spacing into a float (APPENDIX_KEY_TYPES); every other key is kept as a raw string, never dropped, so a future rewrite can carry it forward. A version-2 block gives each value the type its JSON holds, sequences as tuples.

load_rec_appendix

load_rec_appendix(filename: str | Path) -> dict[str, Any] | None

Read the trailing metadata appendix from a .rec/.arec file, if present.

Works uniformly for text- and binary-mode files: the appendix is located by finding the last # rec-appendix marker in the file. It is written only ever as the literal first line of the trailing appendix block (see write_rec_appendix), so its last occurrence marks the start of the block -- note that binary-mode payloads have no guaranteed newline before this marker, so the search cannot require one.

Parameters:

Name Type Description Default
filename str | Path

the path to the file on disk.

required

Returns:

Type Description
dict[str, Any] | None

dict[str, Any] | None: the parsed appendix fields (see parse_rec_appendix), or None if the file has no appendix. A None return must be treated by the caller as coordinate_frame == "unknown", never as isotropic spacing -- a legacy file's absent appendix carries no information about spacing at all.

save_rec

save_rec(filename: str | Path, points: NDArray[float64], triangles: NDArray[int64], labels: NDArray[int64], binary_mode: bool = False, metadata: dict[str, Any] | None = None, crop_faces: NDArray[bool_] | None = None) -> None

Save a rec mesh file at filename. Binary or text mode are available.

Binary mode is more compact but might not be universally understood. Its layout, little-endian on every machine (iorec's), is: the number of points (uint64); the points, 3 float64 each; the number of triangles (uint64); per triangle, its 3 vertex indices (int64) then its 2 labels (int32). The points are always written as float64, the dtype load_rec reads, whatever their dtype in memory (before 0.7.0 they were written in their own dtype, so float32 points did not read back). The text layout is the point count, one line of 3 coordinates per point (each the shortest text that reads back to the same float64), the triangle count, and one v0 v1 v2 label1 label2 line per triangle. Either layout may be followed by the metadata appendix (version 1, APPENDIX_VERSION_WRITTEN). The file is written by iorec.save_rec.

Parameters:

Name Type Description Default
filename str | Path

where to save the mesh file.

required
points NDArray[float64]

(n, 3) mesh points, written as given.

required
triangles NDArray[int64]

(m, 3) mesh triangles (topology).

required
labels NDArray[int64]

(m, 2) the two regions each triangle separates.

required
binary_mode bool

Choose binary mode. Defaults to False.

False
metadata dict[str, Any] | None

appendix fields (coordinate_frame, axis_order, spacing, spacing_unit, source_shape, crop_offset, ...). Defaults to None, which writes nothing extra -- byte-for-byte the same file as before this option existed. When supplied, a trailing metadata appendix is appended after the geometry data; see write_rec_appendix.

None
crop_faces NDArray[bool_] | None

(n_triangles,), True on the crop faces (see dw3d.crop_faces). When given, the crop faces are written as the last block of triangle rows (the other rows first, both blocks in their original order) and the appendix records crop_faces = <first row> <count> (<count> may be 0), so the file's rows are in a different order from the arrays passed in. A reader that ignores the appendix still reads a valid mesh, in which the crop faces look like contact with the medium; load_rec_with_crop_faces reads them back. Defaults to None, which writes the file as before this option existed.

None

Raises:

Type Description
ValueError

if crop_faces is not a boolean array with one entry per triangle.