playnano.io package

Subpackages

Submodules

playnano.io.data_loaders module

Data loaders for AFM image stacks exported by playNano.

This module provides readers for serialized AFMImageStack bundles created by the export routines (.npz, .h5, and OME-TIFF). Each loader reconstructs a AFMImageStack with correct data, pixel size, channel name, and per-frame metadata (timestamps). All loaders restore provenance and any stored processing or mask data.

Functions

load_npz_bundle

Load a .npz bundle into an AFMImageStack.

load_h5_bundle

Load a .h5 bundle into an AFMImageStack.

load_ome_tiff_stack

Load an OME-TIFF bundle into an AFMImageStack.

playnano.io.data_loaders.load_h5_bundle(path: Path, channel: str = 'height_trace') AFMImageStack[source]

Load an AFMImageStack from an HDF5 bundle.

Expected HDF5 structure

Datasets
  • /data : float32 array of shape (n_frames, H, W)

  • /processed/<step> : optional processed datasets

  • /masks/<mask> : optional boolean mask datasets

  • /frame_metadata_json : UTF-8 encoded JSON (list of dicts)

  • /provenance_json : UTF-8 encoded JSON (dict)

  • /state_backups_json : optional UTF-8 JSON (dict)

Attributes
  • pixel_size_nm : scalar float

  • channel : string

Files with the structure are produced by playNano.io.export_data.save_h5_bundle().

param path:

Path to the .h5 file.

type path:

pathlib.Path

param channel:

Provided for API compatibility with load_afm_stack() but ignored when reading the bundle.

type channel:

str, default=”height_trace”

returns:

Fully reconstructed AFM image stack with provenance, processed steps, and masks restored.

rtype:

playNano.afm_stack.AFMImageStack

raises ValueError:

If required datasets are missing or JSON decoding fails. If required datasets (frame_metadata_json or provenance_json) are missing or contain invalid JSON.

playnano.io.data_loaders.load_npz_bundle(path: Path, channel: str = 'height_trace') AFMImageStack[source]

Load an AFMImageStack from a .npz bundle.

The .npz file must contain the following keys:

  • data : float32 array of shape (n_frames, H, W)

  • pixel_size_nm : scalar float

  • channel : str scalar

  • frame_metadata_json : JSON-encoded list of dicts

  • provenance_json : JSON-encoded dict

  • processed__<step> : optional processed frame arrays

  • masks__<mask> : optional boolean mask arrays

  • state_backups_json : optional JSON-encoded dict of saved states

This is the structure produced by playNano.io.export_data.save_npz_bundle().

Parameters:
  • path (pathlib.Path) – Path to the .npz file.

  • channel (str, default="height_trace") – Provided for API compatibility with load_afm_stack() but ignored when reading the bundle.

Returns:

Reconstructed AFM image stack with attributes populated: .processed, .masks, and .provenance.

Return type:

playNano.afm_stack.AFMImageStack

Raises:

ValueError – If required keys are missing or JSON blobs cannot be decoded.

playnano.io.data_loaders.load_ome_tiff_stack(path: Path, channel: str = 'height_trace') AFMImageStack[source]

Load an OME-TIFF bundle into an AFMImageStack.

Attempts to parse OME-XML and custom metadata tags to reconstruct pixel size, timestamps, and provenance. Falls back gracefully if certain metadata are unavailable.

Parameters:
  • path (pathlib.Path) – Path to the .ome.tif file created by save_ome_tiff_stack().

  • channel (str, optional) – Fallback channel name if none is found in OME metadata.

Returns:

Reconstructed AFMImageStack with:

  • data : 3D float32 array (T, H, W)

  • pixel_size_nm : float, derived from OME physical size

  • channel : str, from OME Channel or fallback

  • frame_metadata : list of dicts containing timestamps

  • provenance : dict reconstructed from custom or embedded tags

Return type:

playNano.afm_stack.AFMImageStack

Raises:

ValueError – If the image array shape is unsupported or essential metadata cannot be parsed.

playnano.io.export_data module

Tools for exporting AFM image stacks in multiple formats.

