playnano.utils.io_utils module

Utility functions for IO operations in playNano.

playnano.utils.io_utils.OUTPUT_EXTENSIONS = ('.ome.tiff', '.ome.tif', '.tiff', '.tif', '.h5', '.hdf5', '.npz', '.json', '.gif', '.mp4', '.avi', '.mov', '.mkv', '.png', '.jpg', '.jpeg', '.csv', '.yaml', '.yml')

File extensions removed from user-supplied output names. Anything else after a dot is kept, so names such as exp_1.5nM or run.v2 stay intact.

playnano.utils.io_utils.build_frame_metadata(*, timestamp: float, frame_pixel_size_nm: float, frame_duration_s: float | None = None, start_epoch_ms: int | None = None, scan_direction: str | None = None, line_rate: float | None = None) → dict[source]

Build a canonical per-frame metadata dict shared by all playNano readers.

Every value is cast to a native Python type so the dict is JSON-serialisable (frame_metadata is saved via json.dumps on export; numpy bools/floats otherwise raise TypeError).

Fields a format cannot provide are stored as None.

Whole-video acquisition modes (e.g. bidirectional) belong on the stack, not here. start_time (human-readable ISO) is derived from the first frame’s start_epoch_ms at the stack level; don’t duplicate it per frame.

Parameters:
  • timestamp (float) – Frame time in seconds relative to frame 0. Required.

  • frame_pixel_size_nm (float) – Physical size of one pixel in nanometres for this frame. Required.

  • frame_duration_s (float, optional) – Frame acquisition duration in seconds; None if unknown.

  • start_epoch_ms (int, optional) – Frame start as Unix epoch milliseconds (UTC); None for formats without absolute timing.

  • scan_direction (str, optional) – Slow-axis frame direction (e.g. 'topDown'/'bottomUp'). Per-frame because NanoScope spm sequences can alternate.

  • line_rate (float, optional) – Fast-scan line rate (lines per second); None if unknown.

Returns:

Exactly the keys in FRAME_METADATA_KEYS.

Return type:

dict

playnano.utils.io_utils.compute_zscale_range(data: ndarray, zmin: float | str = 'auto', zmax: float | str = 'auto', lower_percentile: int = 1, upper_percentile: int = 99) → tuple[float, float][source]

Compute robust Z-scale bounds (height or intensity range) for normalization.

Parameters:
  • data (np.ndarray) – 2D or 3D array of AFM image data.

  • zmin (float, "auto", or None) – Lower bound: “auto” uses percentile, None uses data min, float uses value.

  • zmax (float or "auto") – Upper bound: “auto” uses percentile, None uses data max, float uses value.

  • lower_percentile (int, optional) – Percentile to use for lower bound when zmin == “auto”. Default is 1.

  • upper_percentile (int, optional) – Percentile to use for upper bound when zmax == “auto”. Default is 99.

Returns:

zmin and zmax values suitable for normalization.

Return type:

(float, float)

Raises:

ValueError – If zmin > zmax after processing or invalid input types.

playnano.utils.io_utils.convert_height_units_to_nm(data: ndarray, unit: str) → ndarray[source]

Convert AFM height data from the guessed unit to nanometers.

Parameters:
  • data (np.ndarray) – Input height data array, typically 2D or 3D.

  • unit (str) – Unit string as returned by guess_height_data_units. Must be one of: ‘pm’, ‘nm’, ‘um’, ‘mm’, or ‘m’.

Returns:

The input data converted to nanometers.

Return type:

np.ndarray

Raises:

ValueError – If the provided unit string is not recognized.

playnano.utils.io_utils.decode_hdf5_attr(attr: bytes | str) → str[source]

Decode an attribute that may be bytes or a string.

Parameters:

attr (bytes or str) – The attribute to decode.

Returns:

The decoded string.

Return type:

str

playnano.utils.io_utils.ensure_not_input_path(output_path: str | Path, input_path: str | Path | None) → None[source]

Raise an error if writing to output_path would overwrite the input file.

Parameters:
  • output_path (str or Path) – File that is about to be written.

  • input_path (str, Path or None) – File or folder the data was loaded from. If None, nothing is checked.

Raises:

ValueError – If output_path and input_path refer to the same file.

playnano.utils.io_utils.guess_height_data_units(stack: ndarray) → str[source]

Guess the most likely units of AFM height data from the data range.

Parameters:

stack (np.ndarray) – AFM height data array, typically 2D or 3D. Non-finite values (NaN or infinity) are ignored when determining the range.

Returns:

A string indicating the guessed unit of the height data, one of: ‘pm’ (picometers), ‘nm’ (nanometers), ‘um’ (micrometers), ‘mm’ (millimeters), or ‘m’ (meters).

Return type:

str

Raises:

ValueError – If the input array contains no finite values.

Notes

The unit is estimated based on the numeric range of the data as follows:
  • Range > 1e4 : ‘pm’

  • 1e-2 < Range <= 1e4 : ‘nm’

  • 1e-4 < Range <= 1e-2 : ‘um’

  • 1e-5 < Range <= 1e-4 : ‘mm’

  • Range <= 1e-5 : ‘m’

Examples

>>> import numpy as np
>>> data = np.array([[0, 5e-9], [1e-8, 2e-8]])
>>> guess_height_data_units(data)
'nm'
playnano.utils.io_utils.make_json_safe(obj)[source]

Recursively convert NumPy types and non-JSON objects into serializable ones.

playnano.utils.io_utils.normalize_to_uint8(image: ndarray) → ndarray[source]

Normalize a float image to the uint8 [0, 255] range, handling NaNs and Infs.

Parameters:

image (np.ndarray) – Input image as a NumPy array of floats. May contain NaNs or infinite values.

Returns:

Normalized image as a uint8 NumPy array with values in the range [0, 255].

Return type:

np.ndarray

playnano.utils.io_utils.prepare_output_directory(folder: str | None, default: str = 'output') → Path[source]

Validate, resolve, and create the output directory if it doesn’t exist.

Parameters:
  • folder (str or None) – User-provided output folder path. If None, use default.

  • default (str, optional) – Default folder name to use if folder not specified.

Returns:

A Path object pointing to the created output directory.

Return type:

Path

Raises:

ValueError – If any part of the folder path contains invalid characters.

playnano.utils.io_utils.sanitize_output_name(name: str, default: str) → str[source]

Sanitize output file names by removing a file extension and stripping whitespace.

Only known output extensions (see OUTPUT_EXTENSIONS) are removed, so dots elsewhere in the name are kept: "exp_1.5nM.gif" becomes "exp_1.5nM".

Parameters:
  • name (str) – The output file name provided by the user.

  • default (str) – Default name to use if name is empty or None.

Returns:

Sanitized base file name without extension.

Return type:

str