|
1 | 1 | import json |
2 | | - |
| 2 | +import typing |
3 | 3 | import numpy |
4 | 4 |
|
| 5 | +from ._errors import EventModelValueError |
| 6 | + |
5 | 7 |
|
6 | 8 | def sanitize_doc(doc): |
7 | 9 | """Return a copy with any numpy objects converted to built-in Python types. |
@@ -51,3 +53,49 @@ def default(self, obj): |
51 | 53 | return obj.item() |
52 | 54 | return obj.tolist() |
53 | 55 | return json.JSONEncoder.default(self, obj) |
| 56 | + |
| 57 | + |
| 58 | +def infer_datakeys(val): |
| 59 | + """ |
| 60 | + Given a value, infer what the datatype (as Ewent Model would describe it). |
| 61 | +
|
| 62 | + Parameters |
| 63 | + ---------- |
| 64 | + val : Any |
| 65 | +
|
| 66 | + """ |
| 67 | + bad_iterables = (str, bytes, dict) |
| 68 | + _type_map = { |
| 69 | + "number": (float, numpy.floating, complex), |
| 70 | + "array": (numpy.ndarray, list, tuple), |
| 71 | + "string": (str,), |
| 72 | + "integer": (int, numpy.integer), |
| 73 | + } |
| 74 | + |
| 75 | + if isinstance(val, typing.Iterable) and not isinstance(val, bad_iterables): |
| 76 | + dtype = "array" |
| 77 | + else: |
| 78 | + for json_type, py_types in _type_map.items(): |
| 79 | + if isinstance(val, py_types): |
| 80 | + dtype = json_type |
| 81 | + break |
| 82 | + else: |
| 83 | + raise EventModelValueError( |
| 84 | + f"Cannot determine the appropriate bluesky-friendly data type for " |
| 85 | + f"value {val} of Python type {type(val)}. " |
| 86 | + f"Supported types include: int, float, str, and iterables such as " |
| 87 | + f"list, tuple, np.ndarray, and so on." |
| 88 | + ) |
| 89 | + |
| 90 | + # this should only make a copy if it _has to_. If we have lots of |
| 91 | + # non-already-numpy arrays flowing through and this is doing things like |
| 92 | + # computing huge dask arrays etc. |
| 93 | + arr_val = numpy.asanyarray(val) |
| 94 | + arr_dtype = arr_val.dtype |
| 95 | + |
| 96 | + return { |
| 97 | + "dtype": dtype, |
| 98 | + "dtype_str": arr_dtype.str, |
| 99 | + "dtype_descr": arr_dtype.descr, |
| 100 | + "shape": list(arr_val.shape), |
| 101 | + } |
0 commit comments