This module provides utilities for serializing AFMImageStack objects into round-trip-safe formats: OME-TIFF, NPZ, and HDF5. Each export preserves pixel data, metadata, masks, provenance, and processing history.

Supported formats

  • OME-TIFF: For image analysis interoperability (Bio-Formats compatible).

  • NPZ: Compact NumPy archive with full AFMImageStack data and metadata.

  • HDF5: Hierarchical bundle ideal for provenance-rich workflows.

Each export supports both filtered and raw modes.

playnano.io.export_data.check_path_is_path(path: str | Path) Path[source]

Ensure the input is returned as a pathlib.Path.

Converts strings to Path objects. Raises TypeError for unsupported types.

Parameters:

path (str or Path) – The input path to validate or convert.

Returns:

A pathlib.Path object representing the input path.

Return type:

Path

Raises:

TypeError – If the input is not a str or Path.

playnano.io.export_data.export_bundles(afm_stack: AFMImageStack, output_folder: Path, base_name: str, formats: list[str], raw: bool = False) None[source]

Export an AFMImageStack in one or more serialization formats.

Parameters:
  • afm_stack (AFMImageStack) – The stack to export.

  • output_folder (Path) – Target directory for output files.

  • base_name (str) – Base filename (no extension).

  • formats (list of {"tif", "npz", "h5"}) – Which formats to produce.

  • raw (bool, optional) – If True, exports only the unprocessed raw snapshot, (.processed['raw']). Default is False.

Raises:

SystemExit – If an unsupported format string is provided.

playnano.io.export_data.save_h5_bundle(path: Path, stack: AFMImageStack, raw: bool = False) None[source]

Save an AFMImageStack and metadata as an HDF5 bundle.

The hierarchical layout preserves round-trip reconstruction fidelity and stores all relevant AFM stack data, processed layers, masks, timestamps, and provenance.

File structure

/data

: float32 array of shape (n_frames, H, W)

/processed/<step> : float32 datasets for each processing step /masks/<mask> : bool datasets for each mask /timestamps : float64 array of length n_frames /frame_metadata_json : UTF-8 encoded JSON string /provenance_json : UTF-8 encoded JSON string /state_backups_json : UTF-8 encoded JSON string (only if present)

Root attributes

pixel_size_nmfloat

Physical pixel size in nanometers.

channelstr

Name of the imaging channel.

param path:

Destination path for the HDF5 file. The ‘.h5’ suffix will be added automatically.

type path:

Path

param stack:

The stack to export.

type stack:

AFMImageStack

param raw:

If True, only the unprocessed raw snapshot (processed[‘raw’]) is exported. Otherwise, the full .data, masks, and processed layers are included.

type raw:

bool, optional

Notes

  • state_backups_json is only created if the stack has a non-empty

state_backups attribute. - Timestamps are taken from state_backups[‘frame_metadata_before_edit’] if exporting raw data, otherwise from .frame_metadata. - Provenance is sanitized via make_json_safe().

playnano.io.export_data.save_npz_bundle(path: Path, stack: AFMImageStack, raw: bool = False) None[source]

Save AFMImageStack with metadata as a .npz bundle.

The NPZ archive consolidates the AFM stack data, metadata, provenance, masks, and processed layers for full round-trip reconstruction.

File structure

data : float32 array of shape (n_frames, H, W) processed__<step> : float32 arrays for each processing step masks__<mask> : bool arrays for each mask timestamps : float64 array of length n_frames frame_metadata_json : UTF-8 encoded JSON string provenance_json : UTF-8 encoded JSON string state_backups_json : UTF-8 encoded JSON string (only if present) pixel_size_nm : float32 scalar channel : object array (string)

param path:

Destination path for the .npz file. The extension will be added automatically.

type path:

Path

param stack:

The stack to export.

type stack:

AFMImageStack

param raw:

If True, only the unprocessed raw snapshot and essential metadata are saved. Otherwise, the full data (.data), masks, and processed layers are included.

type raw:

bool, optional

