Skip to content

Instantly share code, notes, and snippets.

@maartenbreddels
Created April 12, 2017 19:16
Show Gist options
  • Save maartenbreddels/270420a88ba7653ef0b432768657b9d8 to your computer and use it in GitHub Desktop.
Save maartenbreddels/270420a88ba7653ef0b432768657b9d8 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 73,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import ipywidgets as widgets\n",
"from traitlets import Unicode, validate, CInt, CFloat\n",
"from traittypes import Array\n",
"import numpy as np\n",
"def from_json(value, obj=None):\n",
" return []\n",
"\n",
"def array_to_binary(ar, obj=None):\n",
" if ar is not None:\n",
" ar = ar.astype(np.float32)\n",
" mv = memoryview(ar)\n",
" # 'nested' is just to show the (de)serialization goes all fine\n",
" return {'data': mv, 'shape': ar.shape, 'nested': {'list': [mv, 'test']}}\n",
" else:\n",
" return None\n",
"\n",
"last_value = None\n",
"setters = 0\n",
"def binary_to_array(value, obj=None):\n",
" global last_value, setters\n",
" setters += 1\n",
" print(\">>\", value) # print msg'es get lost, but check the websocket output\n",
" last_value = value # or keep a reference to a global for debugging\n",
" return np.frombuffer(value, dtype=np.float32)\n",
" #return np.frombuffer(value['data'], dtype=np.float32)\n",
"\n",
"array_binary_serialization = dict(to_json=array_to_binary, from_json=binary_to_array)\n",
"\n",
"class DoublerWidget(widgets.DOMWidget):\n",
" _model_name = Unicode('DoublerModel').tag(sync=True)\n",
" _model_module = Unicode('doubler').tag(sync=True)\n",
" a = CInt().tag(sync=True)\n",
" x = Array(default_value=None).tag(sync=True, **array_binary_serialization)\n",
" y = Array(default_value=None, allow_none=True).tag(sync=True, **array_binary_serialization)\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"data": {
"application/javascript": [
"require.undef('doubler');\n",
"\n",
"define('doubler', [\"jupyter-js-widgets\"], function(widgets) {\n",
"\n",
" function deserialize_numpy_array(data, manager) {\n",
" if(data == null)\n",
" return null;\n",
" console.log(\"binary array\")\n",
" window.last_data = data\n",
" var ar = new Float32Array(data.data.buffer)\n",
" window.last_array = ar\n",
" return {data:ar, shape:data.shape, nested:data.nested}\n",
" }\n",
" \n",
" function serialize_numpy_array(data, m) {\n",
" console.log(\"serialize\", data)\n",
" return data;//[0,9]\n",
" }\n",
" \n",
" // Define the HelloView\n",
" var DoublerModel = widgets.WidgetModel.extend({\n",
" defaults: function() {\n",
" return _.extend(widgets.WidgetModel.prototype.defaults(), {\n",
" _model_name : 'DoublerModel',\n",
" _model_module : 'doubler',\n",
" })\n",
" },\n",
" initialize: function(attributes, options) {\n",
" console.log(this)\n",
" window.last_doubler = this\n",
" DoublerModel.__super__.initialize.apply(this, arguments);\n",
" this.on('change:x', this.double_x, this)\n",
" this.double_x()\n",
" },\n",
" double_x: function() {\n",
" var x = this.get('x')\n",
" var y = x.data.slice()\n",
" for(var i = 0; i < x.data.length; i++) {\n",
" y[i] = x.data[i]*x.data[i];\n",
" console.log('x[', i, '] = ', x.data[i], '; y[', i, '] = ', y[i])\n",
" }\n",
" this.set('y', {data: y, shape: x.shape, nested: x.nested})\n",
" this.save()\n",
" }\n",
" }, {\n",
" serializers: _.extend({\n",
" x: { deserialize: deserialize_numpy_array, serialize: serialize_numpy_array },\n",
" y: { deserialize: deserialize_numpy_array, serialize: serialize_numpy_array },\n",
" }, widgets.WidgetModel.serializers)\n",
"});\n",
"\n",
" \n",
" return {\n",
" DoublerModel: DoublerModel\n",
" }\n",
"});"
],
"text/plain": [
"<IPython.core.display.Javascript object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%%javascript\n",
"require.undef('doubler');\n",
"\n",
"define('doubler', [\"jupyter-js-widgets\"], function(widgets) {\n",
"\n",
" function deserialize_numpy_array(data, manager) {\n",
" if(data == null)\n",
" return null;\n",
" console.log(\"binary array\")\n",
" window.last_data = data\n",
" var ar = new Float32Array(data.data.buffer)\n",
" window.last_array = ar\n",
" return {data:ar, shape:data.shape, nested:data.nested}\n",
" }\n",
" \n",
" function serialize_numpy_array(data, m) {\n",
" console.log(\"serialize\", data)\n",
" return data;//[0,9]\n",
" }\n",
" \n",
" // Define the HelloView\n",
" var DoublerModel = widgets.WidgetModel.extend({\n",
" defaults: function() {\n",
" return _.extend(widgets.WidgetModel.prototype.defaults(), {\n",
" _model_name : 'DoublerModel',\n",
" _model_module : 'doubler',\n",
" })\n",
" },\n",
" initialize: function(attributes, options) {\n",
" console.log(this)\n",
" window.last_doubler = this\n",
" DoublerModel.__super__.initialize.apply(this, arguments);\n",
" this.on('change:x', this.double_x, this)\n",
" this.double_x()\n",
" },\n",
" double_x: function() {\n",
" var x = this.get('x')\n",
" var y = x.data.slice()\n",
" for(var i = 0; i < x.data.length; i++) {\n",
" y[i] = x.data[i]*x.data[i];\n",
" console.log('x[', i, '] = ', x.data[i], '; y[', i, '] = ', y[i])\n",
" }\n",
" this.set('y', {data: y, shape: x.shape, nested: x.nested})\n",
" this.save()\n",
" }\n",
" }, {\n",
" serializers: _.extend({\n",
" x: { deserialize: deserialize_numpy_array, serialize: serialize_numpy_array },\n",
" y: { deserialize: deserialize_numpy_array, serialize: serialize_numpy_array },\n",
" }, widgets.WidgetModel.serializers)\n",
"});\n",
"\n",
" \n",
" return {\n",
" DoublerModel: DoublerModel\n",
" }\n",
"});"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.arange(5, dtype=np.float32)\n",
"doubler = DoublerWidget(x=x)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([ 0., 1., 2., 3., 4.], dtype=float32), None)"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x, doubler.y"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'data': <memory at 0x113849c48>,\n",
" 'nested': {'list': [<memory at 0x113849a08>, 'test']},\n",
" 'shape': [5]}"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"last_value"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"setters"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# now, check the JS console, last_doubler._buffered_state_diff containts a value\n",
"# calling last_doubler.save_changes() will send this back to the pyside"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 80,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"setters # as confirmed by printing out this again"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [default]",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment