playnano.analysis.utils.common module

Common utility functions for analysis.

playnano.analysis.utils.common.MAX_SANITIZE_DEPTH = 50

Nesting depth at which sanitize_analysis_for_logging() stops. Analysis results are far shallower than this; the limit only guards against runaway recursion.

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.TYPE_ATTR = '_playnano_type'

HDF5 attribute recording what Python type each group was written from, so load_analysis_from_hdf5() can rebuild it exactly.

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, one subgroup per key. Keys are stored as strings.

  • Lists of numbers, or of strings, become a values dataset.

  • Other lists become subgroups item_0, item_1, etc.

  • NumPy arrays become a values dataset with their original dtype.

  • Scalars and strings are stored in a value attribute.

Each group also records the type it came from (attribute _playnano_type), so load_analysis_from_hdf5() returns the same structure: None, empty dicts, float lists and keys named values all survive the round trip. Tuples and sets are stored as lists.

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 reverses export_to_hdf5. Files written by this version record the type of every value, so dicts, lists, arrays, None and scalars come back as they were saved. Files written by earlier versions have no type records; for those, integer-valued floats are converted to Python ints (for use as list indices), and None and empty dicts cannot be told apart from other values.

Parameters:
  • file_path (str or Path) – Path to the HDF5 file containing the saved analysis dictionary.

  • dataset_name (str) – Name of the top-level group in the HDF5 file where the dictionary is stored. Default is ‘analysis_record’.

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.common.safe_json_dumps(obj)[source]

Serialize an object to JSON safely, falling back to str() on failure.

playnano.analysis.utils.common.sanitize_analysis_for_logging(obj, path='root', _depth=0, _max_depth=50)[source]

Return a JSON-safe version of any object, for the analysis JSON output.

Dicts, lists, tuples and sets are converted recursively. NumPy arrays are replaced by a summary (shape, dtype, min, max, mean), functions by a placeholder string, and NumPy scalars by Python scalars. Numbers and strings are always kept, however deeply nested.

Parameters:
  • obj (Any) – The object to convert.

  • path (str, optional) – Location of obj in the record, used in log messages.

  • _depth (int) – Internal recursion counters. A container nested deeper than _max_depth is replaced by a placeholder string and a warning is logged.

  • _max_depth (int) – Internal recursion counters. A container nested deeper than _max_depth is replaced by a placeholder string and a warning is logged.

Returns:

A structure of dicts, lists, numbers, strings, booleans and None.

Return type:

Any