Notes

  • state_backups_json is only included if the stack defines a state_backups attribute.

  • When raw=True, timestamps are taken from state_backups['frame_metadata_before_edit'] (if available), otherwise from .frame_metadata.

  • Provenance is serialized using make_json_safe() to ensure JSON compatibility.

  • The saved file can be reloaded via load_npz_bundle().

Examples

>>> from pathlib import Path
>>> from playnano.io.export_data import save_npz_bundle
>>> save_npz_bundle(Path("output/stack_export"), stack)
>>> save_npz_bundle(Path("output/raw_only"), stack, raw=True)
playnano.io.export_data.save_ome_tiff_stack(path: Path, afm_stack: AFMImageStack, raw: bool = False) None[source]

Save an AFMImageStack as an OME-TIFF file.

The OME-TIFF export embeds image data, pixel calibration, timestamps, and provenance metadata into a single, standards-compliant file suitable for downstream analysis in microscopy or image-processing software.

File structure

  • Image data is stored in 5D OME-TIFF format with axes (T, C, Z, Y, X). Only a single channel (C=1) and a single Z-slice (Z=1) are used.

  • Physical calibration is stored in micrometres (µm) under PhysicalSizeX and PhysicalSizeY.

  • Provenance and processed-layer keys are stored as binary JSON under private TIFF tags 65000 and 65001.

param path:

Output path for the .ome.tif file.

type path:

Path

param afm_stack:

The AFM image stack to export.

type afm_stack:

AFMImageStack

param raw:

If True, export the unprocessed raw snapshot (processed['raw'] if present). Otherwise, export the current data in .data with all processing applied.

type raw:

bool, optional

Notes

  • Each frame’s timestamp is stored in the OME metadata as DeltaT.

  • The pixel size (in nm) is converted to micrometres for OME compliance.

  • The exported file includes additional TIFF tags:

    • 65000: JSON-encoded provenance dictionary

    • 65001: JSON list of processed layer names

  • The file can be reloaded with standard OME-TIFF readers such as tifffile or aicsimageio.

Examples

>>> from pathlib import Path
>>> from playnano.io.export_data import save_ome_tiff_stack
>>> save_ome_tiff_stack(Path("output/stack.ome.tif"), stack)
>>> save_ome_tiff_stack(Path("output/raw_stack.ome.tif"), stack, raw=True)

playnano.io.gif_export module

GIF export utilities for AFM image stacks.

This module provides functions for generating animated GIFs from AFM image stacks, with optional timestamps and scale bars. Frames can be normalized automatically or scaled using a fixed z-range.

Dependencies

  • matplotlib

  • numpy

  • Pillow (PIL)

playnano.io.gif_export.create_gif_with_scale_and_timestamp(image_stack, pixel_size_nm, timestamps=None, scale_bar_length_nm=100, output_path='output', duration=0.5, cmap_name='afmhot', zmin: float | str | None = None, zmax: float | str | None = None, draw_ts: bool = True, draw_scale: bool = True)[source]

Create an animated GIF from an AFM image stack with optional overlays.

Frames are normalized, colorized using a matplotlib colormap, and annotated with a scale bar and timestamps before being compiled into a GIF.

Parameters:
  • image_stack (np.ndarray) – 3D array of shape (N, H, W) representing the AFM image stack.

  • pixel_size_nm (float) – Size of each pixel in nanometers.

  • timestamps (list[float] or tuple[float], optional) – Timestamps for each frame in seconds. If None or invalid, frame indices are used.

  • scale_bar_length_nm (int) – Length of the scale bar in nanometers. Default is 100.

  • output_path (str) – Path where the GIF will be saved. Default is ‘output’.

  • duration (float) – Duration of each frame in seconds. Default is 0.5.

  • cmap_name (str) – Name of the matplotlib colormap to apply. Default is ‘afmhot’.

  • zmin (float or str or None, optional) – Minimum z-value mapped to colormap low end. The string literal "auto" uses the 1st percentile.

zmaxfloat or str or None, optional

Maximum z-value mapped to colormap high end. The string literal "auto" uses the 99th percentile.

draw_tsbool

Whether to draw timestamps. Default is True.

draw_scalebool

Whether to draw a scale bar. Default is True.

Raises:

ValueError – If zmin equals zmax or timestamps have incorrect shape.

