playnano.afm_stack module¶
The AFMImageStack class, which holds an AFM video and everything done to it.
The module also builds the lookup tables of built-in steps that
AFMImageStack.apply() and the processing pipeline use: FILTER_MAP,
MASK_MAP, MASK_FILTERS_MAP, VIDEO_FILTER_MAP and STACK_EDIT_MAP.
- class playnano.afm_stack.AFMImageStack(data: ndarray, pixel_size_nm: float, channel: str, file_path: Path, frame_metadata: list[dict[str, Any]] = None)[source]¶
Bases:
objectAn AFM video: frames, pixel size, per-frame metadata, results and provenance.
Usually made by
load_data()orplaynano.io.loader.load_afm_stack(), and changed byplaynano.processing.pipeline.ProcessingPipelineandplaynano.analysis.pipeline.AnalysisPipeline.- Parameters:
data (numpy.ndarray) – Frames, shape (n_frames, height, width), heights in nm. Stored as given, without copying.
pixel_size_nm (int or float) – Pixel size in nm, used when a frame has no
frame_pixel_size_nm. Must be a positive Pythonintorfloat: NumPy numbers are rejected.channel (str) – Channel name, for example
"height_trace".file_path (str or pathlib.Path) – File or folder the data came from. Stored as given; used for default output names.
frame_metadata (list of dict, optional) – One dict per frame, with keys from
FRAME_METADATA_KEYSinplaynano.utils.io_utils; other keys give a warning. A shorter list is padded with empty dicts. Timestamps are converted withplaynano.utils.time_utils.normalize_timestamps(), and a frame without one gets"timestamp": None. Default is None (no metadata).
- data¶
The current frames, shape (n_frames, height, width). Processing replaces this array.
- Type:
- file_path¶
File or folder the data came from.
- Type:
str or pathlib.Path
- frame_metadata¶
One dict per frame. Every dict has
"timestamp"(s, or None); files loaded by playNano also have the otherFRAME_METADATA_KEYS.
- processed¶
Copies of the data, as arrays:
"raw"before the first step, then one per step, keyed"step_<n>_<name>"by the processing pipeline or by step name byapply().- Type:
- provenance¶
What was done and with what:
"environment"(software versions),"acquisition"(seeacquisition),"processing"(steps and their keys) and"analysis"(steps, results by name, frame times).- Type:
- state_backups¶
Data kept so changes can be undone:
"frame_metadata_before_edit"holds the frame metadata from before frames were removed.- Type:
- Raises:
TypeError – If
datais not a NumPy array.ValueError – If
datais not 3D,pixel_size_nmis not a positive int or float, orframe_metadatahas more entries than there are frames.
Examples
>>> import numpy as np >>> from playnano.afm_stack import AFMImageStack >>> data = np.zeros((3, 64, 64)) >>> stack = AFMImageStack( ... data, ... pixel_size_nm=2.0, ... channel="height_trace", ... file_path="demo.h5-jpk", ... frame_metadata=[{"timestamp": 0.0}, {"timestamp": 0.5}], ... ) >>> stack.n_frames, stack.image_shape (3, (64, 64)) >>> stack.get_frame_times() [0.0, 0.5, 2.0]
- property acquisition: dict[str, Any]¶
Settings of the whole recording, from the file’s header.
For example whether the scan was bidirectional, or the file version, depending on the format; empty if the reader found none. Stored in
provenance["acquisition"], and kept when frames are removed.
- apply(steps: list[str], **kwargs) ndarray[source]¶
Apply processing steps by name, without recording provenance.
A quick way to process a stack interactively. For processing you can repeat and report, use
playnano.processing.pipeline.ProcessingPipeline.Each name is looked up in this order:
"clear": forget the current mask;a mask generator (
MASK_MAP), which sets the mask for later filters;a method of this class;
a plugin registered under
playnano.filtersorplaynano.video_processing;a built-in filter (
FILTER_MAP); if a mask is set and the filter has a masked version (MASK_FILTERS_MAP), that version is used;a video filter (
VIDEO_FILTER_MAP);a stack edit (
STACK_EDIT_MAP), which also clears the mask.
- Parameters:
- Returns:
The processed data, also stored in
data.- Return type:
- Raises:
ValueError – If a step name is not found.
Notes
processedgets"raw"(if not already there) and a copy of the data after each step except"clear"and masks, keyed by step name, so a repeated step replaces its earlier copy. Masks are not stored. If a filter fails on a frame, that frame is left unchanged and a warning is logged; if a video filter fails, the step is skipped.Examples
>>> import numpy as np >>> from playnano.afm_stack import AFMImageStack >>> yy, xx = np.mgrid[0:32, 0:32] >>> data = np.stack([0.1 * xx + 0.05 * yy] * 2).astype(float) >>> stack = AFMImageStack(data, 1.0, "height_trace", "demo.h5-jpk") >>> out = stack.apply(["remove_plane"]) >>> sorted(stack.processed), bool(np.allclose(out, 0)) (['raw', 'remove_plane'], True)
- channel_for_frame(idx: int) str[source]¶
Return a frame’s channel name.
- Parameters:
idx (int) – Frame index.
- Returns:
The frame’s
"channel"metadata if it has one, otherwisechannel.- Return type:
- Raises:
IndexError – If
idxis out of range.
- export_analysis_log(path: str) None[source]¶
Save the analysis results as a JSON file. Currently always raises an error.
It looks for results in an
analysis_resultsattribute, which nothing in playNano sets, so it raisesValueErroreven after an analysis has run. To save results, pass the record returned byplaynano.analysis.pipeline.AnalysisPipeline.run()toplaynano.analysis.export.export_analysis_to_json().- Parameters:
path (str or pathlib.Path) – File to write. Its folder is created if missing.
- Raises:
ValueError – If the stack has no
analysis_resultsattribute, or it is empty.
- export_processing_log(path: str) None[source]¶
Save the environment and processing provenance as a JSON file.
The file holds
{"environment": ..., "processing": {"steps": ..., "keys_by_name": ...}}fromprovenance.- Parameters:
path (str or pathlib.Path) – File to write. Its folder is created if missing; an existing file is overwritten.
- frames_with_metadata()[source]¶
Iterate over the frames with their index and metadata.
- Yields:
tuple of (int, numpy.ndarray, dict) – Frame index, frame (a view of
data) and metadata dict.
- get_frame(index: int) ndarray[source]¶
Return one frame.
- Parameters:
index (int) – Frame index; negative values count from the end.
- Returns:
The frame, shape (height, width). It is a view of
data, so changing it changes the stack.- Return type:
- Raises:
IndexError – If
indexis out of range.
- get_frame_metadata(index: int) dict[str, Any][source]¶
Return one frame’s metadata.
- Parameters:
index (int) – Frame index, from 0 to
n_frames - 1. Negative values are not accepted.- Returns:
The frame’s metadata dict itself, not a copy.
- Return type:
- Raises:
IndexError – If
indexis out of range.
- get_frame_times() list[float][source]¶
Return every frame’s time in seconds.
Uses
time_for_frame(), so a frame without a time gets its index.Examples
>>> import numpy as np >>> from playnano.afm_stack import AFMImageStack >>> stack = AFMImageStack( ... np.zeros((3, 4, 4)), ... 1.0, ... "height_trace", ... "demo.h5-jpk", ... frame_metadata=[{"timestamp": 0.0}, {"timestamp": 0.5}], ... ) >>> stack.get_frame_times() [0.0, 0.5, 2.0]
- get_frames() list[ndarray][source]¶
Return all frames as a list.
- Returns:
One 2D array per frame; each is a view of
data.- Return type:
- classmethod load_data(path: str | Path, channel: str = 'height_trace') AFMImageStack[source]¶
Load a stack from an AFM file, a folder of frames, or a saved playNano file.
Calls
playnano.io.loader.load_afm_stack(), which picks the reader from the file extension.- Parameters:
path (str or pathlib.Path) – File or folder to load.
channel (str, optional) – Channel to read. Ignored for files saved by playNano, which keep their own channel. Default is
"height_trace".
- Returns:
The stack. Files saved by playNano also restore
processed,masksandprovenance.- Return type:
- Raises:
FileNotFoundError – If the path does not exist, or a folder holds no known file type.
ValueError – If the file type is not supported.
- restore_frame_metadata()[source]¶
Put back the frame metadata saved before frames were removed.
Takes it out of
state_backups["frame_metadata_before_edit"]. Does nothing if there is none.datais not changed; seerestore_raw().
- restore_raw() ndarray[source]¶
Restore the original data by loading from the ‘raw’ snapshot in self.processed.
Copies
processed["raw"]intodataand callsrestore_frame_metadata().processed,masksandprovenanceare not changed.- Returns:
The restored data.
- Return type:
- Raises:
KeyError – If there is no
processed["raw"].
- scaling_for_frame(idx: int) float[source]¶
Return a frame’s pixel size in nm.
- Parameters:
idx (int) – Frame index.
- Returns:
The frame’s
"frame_pixel_size_nm", orpixel_size_nmif the frame has no such key. A key set to None returns None.- Return type:
- Raises:
IndexError – If
idxis out of range.
Examples
>>> import numpy as np >>> from playnano.afm_stack import AFMImageStack >>> stack = AFMImageStack( ... np.zeros((2, 4, 4)), ... 1.0, ... "height_trace", ... "demo.h5-jpk", ... frame_metadata=[{"frame_pixel_size_nm": 2.0}, {}], ... ) >>> stack.scaling_for_frame(0), stack.scaling_for_frame(1) (2.0, 1.0)
- time_for_frame(idx: int) float[source]¶
Return a frame’s time in seconds, or its index if it has no time.
- Parameters:
idx (int) – Frame index.
- Returns:
The frame’s
"timestamp", orfloat(idx)if it is missing or None.- Return type:
- Raises:
IndexError – If
idxis out of range.
Examples
>>> import numpy as np >>> from playnano.afm_stack import AFMImageStack >>> stack = AFMImageStack( ... np.zeros((3, 4, 4)), ... 1.0, ... "height_trace", ... "demo.h5-jpk", ... frame_metadata=[{"timestamp": 0.0}, {}, {"timestamp": 0.4}], ... ) >>> stack.time_for_frame(1), stack.time_for_frame(2) (1.0, 0.4)