playnano.analysis.utils.common module

Convert analysis results for saving as JSON or HDF5.

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

JSON encoder that also writes NumPy arrays, NumPy numbers and functions.

Arrays become (nested) lists, NumPy integers, floats and bools become Python numbers and bools, and functions become the text "<function name>". Pass it as cls to json.dump() or json.dumps().

Examples

>>> import json
>>> import numpy as np
>>> json.dumps({"a": np.arange(3), "b": np.float32(0.5)}, cls=NumpyEncoder)
'{"a": [0, 1, 2], "b": 0.5}'
default(obj)[source]

Return a JSON-serialisable form of obj.

Parameters:

obj (Any) – A value the standard encoder cannot write.

Returns:

The converted value.

Return type:

list or int or float or bool or str

Raises:

TypeError – If obj is none of the types above (for example, a set).

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 nested dicts, lists and arrays, such as an analysis record, to HDF5.

Nothing is summarised, so load_analysis_from_hdf5() returns the same structure. Each value becomes an HDF5 group:

  • dicts: one subgroup per key, with keys stored as str;

  • lists of numbers, or of str, and arrays: a values dataset;

  • other lists: subgroups item_0, item_1 and so on;

  • numbers, str and other values: a value attribute (values HDF5 cannot store are saved as str(value));

  • None: an empty group.

Each group’s _playnano_type attribute records the type it came from. Tuples and sets are saved as lists.

Parameters:
  • record (dict) – The structure to save, for example the record returned by run().

  • out_path (str or pathlib.Path) – The file to write; overwritten if it exists. Missing folders are created.

  • dataset_name (str, optional) – Name of the top-level group. Default is "analysis_record".

playnano.analysis.utils.common.load_analysis_from_hdf5(file_path: str | Path, dataset_name: str = 'analysis_record') → dict[source]

Load a structure saved by export_to_hdf5().

Parameters:
  • file_path (str or pathlib.Path) – The HDF5 file.

  • dataset_name (str, optional) – Name of the top-level group. Default is "analysis_record".

Returns:

The saved structure, with dicts, lists, arrays, numbers, str and None as they were saved (tuples and sets come back as lists).

Files written by playNano before 0.5.2 do not record types. For these, the type is inferred from the layout: integer-valued floats become ints, and None and empty dicts cannot be recovered.

Return type:

dict

Raises:

KeyError – If the file has no group called dataset_name.

playnano.analysis.utils.common.make_json_safe(record: dict) → dict[source]

Return a JSON-safe copy of an analysis record, with arrays summarised.

Runs sanitize_analysis_for_logging() on each part of the record.

Parameters:

record (dict) – The record returned by run().

Returns:

A new dict with the keys "environment", "analysis" and "provenance".

Return type:

dict

Raises:

KeyError – If one of those keys is missing.

See also

playnano.utils.io_utils.make_json_safe

A different function with the same name, used for stack provenance.

playnano.analysis.utils.common.safe_json_dumps(obj)[source]

Return obj as JSON text, or as str(obj) if it cannot be written as JSON.

Parameters:

obj (Any) – The value to convert, written with NumpyEncoder.

Returns:

The JSON text, or str(obj). In that case a message is printed.

Return type:

str

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

Return a JSON-safe copy of obj in which arrays are summarised.

Dicts, lists, tuples and sets are converted recursively, with dict keys made JSON-safe. Arrays are replaced by a summary dict with the keys "_array_shape", "_array_dtype" and "_summary" (min, max and mean, each None for an empty array; "_summary" itself is None for arrays that are not numbers or bools, such as text). Functions become the text "<function name>", NumPy numbers become Python numbers and bytes are decoded as UTF-8.

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

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

  • _depth (int, optional) – Used internally. A container nested more than _max_depth levels deep (default 50) is replaced by a placeholder text, and a warning is logged.

  • _max_depth (int, optional) – Used internally. A container nested more than _max_depth levels deep (default 50) is replaced by a placeholder text, and a warning is logged.

Returns:

The converted value, made only of dicts, lists, str, numbers, bools and None. Other objects are returned unchanged.

Return type:

Any