Return type:

None

Notes

  • Timestamps and scale bars are drawn in white.

  • Frames are normalized globally if zmin and zmax are provided; otherwise, per-frame.

playnano.io.gif_export.export_gif(afm_stack, make_gif: bool, output_folder: str | None, output_name: str | None, scale_bar_nm: int | None, raw: bool = False, zmin: float | None = None, zmax: float | None = None, draw_ts: bool = True, draw_scale: bool = True) None[source]

Export an AFM image stack as an annotated GIF.

Parameters:
  • afm_stack (AFMImageStack) – AFM stack object containing raw and/or processed data.

  • make_gif (bool) – Whether to generate the GIF. If False, the function exits immediately.

  • output_folder (str or None) – Directory to save the GIF. Defaults to "output" if None.

  • output_name (str or None) – Base name for the GIF file. If None, derived from the stack file name.

  • scale_bar_nm (int or None) – Length of the scale bar in nanometers. Defaults to 100 nm.

  • raw (bool) – If True, export raw (unprocessed) data; otherwise export processed data if available. Default is False.

  • zmin (float or None, optional) – Minimum z-value mapped to colormap low end. The string literal "auto" can also be used to automatically set the 1st percentile. None uses the minimum value of the data.

  • zmax (float or None, optional) – Maximum z-value mapped to colormap high end. The string literal "auto" can also be used to automatically set the 99th percentile. None uses the maximum value of the data.

  • draw_ts (bool) – Whether to draw timestamps on each frame. Default is True.

  • draw_scale (bool) – Whether to draw a scale bar on each frame. Default is True.

Return type:

None

Notes

  • Uses processed data if available; otherwise falls back to raw data.

  • Timestamps and pixel size are read from afm_stack metadata although if raw data is exported after an edit_stack processing step then the timestamps in afm_stack.state_backups['frame_metadata_before_edit'] are retrieved and used.

  • Output file name includes "_filtered" if processed data is exported.

playnano.io.loader module

Common loader for various high speed AFM video formats and playNano export bundles.

Supported extensions:
  • .jpk (folder)

  • .spm (folder)

  • .h5-jpk (single-file JPK)

  • .asd (single-file ASD)

  • .ome.tif / .tif (OME-TIFF bundles)

  • .npz (playNano NPZ bundles)

  • .h5 (playNano HDF5 bundles)

playnano.io.loader.get_loader_for_file(file_path: Path, file_loaders: dict, folder_loaders: dict) callable[source]

Determine the appropriate loader for a single multi-frame AFM file.

Parameters:
  • file_path (Path) – Path to the file.

  • file_loaders (dict) – Mapping from file extensions to file loader functions.

  • folder_loaders (dict) – Mapping from extensions for folder loaders (for error handling).

Returns:

The file extension string and the loader function for the file.

Return type:

(str, callable)

Raises:

ValueError – If the file type is unsupported or better handled as a folder.

playnano.io.loader.get_loader_for_folder(folder_path: Path, folder_loaders: dict) tuple[str, callable][source]

Determine the appropriate loader for a folder containing AFM data.

Parameters:
  • folder_path (Path) – Path to the folder.

  • folder_loaders (dict) – Mapping from file extension to loader function.

Returns:

The chosen extension and loader function.

Return type:

(str, callable)

Raises:

FileNotFoundError – If no known file types are found.

playnano.io.loader.load_afm_stack(file_path: Path, channel: str = 'height_trace') AFMImageStack[source]

Unified interface to load AFM stacks from various file formats.

High speed AFM videos can be saved as either individual frames within a folder or as multiple frames within a single file. This loader splits these two approaches and loads both into the common AFMImageStack object for processing.

As well as the file formats exported from AFM instruments, this function also read raw and processed exports from playnano (NPZ, OME_TIF and HDF5).

All data values with length units (i.e. m) are converted to nm.

Parameters:
  • file_path (Path | str) – Path to the AFM data file or folder of files.

  • channel (str) – Scan channel name.

Returns:

Loaded image stack with metadata.

Return type:

AFMImageStack

Module contents

Public package initialization.