|
| 1 | +""" |
| 2 | +Simple serialization for numpy arrays |
| 3 | +""" |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +from traitlets import Instance, TraitError, TraitType, Undefined |
| 7 | + |
| 8 | +# Format: |
| 9 | +# {'dtype': string, 'shape': tuple, 'array': memoryview} |
| 10 | + |
| 11 | +def array_to_json(value, widget): |
| 12 | + return { |
| 13 | + 'shape': value.shape, |
| 14 | + 'dtype': str(value.dtype), |
| 15 | + 'buffer': memoryview(value) # maybe should do array.tobytes(order='C') to copy |
| 16 | + } |
| 17 | + |
| 18 | +def array_from_json(value, widget): |
| 19 | + # may need to copy the array if the underlying buffer is readonly |
| 20 | + n = np.frombuffer(value['buffer'], dtype=value['dtype']) |
| 21 | + n.shape = value['shape'] |
| 22 | + return n |
| 23 | + |
| 24 | +array_serialization = dict(to_json=array_to_json, from_json=array_from_json) |
| 25 | + |
| 26 | +def shape_constraints(*args): |
| 27 | + """Example: shape_constraints(None,3) insists that the shape looks like (*,3)""" |
| 28 | + def validator(trait, value): |
| 29 | + if len(value.shape) != len(args): |
| 30 | + raise TraitError('%s shape expected to have %s components, but got %s components'%(trait.name, len(args), (value, type(value)))) |
| 31 | + for i, constraint in enumerate(args): |
| 32 | + if constraint is not None: |
| 33 | + if value.shape[i] != constraint: |
| 34 | + raise TraitError('Dimension %i is supposed to be size %d, but got dimension %d'%(i, constraint, value.shape[i])) |
| 35 | + return value |
| 36 | + return validator |
0 commit comments