playnano.analysis.utils.common module¶
Convert analysis results for saving as JSON or HDF5.
NumpyEncoderandsafe_json_dumps()write NumPy values as JSON.sanitize_analysis_for_logging()andmake_json_safe()make a smaller, JSON-safe copy in which arrays are summarised.export_to_hdf5()andload_analysis_from_hdf5()save and reload a record in full.
- 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:
JSONEncoderJSON 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 asclstojson.dump()orjson.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}'
- 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
valuesdataset;other lists: subgroups
item_0,item_1and so on;numbers, str and other values: a
valueattribute (values HDF5 cannot store are saved asstr(value));None: an empty group.
Each group’s
_playnano_typeattribute 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:
- 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:
- Returns:
A new dict with the keys
"environment","analysis"and"provenance".- Return type:
- Raises:
KeyError – If one of those keys is missing.
See also
playnano.utils.io_utils.make_json_safeA different function with the same name, used for stack provenance.
- playnano.analysis.utils.common.safe_json_dumps(obj)[source]¶
Return
objas JSON text, or asstr(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:
- playnano.analysis.utils.common.sanitize_analysis_for_logging(obj, path='root', _depth=0, _max_depth=50)[source]¶
Return a JSON-safe copy of
objin 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,maxandmean, 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
objin the record, used in log messages. Default is"root"._depth (int, optional) – Used internally. A container nested more than
_max_depthlevels 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_depthlevels 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