playnano.utils.io_utils module¶
Helpers for reading and writing data.
Frame metadata, height units, scaling images to 8-bit, output names and folders, and converting results to types JSON can store.
- 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.5nMorrun.v2stay 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]¶
Make one frame’s metadata dict, as every playNano reader does.
Values are converted to plain Python types so the dict can be saved as JSON. Settings of the whole recording, such as bidirectional scanning, go in
playnano.afm_stack.AFMImageStack.acquisitioninstead.- Parameters:
timestamp (float) – Time of the frame in seconds, from the start of frame 0.
frame_pixel_size_nm (float) – Pixel size of this frame, in nm.
frame_duration_s (float, optional) – Time taken to record the frame, in seconds. Default is None (unknown).
start_epoch_ms (int, optional) – Start of the frame, in milliseconds since 1970 (UTC). Default is None (unknown).
scan_direction (str, optional) – Slow-scan direction of this frame, for example
"topDown"or"bottomUp"(NanoScope.spmsequences can alternate). Default is None (unknown).line_rate (float, optional) – Lines scanned per second. Default is None (unknown).
- Returns:
The keys of
FRAME_METADATA_KEYS, with None for unknown values.- Return type:
- 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]¶
Work out the lower and upper limits of a colour scale.
- Parameters:
data (numpy.ndarray) – Heights, any shape. NaN and infinite values are ignored.
zmin (float, "auto" or None, optional) – Lower limit: a number is used as given,
"auto"uses thelower_percentilepercentile ofdataand None its minimum. Default is"auto".zmax (float, "auto" or None, optional) – Upper limit, in the same way, using
upper_percentileor the maximum. Default is"auto".lower_percentile (float, optional) – Percentile for
zmin="auto". Default is 1.upper_percentile (float, optional) – Percentile for
zmax="auto". Default is 99.
- Returns:
(zmin, zmax).- Return type:
- Raises:
ValueError – If
zminorzmaxis not a number,"auto"or None, or the lower limit is greater than the upper. Also ifdatahas no finite values and a limit is None.IndexError – If
datahas no finite values and a limit is"auto".
Examples
>>> import numpy as np >>> from playnano.utils.io_utils import compute_zscale_range >>> data = np.arange(101.0) >>> [float(z) for z in compute_zscale_range(data)] [1.0, 99.0] >>> [float(z) for z in compute_zscale_range(data, zmin=None, zmax=50)] [0.0, 50.0]
- playnano.utils.io_utils.convert_height_units_to_nm(data: ndarray, unit: str) ndarray[source]¶
Convert height data to nm.
- Parameters:
data (numpy.ndarray) – Height data.
unit ({"pm", "nm", "um", "mm", "m"}) – Unit of
data, for example fromguess_height_data_units().
- Returns:
A new array in nm.
- Return type:
- Raises:
ValueError – If
unitis not one of the units above.
- playnano.utils.io_utils.decode_hdf5_attr(attr: bytes | str) str[source]¶
Return an HDF5 attribute as a string.
- 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_pathwould overwrite the input file.- Parameters:
- Raises:
ValueError – If
output_pathandinput_pathrefer to the same file.
- playnano.utils.io_utils.guess_height_data_units(stack: ndarray) str[source]¶
Guess the unit of height data from the range of its values.
The range (largest minus smallest finite value) gives:
more than 1e4:
"pm";more than 1e-2, up to 1e4:
"nm";more than 1e-4, up to 1e-2:
"um";more than 1e-5, up to 1e-4:
"mm";up to 1e-5:
"m".
A single extreme value can change the result.
- Parameters:
stack (numpy.ndarray) – Height data, any shape. NaN and infinite values are ignored.
- Returns:
The guessed unit.
- Return type:
{“pm”, “nm”, “um”, “mm”, “m”}
- Raises:
ValueError – If there are no finite values.
Examples
>>> import numpy as np >>> from playnano.utils.io_utils import guess_height_data_units >>> guess_height_data_units(np.array([0.0, 5e-9, 2e-8])) 'm' >>> guess_height_data_units(np.array([0.0, 3.0])) 'nm'
- playnano.utils.io_utils.make_json_safe(obj)[source]¶
Convert NumPy values and functions in nested data to types JSON can store.
NumPy arrays become lists, and NumPy integers and floats become
intandfloat.Dicts, lists and tuples are converted item by item; tuples stay tuples (JSON writes them as lists). Dict keys that JSON cannot store become strings.
Functions and classes are replaced by their name.
Anything else is returned unchanged, including NumPy booleans and sets, which JSON cannot store.
- Parameters:
obj (object) – The data to convert. Not changed.
- Returns:
The converted data.
- Return type:
Examples
>>> import numpy as np >>> from playnano.utils.io_utils import make_json_safe >>> make_json_safe({"n": np.int64(3), "xy": np.array([1.5, 2.0]), "f": len}) {'n': 3, 'xy': [1.5, 2.0], 'f': 'len'}
- playnano.utils.io_utils.normalize_to_uint8(image: ndarray) ndarray[source]¶
Scale an image to 0-255 as uint8, from its minimum to its maximum.
NaN and infinite values are set to 0 first, so they count as 0. Values are rounded down. An image with one value gives all zeros.
- Parameters:
image (numpy.ndarray) – Image, any shape.
- Returns:
Array of the same shape, dtype uint8.
- Return type:
- playnano.utils.io_utils.prepare_output_directory(folder: str | None, default: str = 'output') Path[source]¶
Check an output folder and create it if missing.
- Parameters:
folder (str, pathlib.Path or None) – The folder; relative paths are relative to the current folder. If None or empty,
default.default (str, optional) – Folder used when
folderis not given. Default is"output".
- Returns:
The absolute path of the folder, which now exists.
- Return type:
- Raises:
ValueError – If any part of the path contains any of
* ? " < > |.
- playnano.utils.io_utils.sanitize_output_name(name: str, default: str) str[source]¶
Clean a user-supplied output name.
Folders and surrounding spaces are removed, then one known extension (
OUTPUT_EXTENSIONS, in any case), so other dots are kept:"exp_1.5nM.gif"becomes"exp_1.5nM".- Parameters:
- Returns:
The cleaned name, without an extension.
- Return type:
- Raises:
ValueError – If the cleaned name contains a character in
INVALID_CHARS.
Examples
>>> from playnano.utils.io_utils import sanitize_output_name >>> sanitize_output_name(" results/exp_1.5nM.GIF ", "default") 'exp_1.5nM' >>> sanitize_output_name(None, "default") 'default'