playNano.analysis.utils package¶
Submodules¶
playNano.analysis.utils.common module¶
Common utility functions for analysis.
- class playNano.analysis.utils.common.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶
Bases:
JSONEncoder
Custom JSON encoder for serializing NumPy ndarray and scalar objects.
This encoder converts NumPy arrays to native Python lists and NumPy scalar types (e.g., float32, int64) to their native Python equivalents so they can be serialized by the standard json module. It can be used with json.dump or json.dumps by passing it as the cls argument.
Example
json.dump(data, file, cls=NumpyEncoder)
- default(obj)[source]¶
Override default method to convert NumPy arrays and scalar types.
Convert NumPy arrays ad scalar types to JSON-serializable forms.
- Parameters:
obj (Any) – The object to be serialized.
- Returns:
A JSON-serializable version of the object. If the object is a NumPy ndarray, it is converted to a list. If the object is a NumPy scalar (e.g., np.float32, np.int64), it is converted to the equivalent Python scalar. Otherwise, the superclass’s default method is used.
- Raises:
TypeError – If the object cannot be serialized by the superclass.
- playNano.analysis.utils.common.export_to_hdf5(record: Mapping[str, Any], out_path: Path, dataset_name: str = 'analysis_record') None [source]¶
Save a nested dict/list/array structure to HDF5 with full breakdown.
Dicts become groups.
Lists of primitives become datasets.
Lists of complex objects become subgroups item_0, item_1, etc.
NumPy arrays become datasets.
- playNano.analysis.utils.common.load_analysis_from_hdf5(file_path: str | Path, dataset_name: str = 'analysis_record') dict [source]¶
Load a nested dict/list/NumPy array structure from an HDF5 file.
This exactly reverses export_to_hdf5. Automatically converts integer-valued NumPy floats to Python ints recursively for use as list indices.
- Parameters:
file_path (str or Path) – Path to the HDF5 file containing the saved analysis dictionary.
dataset_name (str, default='analysis_record') – Name of the top-level group in the HDF5 file where the dictionary is stored.
- Returns:
record – Nested dictionary reconstructed from the HDF5 file. The structure preserves: - dicts as dicts - lists as lists - NumPy arrays as np.ndarray - strings as str - empty lists as [] - primitive values stored in attributes - integer-valued floats converted to Python int recursively
- Return type:
dict
- Raises:
KeyError – If dataset_name is not found in the HDF5 file.
- playNano.analysis.utils.common.make_json_safe(record: dict) dict [source]¶
Make a AnalysisRecord safe for export through JSON dumping.
Prepare an AnalysisRecord for JSON dumping by stripping out or summarizing any non-JSON-serializable entries.
- Parameters:
record (dict) – The full AnalysisRecord returned by AnalysisPipeline.run().
- Returns:
A new dict with the same top-level keys (“environment”, “analysis”, “provenance”), but with each value run through your sanitizers so that they contain only numbers, strings, lists, and dicts.
- Return type:
dict
playNano.analysis.utils.frames module¶
Frame-based post-processing helpers.
E.g. summarize per-frame statistics or produce histograms.
- playNano.analysis.utils.frames.frame_summary_to_dataframe(features_per_frame: Sequence[Sequence[dict]]) DataFrame [source]¶
Build a DataFrame with one row per frame.
Summarises number of features, total area, mean intensity, etc.
- Parameters:
features_per_frame (list of lists of dict) – As returned by FeatureDetectionModule.run()[“features_per_frame”].
- Returns:
- Columns:
frame_index (int)
n_features (int)
total_area (int)
mean_area (float)
mean_intensity (float)
- Return type:
pd.DataFrame
- playNano.analysis.utils.frames.plot_frame_histogram(df: DataFrame, column: str, ax: Axes | None = None, save_to: Path | None = None, bins: int = 20) Axes [source]¶
Plot a histogram of a per-frame summary metric.
- Parameters:
df (pandas.DataFrame) – As returned by frame_summary_to_dataframe.
column (str) – Which column to histogram (e.g. ‘n_features’).
ax (matplotlib Axes, optional)
save_to (Path, optional)
bins (int) – Number of histogram bins.
- Returns:
ax
- Return type:
matplotlib Axes
playNano.analysis.utils.particles module¶
Particle-based postprocessing helpers.
These functions take the raw outputs of feature detection and particle tracking modules and turn them into tabular data, plots, and CSV/HDF5 exports.
- playNano.analysis.utils.particles.export_particle_csv(df: DataFrame, out_path: Path) None [source]¶
Write the flattened track DataFrame to CSV.
- Parameters:
df (pandas.DataFrame)
out_path (Path) – Path to write the .csv file (will create parent dirs).
- playNano.analysis.utils.particles.flatten_particle_features(grouping_output: Mapping[str, Any], detection_output: Mapping[str, Any], *, object_key: str | None = None, object_id_field: str = 'cluster_id', frame_key: str = 'frames', index_key: str = 'point_indices') DataFrame [source]¶
Build a DataFrame linking each grouping analysis results to detected features.
Each object (e.g. cluster or track) is linked to its corresponding detected feature metadata using (frame index, point index) pairs to locate features in the output of a feature detection step and merges metadata into one flattened table.
- Parameters:
grouping_output (dict) – Dictionary from a grouping module (e.g. clustering or tracking). Must contain a list of group objects under the object_key, where each object has lists of frames and point_indices.
detection_output (dict) – Dictionary from a detection module (e.g. feature_detection), which must contain the key ‘features_per_frame’: a list of feature dicts per frame.
object_key (str, optional) – Key in grouping_output pointing to the list of group objects. Default is “clusters”.
object_id_field (str, optional) – Column name to use in the output DataFrame to identify the group, e.g., “cluster_id” or “track_id”. Default is “cluster_id”.
frame_key (str, optional) – Key in each group object listing the frames the object appears in. Default is “frames”.
index_key (str, optional) – Key in each group object listing the per-frame point indices (used to match detections in features_per_frame). Default is “point_indices”.
- Returns:
Flattened DataFrame linking features to group membership. Includes feature metadata and:
object_id_field (e.g. “cluster_id”)
frame
timestamp
label
centroid_x, centroid_y
area
mean_intensity
min_intensity
max_intensity
- Return type:
pd.DataFrame
- playNano.analysis.utils.particles.plot_particle_labels_3d(df: DataFrame, object_id_field: str = 'track_id', ax: Axes | None = None, save_to: Path | None = None, cmap: str = 'tab10') Axes [source]¶
Plot particle ids in 3D (x, y, time), colored by object ID.
- Parameters:
df (pandas.DataFrame) – Must contain [‘centroid_x’,’centroid_y’,’timestamp’, object_id_field]
object_id_field (str) – Column to use for color grouping (e.g. “track_id”, “cluster_id”)
ax (matplotlib Axes, optional) – A 3D Axes to draw into, or None to create a new one.
save_to (Path, optional) – If given, save the figure to file.
cmap (str) – Colormap name for particle group colors.
- Returns:
ax – The 3D axes used.
- Return type:
Axes
Module contents¶
Public package initialization.