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: object

An AFM video: frames, pixel size, per-frame metadata, results and provenance.

Usually made by load_data() or playnano.io.loader.load_afm_stack(), and changed by playnano.processing.pipeline.ProcessingPipeline and playnano.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 Python int or float: 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_KEYS in playnano.utils.io_utils; other keys give a warning. A shorter list is padded with empty dicts. Timestamps are converted with playnano.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:

numpy.ndarray

pixel_size_nm

Pixel size in nm for frames without their own.

Type:

float

channel

Channel name.

Type:

str

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 other FRAME_METADATA_KEYS.

Type:

list of dict

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 by apply().

Type:

dict

masks

Boolean mask arrays from the processing pipeline, keyed "step_<n>_<name>".

Type:

dict

analysis

Analysis results, keyed "step_<n>_<module name>".

Type:

dict

provenance

What was done and with what: "environment" (software versions), "acquisition" (see acquisition), "processing" (steps and their keys) and "analysis" (steps, results by name, frame times).

Type:

dict

state_backups

Data kept so changes can be undone: "frame_metadata_before_edit" holds the frame metadata from before frames were removed.

Type:

dict

Raises:
  • TypeError – If data is not a NumPy array.

  • ValueError – If data is not 3D, pixel_size_nm is not a positive int or float, or frame_metadata has 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:

  1. "clear": forget the current mask;

  2. a mask generator (MASK_MAP), which sets the mask for later filters;

  3. a method of this class;

  4. a plugin registered under playnano.filters or playnano.video_processing;

  5. 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;

  6. a video filter (VIDEO_FILTER_MAP);

  7. a stack edit (STACK_EDIT_MAP), which also clears the mask.

Parameters:
  • steps (list of str) – Step names, applied in order, for example ["remove_plane", "mask_threshold", "row_median_align"].

  • **kwargs – Passed to every step. A step that does not accept them is called without any.

Returns:

The processed data, also stored in data.

Return type:

numpy.ndarray

Raises:

ValueError – If a step name is not found.

Notes

processed gets "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, otherwise channel.

Return type:

str

Raises:

IndexError – If idx is 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_results attribute, which nothing in playNano sets, so it raises ValueError even after an analysis has run. To save results, pass the record returned by playnano.analysis.pipeline.AnalysisPipeline.run() to playnano.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_results attribute, 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": ...}} from provenance.

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:

numpy.ndarray

Raises:

IndexError – If index is 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:

dict

Raises:

IndexError – If index is 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.

Returns:

One time per frame.

Return type:

list of float

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:

list of numpy.ndarray

property height: int

Height of each frame, in pixels (rows).

property image_shape: tuple[int, int]

Shape of each frame, (height, width), in pixels.

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, masks and provenance.

Return type:

AFMImageStack

Raises:
  • FileNotFoundError – If the path does not exist, or a folder holds no known file type.

  • ValueError – If the file type is not supported.

property n_frames: int

Number of frames.

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. data is not changed; see restore_raw().

restore_raw() → ndarray[source]

Restore the original data by loading from the ‘raw’ snapshot in self.processed.

Copies processed["raw"] into data and calls restore_frame_metadata(). processed, masks and provenance are not changed.

Returns:

The restored data.

Return type:

numpy.ndarray

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", or pixel_size_nm if the frame has no such key. A key set to None returns None.

Return type:

float

Raises:

IndexError – If idx is 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", or float(idx) if it is missing or None.

Return type:

float

Raises:

IndexError – If idx is 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)
property width: int

Width of each frame, in pixels (columns).