Skip to content

Commit 939c9bf

Browse files
committed
Use datawidget union
1 parent f1995ab commit 939c9bf

File tree

7 files changed

+58
-47
lines changed

7 files changed

+58
-47
lines changed

js/scripts/generate-wrappers.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -423,14 +423,13 @@ _.extend(JavascriptWrapper.prototype, {
423423

424424
}, this);
425425

426-
this.serializedProps = _.reduce(this.config.properties, function(result, prop, propName) {
427-
428-
if (prop.serialize) {
429-
result.push(propName);
430-
}
431-
return result;
432-
433-
}, []);
426+
this.serializedProps = _.mapObject(_.pick(this.config.properties,
427+
function(prop, propName) {
428+
return !!prop.serializer;
429+
}),
430+
function(prop, propName) {
431+
return prop.serializer;
432+
}, {});
434433

435434
this.enum_properties = _.reduce(this.config.properties, function(result, prop, propName) {
436435
if (prop.enumTypeName) {

js/scripts/prop-types.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
var _ = require('underscore');
22

3+
var WIDGET_SERIALIZER = '{ deserialize: widgets.unpack_models }';
4+
35
function BaseType() {}
46
_.extend(BaseType.prototype, {
57
getJSPropertyValue: function() {
@@ -30,7 +32,7 @@ _.extend(BaseType.prototype, {
3032
function ThreeType(typeName, options={}) {
3133
this.typeName = typeName;
3234
this.defaultValue = null;
33-
this.serialize = true;
35+
this.serializer = WIDGET_SERIALIZER;
3436
this.nullable = options.nullable !== false;
3537
this.args = options.args;
3638
this.kwargs = options.kwargs;
@@ -114,7 +116,7 @@ _.extend(InitializedThreeType.prototype, ThreeType.prototype, {
114116
function ThreeTypeArray(typeName) {
115117
this.typeName = typeName;
116118
this.defaultValue = [];
117-
this.serialize = true;
119+
this.serializer = WIDGET_SERIALIZER;
118120
}
119121
_.extend(ThreeTypeArray.prototype, BaseType.prototype, {
120122
getTraitlet: function() {
@@ -136,7 +138,7 @@ _.extend(ThreeTypeArray.prototype, BaseType.prototype, {
136138
function ThreeTypeDict(typeName) {
137139
this.typeName = typeName;
138140
this.defaultValue = {};
139-
this.serialize = true;
141+
this.serializer = WIDGET_SERIALIZER;
140142
}
141143
_.extend(ThreeTypeDict.prototype, BaseType.prototype, {
142144
getTraitlet: function() {
@@ -260,22 +262,24 @@ _.extend(ArrayType.prototype, BaseType.prototype, {
260262
},
261263
});
262264

263-
// TODO: support more than Float32Array
264-
function ArrayBufferType(arrayType, shape_constraint) {
265+
266+
function ArrayBufferType(arrayType, shapeConstraint) {
265267
this.arrayType = arrayType;
266-
this.shape_constraint = shape_constraint;
268+
this.shapeConstraint = shapeConstraint;
267269
this.defaultValue = null;
270+
this.serializer = 'datawidgets.data_union_serialization';
268271
}
269272
_.extend(ArrayBufferType.prototype, BaseType.prototype, {
270273
getTraitlet: function() {
271-
var r = `NDArray(dtype=${this.arrayType || 'None'}).tag(sync=True, **array_serialization)`;
272-
if (this.shape_constraint) {
273-
var constraint = this.shape_constraint.reduce(function(wip, element) {
274-
return wip + `, ${element === null ? 'None' : element}`;
275-
}, this);
276-
r += `.valid(shape_constraint([${this.shape_constraint}]))`
274+
var args = [];
275+
if (this.arrayType) {
276+
args.push(`dtype=${this.arrayType}`);
277277
}
278-
return r;
278+
if (this.shapeConstraint) {
279+
args.push(`shape_constraint=${this.shapeConstraint}`);
280+
}
281+
282+
return `DataUnion(${args.join(', ')}).tag(sync=True)`;
279283
},
280284
getPropertyConverterFn: function() {
281285
return 'convertArrayBuffer';

js/scripts/templates/js_wrapper.mustache

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ var {{ modelName }} = {{ superClass.modelName }}.extend({
7272
7373
model_name: '{{ modelName }}',
7474
75-
{{#if serialized_props}}
75+
{{#if serialized_props }}
7676
serializers: _.extend({
77-
{{#each serialized_props as |propName|}}
78-
{{ propName }}: { deserialize: widgets.unpack_models },
77+
{{#each serialized_props as |serializer propName|}}
78+
{{ propName }}: {{ serializer }},
7979
{{/each}}
80-
}, {{ superClass.modelName }}.serializers),
80+
}{{#if superClass }}, {{ superClass.modelName }}.serializers){{/if}},
8181
{{/if}}
8282
});
8383

js/scripts/templates/py_wrapper.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ from traitlets import (
66
Tuple, List, Dict, Float, CFloat, Bool, Union, Any,
77
)
88

9-
from ipydatawidgets import NDArray, array_serialization, NDArrayWidget
9+
from ipydatawidgets import DataUnion
1010

1111
from {{ py_base_relative_path }}enums import *
1212
from {{ py_base_relative_path }}traits import *

js/src/core/BufferAttribute.js

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,13 @@ var BufferAttributeModel = BufferAttributeAutogen.extend({
1515

1616
decodeData() {
1717
var rawData = this.get('array');
18-
if (rawData.dimension > 2) {
19-
throw Error('Array has too many dimensions:', array)
20-
}
21-
var itemSize = rawData.dimension === 1 ? 1 : rawData.shape[1];
18+
var itemSize = rawData.dimension === 1 ? 1 : rawData.shape[rawData.dimension - 1];
2219

2320
var data = this.convertArrayBufferModelToThree(rawData, 'array');
2421
return {
2522
array: data,
2623
itemSize: itemSize,
27-
}
24+
};
2825
},
2926

3027
constructThreeObject: function() {
@@ -56,10 +53,6 @@ var BufferAttributeModel = BufferAttributeAutogen.extend({
5653
}
5754
},
5855

59-
}, {
60-
serializers: _.extend({
61-
array: datawidgets.array_serialization,
62-
}, BufferAttributeAutogen.serializers),
6356
});
6457

6558
module.exports = {

pythreejs/core/BufferAttribute.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22
from ipywidgets import register
33
from traitlets import validate, TraitError, Undefined
4-
from ipydatawidgets import NDArray, array_serialization, NDArrayWidget
4+
from ipydatawidgets import NDArrayWidget
55

66
from .BufferAttribute_autogen import BufferAttribute as BaseBufferAttribute
77

@@ -20,11 +20,14 @@ def __init__(self, array=None, normalized=True, **kwargs):
2020

2121
@validate('array')
2222
def _valid_array(self, proposal):
23-
# Validate shape
24-
if np.ndim(proposal) > 2:
25-
raise TraitError('Array needs to have at most two dimensions. Given shape was: %r'
26-
% np.shape(proposal))
2723
value = proposal['value']
24+
if isinstance(value, NDArrayWidget):
25+
value = value.array
26+
27+
if isinstance(proposal['value'], NDArrayWidget):
28+
if value is not Undefined and value.dtype == np.float64:
29+
raise TraitError('Cannot use a float64 data widget as a BufferAttribute source.')
30+
return proposal['value']
2831
if value is not Undefined and value.dtype == np.float64:
2932
# 64-bit not supported, coerce to 32-bit
3033
value = value.astype(np.float32)

pythreejs/textures/DataTexture.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import numpy as np
22
from ipywidgets import register
3-
from traitlets import validate, TraitError
3+
from traitlets import validate, TraitError, Undefined
4+
from ipydatawidgets import NDArrayWidget
45

56
from .DataTexture_autogen import DataTexture as BaseDataTexture
67

@@ -10,15 +11,26 @@ class DataTexture(BaseDataTexture):
1011

1112
@validate('data')
1213
def _valid_data(self, proposal):
14+
value = proposal['value']
15+
if isinstance(value, NDArrayWidget):
16+
value = value.array
17+
1318
# Validate shape
14-
if np.ndim(proposal) > 2:
19+
if np.ndim(value) < 2 or np.ndim(value) > 3:
1520
raise TraitError('Data needs to have two or three dimensions. Given shape was: %r'
16-
% np.shape(proposal))
21+
% (np.shape(value),))
22+
1723
old = self._trait_values.get(proposal['trait'].name, None)
18-
value = proposal['value']
19-
if old is not None and np.shape(old) != np.shape(value):
20-
raise TraitError('Cannot change shape of previously initialized DataTexture.')
21-
if value.dtype == np.float64:
24+
if old is not None and np.ndim(old) > 0 and np.shape(old) != np.shape(value):
25+
raise TraitError('Cannot change shape of previously initialized DataTexture. %r vs %r'
26+
% (np.shape(old), np.shape(value)))
27+
28+
if isinstance(proposal['value'], NDArrayWidget):
29+
if value is not Undefined and value.dtype == np.float64:
30+
raise TraitError('Cannot use a float64 data widget as a BufferAttribute source.')
31+
return proposal['value']
32+
if value is not Undefined and value.dtype == np.float64:
2233
# 64-bit not supported, coerce to 32-bit
2334
value = value.astype(np.float32)
2435
return value
36+

0 commit comments

Comments
 (0)