Skip to content

Commit 506fd6f

Browse files
committed
add traits numpy file
1 parent 3435e91 commit 506fd6f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

pythreejs/traits_numpy.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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

Comments
 (0)