Skip to content

Commit

Permalink
fix(core): added a json converter class in json_encoder.py to pyscan/…
Browse files Browse the repository at this point in the history
…general. This is now implemented in the save_metadata method of abstract_experiment.py which enables numpy values to be used as data inputs before saving. The converter changes the numpy values to standard python values and no longer throws the same type error as before.
  • Loading branch information
rsbrost committed Jun 11, 2024
1 parent 17704b5 commit c2c2b8f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
17 changes: 17 additions & 0 deletions pyscan/general/json_encoder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import json
import numpy as np


class NumpyEncoder(json.JSONEncoder):
"""
Custom encoder for numpy data types.
"""
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NumpyEncoder, self).default(obj)
5 changes: 3 additions & 2 deletions pyscan/measurement/abstract_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
recursive_to_dict,
is_list_type)
from pyscan.measurement.scans import PropertyScan, RepeatScan
from pyscan.general.json_encoder import NumpyEncoder


class AbstractExperiment(ItemAttribute):
Expand Down Expand Up @@ -229,8 +230,8 @@ def save_metadata(self):
data = recursive_to_dict(self.__dict__)

with h5py.File(save_name, 'a') as f:
f.attrs['runinfo'] = json.dumps(data['runinfo'])
f.attrs['devices'] = json.dumps(data['devices'])
f.attrs['runinfo'] = json.dumps(data['runinfo'], cls=NumpyEncoder)
f.attrs['devices'] = json.dumps(data['devices'], cls=NumpyEncoder)

def start_thread(self):
'''Starts experiment as a background thread, this works in conjunction with live plot
Expand Down

0 comments on commit c2c2b8f

Please sign in to comment.